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 'dart:async'; import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; import '../../common/test_initialization.dart'; EngineSemantics semantics() => EngineSemantics.instance; void main() { internalBootstrapBrowserTest(() { return testMain; }); } Future<void> testMain() async { await bootstrapAndRunApp(withImplicitView: true); test('EngineSemantics is enabled via a placeholder click', () async { expect(semantics().semanticsEnabled, isFalse); // Synthesize a click on the placeholder. final DomElement placeholder = domDocument.querySelector('flt-semantics-placeholder')!; expect(placeholder.isConnected, isTrue); final DomRect rect = placeholder.getBoundingClientRect(); placeholder.dispatchEvent(createDomMouseEvent('click', <Object?, Object?>{ 'clientX': (rect.left + (rect.right - rect.left) / 2).floor(), 'clientY': (rect.top + (rect.bottom - rect.top) / 2).floor(), })); // On mobile semantics is enabled asynchronously. if (isMobile) { while (placeholder.isConnected!) { await Future<void>.delayed(const Duration(milliseconds: 50)); } } expect(semantics().semanticsEnabled, isTrue); expect(placeholder.isConnected, isFalse); }); }
engine/lib/web_ui/test/engine/semantics/semantics_placeholder_enable_test.dart/0
{ "file_path": "engine/lib/web_ui/test/engine/semantics/semantics_placeholder_enable_test.dart", "repo_id": "engine", "token_count": 489 }
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. 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 '../../common/matchers.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } Future<void> testMain() async { const ui.Size size = ui.Size(640, 480); group('ViewConstraints.fromJs', () { test('Negative min constraints -> Assertion error.', () async { expect( () => ViewConstraints.fromJs( JsViewConstraints( minWidth: -1, ), size), throwsAssertionError); expect( () => ViewConstraints.fromJs( JsViewConstraints( minHeight: -1, ), size), throwsAssertionError); }); test('Infinite min constraints -> Assertion error.', () async { expect( () => ViewConstraints.fromJs( JsViewConstraints( minWidth: double.infinity, ), size), throwsAssertionError); expect( () => ViewConstraints.fromJs( JsViewConstraints( minHeight: double.infinity, ), size), throwsAssertionError); }); test('Negative max constraints -> Assertion error.', () async { expect( () => ViewConstraints.fromJs( JsViewConstraints( maxWidth: -1, ), size), throwsAssertionError); expect( () => ViewConstraints.fromJs( JsViewConstraints( maxHeight: -1, ), size), throwsAssertionError); }); test('null JS Constraints -> Tight to size', () async { expect( ViewConstraints.fromJs(null, size), const ViewConstraints( minWidth: 640, maxWidth: 640, // minHeight: 480, maxHeight: 480, // )); }); test('non-null JS Constraints -> Computes sizes', () async { final JsViewConstraints constraints = JsViewConstraints( minWidth: 500, maxWidth: 600, // minHeight: 300, maxHeight: 400, // ); expect( ViewConstraints.fromJs(constraints, size), const ViewConstraints( minWidth: 500, maxWidth: 600, // minHeight: 300, maxHeight: 400, // )); }); test('null JS Width -> Tight to width. Computes height.', () async { final JsViewConstraints constraints = JsViewConstraints( minHeight: 200, maxHeight: 320, ); expect( ViewConstraints.fromJs(constraints, size), const ViewConstraints( minWidth: 640, maxWidth: 640, // minHeight: 200, maxHeight: 320, // )); }); test('null JS Height -> Tight to height. Computed width.', () async { final JsViewConstraints constraints = JsViewConstraints( minWidth: 200, maxWidth: 320, ); expect( ViewConstraints.fromJs(constraints, size), const ViewConstraints( minWidth: 200, maxWidth: 320, // minHeight: 480, maxHeight: 480, // )); }); test( 'non-null JS Constraints -> Computes sizes. Max values can be greater than available size.', () async { final JsViewConstraints constraints = JsViewConstraints( minWidth: 500, maxWidth: 1024, // minHeight: 300, maxHeight: 768, // ); expect( ViewConstraints.fromJs(constraints, size), const ViewConstraints( minWidth: 500, maxWidth: 1024, // minHeight: 300, maxHeight: 768, // )); }); test( 'non-null JS Constraints -> Computes sizes. Max values can be unconstrained.', () async { final JsViewConstraints constraints = JsViewConstraints( minWidth: 500, maxWidth: double.infinity, minHeight: 300, maxHeight: double.infinity, ); expect( ViewConstraints.fromJs(constraints, size), const ViewConstraints( // ignore: avoid_redundant_argument_values minWidth: 500, maxWidth: double.infinity, // ignore: avoid_redundant_argument_values minHeight: 300, maxHeight: double.infinity, )); }); }); }
engine/lib/web_ui/test/engine/view/view_constraints_test.dart/0
{ "file_path": "engine/lib/web_ui/test/engine/view/view_constraints_test.dart", "repo_id": "engine", "token_count": 2199 }
313
# See the `README.md` in this directory for documentation on the structure of # this file. compile-configs: - name: dart2js-html compiler: dart2js renderer: html - name: dart2js-canvaskit compiler: dart2js renderer: canvaskit - name: dart2js-skwasm compiler: dart2js renderer: skwasm - name: dart2wasm-html compiler: dart2wasm renderer: html - name: dart2wasm-canvaskit compiler: dart2wasm renderer: canvaskit - name: dart2wasm-skwasm compiler: dart2wasm renderer: skwasm test-sets: # Tests for non-renderer logic - name: engine directory: engine # Tests for canvaskit-renderer-specific functionality - name: canvaskit directory: canvaskit # Tests for html-renderer-specific functionality - name: html directory: html # Tests for renderer functionality that can be run on any renderer - name: ui directory: ui # Tests for fallback functionality between build variants - name: fallbacks directory: fallbacks test-bundles: - name: dart2js-html-engine test-set: engine compile-configs: dart2js-html - name: dart2js-html-html test-set: html compile-configs: dart2js-html - name: dart2js-html-ui test-set: ui compile-configs: dart2js-html - name: dart2js-canvaskit-canvaskit test-set: canvaskit compile-configs: dart2js-canvaskit - name: dart2js-canvaskit-ui test-set: ui compile-configs: dart2js-canvaskit - name: dart2wasm-html-engine test-set: engine compile-configs: dart2wasm-html - name: dart2wasm-html-html test-set: html compile-configs: dart2wasm-html - name: dart2wasm-html-ui test-set: ui compile-configs: dart2wasm-html - name: dart2wasm-canvaskit-canvaskit test-set: canvaskit compile-configs: dart2wasm-canvaskit - name: dart2wasm-canvaskit-ui test-set: ui compile-configs: dart2wasm-canvaskit - name: dart2wasm-skwasm-ui test-set: ui compile-configs: dart2wasm-skwasm - name: fallbacks test-set: fallbacks compile-configs: - dart2wasm-skwasm - dart2js-canvaskit run-configs: - name: chrome browser: chrome canvaskit-variant: chromium - name: chrome-full browser: chrome canvaskit-variant: full - name: edge browser: edge canvaskit-variant: chromium - name: edge-full browser: edge canvaskit-variant: full - name: firefox browser: firefox canvaskit-variant: full - name: safari browser: safari canvaskit-variant: full test-suites: - name: chrome-dart2js-html-engine test-bundle: dart2js-html-engine run-config: chrome - name: chrome-dart2js-html-html test-bundle: dart2js-html-html run-config: chrome - name: chrome-dart2js-html-ui test-bundle: dart2js-html-ui run-config: chrome - name: chrome-dart2js-canvaskit-canvaskit test-bundle: dart2js-canvaskit-canvaskit run-config: chrome artifact-deps: [ canvaskit_chromium ] - name: chrome-dart2js-canvaskit-ui test-bundle: dart2js-canvaskit-ui run-config: chrome artifact-deps: [ canvaskit_chromium ] - name: chrome-full-dart2js-canvaskit-canvaskit test-bundle: dart2js-canvaskit-canvaskit run-config: chrome-full artifact-deps: [ canvaskit ] - name: chrome-full-dart2js-canvaskit-ui test-bundle: dart2js-canvaskit-ui run-config: chrome-full artifact-deps: [ canvaskit ] - name: edge-dart2js-html-engine test-bundle: dart2js-html-engine run-config: edge - name: edge-dart2js-html-html test-bundle: dart2js-html-html run-config: edge - name: edge-dart2js-html-ui test-bundle: dart2js-html-ui run-config: edge - name: edge-dart2js-canvaskit-canvaskit test-bundle: dart2js-canvaskit-canvaskit run-config: edge artifact-deps: [ canvaskit_chromium ] - name: edge-dart2js-canvaskit-ui test-bundle: dart2js-canvaskit-ui run-config: edge artifact-deps: [ canvaskit_chromium ] - name: edge-full-dart2js-canvaskit-canvaskit test-bundle: dart2js-canvaskit-canvaskit run-config: edge-full artifact-deps: [ canvaskit ] - name: edge-full-dart2js-canvaskit-ui test-bundle: dart2js-canvaskit-ui run-config: edge-full artifact-deps: [ canvaskit ] - name: firefox-dart2js-html-engine test-bundle: dart2js-html-engine run-config: firefox - name: firefox-dart2js-html-html test-bundle: dart2js-html-html run-config: firefox - name: firefox-dart2js-html-ui test-bundle: dart2js-html-ui run-config: firefox - name: firefox-dart2js-canvaskit-canvaskit test-bundle: dart2js-canvaskit-canvaskit run-config: firefox artifact-deps: [ canvaskit ] - name: firefox-dart2js-canvaskit-ui test-bundle: dart2js-canvaskit-ui run-config: firefox artifact-deps: [ canvaskit ] - name: safari-dart2js-html-engine test-bundle: dart2js-html-engine run-config: safari - name: safari-dart2js-html-html test-bundle: dart2js-html-html run-config: safari - name: safari-dart2js-html-ui test-bundle: dart2js-html-ui run-config: safari - name: safari-dart2js-canvaskit-canvaskit test-bundle: dart2js-canvaskit-canvaskit run-config: safari artifact-deps: [ canvaskit ] - name: safari-dart2js-canvaskit-ui test-bundle: dart2js-canvaskit-ui run-config: safari artifact-deps: [ canvaskit ] - name: chrome-dart2wasm-html-engine test-bundle: dart2wasm-html-engine run-config: chrome - name: chrome-dart2wasm-html-html test-bundle: dart2wasm-html-html run-config: chrome - name: chrome-dart2wasm-html-ui test-bundle: dart2wasm-html-ui run-config: chrome - name: chrome-dart2wasm-canvaskit-canvaskit test-bundle: dart2wasm-canvaskit-canvaskit run-config: chrome artifact-deps: [ canvaskit_chromium ] - name: chrome-dart2wasm-canvaskit-ui test-bundle: dart2wasm-canvaskit-ui run-config: chrome artifact-deps: [ canvaskit_chromium ] - name: chrome-dart2wasm-skwasm-ui test-bundle: dart2wasm-skwasm-ui run-config: chrome artifact-deps: [ skwasm ] - name: chrome-full-dart2wasm-canvaskit-canvaskit test-bundle: dart2wasm-canvaskit-canvaskit run-config: chrome-full artifact-deps: [ canvaskit ] - name: chrome-full-dart2wasm-canvaskit-ui test-bundle: dart2wasm-canvaskit-ui run-config: chrome-full artifact-deps: [ canvaskit ] - name: chrome-fallbacks test-bundle: fallbacks run-config: chrome artifact-deps: [ canvaskit, skwasm ] - name: firefox-fallbacks test-bundle: fallbacks run-config: firefox artifact-deps: [ canvaskit ] - name: safari-fallbacks test-bundle: fallbacks run-config: safari artifact-deps: [ canvaskit ]
engine/lib/web_ui/test/felt_config.yaml/0
{ "file_path": "engine/lib/web_ui/test/felt_config.yaml", "repo_id": "engine", "token_count": 2918 }
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. 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, 400, 600); late BitmapCanvas canvas; setUp(() { canvas = BitmapCanvas(region, RenderStrategy()); }); tearDown(() { canvas.rootElement.remove(); }); test('draws arcs with largeArc , anticlockwise variations', () async { paintArc(canvas, Offset.zero, distance: 20); paintArc(canvas, const Offset(200, 0), largeArc: true, distance: 20); paintArc(canvas, const Offset(0, 150), clockwise: true, distance: 20); paintArc(canvas, const Offset(200, 150), largeArc: true, clockwise: true, distance: 20); paintArc(canvas, const Offset(0, 300), distance: -20); paintArc(canvas, const Offset(200, 300), largeArc: true, distance: -20); paintArc(canvas, const Offset(0, 400), clockwise: true, distance: -20); paintArc(canvas, const Offset(200, 400), largeArc: true, clockwise: true, distance: -20); domDocument.body!.append(canvas.rootElement); await matchGoldenFile('canvas_arc_to_point.png', region: region); }); test('Path.addArc that starts new path has correct start point', () async { const Rect rect = Rect.fromLTWH(20, 20, 200, 200); final Path p = Path() ..fillType = PathFillType.evenOdd ..addRect(rect) ..addArc(Rect.fromCircle(center: rect.center, radius: rect.size.shortestSide / 2), 0.25 * math.pi, 1.5 * math.pi); canvas.drawPath(p, SurfacePaintData() ..color = 0xFFFF9800 // orange ..style = PaintingStyle.fill); domDocument.body!.append(canvas.rootElement); await matchGoldenFile('canvas_addarc.png', region: region); }); test('Should render counter clockwise arcs', () async { final Path path = Path(); path.moveTo(149.999999999999997, 50); path.lineTo(149.999999999999997, 20); path.arcTo(const Rect.fromLTRB(20, 20, 280, 280), 4.71238898038469, 5.759586531581287 - 4.71238898038469, true); path.lineTo(236.60254037844385, 99.99999999999999); path.arcTo(const Rect.fromLTRB(50, 50, 250, 250), 5.759586531581287, 4.71238898038469 - 5.759586531581287, true); path.lineTo(149.999999999999997, 20); canvas.drawPath(path, SurfacePaintData() ..color = 0xFFFF9800 // orange ..style = PaintingStyle.fill); domDocument.body!.append(canvas.rootElement); await matchGoldenFile('canvas_addarc_ccw.png', region: region); }); } void paintArc(BitmapCanvas canvas, Offset offset, {bool largeArc = false, bool clockwise = false, double distance = 0}) { final Offset startP = Offset(75 - distance + offset.dx, 75 - distance + offset.dy); final Offset endP = Offset(75.0 + distance + offset.dx, 75.0 + distance + offset.dy); canvas.drawRect( Rect.fromLTRB(startP.dx, startP.dy, endP.dx, endP.dy), SurfacePaintData() ..strokeWidth = 1 ..color = 0xFFFF9800 // orange ..style = PaintingStyle.stroke); final Path path = Path(); path.moveTo(startP.dx, startP.dy); path.arcToPoint(endP, rotation: 45, radius: const Radius.elliptical(40, 60), largeArc: largeArc, clockwise: clockwise); canvas.drawPath( path, SurfacePaintData() ..strokeWidth = 2 ..color = 0x61000000 // black38 ..style = PaintingStyle.stroke); }
engine/lib/web_ui/test/html/drawing/canvas_arc_golden_test.dart/0
{ "file_path": "engine/lib/web_ui/test/html/drawing/canvas_arc_golden_test.dart", "repo_id": "engine", "token_count": 1470 }
315
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. 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' hide window; import '../../common/test_initialization.dart'; import 'helper.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } Future<void> testMain() async { setUpUnitTests( withImplicitView: true, emulateTesterEnvironment: false, setUpTestViewDimensions: false, ); void testJustifyWithMultipleSpans(EngineCanvas canvas) { void build(CanvasParagraphBuilder builder) { builder.pushStyle(EngineTextStyle.only(color: black)); builder.addText('Lorem ipsum dolor sit '); builder.pushStyle(EngineTextStyle.only(color: blue)); builder.addText('amet, consectetur '); builder.pushStyle(EngineTextStyle.only(color: green)); builder.addText('adipiscing elit, sed do eiusmod tempor incididunt ut '); builder.pushStyle(EngineTextStyle.only(color: red)); builder .addText('labore et dolore magna aliqua. Ut enim ad minim veniam, '); builder.pushStyle(EngineTextStyle.only(color: lightPurple)); builder.addText('quis nostrud exercitation ullamco '); builder.pushStyle(EngineTextStyle.only(color: blue)); builder.addText('laboris nisi ut aliquip ex ea commodo consequat.'); } final CanvasParagraph paragraph = rich( EngineParagraphStyle( fontFamily: 'Roboto', fontSize: 20.0, textAlign: TextAlign.justify, ), build, ); paragraph.layout(constrain(250.0)); canvas.drawParagraph(paragraph, Offset.zero); } test('TextAlign.justify with multiple spans', () { const Rect bounds = Rect.fromLTWH(0, 0, 400, 400); final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy()); testJustifyWithMultipleSpans(canvas); return takeScreenshot(canvas, bounds, 'canvas_paragraph_justify'); }); test('TextAlign.justify with multiple spans (DOM)', () { const Rect bounds = Rect.fromLTWH(0, 0, 400, 400); final DomCanvas canvas = DomCanvas(domDocument.createElement('flt-picture')); testJustifyWithMultipleSpans(canvas); return takeScreenshot(canvas, bounds, 'canvas_paragraph_justify_dom'); }); void testJustifyWithEmptyLine(EngineCanvas canvas) { void build(CanvasParagraphBuilder builder) { builder.pushStyle(bg(yellow)); builder.pushStyle(EngineTextStyle.only(color: black)); builder.addText('Loremipsumdolorsit'); builder.pushStyle(EngineTextStyle.only(color: blue)); builder.addText('amet, consectetur\n\n'); builder.pushStyle(EngineTextStyle.only(color: lightPurple)); builder.addText('adipiscing elit, sed do eiusmod tempor incididunt ut '); builder.pushStyle(EngineTextStyle.only(color: red)); builder.addText('labore et dolore magna aliqua.'); } final CanvasParagraph paragraph = rich( EngineParagraphStyle( fontFamily: 'Roboto', fontSize: 20.0, textAlign: TextAlign.justify, ), build, ); paragraph.layout(constrain(250.0)); canvas.drawParagraph(paragraph, Offset.zero); } test('TextAlign.justify with single space and empty line', () { const Rect bounds = Rect.fromLTWH(0, 0, 400, 400); final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy()); testJustifyWithEmptyLine(canvas); return takeScreenshot( canvas, bounds, 'canvas_paragraph_justify_empty_line'); }); test('TextAlign.justify with single space and empty line (DOM)', () { const Rect bounds = Rect.fromLTWH(0, 0, 400, 400); final DomCanvas canvas = DomCanvas(domDocument.createElement('flt-picture')); testJustifyWithEmptyLine(canvas); return takeScreenshot( canvas, bounds, 'canvas_paragraph_justify_empty_line_dom'); }); void testJustifyWithEllipsis(EngineCanvas canvas) { final EngineParagraphStyle paragraphStyle = EngineParagraphStyle( fontFamily: 'Roboto', fontSize: 20.0, textAlign: TextAlign.justify, maxLines: 4, ellipsis: '...', ); final CanvasParagraph paragraph = rich( paragraphStyle, (CanvasParagraphBuilder builder) { builder.pushStyle(EngineTextStyle.only(color: black)); builder.addText('Lorem ipsum dolor sit '); builder.pushStyle(EngineTextStyle.only(color: blue)); builder.addText('amet, consectetur '); builder.pushStyle(EngineTextStyle.only(color: green)); builder .addText('adipiscing elit, sed do eiusmod tempor incididunt ut '); builder.pushStyle(EngineTextStyle.only(color: red)); builder.addText( 'labore et dolore magna aliqua. Ut enim ad minim veniam, '); builder.pushStyle(EngineTextStyle.only(color: lightPurple)); builder.addText('quis nostrud exercitation ullamco '); builder.pushStyle(EngineTextStyle.only(color: blue)); builder.addText('laboris nisi ut aliquip ex ea commodo consequat.'); }, ); paragraph.layout(constrain(250)); canvas.drawParagraph(paragraph, Offset.zero); } test('TextAlign.justify with ellipsis', () { const Rect bounds = Rect.fromLTWH(0, 0, 400, 300); final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy()); testJustifyWithEllipsis(canvas); return takeScreenshot(canvas, bounds, 'canvas_paragraph_justify_ellipsis'); }); test('TextAlign.justify with ellipsis (DOM)', () { const Rect bounds = Rect.fromLTWH(0, 0, 400, 300); final DomCanvas canvas = DomCanvas(domDocument.createElement('flt-picture')); testJustifyWithEllipsis(canvas); return takeScreenshot(canvas, bounds, 'canvas_paragraph_justify_ellipsis_dom'); }); void testJustifyWithBackground(EngineCanvas canvas) { final EngineParagraphStyle paragraphStyle = EngineParagraphStyle( fontFamily: 'Roboto', fontSize: 20.0, textAlign: TextAlign.justify, ); final CanvasParagraph paragraph = rich( paragraphStyle, (CanvasParagraphBuilder builder) { builder.pushStyle(EngineTextStyle.only(color: black)); builder.pushStyle(bg(blue)); builder.addText('Lorem ipsum dolor sit '); builder.pushStyle(bg(black)); builder.pushStyle(EngineTextStyle.only(color: white)); builder.addText('amet, consectetur '); builder.pop(); builder.pushStyle(bg(green)); builder .addText('adipiscing elit, sed do eiusmod tempor incididunt ut '); builder.pushStyle(bg(yellow)); builder.addText( 'labore et dolore magna aliqua. Ut enim ad minim veniam, '); builder.pushStyle(bg(red)); builder.addText('quis nostrud exercitation ullamco '); builder.pushStyle(bg(green)); builder.addText('laboris nisi ut aliquip ex ea commodo consequat.'); }, ); paragraph.layout(constrain(250)); canvas.drawParagraph(paragraph, Offset.zero); } test('TextAlign.justify with background', () { const Rect bounds = Rect.fromLTWH(0, 0, 400, 400); final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy()); testJustifyWithBackground(canvas); return takeScreenshot( canvas, bounds, 'canvas_paragraph_justify_background'); }); test('TextAlign.justify with background (DOM)', () { const Rect bounds = Rect.fromLTWH(0, 0, 400, 400); final DomCanvas canvas = DomCanvas(domDocument.createElement('flt-picture')); testJustifyWithBackground(canvas); return takeScreenshot( canvas, bounds, 'canvas_paragraph_justify_background_dom'); }); void testJustifyWithPlaceholder(EngineCanvas canvas) { void build(CanvasParagraphBuilder builder) { builder.pushStyle(EngineTextStyle.only(color: black)); builder.addText('Lorem ipsum dolor sit '); builder.pushStyle(EngineTextStyle.only(color: blue)); builder.addText('amet, consectetur '); builder.pushStyle(EngineTextStyle.only(color: green)); builder.addText('adipiscing elit, sed do '); builder.addPlaceholder(40, 40, PlaceholderAlignment.bottom); builder.addText(' eiusmod tempor incididunt ut '); builder.pushStyle(EngineTextStyle.only(color: red)); builder.addText('labore et dolore magna aliqua.'); } final CanvasParagraph paragraph = rich( EngineParagraphStyle( fontFamily: 'Roboto', fontSize: 20.0, textAlign: TextAlign.justify, ), build, ); paragraph.layout(constrain(250.0)); canvas.drawParagraph(paragraph, Offset.zero); fillPlaceholder(canvas, Offset.zero, paragraph); } test('TextAlign.justify with placeholder', () { const Rect bounds = Rect.fromLTWH(0, 0, 400, 400); final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy()); testJustifyWithPlaceholder(canvas); return takeScreenshot(canvas, bounds, 'canvas_paragraph_justify_placeholder'); }); test('TextAlign.justify with placeholder (DOM)', () { const Rect bounds = Rect.fromLTWH(0, 0, 400, 400); final DomCanvas canvas = DomCanvas(domDocument.createElement('flt-picture')); testJustifyWithPlaceholder(canvas); return takeScreenshot(canvas, bounds, 'canvas_paragraph_justify_placeholder_dom'); }); void testJustifyWithSelection(EngineCanvas canvas) { void build(CanvasParagraphBuilder builder) { builder.pushStyle(EngineTextStyle.only(color: black)); builder.addText('Lorem ipsum dolor sit '); builder.pushStyle(EngineTextStyle.only(color: blue)); builder.addText('amet, consectetur '); // 40 builder.pushStyle(EngineTextStyle.only(color: green)); builder.addText('adipiscing elit, sed do eiusmod tempor incididunt ut '); builder.pushStyle(EngineTextStyle.only(color: red)); builder.addText('labore et dolore magna aliqua.'); } final CanvasParagraph paragraph = rich( EngineParagraphStyle( fontFamily: 'Roboto', fontSize: 20.0, textAlign: TextAlign.justify, ), build, ); paragraph.layout(constrain(250.0)); // Draw selection for "em ipsum d". fillBoxes(canvas, Offset.zero, paragraph.getBoxesForRange(3, 13), lightBlue); // Draw selection for " ut labore et dolore mag". fillBoxes(canvas, Offset.zero, paragraph.getBoxesForRange(89, 113), lightPurple); canvas.drawParagraph(paragraph, Offset.zero); } test('TextAlign.justify with selection', () { const Rect bounds = Rect.fromLTWH(0, 0, 400, 400); final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy()); testJustifyWithSelection(canvas); return takeScreenshot(canvas, bounds, 'canvas_paragraph_justify_selection'); }); test('TextAlign.justify with selection (DOM)', () { const Rect bounds = Rect.fromLTWH(0, 0, 400, 400); final DomCanvas canvas = DomCanvas(domDocument.createElement('flt-picture')); testJustifyWithSelection(canvas); return takeScreenshot(canvas, bounds, 'canvas_paragraph_justify_selection_dom'); }); void testJustifyRtl(EngineCanvas canvas) { const String rtlWord = 'مرحبا'; void build(CanvasParagraphBuilder builder) { builder.pushStyle(EngineTextStyle.only(color: black)); builder.addText('Lorem $rtlWord dolor sit '); builder.pushStyle(EngineTextStyle.only(color: blue)); builder.addText('amet, consectetur '); // 40 builder.pushStyle(EngineTextStyle.only(color: green)); builder.addText('adipiscing elit, sed do eiusmod $rtlWord incididunt ut '); builder.pushStyle(EngineTextStyle.only(color: red)); builder.addText('labore et dolore magna aliqua.'); } final CanvasParagraph paragraph = rich( EngineParagraphStyle( fontFamily: 'Roboto', fontSize: 20.0, textAlign: TextAlign.justify, ), build, ); paragraph.layout(constrain(250.0)); // Draw selection for "em $rtlWord d". fillBoxes(canvas, Offset.zero, paragraph.getBoxesForRange(3, 13), lightBlue); // Draw selection for " ut labore et dolore mag". fillBoxes(canvas, Offset.zero, paragraph.getBoxesForRange(89, 113), lightPurple); canvas.drawParagraph(paragraph, Offset.zero); } test('TextAlign.justify rtl', () { const Rect bounds = Rect.fromLTWH(0, 0, 400, 400); final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy()); testJustifyRtl(canvas); return takeScreenshot(canvas, bounds, 'canvas_paragraph_justify_rtl'); }); test('TextAlign.justify rtl (DOM)', () { const Rect bounds = Rect.fromLTWH(0, 0, 400, 400); final DomCanvas canvas = DomCanvas(domDocument.createElement('flt-picture')); testJustifyRtl(canvas); return takeScreenshot(canvas, bounds, 'canvas_paragraph_justify_rtl_dom'); }); } EngineTextStyle bg(Color color) { return EngineTextStyle.only(background: Paint()..color = color); }
engine/lib/web_ui/test/html/paragraph/justify_golden_test.dart/0
{ "file_path": "engine/lib/web_ui/test/html/paragraph/justify_golden_test.dart", "repo_id": "engine", "token_count": 4956 }
316
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart' as ui; import 'package:web_engine_tester/golden_tester.dart'; /// Commit a recording canvas to a bitmap, and compare with the expected. /// /// [region] specifies the area of the canvas that will be included in the /// golden. /// /// If [canvasRect] is omitted, it defaults to the value of [region]. Future<void> canvasScreenshot( RecordingCanvas rc, String fileName, { ui.Rect region = const ui.Rect.fromLTWH(0, 0, 500, 500), ui.Rect? canvasRect, bool setupPerspective = false, }) async { canvasRect ??= region; final EngineCanvas engineCanvas = BitmapCanvas(canvasRect, RenderStrategy()); rc.endRecording(); rc.apply(engineCanvas, region); // Wrap in <flt-scene> so that our CSS selectors kick in. final DomElement sceneElement = createDomElement('flt-scene'); if (isIosSafari) { // Shrink to fit on the iPhone screen. sceneElement.style.position = 'absolute'; sceneElement.style.transformOrigin = '0 0 0'; sceneElement.style.transform = 'scale(0.3)'; } try { if (setupPerspective) { // iFrame disables perspective, set it explicitly for test. engineCanvas.rootElement.style.perspective = '400px'; for (final DomElement element in engineCanvas.rootElement.querySelectorAll('div')) { element.style.perspective = '400px'; } } sceneElement.append(engineCanvas.rootElement); domDocument.body!.append(sceneElement); await matchGoldenFile('$fileName.png', region: region); } finally { // The page is reused across tests, so remove the element after taking the // screenshot. sceneElement.remove(); } } Future<void> sceneScreenshot(SurfaceSceneBuilder sceneBuilder, String fileName, {ui.Rect region = const ui.Rect.fromLTWH(0, 0, 600, 800)}) async { DomElement? sceneElement; try { sceneElement = sceneBuilder .build() .webOnlyRootElement; domDocument.body!.append(sceneElement!); await matchGoldenFile('$fileName.png', region: region); } finally { // The page is reused across tests, so remove the element after taking the // screenshot. sceneElement?.remove(); } }
engine/lib/web_ui/test/html/screenshot.dart/0
{ "file_path": "engine/lib/web_ui/test/html/screenshot.dart", "repo_id": "engine", "token_count": 811 }
317
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart'; import '../paragraph/helper.dart'; import 'line_breaker_test_helper.dart'; import 'line_breaker_test_raw_data.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } void testMain() { groupForEachFragmenter(({required bool isV8}) { List<Line> split(String text) { final LineBreakFragmenter fragmenter = isV8 ? V8LineBreakFragmenter(text) : FWLineBreakFragmenter(text); return <Line>[ for (final LineBreakFragment fragment in fragmenter.fragment()) Line.fromLineBreakFragment(text, fragment) ]; } test('empty string', () { expect(split(''), <Line>[ Line('', endOfText), ]); }); test('whitespace', () { expect(split('foo bar'), <Line>[ Line('foo ', opportunity, sp: 1), Line('bar', endOfText), ]); expect(split(' foo bar '), <Line>[ Line(' ', opportunity, sp: 2), Line('foo ', opportunity, sp: 4), Line('bar ', endOfText, sp: 2), ]); }); test('single-letter lines', () { expect(split('foo a bar'), <Line>[ Line('foo ', opportunity, sp: 1), Line('a ', opportunity, sp: 1), Line('bar', endOfText), ]); expect(split('a b c'), <Line>[ Line('a ', opportunity, sp: 1), Line('b ', opportunity, sp: 1), Line('c', endOfText), ]); expect(split(' a b '), <Line>[ Line(' ', opportunity, sp: 1), Line('a ', opportunity, sp: 1), Line('b ', endOfText, sp: 1), ]); }); test('new line characters', () { final String bk = String.fromCharCode(0x000B); // Can't have a line break between CR×LF. expect(split('foo\r\nbar'), <Line>[ Line('foo\r\n', mandatory, nl: 2, sp: 2), Line('bar', endOfText), ]); // Any other new line is considered a line break on its own. expect(split('foo\n\nbar'), <Line>[ Line('foo\n', mandatory, nl: 1, sp: 1), Line('\n', mandatory, nl: 1, sp: 1), Line('bar', endOfText), ]); expect(split('foo\r\rbar'), <Line>[ Line('foo\r', mandatory, nl: 1, sp: 1), Line('\r', mandatory, nl: 1, sp: 1), Line('bar', endOfText), ]); expect(split('foo$bk${bk}bar'), <Line>[ Line('foo$bk', mandatory, nl: 1, sp: 1), Line(bk, mandatory, nl: 1, sp: 1), Line('bar', endOfText), ]); expect(split('foo\n\rbar'), <Line>[ Line('foo\n', mandatory, nl: 1, sp: 1), Line('\r', mandatory, nl: 1, sp: 1), Line('bar', endOfText), ]); expect(split('foo$bk\rbar'), <Line>[ Line('foo$bk', mandatory, nl: 1, sp: 1), Line('\r', mandatory, nl: 1, sp: 1), Line('bar', endOfText), ]); expect(split('foo\r${bk}bar'), <Line>[ Line('foo\r', mandatory, nl: 1, sp: 1), Line(bk, mandatory, nl: 1, sp: 1), Line('bar', endOfText), ]); expect(split('foo$bk\nbar'), <Line>[ Line('foo$bk', mandatory, nl: 1, sp: 1), Line('\n', mandatory, nl: 1, sp: 1), Line('bar', endOfText), ]); expect(split('foo\n${bk}bar'), <Line>[ Line('foo\n', mandatory, nl: 1, sp: 1), Line(bk, mandatory, nl: 1, sp: 1), Line('bar', endOfText), ]); // New lines at the beginning and end. expect(split('foo\n'), <Line>[ Line('foo\n', mandatory, nl: 1, sp: 1), Line('', endOfText), ]); expect(split('foo\r'), <Line>[ Line('foo\r', mandatory, nl: 1, sp: 1), Line('', endOfText), ]); expect(split('foo$bk'), <Line>[ Line('foo$bk', mandatory, nl: 1, sp: 1), Line('', endOfText), ]); expect(split('\nfoo'), <Line>[ Line('\n', mandatory, nl: 1, sp: 1), Line('foo', endOfText), ]); expect(split('\rfoo'), <Line>[ Line('\r', mandatory, nl: 1, sp: 1), Line('foo', endOfText), ]); expect(split('${bk}foo'), <Line>[ Line(bk, mandatory, nl: 1, sp: 1), Line('foo', endOfText), ]); // Whitespace with new lines. expect(split('foo \n'), <Line>[ Line('foo \n', mandatory, nl: 1, sp: 3), Line('', endOfText), ]); expect(split('foo \n '), <Line>[ Line('foo \n', mandatory, nl: 1, sp: 3), Line(' ', endOfText, sp: 3), ]); expect(split('foo \n bar'), <Line>[ Line('foo \n', mandatory, nl: 1, sp: 3), Line(' ', opportunity, sp: 3), Line('bar', endOfText), ]); expect(split('\n foo'), <Line>[ Line('\n', mandatory, nl: 1, sp: 1), Line(' ', opportunity, sp: 2), Line('foo', endOfText), ]); expect(split(' \n foo'), <Line>[ Line(' \n', mandatory, nl: 1, sp: 4), Line(' ', opportunity, sp: 2), Line('foo', endOfText), ]); }); test('trailing spaces and new lines', () { expect(split('foo bar '), <Line>[ Line('foo ', opportunity, sp: 1), Line('bar ', endOfText, sp: 2), ], ); expect(split('foo \nbar\nbaz \n'), <Line>[ Line('foo \n', mandatory, nl: 1, sp: 3), Line('bar\n', mandatory, nl: 1, sp: 1), Line('baz \n', mandatory, nl: 1, sp: 4), Line('', endOfText), ], ); }); test('leading spaces', () { expect(split(' foo'), <Line>[ Line(' ', opportunity, sp: 1), Line('foo', endOfText), ], ); expect(split(' foo'), <Line>[ Line(' ', opportunity, sp: 3), Line('foo', endOfText), ], ); expect(split(' foo bar'), <Line>[ Line(' ', opportunity, sp: 2), Line('foo ', opportunity, sp: 3), Line('bar', endOfText), ], ); expect(split(' \n foo'), <Line>[ Line(' \n', mandatory, nl: 1, sp: 3), Line(' ', opportunity, sp: 3), Line('foo', endOfText), ], ); }); test('whitespace before the last character', () { expect(split('Lorem sit .'), <Line>[ Line('Lorem ', opportunity, sp: 1), Line('sit ', opportunity, sp: 1), Line('.', endOfText), ], ); }); test('placeholders', () { final CanvasParagraph paragraph = rich( EngineParagraphStyle(), (CanvasParagraphBuilder builder) { builder.addPlaceholder(100, 100, PlaceholderAlignment.top); builder.addText('Lorem'); builder.addPlaceholder(100, 100, PlaceholderAlignment.top); builder.addText('ipsum\n'); builder.addPlaceholder(100, 100, PlaceholderAlignment.top); builder.addText('dolor'); builder.addPlaceholder(100, 100, PlaceholderAlignment.top); builder.addText('\nsit'); builder.addPlaceholder(100, 100, PlaceholderAlignment.top); }, ); final String placeholderChar = String.fromCharCode(0xFFFC); expect(split(paragraph.plainText), <Line>[ Line(placeholderChar, opportunity), Line('Lorem', opportunity), Line(placeholderChar, opportunity), Line('ipsum\n', mandatory, nl: 1, sp: 1), Line(placeholderChar, opportunity), Line('dolor', opportunity), Line('$placeholderChar\n', mandatory, nl: 1, sp: 1), Line('sit', opportunity), Line(placeholderChar, endOfText), ]); }); test('single placeholder', () { final CanvasParagraph paragraph = rich( EngineParagraphStyle(), (CanvasParagraphBuilder builder) { builder.addPlaceholder(100, 100, PlaceholderAlignment.top); }, ); final String placeholderChar = String.fromCharCode(0xFFFC); expect(split(paragraph.plainText), <Line>[ Line(placeholderChar, endOfText), ]); }); test('placeholders surrounded by spaces and new lines', () { final CanvasParagraph paragraph = rich( EngineParagraphStyle(), (CanvasParagraphBuilder builder) { builder.addPlaceholder(100, 100, PlaceholderAlignment.top); builder.addText(' Lorem '); builder.addPlaceholder(100, 100, PlaceholderAlignment.top); builder.addText(' \nipsum \n'); builder.addPlaceholder(100, 100, PlaceholderAlignment.top); builder.addText('\n'); builder.addPlaceholder(100, 100, PlaceholderAlignment.top); }, ); expect(split(paragraph.plainText), <Line>[ Line('$placeholderChar ', opportunity, sp: 2), Line('Lorem ', opportunity, sp: 2), Line('$placeholderChar \n', mandatory, nl: 1, sp: 3), Line('ipsum \n', mandatory, nl: 1, sp: 2), Line('$placeholderChar\n', mandatory, nl: 1, sp: 1), Line(placeholderChar, endOfText), ], ); }); test('surrogates', () { expect(split('A\u{1F600}'), <Line>[ Line('A', opportunity), Line('\u{1F600}', endOfText), ], ); expect(split('\u{1F600}A'), <Line>[ Line('\u{1F600}', opportunity), Line('A', endOfText), ], ); expect(split('\u{1F600}\u{1F600}'), <Line>[ Line('\u{1F600}', opportunity), Line('\u{1F600}', endOfText), ], ); expect(split('A \u{1F600} \u{1F600}'), <Line>[ Line('A ', opportunity, sp: 1), Line('\u{1F600} ', opportunity, sp: 1), Line('\u{1F600}', endOfText), ], ); }); test('comprehensive test', () { final List<TestCase> testCollection = parseRawTestData(rawLineBreakTestData, isV8: isV8); for (int t = 0; t < testCollection.length; t++) { final TestCase testCase = testCollection[t]; final String text = testCase.toText(); final LineBreakFragmenter fragmenter = isV8 ? V8LineBreakFragmenter(text) : FWLineBreakFragmenter(text); final List<LineBreakFragment> fragments = fragmenter.fragment(); // `f` is the index in the `fragments` list. int f = 0; LineBreakFragment currentFragment = fragments[f]; int surrogateCount = 0; // `s` is the index in the `testCase.signs` list. for (int s = 0; s < testCase.signs.length - 1; s++) { // `i` is the index in the `text`. final int i = s + surrogateCount; final Sign sign = testCase.signs[s]; if (sign.isBreakOpportunity) { expect( currentFragment.end, i, reason: 'Failed at test case number $t:\n' '$testCase\n' '"$text"\n' '\nExpected fragment to end at {$i} but ended at {${currentFragment.end}}.', ); currentFragment = fragments[++f]; } else { expect( currentFragment.end, greaterThan(i), reason: 'Failed at test case number $t:\n' '$testCase\n' '"$text"\n' '\nFragment ended in early at {${currentFragment.end}}.', ); } if (s < testCase.chars.length && testCase.chars[s].isSurrogatePair) { surrogateCount++; } } // Now let's look at the last sign, which requires different handling. // The last line break is an endOfText (or a hard break followed by // endOfText if the last character is a hard line break). if (currentFragment.type == mandatory) { // When last character is a hard line break, there should be an // extra fragment to represent the empty line at the end. expect( fragments, hasLength(f + 2), reason: 'Failed at test case number $t:\n' '$testCase\n' '"$text"\n' "\nExpected an extra fragment for endOfText but there wasn't one.", ); currentFragment = fragments[++f]; } expect( currentFragment.type, endOfText, reason: 'Failed at test case number $t:\n' '$testCase\n' '"$text"\n\n' 'Expected an endOfText fragment but found: $currentFragment', ); expect( currentFragment.end, text.length, reason: 'Failed at test case number $t:\n' '$testCase\n' '"$text"\n\n' 'Expected an endOfText fragment ending at {${text.length}} but found: $currentFragment', ); } }); }); group('v8BreakIterator hard line breaks', () { List<Line> split(String text) { return V8LineBreakFragmenter(text) .fragment() .map((LineBreakFragment fragment) => Line.fromLineBreakFragment(text, fragment)) .toList(); } test('thai text with hard line breaks', () { const String thaiText = '\u0E1A\u0E38\u0E1C\u0E25\u0E01\u0E32\u0E23'; expect(split(thaiText), <Line>[ Line('\u0E1A\u0E38', opportunity), Line('\u0E1C\u0E25', opportunity), Line('\u0E01\u0E32\u0E23', endOfText), ]); expect(split('$thaiText\n'), <Line>[ Line('\u0E1A\u0E38', opportunity), Line('\u0E1C\u0E25', opportunity), Line('\u0E01\u0E32\u0E23\n', mandatory, nl: 1, sp: 1), Line('', endOfText), ]); }); test('khmer text with hard line breaks', () { const String khmerText = '\u179B\u1792\u17D2\u179C\u17BE\u17B2\u17D2\u1799'; expect(split(khmerText), <Line>[ Line('\u179B', opportunity), Line('\u1792\u17D2\u179C\u17BE', opportunity), Line('\u17B2\u17D2\u1799', endOfText), ]); expect(split('$khmerText\n'), <Line>[ Line('\u179B', opportunity), Line('\u1792\u17D2\u179C\u17BE', opportunity), Line('\u17B2\u17D2\u1799\n', mandatory, nl: 1, sp: 1), Line('', endOfText), ]); }); }, skip: domIntl.v8BreakIterator == null); } typedef GroupBody = void Function({required bool isV8}); void groupForEachFragmenter(GroupBody callback) { group( '$FWLineBreakFragmenter', () => callback(isV8: false), ); if (domIntl.v8BreakIterator != null) { group( '$V8LineBreakFragmenter', () => callback(isV8: true), ); } } /// Holds information about how a line was split from a string. class Line { Line(this.text, this.breakType, {this.nl = 0, this.sp = 0}); factory Line.fromLineBreakFragment(String text, LineBreakFragment fragment) { return Line( text.substring(fragment.start, fragment.end), fragment.type, nl: fragment.trailingNewlines, sp: fragment.trailingSpaces, ); } final String text; final LineBreakType breakType; final int nl; final int sp; @override int get hashCode => Object.hash(text, breakType, nl, sp); @override bool operator ==(Object other) { return other is Line && other.text == text && other.breakType == breakType && other.nl == nl && other.sp == sp; } String get escapedText { final String bk = String.fromCharCode(0x000B); final String nl = String.fromCharCode(0x0085); return text .replaceAll('"', r'\"') .replaceAll('\n', r'\n') .replaceAll('\r', r'\r') .replaceAll(bk, '{BK}') .replaceAll(nl, '{NL}'); } @override String toString() { return '"$escapedText" ($breakType, nl: $nl, sp: $sp)'; } }
engine/lib/web_ui/test/html/text/line_breaker_test.dart/0
{ "file_path": "engine/lib/web_ui/test/html/text/line_breaker_test.dart", "repo_id": "engine", "token_count": 7611 }
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. import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/ui.dart' as ui; import 'package:web_engine_tester/golden_tester.dart'; import '../common/test_initialization.dart'; import 'utils.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } Future<void> testMain() async { const ui.Rect region = ui.Rect.fromLTWH(0, 0, 300, 300); setUpUnitTests( withImplicitView: true, emulateTesterEnvironment: false, setUpTestViewDimensions: false, ); test('Test drawing a shadow of an opaque object', () async { final ui.Picture picture = drawPicture((ui.Canvas canvas) { final ui.Path path = ui.Path(); path.moveTo(50, 150); path.cubicTo(100, 50, 200, 250, 250, 150); canvas.drawShadow( path, const ui.Color(0xFF000000), 5, false); canvas.drawPath(path, ui.Paint()..color = const ui.Color(0xFFFF00FF)); }); await drawPictureUsingCurrentRenderer(picture); await matchGoldenFile('shadow_opaque_object.png', region: region); }); test('Test drawing a shadow of a translucent object', () async { final ui.Picture picture = drawPicture((ui.Canvas canvas) { final ui.Path path = ui.Path(); path.moveTo(50, 150); path.cubicTo(100, 250, 200, 50, 250, 150); canvas.drawShadow( path, const ui.Color(0xFF000000), 5, true); canvas.drawPath(path, ui.Paint()..color = const ui.Color(0x8F00FFFF)); }); await drawPictureUsingCurrentRenderer(picture); await matchGoldenFile('shadow_translucent_object.png', region: region); }); }
engine/lib/web_ui/test/ui/shadow_test.dart/0
{ "file_path": "engine/lib/web_ui/test/ui/shadow_test.dart", "repo_id": "engine", "token_count": 704 }
319
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_RUNTIME_DART_PLUGIN_REGISTRANT_H_ #define FLUTTER_RUNTIME_DART_PLUGIN_REGISTRANT_H_ #include "third_party/dart/runtime/include/dart_api.h" namespace flutter { /// The name of the library where the Dart Plugin Registrant will be looked for. /// This is available for testing. extern const char* dart_plugin_registrant_library_override; /// Looks for the Dart Plugin Registrant in `library_handle` and invokes it if /// it is found. /// @return `true` when the registrant has been invoked. bool InvokeDartPluginRegistrantIfAvailable(Dart_Handle library_handle); /// @return `true` when the registrant has been invoked. bool FindAndInvokeDartPluginRegistrant(); } // namespace flutter #endif // FLUTTER_RUNTIME_DART_PLUGIN_REGISTRANT_H_
engine/runtime/dart_plugin_registrant.h/0
{ "file_path": "engine/runtime/dart_plugin_registrant.h", "repo_id": "engine", "token_count": 298 }
320
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_RUNTIME_DART_VM_LIFECYCLE_H_ #define FLUTTER_RUNTIME_DART_VM_LIFECYCLE_H_ #include <memory> #include "flutter/fml/macros.h" #include "flutter/lib/ui/isolate_name_server/isolate_name_server.h" #include "flutter/runtime/dart_vm.h" #include "flutter/runtime/service_protocol.h" #include "third_party/dart/runtime/include/dart_tools_api.h" namespace flutter { // A strong reference to the Dart VM. There can only be one VM running in the // process at any given time. A reference to the VM may only be obtained via the // |Create| method. In case there is already a running instance of the VM in the // process, a strong reference to that VM is obtained and the arguments to the // |Create| call ignored. If there is no VM already running in the process, a VM // is initialized in a thread safe manner and returned to the caller. The VM // will shutdown only when all callers relinquish their references (by // collecting their instances of this class). // // DartVMRef instances may be created on any thread. class DartVMRef { public: [[nodiscard]] static DartVMRef Create( const Settings& settings, fml::RefPtr<const DartSnapshot> vm_snapshot = nullptr, fml::RefPtr<const DartSnapshot> isolate_snapshot = nullptr); DartVMRef(const DartVMRef&) = default; DartVMRef(DartVMRef&&); ~DartVMRef(); // This is an inherently racy way to check if a VM instance is running and // should not be used outside of unit-tests where there is a known threading // model. static bool IsInstanceRunning(); static std::shared_ptr<const DartVMData> GetVMData(); static std::shared_ptr<ServiceProtocol> GetServiceProtocol(); static std::shared_ptr<IsolateNameServer> GetIsolateNameServer(); explicit operator bool() const { return static_cast<bool>(vm_); } DartVM* get() { FML_DCHECK(vm_); return vm_.get(); } const DartVM* get() const { FML_DCHECK(vm_); return vm_.get(); } DartVM* operator->() { FML_DCHECK(vm_); return vm_.get(); } const DartVM* operator->() const { FML_DCHECK(vm_); return vm_.get(); } // NOLINTNEXTLINE(google-runtime-operator) DartVM* operator&() { FML_DCHECK(vm_); return vm_.get(); } private: friend class DartIsolate; std::shared_ptr<DartVM> vm_; explicit DartVMRef(std::shared_ptr<DartVM> vm); // Only used by Dart Isolate to register itself with the VM. static DartVM* GetRunningVM(); }; } // namespace flutter #endif // FLUTTER_RUNTIME_DART_VM_LIFECYCLE_H_
engine/runtime/dart_vm_lifecycle.h/0
{ "file_path": "engine/runtime/dart_vm_lifecycle.h", "repo_id": "engine", "token_count": 893 }
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. // It is __imperative__ that the functions in this file are __not__ included in // release or profile builds. // // They call into the "private" ptrace() API to ensure that the current process // is being ptrace()-d. Only debug builds rely on ptrace(), and the ptrace() API // is not allowed for use in the App Store, so we must exclude it from profile- // and release-builds. // // When an app is launched from a host workstation (e.g. via Xcode or // "ios-deploy"), the process is already ptrace()-d by debugserver. However, // when an app is launched from the home screen, it is not, so for debug builds // we initialize the ptrace() relationship via PT_TRACE_ME if necessary. // // Please see the following documents for more details: // - go/decommissioning-dbc // - go/decommissioning-dbc-engine // - go/decommissioning-dbc-tools #include "flutter/runtime/ptrace_check.h" #if TRACING_CHECKS_NECESSARY #include <sys/sysctl.h> #include <sys/types.h> #include <mutex> #include "flutter/fml/build_config.h" // Being extra careful and adding additional landmines that will prevent // compilation of this TU in an incorrect runtime mode. static_assert(FML_OS_IOS, "This translation unit is iOS specific."); static_assert(FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG, "This translation unit must only be compiled in the debug " "runtime mode as it " "contains private API usage."); #define PT_TRACE_ME 0 #define PT_SIGEXC 12 extern "C" int ptrace(int request, pid_t pid, caddr_t addr, int data); namespace flutter { static bool IsLaunchedByFlutterCLI(const Settings& vm_settings) { // Only the Flutter CLI passes "--enable-checked-mode". Therefore, if the flag // is present, we have been launched by "ios-deploy" via "debugserver". // // We choose this flag because it is always passed to launch debug builds. return vm_settings.enable_checked_mode; } static bool IsLaunchedByXcode() { // Use "sysctl()" to check if we're currently being debugged (e.g. by Xcode). // We could also check "getppid() != 1" (launchd), but this is more direct. const pid_t self = getpid(); int mib[5] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, self, 0}; auto proc = std::make_unique<struct kinfo_proc>(); size_t proc_size = sizeof(struct kinfo_proc); if (::sysctl(mib, 4, proc.get(), &proc_size, nullptr, 0) < 0) { FML_LOG(ERROR) << "Could not execute sysctl() to get current process info: " << strerror(errno); return false; } return proc->kp_proc.p_flag & P_TRACED; } static bool EnableTracingManually(const Settings& vm_settings) { if (::ptrace(PT_TRACE_ME, 0, nullptr, 0) == -1) { FML_LOG(ERROR) << "Could not call ptrace(PT_TRACE_ME): " << strerror(errno); // No use trying PT_SIGEXC -- it's only needed if PT_TRACE_ME succeeds. return false; } if (::ptrace(PT_SIGEXC, 0, nullptr, 0) == -1) { FML_LOG(ERROR) << "Could not call ptrace(PT_SIGEXC): " << strerror(errno); return false; } // The previous operation causes this process to not be reaped after it // terminates (even if PT_SIGEXC fails). Issue a warning to the console every // (approximiately) maxproc/10 leaks. See the links above for an explanation // of this issue. size_t maxproc = 0; size_t maxproc_size = sizeof(size_t); const int sysctl_result = ::sysctlbyname("kern.maxproc", &maxproc, &maxproc_size, nullptr, 0); if (sysctl_result < 0) { FML_LOG(ERROR) << "Could not execute sysctl() to determine process count limit: " << strerror(errno); return false; } const char* warning = "Launching a debug-mode app from the home screen may cause problems.\n" "Please compile a profile-/release-build, launch your app via \"flutter " "run\", or see https://github.com/flutter/flutter/wiki/" "PID-leak-in-iOS-debug-builds-launched-from-home-screen for details."; if (vm_settings.verbose_logging // used for testing and also informative || sysctl_result < 0 // could not determine maximum process count || maxproc / 10 == 0 // avoid division (%) by 0 || getpid() % (maxproc / 10) == 0) // warning every ~maxproc/10 leaks { FML_LOG(ERROR) << warning; } return true; } static bool EnableTracingIfNecessaryOnce(const Settings& vm_settings) { if (IsLaunchedByFlutterCLI(vm_settings)) { return true; } if (IsLaunchedByXcode()) { return true; } return EnableTracingManually(vm_settings); } static TracingResult sTracingResult = TracingResult::kNotAttempted; bool EnableTracingIfNecessaryImpl(const Settings& vm_settings) { static std::once_flag tracing_flag; std::call_once(tracing_flag, [&vm_settings]() { sTracingResult = EnableTracingIfNecessaryOnce(vm_settings) ? TracingResult::kEnabled : TracingResult::kDisabled; }); return sTracingResult != TracingResult::kDisabled; } TracingResult GetTracingResultImpl() { return sTracingResult; } } // namespace flutter #endif // TRACING_CHECKS_NECESSARY
engine/runtime/ptrace_check.cc/0
{ "file_path": "engine/runtime/ptrace_check.cc", "repo_id": "engine", "token_count": 1884 }
322
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_COMMON_ANIMATOR_H_ #define FLUTTER_SHELL_COMMON_ANIMATOR_H_ #include <deque> #include "flutter/common/task_runners.h" #include "flutter/flow/frame_timings.h" #include "flutter/fml/memory/ref_ptr.h" #include "flutter/fml/memory/weak_ptr.h" #include "flutter/fml/synchronization/semaphore.h" #include "flutter/fml/time/time_point.h" #include "flutter/shell/common/pipeline.h" #include "flutter/shell/common/rasterizer.h" #include "flutter/shell/common/vsync_waiter.h" namespace flutter { namespace testing { class ShellTest; } /// Executor of animations. /// /// In conjunction with the |VsyncWaiter| it allows callers (typically Dart /// code) to schedule work that ends up generating a |LayerTree|. class Animator final { public: class Delegate { public: virtual void OnAnimatorBeginFrame(fml::TimePoint frame_target_time, uint64_t frame_number) = 0; virtual void OnAnimatorNotifyIdle(fml::TimeDelta deadline) = 0; virtual void OnAnimatorUpdateLatestFrameTargetTime( fml::TimePoint frame_target_time) = 0; virtual void OnAnimatorDraw(std::shared_ptr<FramePipeline> pipeline) = 0; virtual void OnAnimatorDrawLastLayerTrees( std::unique_ptr<FrameTimingsRecorder> frame_timings_recorder) = 0; }; Animator(Delegate& delegate, const TaskRunners& task_runners, std::unique_ptr<VsyncWaiter> waiter); ~Animator(); void RequestFrame(bool regenerate_layer_trees = true); //-------------------------------------------------------------------------- /// @brief Tells the Animator that all views that should render for this /// frame have been rendered. /// /// In regular frames, since all `Render` calls must take place /// during a vsync task, the Animator knows that all views have /// been rendered at the end of the vsync task, therefore calling /// this method is not needed. /// /// However, the engine might decide to start it a bit earlier, for /// example, if the engine decides that no more views can be /// rendered, so that the rasterization can start a bit earlier. /// /// This method is also useful in warm-up frames. In a warm up /// frame, `Animator::Render` is called out of vsync tasks, and /// Animator requires an explicit end-of-frame call to know when to /// send the layer trees to the pipeline. /// /// For more about warm up frames, see /// `PlatformDispatcher.scheduleWarmUpFrame`. /// void OnAllViewsRendered(); //-------------------------------------------------------------------------- /// @brief Tells the Animator that this frame needs to render another view. /// /// This method must be called during a vsync callback, or /// technically, between Animator::BeginFrame and Animator::EndFrame /// (both private methods). Otherwise, this call will be ignored. /// void Render(int64_t view_id, std::unique_ptr<flutter::LayerTree> layer_tree, float device_pixel_ratio); const std::weak_ptr<VsyncWaiter> GetVsyncWaiter() const; //-------------------------------------------------------------------------- /// @brief Schedule a secondary callback to be executed right after the /// main `VsyncWaiter::AsyncWaitForVsync` callback (which is added /// by `Animator::RequestFrame`). /// /// Like the callback in `AsyncWaitForVsync`, this callback is /// only scheduled to be called once, and it's supposed to be /// called in the UI thread. If there is no AsyncWaitForVsync /// callback (`Animator::RequestFrame` is not called), this /// secondary callback will still be executed at vsync. /// /// This callback is used to provide the vsync signal needed by /// `SmoothPointerDataDispatcher`, and for our own flow events. /// /// @see `PointerDataDispatcher::ScheduleSecondaryVsyncCallback`. void ScheduleSecondaryVsyncCallback(uintptr_t id, const fml::closure& callback); // Enqueue |trace_flow_id| into |trace_flow_ids_|. The flow event will be // ended at either the next frame, or the next vsync interval with no active // rendering. void EnqueueTraceFlowId(uint64_t trace_flow_id); private: // Animator's work during a vsync is split into two methods, BeginFrame and // EndFrame. The two methods should be called synchronously back-to-back to // avoid being interrupted by a regular vsync. The reason to split them is to // allow ShellTest::PumpOneFrame to insert a Render in between. void BeginFrame(std::unique_ptr<FrameTimingsRecorder> frame_timings_recorder); void EndFrame(); bool CanReuseLastLayerTrees(); void DrawLastLayerTrees( std::unique_ptr<FrameTimingsRecorder> frame_timings_recorder); void AwaitVSync(); // Clear |trace_flow_ids_| if |frame_scheduled_| is false. void ScheduleMaybeClearTraceFlowIds(); Delegate& delegate_; TaskRunners task_runners_; std::shared_ptr<VsyncWaiter> waiter_; std::unique_ptr<FrameTimingsRecorder> frame_timings_recorder_; std::unordered_map<int64_t, std::unique_ptr<LayerTreeTask>> layer_trees_tasks_; uint64_t frame_request_number_ = 1; fml::TimeDelta dart_frame_deadline_; std::shared_ptr<FramePipeline> layer_tree_pipeline_; fml::Semaphore pending_frame_semaphore_; FramePipeline::ProducerContinuation producer_continuation_; bool regenerate_layer_trees_ = false; bool frame_scheduled_ = false; std::deque<uint64_t> trace_flow_ids_; bool has_rendered_ = false; fml::WeakPtrFactory<Animator> weak_factory_; friend class testing::ShellTest; FML_DISALLOW_COPY_AND_ASSIGN(Animator); }; } // namespace flutter #endif // FLUTTER_SHELL_COMMON_ANIMATOR_H_
engine/shell/common/animator.h/0
{ "file_path": "engine/shell/common/animator.h", "repo_id": "engine", "token_count": 2164 }
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/common/engine.h" #include <cstring> #include <memory> #include <string> #include <utility> #include <vector> #include "flutter/common/settings.h" #include "flutter/fml/make_copyable.h" #include "flutter/fml/trace_event.h" #include "flutter/lib/snapshot/snapshot.h" #include "flutter/lib/ui/text/font_collection.h" #include "flutter/shell/common/animator.h" #include "flutter/shell/common/platform_view.h" #include "flutter/shell/common/shell.h" #include "impeller/runtime_stage/runtime_stage.h" #include "rapidjson/document.h" #include "third_party/dart/runtime/include/dart_tools_api.h" namespace flutter { static constexpr char kAssetChannel[] = "flutter/assets"; static constexpr char kLifecycleChannel[] = "flutter/lifecycle"; static constexpr char kNavigationChannel[] = "flutter/navigation"; static constexpr char kLocalizationChannel[] = "flutter/localization"; static constexpr char kSettingsChannel[] = "flutter/settings"; static constexpr char kIsolateChannel[] = "flutter/isolate"; namespace { fml::MallocMapping MakeMapping(const std::string& str) { return fml::MallocMapping::Copy(str.c_str(), str.length()); } } // namespace Engine::Engine( Delegate& delegate, const PointerDataDispatcherMaker& dispatcher_maker, const std::shared_ptr<fml::ConcurrentTaskRunner>& image_decoder_task_runner, const TaskRunners& task_runners, const Settings& settings, std::unique_ptr<Animator> animator, const fml::WeakPtr<IOManager>& io_manager, const std::shared_ptr<FontCollection>& font_collection, std::unique_ptr<RuntimeController> runtime_controller, const std::shared_ptr<fml::SyncSwitch>& gpu_disabled_switch) : delegate_(delegate), settings_(settings), animator_(std::move(animator)), runtime_controller_(std::move(runtime_controller)), font_collection_(font_collection), image_decoder_(ImageDecoder::Make(settings_, task_runners, image_decoder_task_runner, io_manager, gpu_disabled_switch)), task_runners_(task_runners), weak_factory_(this) { pointer_data_dispatcher_ = dispatcher_maker(*this); } Engine::Engine(Delegate& delegate, const PointerDataDispatcherMaker& dispatcher_maker, DartVM& vm, fml::RefPtr<const DartSnapshot> isolate_snapshot, const TaskRunners& task_runners, const PlatformData& platform_data, const Settings& settings, std::unique_ptr<Animator> animator, fml::WeakPtr<IOManager> io_manager, const fml::RefPtr<SkiaUnrefQueue>& unref_queue, fml::TaskRunnerAffineWeakPtr<SnapshotDelegate> snapshot_delegate, std::shared_ptr<VolatilePathTracker> volatile_path_tracker, const std::shared_ptr<fml::SyncSwitch>& gpu_disabled_switch, impeller::RuntimeStageBackend runtime_stage_type) : Engine(delegate, dispatcher_maker, vm.GetConcurrentWorkerTaskRunner(), task_runners, settings, std::move(animator), io_manager, std::make_shared<FontCollection>(), nullptr, gpu_disabled_switch) { runtime_controller_ = std::make_unique<RuntimeController>( *this, // runtime delegate &vm, // VM std::move(isolate_snapshot), // isolate snapshot settings_.idle_notification_callback, // idle notification callback platform_data, // platform data settings_.isolate_create_callback, // isolate create callback settings_.isolate_shutdown_callback, // isolate shutdown callback settings_.persistent_isolate_data, // persistent isolate data UIDartState::Context{ task_runners_, // task runners std::move(snapshot_delegate), // snapshot delegate std::move(io_manager), // io manager unref_queue, // Skia unref queue image_decoder_->GetWeakPtr(), // image decoder image_generator_registry_.GetWeakPtr(), // image generator registry settings_.advisory_script_uri, // advisory script uri settings_.advisory_script_entrypoint, // advisory script entrypoint std::move(volatile_path_tracker), // volatile path tracker vm.GetConcurrentWorkerTaskRunner(), // concurrent task runner settings_.enable_impeller, // enable impeller runtime_stage_type, // runtime stage type }); } std::unique_ptr<Engine> Engine::Spawn( Delegate& delegate, const PointerDataDispatcherMaker& dispatcher_maker, const Settings& settings, std::unique_ptr<Animator> animator, const std::string& initial_route, const fml::WeakPtr<IOManager>& io_manager, fml::TaskRunnerAffineWeakPtr<SnapshotDelegate> snapshot_delegate, const std::shared_ptr<fml::SyncSwitch>& gpu_disabled_switch) const { auto result = std::make_unique<Engine>( /*delegate=*/delegate, /*dispatcher_maker=*/dispatcher_maker, /*image_decoder_task_runner=*/ runtime_controller_->GetDartVM()->GetConcurrentWorkerTaskRunner(), /*task_runners=*/task_runners_, /*settings=*/settings, /*animator=*/std::move(animator), /*io_manager=*/io_manager, /*font_collection=*/font_collection_, /*runtime_controller=*/nullptr, /*gpu_disabled_switch=*/gpu_disabled_switch); result->runtime_controller_ = runtime_controller_->Spawn( /*p_client=*/*result, /*advisory_script_uri=*/settings.advisory_script_uri, /*advisory_script_entrypoint=*/settings.advisory_script_entrypoint, /*idle_notification_callback=*/settings.idle_notification_callback, /*isolate_create_callback=*/settings.isolate_create_callback, /*isolate_shutdown_callback=*/settings.isolate_shutdown_callback, /*persistent_isolate_data=*/settings.persistent_isolate_data, /*io_manager=*/io_manager, /*image_decoder=*/result->GetImageDecoderWeakPtr(), /*image_generator_registry=*/result->GetImageGeneratorRegistry(), /*snapshot_delegate=*/std::move(snapshot_delegate)); result->initial_route_ = initial_route; result->asset_manager_ = asset_manager_; return result; } Engine::~Engine() = default; fml::WeakPtr<Engine> Engine::GetWeakPtr() const { return weak_factory_.GetWeakPtr(); } void Engine::SetupDefaultFontManager() { TRACE_EVENT0("flutter", "Engine::SetupDefaultFontManager"); font_collection_->SetupDefaultFontManager(settings_.font_initialization_data); } std::shared_ptr<AssetManager> Engine::GetAssetManager() { return asset_manager_; } fml::WeakPtr<ImageDecoder> Engine::GetImageDecoderWeakPtr() { return image_decoder_->GetWeakPtr(); } fml::WeakPtr<ImageGeneratorRegistry> Engine::GetImageGeneratorRegistry() { return image_generator_registry_.GetWeakPtr(); } bool Engine::UpdateAssetManager( const std::shared_ptr<AssetManager>& new_asset_manager) { if (asset_manager_ && new_asset_manager && *asset_manager_ == *new_asset_manager) { return false; } asset_manager_ = new_asset_manager; if (!asset_manager_) { return false; } // Using libTXT as the text engine. if (settings_.use_asset_fonts) { font_collection_->RegisterFonts(asset_manager_); } if (settings_.use_test_fonts) { font_collection_->RegisterTestFonts(); } return true; } bool Engine::Restart(RunConfiguration configuration) { TRACE_EVENT0("flutter", "Engine::Restart"); if (!configuration.IsValid()) { FML_LOG(ERROR) << "Engine run configuration was invalid."; return false; } delegate_.OnPreEngineRestart(); runtime_controller_ = runtime_controller_->Clone(); UpdateAssetManager(nullptr); return Run(std::move(configuration)) == Engine::RunStatus::Success; } Engine::RunStatus Engine::Run(RunConfiguration configuration) { if (!configuration.IsValid()) { FML_LOG(ERROR) << "Engine run configuration was invalid."; return RunStatus::Failure; } last_entry_point_ = configuration.GetEntrypoint(); last_entry_point_library_ = configuration.GetEntrypointLibrary(); #if (FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG) // This is only used to support restart. last_entry_point_args_ = configuration.GetEntrypointArgs(); #endif UpdateAssetManager(configuration.GetAssetManager()); if (runtime_controller_->IsRootIsolateRunning()) { return RunStatus::FailureAlreadyRunning; } // If the embedding prefetched the default font manager, then set up the // font manager later in the engine launch process. This makes it less // likely that the setup will need to wait for the prefetch to complete. auto root_isolate_create_callback = [&]() { if (settings_.prefetched_default_font_manager) { SetupDefaultFontManager(); } }; if (!runtime_controller_->LaunchRootIsolate( settings_, // root_isolate_create_callback, // configuration.GetEntrypoint(), // configuration.GetEntrypointLibrary(), // configuration.GetEntrypointArgs(), // configuration.TakeIsolateConfiguration()) // ) { return RunStatus::Failure; } auto service_id = runtime_controller_->GetRootIsolateServiceID(); if (service_id.has_value()) { std::unique_ptr<PlatformMessage> service_id_message = std::make_unique<flutter::PlatformMessage>( kIsolateChannel, MakeMapping(service_id.value()), nullptr); HandlePlatformMessage(std::move(service_id_message)); } return Engine::RunStatus::Success; } void Engine::BeginFrame(fml::TimePoint frame_time, uint64_t frame_number) { runtime_controller_->BeginFrame(frame_time, frame_number); } void Engine::ReportTimings(std::vector<int64_t> timings) { runtime_controller_->ReportTimings(std::move(timings)); } void Engine::NotifyIdle(fml::TimeDelta deadline) { runtime_controller_->NotifyIdle(deadline); } void Engine::NotifyDestroyed() { TRACE_EVENT0("flutter", "Engine::NotifyDestroyed"); runtime_controller_->NotifyDestroyed(); } std::optional<uint32_t> Engine::GetUIIsolateReturnCode() { return runtime_controller_->GetRootIsolateReturnCode(); } Dart_Port Engine::GetUIIsolateMainPort() { return runtime_controller_->GetMainPort(); } std::string Engine::GetUIIsolateName() { return runtime_controller_->GetIsolateName(); } bool Engine::UIIsolateHasLivePorts() { return runtime_controller_->HasLivePorts(); } tonic::DartErrorHandleType Engine::GetUIIsolateLastError() { return runtime_controller_->GetLastError(); } void Engine::AddView(int64_t view_id, const ViewportMetrics& view_metrics) { runtime_controller_->AddView(view_id, view_metrics); } bool Engine::RemoveView(int64_t view_id) { return runtime_controller_->RemoveView(view_id); } void Engine::SetViewportMetrics(int64_t view_id, const ViewportMetrics& metrics) { runtime_controller_->SetViewportMetrics(view_id, metrics); ScheduleFrame(); } void Engine::DispatchPlatformMessage(std::unique_ptr<PlatformMessage> message) { std::string channel = message->channel(); if (channel == kLifecycleChannel) { if (HandleLifecyclePlatformMessage(message.get())) { return; } } else if (channel == kLocalizationChannel) { if (HandleLocalizationPlatformMessage(message.get())) { return; } } else if (channel == kSettingsChannel) { HandleSettingsPlatformMessage(message.get()); return; } else if (!runtime_controller_->IsRootIsolateRunning() && channel == kNavigationChannel) { // If there's no runtime_, we may still need to set the initial route. HandleNavigationPlatformMessage(std::move(message)); return; } if (runtime_controller_->IsRootIsolateRunning() && runtime_controller_->DispatchPlatformMessage(std::move(message))) { return; } FML_DLOG(WARNING) << "Dropping platform message on channel: " << channel; } bool Engine::HandleLifecyclePlatformMessage(PlatformMessage* message) { const auto& data = message->data(); std::string state(reinterpret_cast<const char*>(data.GetMapping()), data.GetSize()); // Always schedule a frame when the app does become active as per API // recommendation // https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1622956-applicationdidbecomeactive?language=objc if (state == "AppLifecycleState.resumed" || state == "AppLifecycleState.inactive") { ScheduleFrame(); } runtime_controller_->SetInitialLifecycleState(state); // Always forward these messages to the framework by returning false. return false; } bool Engine::HandleNavigationPlatformMessage( std::unique_ptr<PlatformMessage> message) { const auto& data = message->data(); rapidjson::Document document; document.Parse(reinterpret_cast<const char*>(data.GetMapping()), data.GetSize()); if (document.HasParseError() || !document.IsObject()) { return false; } auto root = document.GetObject(); auto method = root.FindMember("method"); if (method->value != "setInitialRoute") { return false; } auto route = root.FindMember("args"); initial_route_ = route->value.GetString(); return true; } bool Engine::HandleLocalizationPlatformMessage(PlatformMessage* message) { const auto& data = message->data(); rapidjson::Document document; document.Parse(reinterpret_cast<const char*>(data.GetMapping()), data.GetSize()); if (document.HasParseError() || !document.IsObject()) { return false; } auto root = document.GetObject(); auto method = root.FindMember("method"); if (method == root.MemberEnd()) { return false; } const size_t strings_per_locale = 4; if (method->value == "setLocale") { // Decode and pass the list of locale data onwards to dart. auto args = root.FindMember("args"); if (args == root.MemberEnd() || !args->value.IsArray()) { return false; } if (args->value.Size() % strings_per_locale != 0) { return false; } std::vector<std::string> locale_data; for (size_t locale_index = 0; locale_index < args->value.Size(); locale_index += strings_per_locale) { if (!args->value[locale_index].IsString() || !args->value[locale_index + 1].IsString()) { return false; } locale_data.push_back(args->value[locale_index].GetString()); locale_data.push_back(args->value[locale_index + 1].GetString()); locale_data.push_back(args->value[locale_index + 2].GetString()); locale_data.push_back(args->value[locale_index + 3].GetString()); } return runtime_controller_->SetLocales(locale_data); } return false; } void Engine::HandleSettingsPlatformMessage(PlatformMessage* message) { const auto& data = message->data(); std::string jsonData(reinterpret_cast<const char*>(data.GetMapping()), data.GetSize()); if (runtime_controller_->SetUserSettingsData(jsonData)) { ScheduleFrame(); } } void Engine::DispatchPointerDataPacket( std::unique_ptr<PointerDataPacket> packet, uint64_t trace_flow_id) { TRACE_EVENT0_WITH_FLOW_IDS("flutter", "Engine::DispatchPointerDataPacket", /*flow_id_count=*/1, /*flow_ids=*/&trace_flow_id); TRACE_FLOW_STEP("flutter", "PointerEvent", trace_flow_id); pointer_data_dispatcher_->DispatchPacket(std::move(packet), trace_flow_id); } void Engine::DispatchSemanticsAction(int node_id, SemanticsAction action, fml::MallocMapping args) { runtime_controller_->DispatchSemanticsAction(node_id, action, std::move(args)); } void Engine::SetSemanticsEnabled(bool enabled) { runtime_controller_->SetSemanticsEnabled(enabled); } void Engine::SetAccessibilityFeatures(int32_t flags) { runtime_controller_->SetAccessibilityFeatures(flags); } std::string Engine::DefaultRouteName() { if (!initial_route_.empty()) { return initial_route_; } return "/"; } void Engine::ScheduleFrame(bool regenerate_layer_trees) { animator_->RequestFrame(regenerate_layer_trees); } void Engine::OnAllViewsRendered() { animator_->OnAllViewsRendered(); } void Engine::Render(int64_t view_id, std::unique_ptr<flutter::LayerTree> layer_tree, float device_pixel_ratio) { if (!layer_tree) { return; } // Ensure frame dimensions are sane. if (layer_tree->frame_size().isEmpty() || device_pixel_ratio <= 0.0f) { return; } animator_->Render(view_id, std::move(layer_tree), device_pixel_ratio); } void Engine::UpdateSemantics(SemanticsNodeUpdates update, CustomAccessibilityActionUpdates actions) { delegate_.OnEngineUpdateSemantics(std::move(update), std::move(actions)); } void Engine::HandlePlatformMessage(std::unique_ptr<PlatformMessage> message) { if (message->channel() == kAssetChannel) { HandleAssetPlatformMessage(std::move(message)); } else { delegate_.OnEngineHandlePlatformMessage(std::move(message)); } } void Engine::OnRootIsolateCreated() { delegate_.OnRootIsolateCreated(); } void Engine::UpdateIsolateDescription(const std::string isolate_name, int64_t isolate_port) { delegate_.UpdateIsolateDescription(isolate_name, isolate_port); } std::unique_ptr<std::vector<std::string>> Engine::ComputePlatformResolvedLocale( const std::vector<std::string>& supported_locale_data) { return delegate_.ComputePlatformResolvedLocale(supported_locale_data); } double Engine::GetScaledFontSize(double unscaled_font_size, int configuration_id) const { return delegate_.GetScaledFontSize(unscaled_font_size, configuration_id); } void Engine::SetNeedsReportTimings(bool needs_reporting) { delegate_.SetNeedsReportTimings(needs_reporting); } FontCollection& Engine::GetFontCollection() { return *font_collection_; } void Engine::DoDispatchPacket(std::unique_ptr<PointerDataPacket> packet, uint64_t trace_flow_id) { animator_->EnqueueTraceFlowId(trace_flow_id); if (runtime_controller_) { runtime_controller_->DispatchPointerDataPacket(*packet); } } void Engine::ScheduleSecondaryVsyncCallback(uintptr_t id, const fml::closure& callback) { animator_->ScheduleSecondaryVsyncCallback(id, callback); } void Engine::HandleAssetPlatformMessage( std::unique_ptr<PlatformMessage> message) { fml::RefPtr<PlatformMessageResponse> response = message->response(); if (!response) { return; } const auto& data = message->data(); std::string asset_name(reinterpret_cast<const char*>(data.GetMapping()), data.GetSize()); if (asset_manager_) { std::unique_ptr<fml::Mapping> asset_mapping = asset_manager_->GetAsMapping(asset_name); if (asset_mapping) { response->Complete(std::move(asset_mapping)); return; } } response->CompleteEmpty(); } const std::string& Engine::GetLastEntrypoint() const { return last_entry_point_; } const std::string& Engine::GetLastEntrypointLibrary() const { return last_entry_point_library_; } const std::vector<std::string>& Engine::GetLastEntrypointArgs() const { return last_entry_point_args_; } // |RuntimeDelegate| void Engine::RequestDartDeferredLibrary(intptr_t loading_unit_id) { return delegate_.RequestDartDeferredLibrary(loading_unit_id); } std::weak_ptr<PlatformMessageHandler> Engine::GetPlatformMessageHandler() const { return delegate_.GetPlatformMessageHandler(); } void Engine::SendChannelUpdate(std::string name, bool listening) { delegate_.OnEngineChannelUpdate(std::move(name), listening); } void Engine::LoadDartDeferredLibrary( intptr_t loading_unit_id, std::unique_ptr<const fml::Mapping> snapshot_data, std::unique_ptr<const fml::Mapping> snapshot_instructions) { if (runtime_controller_->IsRootIsolateRunning()) { runtime_controller_->LoadDartDeferredLibrary( loading_unit_id, std::move(snapshot_data), std::move(snapshot_instructions)); } else { LoadDartDeferredLibraryError(loading_unit_id, "No running root isolate.", true); } } void Engine::LoadDartDeferredLibraryError(intptr_t loading_unit_id, const std::string& error_message, bool transient) { if (runtime_controller_->IsRootIsolateRunning()) { runtime_controller_->LoadDartDeferredLibraryError(loading_unit_id, error_message, transient); } } const std::weak_ptr<VsyncWaiter> Engine::GetVsyncWaiter() const { return animator_->GetVsyncWaiter(); } void Engine::SetDisplays(const std::vector<DisplayData>& displays) { runtime_controller_->SetDisplays(displays); ScheduleFrame(); } void Engine::ShutdownPlatformIsolates() { runtime_controller_->ShutdownPlatformIsolates(); } } // namespace flutter
engine/shell/common/engine.cc/0
{ "file_path": "engine/shell/common/engine.cc", "repo_id": "engine", "token_count": 8361 }
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_COMMON_POINTER_DATA_DISPATCHER_H_ #define FLUTTER_SHELL_COMMON_POINTER_DATA_DISPATCHER_H_ #include "flutter/runtime/runtime_controller.h" #include "flutter/shell/common/animator.h" namespace flutter { class PointerDataDispatcher; //------------------------------------------------------------------------------ /// The `Engine` pointer data dispatcher that forwards the packet received from /// `PlatformView::DispatchPointerDataPacket` on the platform thread, to /// `Window::DispatchPointerDataPacket` on the UI thread. /// /// This class is used to filter the packets so the Flutter framework on the UI /// thread will receive packets with some desired properties. See /// `SmoothPointerDataDispatcher` for an example which filters irregularly /// delivered packets, and dispatches them in sync with the VSYNC signal. /// /// This object will be owned by the engine because it relies on the engine's /// `Animator` (which owns `VsyncWaiter`) and `RuntimeController` to do the /// filtering. This object is currently designed to be only called from the UI /// thread (no thread safety is guaranteed). /// /// The `PlatformView` decides which subclass of `PointerDataDispatcher` is /// constructed by sending a `PointerDataDispatcherMaker` to the engine's /// constructor in `Shell::CreateShellOnPlatformThread`. This is needed because: /// (1) Different platforms (e.g., Android, iOS) have different dispatchers /// so the decision has to be made per `PlatformView`. /// (2) The `PlatformView` can only be accessed from the PlatformThread while /// this class (as owned by engine) can only be accessed in the UI thread. /// Hence `PlatformView` creates a `PointerDataDispatchMaker` on the /// platform thread, and sends it to the UI thread for the final /// construction of the `PointerDataDispatcher`. class PointerDataDispatcher { public: /// The interface for Engine to implement. class Delegate { public: /// Actually dispatch the packet using Engine's `animator_` and /// `runtime_controller_`. virtual void DoDispatchPacket(std::unique_ptr<PointerDataPacket> packet, uint64_t trace_flow_id) = 0; //-------------------------------------------------------------------------- /// @brief Schedule a secondary callback to be executed right after the /// main `VsyncWaiter::AsyncWaitForVsync` callback (which is added /// by `Animator::RequestFrame`). /// /// Like the callback in `AsyncWaitForVsync`, this callback is /// only scheduled to be called once per |id|, and it will be /// called in the UI thread. If there is no AsyncWaitForVsync /// callback (`Animator::RequestFrame` is not called), this /// secondary callback will still be executed at vsync. /// /// This callback is used to provide the vsync signal needed by /// `SmoothPointerDataDispatcher`, and for `Animator` input flow /// events. virtual void ScheduleSecondaryVsyncCallback( uintptr_t id, const fml::closure& callback) = 0; }; //---------------------------------------------------------------------------- /// @brief Signal that `PlatformView` has a packet to be dispatched. /// /// @param[in] packet The `PointerDataPacket` to be dispatched. /// @param[in] trace_flow_id The id for `Animator::EnqueueTraceFlowId`. virtual void DispatchPacket(std::unique_ptr<PointerDataPacket> packet, uint64_t trace_flow_id) = 0; //---------------------------------------------------------------------------- /// @brief Default destructor. virtual ~PointerDataDispatcher(); }; //------------------------------------------------------------------------------ /// The default dispatcher that forwards the packet without any modification. /// class DefaultPointerDataDispatcher : public PointerDataDispatcher { public: explicit DefaultPointerDataDispatcher(Delegate& delegate) : delegate_(delegate) {} // |PointerDataDispatcer| void DispatchPacket(std::unique_ptr<PointerDataPacket> packet, uint64_t trace_flow_id) override; virtual ~DefaultPointerDataDispatcher(); protected: Delegate& delegate_; FML_DISALLOW_COPY_AND_ASSIGN(DefaultPointerDataDispatcher); }; //------------------------------------------------------------------------------ /// A dispatcher that may temporarily store and defer the last received /// PointerDataPacket if multiple packets are received in one VSYNC. The /// deferred packet will be sent in the next vsync in order to smooth out the /// events. This filters out irregular input events delivery to provide a smooth /// scroll on iPhone X/Xs. /// /// It works as follows: /// /// When `DispatchPacket` is called while a previous pointer data dispatch is /// still in progress (its frame isn't finished yet), it means that an input /// event is delivered to us too fast. That potentially means a later event will /// be too late which could cause the missing of a frame. Hence we'll cache it /// in `pending_packet_` for the next frame to smooth it out. /// /// If the input event is sent to us regularly at the same rate of VSYNC (say /// at 60Hz), this would be identical to `DefaultPointerDataDispatcher` where /// `runtime_controller_->DispatchPointerDataPacket` is always called right /// away. That's because `is_pointer_data_in_progress_` will always be false /// when `DispatchPacket` is called since it will be cleared by the end of a /// frame through `ScheduleSecondaryVsyncCallback`. This is the case for all /// Android/iOS devices before iPhone X/XS. /// /// If the input event is irregular, but with a random latency of no more than /// one frame, this would guarantee that we'll miss at most 1 frame. Without /// this, we could miss half of the frames. /// /// If the input event is delivered at a higher rate than that of VSYNC, this /// would at most add a latency of one event delivery. For example, if the /// input event is delivered at 120Hz (this is only true for iPad pro, not even /// iPhone X), this may delay the handling of an input event by 8ms. /// /// The assumption of this solution is that the sampling itself is still /// regular. Only the event delivery is allowed to be irregular. So far this /// assumption seems to hold on all devices. If it's changed in the future, /// we'll need a different solution. /// /// See also input_events_unittests.cc where we test all our claims above. class SmoothPointerDataDispatcher : public DefaultPointerDataDispatcher { public: explicit SmoothPointerDataDispatcher(Delegate& delegate); // |PointerDataDispatcer| void DispatchPacket(std::unique_ptr<PointerDataPacket> packet, uint64_t trace_flow_id) override; virtual ~SmoothPointerDataDispatcher(); private: void DispatchPendingPacket(); void ScheduleSecondaryVsyncCallback(); // If non-null, this will be a pending pointer data packet for the next frame // to consume. This is used to smooth out the irregular drag events delivery. // See also `DispatchPointerDataPacket` and input_events_unittests.cc. std::unique_ptr<PointerDataPacket> pending_packet_; int pending_trace_flow_id_ = -1; bool is_pointer_data_in_progress_ = false; // WeakPtrFactory must be the last member. fml::WeakPtrFactory<SmoothPointerDataDispatcher> weak_factory_; FML_DISALLOW_COPY_AND_ASSIGN(SmoothPointerDataDispatcher); }; //-------------------------------------------------------------------------- /// @brief Signature for constructing PointerDataDispatcher. /// /// @param[in] delegate the `Flutter::Engine` /// using PointerDataDispatcherMaker = std::function<std::unique_ptr<PointerDataDispatcher>( PointerDataDispatcher::Delegate&)>; } // namespace flutter #endif // FLUTTER_SHELL_COMMON_POINTER_DATA_DISPATCHER_H_
engine/shell/common/pointer_data_dispatcher.h/0
{ "file_path": "engine/shell/common/pointer_data_dispatcher.h", "repo_id": "engine", "token_count": 2416 }
325
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_COMMON_SHELL_IO_MANAGER_H_ #define FLUTTER_SHELL_COMMON_SHELL_IO_MANAGER_H_ #include <memory> #include "flutter/flow/skia_gpu_object.h" #include "flutter/fml/macros.h" #include "flutter/fml/memory/weak_ptr.h" #include "flutter/lib/ui/io_manager.h" #include "third_party/skia/include/gpu/GrDirectContext.h" #include "third_party/skia/include/gpu/GrTypes.h" struct GrGLInterface; namespace flutter { class ShellIOManager final : public IOManager { public: // Convenience methods for platforms to create a GrDirectContext used to // supply to the IOManager. The platforms may create the context themselves if // they so desire. static sk_sp<GrDirectContext> CreateCompatibleResourceLoadingContext( GrBackendApi backend, const sk_sp<const GrGLInterface>& gl_interface); ShellIOManager( sk_sp<GrDirectContext> resource_context, std::shared_ptr<const fml::SyncSwitch> is_gpu_disabled_sync_switch, fml::RefPtr<fml::TaskRunner> unref_queue_task_runner, std::shared_ptr<impeller::Context> impeller_context, fml::TimeDelta unref_queue_drain_delay = fml::TimeDelta::FromMilliseconds(8)); ~ShellIOManager() override; // This method should be called when a resource_context first becomes // available. It is safe to call multiple times, and will only update // the held resource context if it has not already been set. void NotifyResourceContextAvailable(sk_sp<GrDirectContext> resource_context); // This method should be called if you want to force the IOManager to // update its resource context reference. It should not be called // if there are any Dart objects that have a reference to the old // resource context, but may be called if the Dart VM is restarted. void UpdateResourceContext(sk_sp<GrDirectContext> resource_context); fml::WeakPtr<ShellIOManager> GetWeakPtr(); // |IOManager| fml::WeakPtr<IOManager> GetWeakIOManager() const override; // |IOManager| fml::WeakPtr<GrDirectContext> GetResourceContext() const override; // |IOManager| fml::RefPtr<flutter::SkiaUnrefQueue> GetSkiaUnrefQueue() const override; // |IOManager| std::shared_ptr<const fml::SyncSwitch> GetIsGpuDisabledSyncSwitch() override; // |IOManager| std::shared_ptr<impeller::Context> GetImpellerContext() const override; private: // Resource context management. sk_sp<GrDirectContext> resource_context_; std::unique_ptr<fml::WeakPtrFactory<GrDirectContext>> resource_context_weak_factory_; // Unref queue management. fml::RefPtr<flutter::SkiaUnrefQueue> unref_queue_; std::shared_ptr<const fml::SyncSwitch> is_gpu_disabled_sync_switch_; std::shared_ptr<impeller::Context> impeller_context_; fml::WeakPtrFactory<ShellIOManager> weak_factory_; FML_DISALLOW_COPY_AND_ASSIGN(ShellIOManager); }; } // namespace flutter #endif // FLUTTER_SHELL_COMMON_SHELL_IO_MANAGER_H_
engine/shell/common/shell_io_manager.h/0
{ "file_path": "engine/shell/common/shell_io_manager.h", "repo_id": "engine", "token_count": 1046 }
326
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_COMMON_SKIA_EVENT_TRACER_IMPL_H_ #define FLUTTER_SHELL_COMMON_SKIA_EVENT_TRACER_IMPL_H_ #include <mutex> #include <optional> #include <string> #include <vector> namespace flutter { void InitSkiaEventTracer( bool enabled, const std::optional<std::vector<std::string>>& allowlist); } // namespace flutter #endif // FLUTTER_SHELL_COMMON_SKIA_EVENT_TRACER_IMPL_H_
engine/shell/common/skia_event_tracer_impl.h/0
{ "file_path": "engine/shell/common/skia_event_tracer_impl.h", "repo_id": "engine", "token_count": 210 }
327
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_COMMON_VARIABLE_REFRESH_RATE_REPORTER_H_ #define FLUTTER_SHELL_COMMON_VARIABLE_REFRESH_RATE_REPORTER_H_ #include <functional> #include <memory> #include <mutex> #include <unordered_map> namespace flutter { /// Abstract class that reprents a platform specific mechanism to report current /// refresh rates. class VariableRefreshRateReporter { public: VariableRefreshRateReporter() = default; virtual double GetRefreshRate() const = 0; FML_DISALLOW_COPY_AND_ASSIGN(VariableRefreshRateReporter); }; } // namespace flutter #endif // FLUTTER_SHELL_COMMON_VARIABLE_REFRESH_RATE_REPORTER_H_
engine/shell/common/variable_refresh_rate_reporter.h/0
{ "file_path": "engine/shell/common/variable_refresh_rate_reporter.h", "repo_id": "engine", "token_count": 268 }
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_GPU_GPU_SURFACE_GL_SKIA_H_ #define FLUTTER_SHELL_GPU_GPU_SURFACE_GL_SKIA_H_ #include <functional> #include <memory> #include "flutter/common/graphics/gl_context_switch.h" #include "flutter/flow/embedded_views.h" #include "flutter/flow/surface.h" #include "flutter/fml/macros.h" #include "flutter/fml/memory/weak_ptr.h" #include "flutter/shell/gpu/gpu_surface_gl_delegate.h" #include "third_party/skia/include/core/SkSurface.h" #include "third_party/skia/include/gpu/GrDirectContext.h" namespace flutter { class GPUSurfaceGLSkia : public Surface { public: static sk_sp<GrDirectContext> MakeGLContext(GPUSurfaceGLDelegate* delegate); GPUSurfaceGLSkia(GPUSurfaceGLDelegate* delegate, bool render_to_surface); // Creates a new GL surface reusing an existing GrDirectContext. GPUSurfaceGLSkia(const sk_sp<GrDirectContext>& gr_context, GPUSurfaceGLDelegate* delegate, bool render_to_surface); // |Surface| ~GPUSurfaceGLSkia() override; // |Surface| bool IsValid() override; // |Surface| std::unique_ptr<SurfaceFrame> AcquireFrame(const SkISize& size) override; // |Surface| SkMatrix GetRootTransformation() const override; // |Surface| GrDirectContext* GetContext() override; // |Surface| std::unique_ptr<GLContextResult> MakeRenderContextCurrent() override; // |Surface| bool ClearRenderContext() override; // |Surface| bool AllowsDrawingWhenGpuDisabled() const override; private: bool CreateOrUpdateSurfaces(const SkISize& size); sk_sp<SkSurface> AcquireRenderSurface( const SkISize& untransformed_size, const SkMatrix& root_surface_transformation); bool PresentSurface(const SurfaceFrame& frame, DlCanvas* canvas); GPUSurfaceGLDelegate* delegate_; sk_sp<GrDirectContext> context_; sk_sp<SkSurface> onscreen_surface_; /// FBO backing the current `onscreen_surface_`. uint32_t fbo_id_ = 0; // The current FBO's existing damage, as tracked by the GPU surface, delegates // still have an option of overriding this damage with their own in // `GLContextFrameBufferInfo`. std::optional<SkIRect> existing_damage_ = std::nullopt; bool context_owner_ = false; // TODO(38466): Refactor GPU surface APIs take into account the fact that an // external view embedder may want to render to the root surface. This is a // hack to make avoid allocating resources for the root surface when an // external view embedder is present. const bool render_to_surface_ = true; bool valid_ = false; // WeakPtrFactory must be the last member. fml::TaskRunnerAffineWeakPtrFactory<GPUSurfaceGLSkia> weak_factory_; FML_DISALLOW_COPY_AND_ASSIGN(GPUSurfaceGLSkia); }; } // namespace flutter #endif // FLUTTER_SHELL_GPU_GPU_SURFACE_GL_SKIA_H_
engine/shell/gpu/gpu_surface_gl_skia.h/0
{ "file_path": "engine/shell/gpu/gpu_surface_gl_skia.h", "repo_id": "engine", "token_count": 1022 }
329
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/gpu/gpu_surface_vulkan_impeller.h" #include "flutter/fml/make_copyable.h" #include "impeller/display_list/dl_dispatcher.h" #include "impeller/renderer/backend/vulkan/surface_context_vk.h" #include "impeller/renderer/renderer.h" #include "impeller/renderer/surface.h" #include "impeller/typographer/backends/skia/typographer_context_skia.h" namespace flutter { GPUSurfaceVulkanImpeller::GPUSurfaceVulkanImpeller( std::shared_ptr<impeller::Context> context) { if (!context || !context->IsValid()) { return; } auto renderer = std::make_shared<impeller::Renderer>(context); if (!renderer->IsValid()) { return; } auto aiks_context = std::make_shared<impeller::AiksContext>( context, impeller::TypographerContextSkia::Make()); if (!aiks_context->IsValid()) { return; } impeller_context_ = std::move(context); impeller_renderer_ = std::move(renderer); aiks_context_ = std::move(aiks_context); is_valid_ = true; } // |Surface| GPUSurfaceVulkanImpeller::~GPUSurfaceVulkanImpeller() = default; // |Surface| bool GPUSurfaceVulkanImpeller::IsValid() { return is_valid_; } // |Surface| std::unique_ptr<SurfaceFrame> GPUSurfaceVulkanImpeller::AcquireFrame( const SkISize& size) { if (!IsValid()) { FML_LOG(ERROR) << "Vulkan surface was invalid."; return nullptr; } if (size.isEmpty()) { FML_LOG(ERROR) << "Vulkan surface was asked for an empty frame."; return nullptr; } auto& context_vk = impeller::SurfaceContextVK::Cast(*impeller_context_); std::unique_ptr<impeller::Surface> surface = context_vk.AcquireNextSurface(); if (!surface) { FML_LOG(ERROR) << "No surface available."; return nullptr; } SurfaceFrame::SubmitCallback submit_callback = fml::MakeCopyable([renderer = impeller_renderer_, // aiks_context = aiks_context_, // surface = std::move(surface) // ](SurfaceFrame& surface_frame, DlCanvas* canvas) mutable -> bool { if (!aiks_context) { return false; } auto display_list = surface_frame.BuildDisplayList(); if (!display_list) { FML_LOG(ERROR) << "Could not build display list for surface frame."; return false; } auto cull_rect = surface->GetTargetRenderPassDescriptor().GetRenderTargetSize(); impeller::Rect dl_cull_rect = impeller::Rect::MakeSize(cull_rect); impeller::DlDispatcher impeller_dispatcher(dl_cull_rect); display_list->Dispatch( impeller_dispatcher, SkIRect::MakeWH(cull_rect.width, cull_rect.height)); auto picture = impeller_dispatcher.EndRecordingAsPicture(); return renderer->Render( std::move(surface), fml::MakeCopyable( [aiks_context, picture = std::move(picture)]( impeller::RenderTarget& render_target) -> bool { return aiks_context->Render(picture, render_target, /*reset_host_buffer=*/true); })); }); return std::make_unique<SurfaceFrame>( nullptr, // surface SurfaceFrame::FramebufferInfo{}, // framebuffer info submit_callback, // submit callback size, // frame size nullptr, // context result true // display list fallback ); } // |Surface| SkMatrix GPUSurfaceVulkanImpeller::GetRootTransformation() const { // This backend does not currently support root surface transformations. Just // return identity. return {}; } // |Surface| GrDirectContext* GPUSurfaceVulkanImpeller::GetContext() { // Impeller != Skia. return nullptr; } // |Surface| std::unique_ptr<GLContextResult> GPUSurfaceVulkanImpeller::MakeRenderContextCurrent() { // This backend has no such concept. return std::make_unique<GLContextDefaultResult>(true); } // |Surface| bool GPUSurfaceVulkanImpeller::EnableRasterCache() const { return false; } // |Surface| std::shared_ptr<impeller::AiksContext> GPUSurfaceVulkanImpeller::GetAiksContext() const { return aiks_context_; } } // namespace flutter
engine/shell/gpu/gpu_surface_vulkan_impeller.cc/0
{ "file_path": "engine/shell/gpu/gpu_surface_vulkan_impeller.cc", "repo_id": "engine", "token_count": 1862 }
330
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_DISPLAY_H_ #define FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_DISPLAY_H_ #include <cstdint> #include "flutter/fml/macros.h" #include "flutter/shell/common/display.h" #include "flutter/shell/platform/android/jni/platform_view_android_jni.h" namespace flutter { /// A |Display| that listens to refresh rate changes. class AndroidDisplay : public Display { public: explicit AndroidDisplay(std::shared_ptr<PlatformViewAndroidJNI> jni_facade); ~AndroidDisplay() = default; // |Display| double GetRefreshRate() const override; // |Display| virtual double GetWidth() const override; // |Display| virtual double GetHeight() const override; // |Display| virtual double GetDevicePixelRatio() const override; private: std::shared_ptr<PlatformViewAndroidJNI> jni_facade_; FML_DISALLOW_COPY_AND_ASSIGN(AndroidDisplay); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_DISPLAY_H_
engine/shell/platform/android/android_display.h/0
{ "file_path": "engine/shell/platform/android/android_display.h", "repo_id": "engine", "token_count": 381 }
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_ANDROID_ANDROID_SURFACE_SOFTWARE_H_ #define FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_SURFACE_SOFTWARE_H_ #include "flutter/fml/macros.h" #include "flutter/fml/platform/android/jni_weak_ref.h" #include "flutter/fml/platform/android/scoped_java_ref.h" #include "flutter/shell/gpu/gpu_surface_software.h" #include "flutter/shell/platform/android/jni/platform_view_android_jni.h" #include "flutter/shell/platform/android/surface/android_surface.h" #include "third_party/skia/include/core/SkSurface.h" namespace flutter { class AndroidSurfaceSoftware final : public AndroidSurface, public GPUSurfaceSoftwareDelegate { public: AndroidSurfaceSoftware(); ~AndroidSurfaceSoftware() override; // |AndroidSurface| bool IsValid() const override; // |AndroidSurface| bool ResourceContextMakeCurrent() override; // |AndroidSurface| bool ResourceContextClearCurrent() override; // |AndroidSurface| std::unique_ptr<Surface> CreateGPUSurface( GrDirectContext* gr_context) override; // |AndroidSurface| void TeardownOnScreenContext() override; // |AndroidSurface| bool OnScreenSurfaceResize(const SkISize& size) override; // |AndroidSurface| bool SetNativeWindow(fml::RefPtr<AndroidNativeWindow> window) override; // |GPUSurfaceSoftwareDelegate| sk_sp<SkSurface> AcquireBackingStore(const SkISize& size) override; // |GPUSurfaceSoftwareDelegate| bool PresentBackingStore(sk_sp<SkSurface> backing_store) override; private: sk_sp<SkSurface> sk_surface_; fml::RefPtr<AndroidNativeWindow> native_window_; SkColorType target_color_type_; SkAlphaType target_alpha_type_; FML_DISALLOW_COPY_AND_ASSIGN(AndroidSurfaceSoftware); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_SURFACE_SOFTWARE_H_
engine/shell/platform/android/android_surface_software.h/0
{ "file_path": "engine/shell/platform/android/android_surface_software.h", "repo_id": "engine", "token_count": 706 }
332
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <memory> #include "flutter/shell/platform/android/external_view_embedder/surface_pool.h" #include "flutter/fml/make_copyable.h" #include "flutter/shell/platform/android/jni/jni_mock.h" #include "flutter/shell/platform/android/surface/android_surface_mock.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "third_party/skia/include/gpu/GrDirectContext.h" namespace flutter { namespace testing { using ::testing::ByMove; using ::testing::Return; class TestAndroidSurfaceFactory : public AndroidSurfaceFactory { public: using TestSurfaceProducer = std::function<std::unique_ptr<AndroidSurface>(void)>; explicit TestAndroidSurfaceFactory(TestSurfaceProducer&& surface_producer) { surface_producer_ = surface_producer; } ~TestAndroidSurfaceFactory() override = default; std::unique_ptr<AndroidSurface> CreateSurface() override { return surface_producer_(); } private: TestSurfaceProducer surface_producer_; }; TEST(SurfacePool, GetLayerAllocateOneLayer) { auto pool = std::make_unique<SurfacePool>(); auto gr_context = GrDirectContext::MakeMock(nullptr); auto android_context = std::make_shared<AndroidContext>(AndroidRenderingAPI::kSoftware); auto jni_mock = std::make_shared<JNIMock>(); auto window = fml::MakeRefCounted<AndroidNativeWindow>(nullptr); EXPECT_CALL(*jni_mock, FlutterViewCreateOverlaySurface()) .WillOnce(Return( ByMove(std::make_unique<PlatformViewAndroidJNI::OverlayMetadata>( 0, window)))); auto surface_factory = std::make_shared<TestAndroidSurfaceFactory>([gr_context, window]() { auto android_surface_mock = std::make_unique<AndroidSurfaceMock>(); EXPECT_CALL(*android_surface_mock, CreateGPUSurface(gr_context.get())); EXPECT_CALL(*android_surface_mock, SetNativeWindow(window)); EXPECT_CALL(*android_surface_mock, IsValid()).WillOnce(Return(true)); return android_surface_mock; }); auto layer = pool->GetLayer(gr_context.get(), *android_context, jni_mock, surface_factory); ASSERT_TRUE(pool->HasLayers()); ASSERT_NE(nullptr, layer); ASSERT_EQ(reinterpret_cast<intptr_t>(gr_context.get()), layer->gr_context_key); } TEST(SurfacePool, GetUnusedLayers) { auto pool = std::make_unique<SurfacePool>(); auto gr_context = GrDirectContext::MakeMock(nullptr); auto android_context = std::make_shared<AndroidContext>(AndroidRenderingAPI::kSoftware); auto jni_mock = std::make_shared<JNIMock>(); auto window = fml::MakeRefCounted<AndroidNativeWindow>(nullptr); EXPECT_CALL(*jni_mock, FlutterViewCreateOverlaySurface()) .WillOnce(Return( ByMove(std::make_unique<PlatformViewAndroidJNI::OverlayMetadata>( 0, window)))); auto surface_factory = std::make_shared<TestAndroidSurfaceFactory>([gr_context, window]() { auto android_surface_mock = std::make_unique<AndroidSurfaceMock>(); EXPECT_CALL(*android_surface_mock, CreateGPUSurface(gr_context.get())); EXPECT_CALL(*android_surface_mock, SetNativeWindow(window)); EXPECT_CALL(*android_surface_mock, IsValid()).WillOnce(Return(true)); return android_surface_mock; }); auto layer = pool->GetLayer(gr_context.get(), *android_context, jni_mock, surface_factory); ASSERT_EQ(0UL, pool->GetUnusedLayers().size()); pool->RecycleLayers(); ASSERT_TRUE(pool->HasLayers()); ASSERT_EQ(1UL, pool->GetUnusedLayers().size()); ASSERT_EQ(layer, pool->GetUnusedLayers()[0]); } TEST(SurfacePool, GetLayerRecycle) { auto pool = std::make_unique<SurfacePool>(); auto gr_context_1 = GrDirectContext::MakeMock(nullptr); auto jni_mock = std::make_shared<JNIMock>(); auto window = fml::MakeRefCounted<AndroidNativeWindow>(nullptr); EXPECT_CALL(*jni_mock, FlutterViewCreateOverlaySurface()) .WillOnce(Return( ByMove(std::make_unique<PlatformViewAndroidJNI::OverlayMetadata>( 0, window)))); auto android_context = std::make_shared<AndroidContext>(AndroidRenderingAPI::kSoftware); auto gr_context_2 = GrDirectContext::MakeMock(nullptr); auto surface_factory = std::make_shared<TestAndroidSurfaceFactory>( [gr_context_1, gr_context_2, window]() { auto android_surface_mock = std::make_unique<AndroidSurfaceMock>(); // Allocate two GPU surfaces for each gr context. EXPECT_CALL(*android_surface_mock, CreateGPUSurface(gr_context_1.get())); EXPECT_CALL(*android_surface_mock, CreateGPUSurface(gr_context_2.get())); // Set the native window once. EXPECT_CALL(*android_surface_mock, SetNativeWindow(window)); EXPECT_CALL(*android_surface_mock, IsValid()).WillOnce(Return(true)); return android_surface_mock; }); auto layer_1 = pool->GetLayer(gr_context_1.get(), *android_context, jni_mock, surface_factory); pool->RecycleLayers(); auto layer_2 = pool->GetLayer(gr_context_2.get(), *android_context, jni_mock, surface_factory); ASSERT_TRUE(pool->HasLayers()); ASSERT_NE(nullptr, layer_1); ASSERT_EQ(layer_1, layer_2); ASSERT_EQ(reinterpret_cast<intptr_t>(gr_context_2.get()), layer_1->gr_context_key); ASSERT_EQ(reinterpret_cast<intptr_t>(gr_context_2.get()), layer_2->gr_context_key); } TEST(SurfacePool, GetLayerAllocateTwoLayers) { auto pool = std::make_unique<SurfacePool>(); auto gr_context = GrDirectContext::MakeMock(nullptr); auto android_context = std::make_shared<AndroidContext>(AndroidRenderingAPI::kSoftware); auto jni_mock = std::make_shared<JNIMock>(); auto window = fml::MakeRefCounted<AndroidNativeWindow>(nullptr); EXPECT_CALL(*jni_mock, FlutterViewCreateOverlaySurface()) .Times(2) .WillOnce(Return( ByMove(std::make_unique<PlatformViewAndroidJNI::OverlayMetadata>( 0, window)))) .WillOnce(Return( ByMove(std::make_unique<PlatformViewAndroidJNI::OverlayMetadata>( 1, window)))); auto surface_factory = std::make_shared<TestAndroidSurfaceFactory>([gr_context, window]() { auto android_surface_mock = std::make_unique<AndroidSurfaceMock>(); EXPECT_CALL(*android_surface_mock, CreateGPUSurface(gr_context.get())); EXPECT_CALL(*android_surface_mock, SetNativeWindow(window)); EXPECT_CALL(*android_surface_mock, IsValid()).WillOnce(Return(true)); return android_surface_mock; }); auto layer_1 = pool->GetLayer(gr_context.get(), *android_context, jni_mock, surface_factory); auto layer_2 = pool->GetLayer(gr_context.get(), *android_context, jni_mock, surface_factory); ASSERT_TRUE(pool->HasLayers()); ASSERT_NE(nullptr, layer_1); ASSERT_NE(nullptr, layer_2); ASSERT_NE(layer_1, layer_2); ASSERT_EQ(0, layer_1->id); ASSERT_EQ(1, layer_2->id); } TEST(SurfacePool, DestroyLayers) { auto pool = std::make_unique<SurfacePool>(); auto jni_mock = std::make_shared<JNIMock>(); EXPECT_CALL(*jni_mock, FlutterViewDestroyOverlaySurfaces()).Times(0); pool->DestroyLayers(jni_mock); auto gr_context = GrDirectContext::MakeMock(nullptr); auto android_context = std::make_shared<AndroidContext>(AndroidRenderingAPI::kSoftware); auto window = fml::MakeRefCounted<AndroidNativeWindow>(nullptr); EXPECT_CALL(*jni_mock, FlutterViewCreateOverlaySurface()) .Times(1) .WillOnce(Return( ByMove(std::make_unique<PlatformViewAndroidJNI::OverlayMetadata>( 0, window)))); auto surface_factory = std::make_shared<TestAndroidSurfaceFactory>([gr_context, window]() { auto android_surface_mock = std::make_unique<AndroidSurfaceMock>(); EXPECT_CALL(*android_surface_mock, CreateGPUSurface(gr_context.get())); EXPECT_CALL(*android_surface_mock, SetNativeWindow(window)); EXPECT_CALL(*android_surface_mock, IsValid()).WillOnce(Return(true)); return android_surface_mock; }); pool->GetLayer(gr_context.get(), *android_context, jni_mock, surface_factory); EXPECT_CALL(*jni_mock, FlutterViewDestroyOverlaySurfaces()); ASSERT_TRUE(pool->HasLayers()); pool->DestroyLayers(jni_mock); ASSERT_FALSE(pool->HasLayers()); ASSERT_TRUE(pool->GetUnusedLayers().empty()); } TEST(SurfacePool, DestroyLayersFrameSizeChanged) { auto pool = std::make_unique<SurfacePool>(); auto jni_mock = std::make_shared<JNIMock>(); auto gr_context = GrDirectContext::MakeMock(nullptr); auto android_context = std::make_shared<AndroidContext>(AndroidRenderingAPI::kSoftware); auto window = fml::MakeRefCounted<AndroidNativeWindow>(nullptr); auto surface_factory = std::make_shared<TestAndroidSurfaceFactory>([gr_context, window]() { auto android_surface_mock = std::make_unique<AndroidSurfaceMock>(); EXPECT_CALL(*android_surface_mock, CreateGPUSurface(gr_context.get())); EXPECT_CALL(*android_surface_mock, SetNativeWindow(window)); EXPECT_CALL(*android_surface_mock, IsValid()).WillOnce(Return(true)); return android_surface_mock; }); pool->SetFrameSize(SkISize::Make(10, 10)); EXPECT_CALL(*jni_mock, FlutterViewDestroyOverlaySurfaces()).Times(0); EXPECT_CALL(*jni_mock, FlutterViewCreateOverlaySurface()) .Times(1) .WillOnce(Return( ByMove(std::make_unique<PlatformViewAndroidJNI::OverlayMetadata>( 0, window)))); ASSERT_FALSE(pool->HasLayers()); pool->GetLayer(gr_context.get(), *android_context, jni_mock, surface_factory); ASSERT_TRUE(pool->HasLayers()); pool->SetFrameSize(SkISize::Make(20, 20)); EXPECT_CALL(*jni_mock, FlutterViewDestroyOverlaySurfaces()).Times(1); EXPECT_CALL(*jni_mock, FlutterViewCreateOverlaySurface()) .Times(1) .WillOnce(Return( ByMove(std::make_unique<PlatformViewAndroidJNI::OverlayMetadata>( 1, window)))); pool->GetLayer(gr_context.get(), *android_context, jni_mock, surface_factory); ASSERT_TRUE(pool->GetUnusedLayers().empty()); ASSERT_TRUE(pool->HasLayers()); } } // namespace testing } // namespace flutter
engine/shell/platform/android/external_view_embedder/surface_pool_unittests.cc/0
{ "file_path": "engine/shell/platform/android/external_view_embedder/surface_pool_unittests.cc", "repo_id": "engine", "token_count": 4191 }
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. package io.flutter; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import io.flutter.embedding.engine.FlutterJNI; import io.flutter.embedding.engine.deferredcomponents.DeferredComponentManager; import io.flutter.embedding.engine.loader.FlutterLoader; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; /** * This class is a simple dependency injector for the relatively thin Android part of the Flutter * engine. * * <p>This simple solution is used facilitate testability without bringing in heavier * app-development centric dependency injection frameworks such as Guice or Dagger2 or spreading * construction injection everywhere. */ public final class FlutterInjector { private static FlutterInjector instance; private static boolean accessed; /** * Use {@link FlutterInjector.Builder} to specify members to be injected via the static {@code * FlutterInjector}. * * <p>This can only be called at the beginning of the program before the {@link #instance()} is * accessed. */ public static void setInstance(@NonNull FlutterInjector injector) { if (accessed) { throw new IllegalStateException( "Cannot change the FlutterInjector instance once it's been " + "read. If you're trying to dependency inject, be sure to do so at the beginning of " + "the program"); } instance = injector; } /** * Retrieve the static instance of the {@code FlutterInjector} to use in your program. * * <p>Once you access it, you can no longer change the values injected. * * <p>If no override is provided for the injector, reasonable defaults are provided. */ public static FlutterInjector instance() { accessed = true; if (instance == null) { instance = new Builder().build(); } return instance; } // This whole class is here to enable testing so to test the thing that lets you test, some degree // of hack is needed. @VisibleForTesting public static void reset() { accessed = false; instance = null; } private FlutterInjector( @NonNull FlutterLoader flutterLoader, @Nullable DeferredComponentManager deferredComponentManager, @NonNull FlutterJNI.Factory flutterJniFactory, @NonNull ExecutorService executorService) { this.flutterLoader = flutterLoader; this.deferredComponentManager = deferredComponentManager; this.flutterJniFactory = flutterJniFactory; this.executorService = executorService; } private FlutterLoader flutterLoader; private DeferredComponentManager deferredComponentManager; private FlutterJNI.Factory flutterJniFactory; private ExecutorService executorService; /** * Returns the {@link io.flutter.embedding.engine.loader.FlutterLoader} instance to use for the * Flutter Android engine embedding. */ @NonNull public FlutterLoader flutterLoader() { return flutterLoader; } /** * Returns the {@link DeferredComponentManager} instance to use for the Flutter Android engine * embedding. */ @Nullable public DeferredComponentManager deferredComponentManager() { return deferredComponentManager; } public ExecutorService executorService() { return executorService; } @NonNull public FlutterJNI.Factory getFlutterJNIFactory() { return flutterJniFactory; } /** * Builder used to supply a custom FlutterInjector instance to {@link * FlutterInjector#setInstance(FlutterInjector)}. * * <p>Non-overridden values have reasonable defaults. */ public static final class Builder { private class NamedThreadFactory implements ThreadFactory { private int threadId = 0; public Thread newThread(Runnable command) { Thread thread = new Thread(command); thread.setName("flutter-worker-" + threadId++); return thread; } } private FlutterLoader flutterLoader; private DeferredComponentManager deferredComponentManager; private FlutterJNI.Factory flutterJniFactory; private ExecutorService executorService; /** * Sets a {@link io.flutter.embedding.engine.loader.FlutterLoader} override. * * <p>A reasonable default will be used if unspecified. */ public Builder setFlutterLoader(@NonNull FlutterLoader flutterLoader) { this.flutterLoader = flutterLoader; return this; } public Builder setDeferredComponentManager( @Nullable DeferredComponentManager deferredComponentManager) { this.deferredComponentManager = deferredComponentManager; return this; } public Builder setFlutterJNIFactory(@NonNull FlutterJNI.Factory factory) { this.flutterJniFactory = factory; return this; } public Builder setExecutorService(@NonNull ExecutorService executorService) { this.executorService = executorService; return this; } private void fillDefaults() { if (flutterJniFactory == null) { flutterJniFactory = new FlutterJNI.Factory(); } if (executorService == null) { executorService = Executors.newCachedThreadPool(new NamedThreadFactory()); } if (flutterLoader == null) { flutterLoader = new FlutterLoader(flutterJniFactory.provideFlutterJNI(), executorService); } // DeferredComponentManager's intended default is null. } /** * Builds a {@link FlutterInjector} from the builder. Unspecified properties will have * reasonable defaults. */ public FlutterInjector build() { fillDefaults(); return new FlutterInjector( flutterLoader, deferredComponentManager, flutterJniFactory, executorService); } } }
engine/shell/platform/android/io/flutter/FlutterInjector.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/FlutterInjector.java", "repo_id": "engine", "token_count": 1931 }
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. package io.flutter.embedding.android; import android.app.Activity; import android.content.ComponentCallbacks2; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver.OnWindowFocusChangeListener; import androidx.activity.OnBackPressedCallback; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentActivity; import androidx.lifecycle.Lifecycle; import io.flutter.Log; import io.flutter.embedding.engine.FlutterEngine; import io.flutter.embedding.engine.FlutterShellArgs; import io.flutter.embedding.engine.renderer.FlutterUiDisplayListener; import io.flutter.plugin.platform.PlatformPlugin; import java.util.ArrayList; import java.util.List; /** * {@code Fragment} which displays a Flutter UI that takes up all available {@code Fragment} space. * * <p>Using a {@code FlutterFragment} requires forwarding a number of calls from an {@code Activity} * to ensure that the internal Flutter app behaves as expected: * * <ol> * <li>{@link #onPostResume()} * <li>{@link #onBackPressed()} * <li>{@link #onRequestPermissionsResult(int, String[], int[])} * <li>{@link #onNewIntent(Intent)} * <li>{@link #onUserLeaveHint()} * </ol> * * {@link #onBackPressed()} does not need to be called through if the fragment is constructed by one * of the builders with {@code shouldAutomaticallyHandleOnBackPressed(true)}. * * <p>Additionally, when starting an {@code Activity} for a result from this {@code Fragment}, be * sure to invoke {@link Fragment#startActivityForResult(Intent, int)} rather than {@link * android.app.Activity#startActivityForResult(Intent, int)}. If the {@code Activity} version of the * method is invoked then this {@code Fragment} will never receive its {@link * Fragment#onActivityResult(int, int, Intent)} callback. * * <p>If convenient, consider using a {@link FlutterActivity} instead of a {@code FlutterFragment} * to avoid the work of forwarding calls. * * <p>{@code FlutterFragment} supports the use of an existing, cached {@link * io.flutter.embedding.engine.FlutterEngine}. To use a cached {@link * io.flutter.embedding.engine.FlutterEngine}, ensure that the {@link * io.flutter.embedding.engine.FlutterEngine} is stored in {@link * io.flutter.embedding.engine.FlutterEngineCache} and then use {@link #withCachedEngine(String)} to * build a {@code FlutterFragment} with the cached {@link * io.flutter.embedding.engine.FlutterEngine}'s ID. * * <p>It is generally recommended to use a cached {@link io.flutter.embedding.engine.FlutterEngine} * to avoid a momentary delay when initializing a new {@link * io.flutter.embedding.engine.FlutterEngine}. The two exceptions to using a cached {@link * FlutterEngine} are: * * <ul> * <li>When {@code FlutterFragment} is in the first {@code Activity} displayed by the app, because * pre-warming a {@link io.flutter.embedding.engine.FlutterEngine} would have no impact in * this situation. * <li>When you are unsure when/if you will need to display a Flutter experience. * </ul> * * <p>The following illustrates how to pre-warm and cache a {@link * io.flutter.embedding.engine.FlutterEngine}: * * <pre>{@code * // Create and pre-warm a FlutterEngine. * FlutterEngineGroup group = new FlutterEngineGroup(context); * FlutterEngine flutterEngine = group.createAndRunDefaultEngine(context); * flutterEngine * .getDartExecutor() * .executeDartEntrypoint(DartEntrypoint.createDefault()); * * // Cache the pre-warmed FlutterEngine in the FlutterEngineCache. * FlutterEngineCache.getInstance().put("my_engine", flutterEngine); * }</pre> * * <p>If Flutter is needed in a location that can only use a {@code View}, consider using a {@link * io.flutter.embedding.android.FlutterView}. Using a {@link * io.flutter.embedding.android.FlutterView} requires forwarding some calls from an {@code * Activity}, as well as forwarding lifecycle calls from an {@code Activity} or a {@code Fragment}. */ public class FlutterFragment extends Fragment implements FlutterActivityAndFragmentDelegate.Host, ComponentCallbacks2, FlutterActivityAndFragmentDelegate.DelegateFactory { /** * The ID of the {@code FlutterView} created by this activity. * * <p>This ID can be used to lookup {@code FlutterView} in the Android view hierarchy. For more, * see {@link android.view.View#findViewById}. */ public static final int FLUTTER_VIEW_ID = View.generateViewId(); private static final String TAG = "FlutterFragment"; /** The Dart entrypoint method name that is executed upon initialization. */ protected static final String ARG_DART_ENTRYPOINT = "dart_entrypoint"; /** The Dart entrypoint method's URI that is executed upon initialization. */ protected static final String ARG_DART_ENTRYPOINT_URI = "dart_entrypoint_uri"; /** The Dart entrypoint arguments that is executed upon initialization. */ protected static final String ARG_DART_ENTRYPOINT_ARGS = "dart_entrypoint_args"; /** Initial Flutter route that is rendered in a Navigator widget. */ protected static final String ARG_INITIAL_ROUTE = "initial_route"; /** Whether the activity delegate should handle the deeplinking request. */ protected static final String ARG_HANDLE_DEEPLINKING = "handle_deeplinking"; /** Path to Flutter's Dart code. */ protected static final String ARG_APP_BUNDLE_PATH = "app_bundle_path"; /** Whether to delay the Android drawing pass till after the Flutter UI has been displayed. */ protected static final String ARG_SHOULD_DELAY_FIRST_ANDROID_VIEW_DRAW = "should_delay_first_android_view_draw"; /** Flutter shell arguments. */ protected static final String ARG_FLUTTER_INITIALIZATION_ARGS = "initialization_args"; /** * {@link RenderMode} to be used for the {@link io.flutter.embedding.android.FlutterView} in this * {@code FlutterFragment} */ protected static final String ARG_FLUTTERVIEW_RENDER_MODE = "flutterview_render_mode"; /** * {@link TransparencyMode} to be used for the {@link io.flutter.embedding.android.FlutterView} in * this {@code FlutterFragment} */ protected static final String ARG_FLUTTERVIEW_TRANSPARENCY_MODE = "flutterview_transparency_mode"; /** See {@link #shouldAttachEngineToActivity()}. */ protected static final String ARG_SHOULD_ATTACH_ENGINE_TO_ACTIVITY = "should_attach_engine_to_activity"; /** * The ID of a {@link io.flutter.embedding.engine.FlutterEngine} cached in {@link * io.flutter.embedding.engine.FlutterEngineCache} that will be used within the created {@code * FlutterFragment}. */ protected static final String ARG_CACHED_ENGINE_ID = "cached_engine_id"; protected static final String ARG_CACHED_ENGINE_GROUP_ID = "cached_engine_group_id"; /** * True if the {@link io.flutter.embedding.engine.FlutterEngine} in the created {@code * FlutterFragment} should be destroyed when the {@code FlutterFragment} is destroyed, false if * the {@link io.flutter.embedding.engine.FlutterEngine} should outlive the {@code * FlutterFragment}. */ protected static final String ARG_DESTROY_ENGINE_WITH_FRAGMENT = "destroy_engine_with_fragment"; /** * True if the framework state in the engine attached to this engine should be stored and restored * when this fragment is created and destroyed. */ protected static final String ARG_ENABLE_STATE_RESTORATION = "enable_state_restoration"; /** * True if the fragment should receive {@link #onBackPressed()} events automatically, without * requiring an explicit activity call through. */ protected static final String ARG_SHOULD_AUTOMATICALLY_HANDLE_ON_BACK_PRESSED = "should_automatically_handle_on_back_pressed"; private final OnWindowFocusChangeListener onWindowFocusChangeListener = new OnWindowFocusChangeListener() { @Override public void onWindowFocusChanged(boolean hasFocus) { if (stillAttachedForEvent("onWindowFocusChanged")) { delegate.onWindowFocusChanged(hasFocus); } } }; /** * Creates a {@code FlutterFragment} with a default configuration. * * <p>{@code FlutterFragment}'s default configuration creates a new {@link * io.flutter.embedding.engine.FlutterEngine} within the {@code FlutterFragment} and uses the * following settings: * * <ul> * <li>Dart entrypoint: "main" * <li>Initial route: "/" * <li>Render mode: surface * <li>Transparency mode: transparent * </ul> * * <p>To use a new {@link io.flutter.embedding.engine.FlutterEngine} with different settings, use * {@link #withNewEngine()}. * * <p>To use a cached {@link io.flutter.embedding.engine.FlutterEngine} instead of creating a new * one, use {@link #withCachedEngine(String)}. */ @NonNull public static FlutterFragment createDefault() { return new NewEngineFragmentBuilder().build(); } /** * Returns a {@link NewEngineFragmentBuilder} to create a {@code FlutterFragment} with a new * {@link io.flutter.embedding.engine.FlutterEngine} and a desired engine configuration. */ @NonNull public static NewEngineFragmentBuilder withNewEngine() { return new NewEngineFragmentBuilder(); } /** * Builder that creates a new {@code FlutterFragment} with {@code arguments} that correspond to * the values set on this {@code NewEngineFragmentBuilder}. * * <p>To create a {@code FlutterFragment} with default {@code arguments}, invoke {@link * #createDefault()}. * * <p>Subclasses of {@code FlutterFragment} that do not introduce any new arguments can use this * {@code NewEngineFragmentBuilder} to construct instances of the subclass without subclassing * this {@code NewEngineFragmentBuilder}. {@code MyFlutterFragment f = new * FlutterFragment.NewEngineFragmentBuilder(MyFlutterFragment.class) .someProperty(...) * .someOtherProperty(...) .build<MyFlutterFragment>(); } * * <p>Subclasses of {@code FlutterFragment} that introduce new arguments should subclass this * {@code NewEngineFragmentBuilder} to add the new properties: * * <ol> * <li>Ensure the {@code FlutterFragment} subclass has a no-arg constructor. * <li>Subclass this {@code NewEngineFragmentBuilder}. * <li>Override the new {@code NewEngineFragmentBuilder}'s no-arg constructor and invoke the * super constructor to set the {@code FlutterFragment} subclass: {@code public MyBuilder() * { super(MyFlutterFragment.class); } } * <li>Add appropriate property methods for the new properties. * <li>Override {@link NewEngineFragmentBuilder#createArgs()}, call through to the super method, * then add the new properties as arguments in the {@link Bundle}. * </ol> * * Once a {@code NewEngineFragmentBuilder} subclass is defined, the {@code FlutterFragment} * subclass can be instantiated as follows. {@code MyFlutterFragment f = new MyBuilder() * .someExistingProperty(...) .someNewProperty(...) .build<MyFlutterFragment>(); } */ public static class NewEngineFragmentBuilder { private final Class<? extends FlutterFragment> fragmentClass; private String dartEntrypoint = "main"; private String dartLibraryUri = null; private List<String> dartEntrypointArgs; private String initialRoute = "/"; private boolean handleDeeplinking = false; private String appBundlePath = null; private FlutterShellArgs shellArgs = null; private RenderMode renderMode = RenderMode.surface; private TransparencyMode transparencyMode = TransparencyMode.transparent; private boolean shouldAttachEngineToActivity = true; private boolean shouldAutomaticallyHandleOnBackPressed = false; private boolean shouldDelayFirstAndroidViewDraw = false; /** * Constructs a {@code NewEngineFragmentBuilder} that is configured to construct an instance of * {@code FlutterFragment}. */ public NewEngineFragmentBuilder() { fragmentClass = FlutterFragment.class; } /** * Constructs a {@code NewEngineFragmentBuilder} that is configured to construct an instance of * {@code subclass}, which extends {@code FlutterFragment}. */ public NewEngineFragmentBuilder(@NonNull Class<? extends FlutterFragment> subclass) { fragmentClass = subclass; } /** The name of the initial Dart method to invoke, defaults to "main". */ @NonNull public NewEngineFragmentBuilder dartEntrypoint(@NonNull String dartEntrypoint) { this.dartEntrypoint = dartEntrypoint; return this; } @NonNull public NewEngineFragmentBuilder dartLibraryUri(@NonNull String dartLibraryUri) { this.dartLibraryUri = dartLibraryUri; return this; } /** Arguments passed as a list of string to Dart's entrypoint function. */ @NonNull public NewEngineFragmentBuilder dartEntrypointArgs(@NonNull List<String> dartEntrypointArgs) { this.dartEntrypointArgs = dartEntrypointArgs; return this; } /** * The initial route that a Flutter app will render in this {@link FlutterFragment}, defaults to * "/". */ @NonNull public NewEngineFragmentBuilder initialRoute(@NonNull String initialRoute) { this.initialRoute = initialRoute; return this; } /** * Whether to handle the deeplinking from the {@code Intent} automatically if the {@code * getInitialRoute} returns null. */ @NonNull public NewEngineFragmentBuilder handleDeeplinking(@NonNull Boolean handleDeeplinking) { this.handleDeeplinking = handleDeeplinking; return this; } /** * The path to the app bundle which contains the Dart app to execute. Null when unspecified, * which defaults to {@link * io.flutter.embedding.engine.loader.FlutterLoader#findAppBundlePath()} */ @NonNull public NewEngineFragmentBuilder appBundlePath(@NonNull String appBundlePath) { this.appBundlePath = appBundlePath; return this; } /** Any special configuration arguments for the Flutter engine */ @NonNull public NewEngineFragmentBuilder flutterShellArgs(@NonNull FlutterShellArgs shellArgs) { this.shellArgs = shellArgs; return this; } /** * Render Flutter either as a {@link RenderMode#surface} or a {@link RenderMode#texture}. You * should use {@code surface} unless you have a specific reason to use {@code texture}. {@code * texture} comes with a significant performance impact, but {@code texture} can be displayed * beneath other Android {@code View}s and animated, whereas {@code surface} cannot. */ @NonNull public NewEngineFragmentBuilder renderMode(@NonNull RenderMode renderMode) { this.renderMode = renderMode; return this; } /** * Support a {@link TransparencyMode#transparent} background within {@link * io.flutter.embedding.android.FlutterView}, or force an {@link TransparencyMode#opaque} * background. * * <p>See {@link TransparencyMode} for implications of this selection. */ @NonNull public NewEngineFragmentBuilder transparencyMode(@NonNull TransparencyMode transparencyMode) { this.transparencyMode = transparencyMode; return this; } /** * Whether or not this {@code FlutterFragment} should automatically attach its {@code Activity} * as a control surface for its {@link io.flutter.embedding.engine.FlutterEngine}. * * <p>Control surfaces are used to provide Android resources and lifecycle events to plugins * that are attached to the {@link io.flutter.embedding.engine.FlutterEngine}. If {@code * shouldAttachEngineToActivity} is true then this {@code FlutterFragment} will connect its * {@link io.flutter.embedding.engine.FlutterEngine} to the surrounding {@code Activity}, along * with any plugins that are registered with that {@link FlutterEngine}. This allows plugins to * access the {@code Activity}, as well as receive {@code Activity}-specific calls, e.g., {@link * android.app.Activity#onNewIntent(Intent)}. If {@code shouldAttachEngineToActivity} is false, * then this {@code FlutterFragment} will not automatically manage the connection between its * {@link io.flutter.embedding.engine.FlutterEngine} and the surrounding {@code Activity}. The * {@code Activity} will need to be manually connected to this {@code FlutterFragment}'s {@link * io.flutter.embedding.engine.FlutterEngine} by the app developer. See {@link * FlutterEngine#getActivityControlSurface()}. * * <p>One reason that a developer might choose to manually manage the relationship between the * {@code Activity} and {@link io.flutter.embedding.engine.FlutterEngine} is if the developer * wants to move the {@link FlutterEngine} somewhere else. For example, a developer might want * the {@link io.flutter.embedding.engine.FlutterEngine} to outlive the surrounding {@code * Activity} so that it can be used later in a different {@code Activity}. To accomplish this, * the {@link io.flutter.embedding.engine.FlutterEngine} will need to be disconnected from the * surrounding {@code Activity} at an unusual time, preventing this {@code FlutterFragment} from * correctly managing the relationship between the {@link * io.flutter.embedding.engine.FlutterEngine} and the surrounding {@code Activity}. * * <p>Another reason that a developer might choose to manually manage the relationship between * the {@code Activity} and {@link io.flutter.embedding.engine.FlutterEngine} is if the * developer wants to prevent, or explicitly control when the {@link * io.flutter.embedding.engine.FlutterEngine}'s plugins have access to the surrounding {@code * Activity}. For example, imagine that this {@code FlutterFragment} only takes up part of the * screen and the app developer wants to ensure that none of the Flutter plugins are able to * manipulate the surrounding {@code Activity}. In this case, the developer would not want the * {@link io.flutter.embedding.engine.FlutterEngine} to have access to the {@code Activity}, * which can be accomplished by setting {@code shouldAttachEngineToActivity} to {@code false}. */ @NonNull public NewEngineFragmentBuilder shouldAttachEngineToActivity( boolean shouldAttachEngineToActivity) { this.shouldAttachEngineToActivity = shouldAttachEngineToActivity; return this; } /** * Whether or not this {@code FlutterFragment} should automatically receive {@link * #onBackPressed()} events, rather than requiring an explicit activity call through. Disabled * by default. * * <p>When enabled, the activity will automatically dispatch back-press events to the fragment's * {@link OnBackPressedCallback}, instead of requiring the activity to manually call {@link * #onBackPressed()} in client code. If enabled, do <b>not</b> invoke {@link #onBackPressed()} * manually. * * <p>This behavior relies on the implementation of {@link #popSystemNavigator()}. It's not * recommended to override that method when enabling this attribute, but if you do, you should * always fall back to calling {@code super.popSystemNavigator()} when not relying on custom * behavior. */ @NonNull public NewEngineFragmentBuilder shouldAutomaticallyHandleOnBackPressed( boolean shouldAutomaticallyHandleOnBackPressed) { this.shouldAutomaticallyHandleOnBackPressed = shouldAutomaticallyHandleOnBackPressed; return this; } /** * Whether to delay the Android drawing pass till after the Flutter UI has been displayed. * * <p>See {#link FlutterActivityAndFragmentDelegate#onCreateView} for more details. */ @NonNull public NewEngineFragmentBuilder shouldDelayFirstAndroidViewDraw( boolean shouldDelayFirstAndroidViewDraw) { this.shouldDelayFirstAndroidViewDraw = shouldDelayFirstAndroidViewDraw; return this; } /** * Creates a {@link Bundle} of arguments that are assigned to the new {@code FlutterFragment}. * * <p>Subclasses should override this method to add new properties to the {@link Bundle}. * Subclasses must call through to the super method to collect all existing property values. */ @NonNull protected Bundle createArgs() { Bundle args = new Bundle(); args.putString(ARG_INITIAL_ROUTE, initialRoute); args.putBoolean(ARG_HANDLE_DEEPLINKING, handleDeeplinking); args.putString(ARG_APP_BUNDLE_PATH, appBundlePath); args.putString(ARG_DART_ENTRYPOINT, dartEntrypoint); args.putString(ARG_DART_ENTRYPOINT_URI, dartLibraryUri); args.putStringArrayList( ARG_DART_ENTRYPOINT_ARGS, dartEntrypointArgs != null ? new ArrayList(dartEntrypointArgs) : null); // TODO(mattcarroll): determine if we should have an explicit FlutterTestFragment instead of // conflating. if (null != shellArgs) { args.putStringArray(ARG_FLUTTER_INITIALIZATION_ARGS, shellArgs.toArray()); } args.putString( ARG_FLUTTERVIEW_RENDER_MODE, renderMode != null ? renderMode.name() : RenderMode.surface.name()); args.putString( ARG_FLUTTERVIEW_TRANSPARENCY_MODE, transparencyMode != null ? transparencyMode.name() : TransparencyMode.transparent.name()); args.putBoolean(ARG_SHOULD_ATTACH_ENGINE_TO_ACTIVITY, shouldAttachEngineToActivity); args.putBoolean(ARG_DESTROY_ENGINE_WITH_FRAGMENT, true); args.putBoolean( ARG_SHOULD_AUTOMATICALLY_HANDLE_ON_BACK_PRESSED, shouldAutomaticallyHandleOnBackPressed); args.putBoolean(ARG_SHOULD_DELAY_FIRST_ANDROID_VIEW_DRAW, shouldDelayFirstAndroidViewDraw); return args; } /** * Constructs a new {@code FlutterFragment} (or a subclass) that is configured based on * properties set on this {@code Builder}. */ @NonNull public <T extends FlutterFragment> T build() { try { @SuppressWarnings("unchecked") T frag = (T) fragmentClass.getDeclaredConstructor().newInstance(); if (frag == null) { throw new RuntimeException( "The FlutterFragment subclass sent in the constructor (" + fragmentClass.getCanonicalName() + ") does not match the expected return type."); } Bundle args = createArgs(); frag.setArguments(args); return frag; } catch (Exception e) { throw new RuntimeException( "Could not instantiate FlutterFragment subclass (" + fragmentClass.getName() + ")", e); } } } /** * Returns a {@link CachedEngineFragmentBuilder} to create a {@code FlutterFragment} with a cached * {@link io.flutter.embedding.engine.FlutterEngine} in {@link * io.flutter.embedding.engine.FlutterEngineCache}. * * <p>An {@code IllegalStateException} will be thrown during the lifecycle of the {@code * FlutterFragment} if a cached {@link io.flutter.embedding.engine.FlutterEngine} is requested but * does not exist in the cache. * * <p>To create a {@code FlutterFragment} that uses a new {@link * io.flutter.embedding.engine.FlutterEngine}, use {@link #createDefault()} or {@link * #withNewEngine()}. */ @NonNull public static CachedEngineFragmentBuilder withCachedEngine(@NonNull String engineId) { return new CachedEngineFragmentBuilder(engineId); } /** * Builder that creates a new {@code FlutterFragment} that uses a cached {@link * io.flutter.embedding.engine.FlutterEngine} with {@code arguments} that correspond to the values * set on this {@code Builder}. * * <p>Subclasses of {@code FlutterFragment} that do not introduce any new arguments can use this * {@code Builder} to construct instances of the subclass without subclassing this {@code * Builder}. {@code MyFlutterFragment f = new * FlutterFragment.CachedEngineFragmentBuilder(MyFlutterFragment.class) .someProperty(...) * .someOtherProperty(...) .build<MyFlutterFragment>(); } * * <p>Subclasses of {@code FlutterFragment} that introduce new arguments should subclass this * {@code CachedEngineFragmentBuilder} to add the new properties: * * <ol> * <li>Ensure the {@code FlutterFragment} subclass has a no-arg constructor. * <li>Subclass this {@code CachedEngineFragmentBuilder}. * <li>Override the new {@code CachedEngineFragmentBuilder}'s no-arg constructor and invoke the * super constructor to set the {@code FlutterFragment} subclass: {@code public MyBuilder() * { super(MyFlutterFragment.class); } } * <li>Add appropriate property methods for the new properties. * <li>Override {@link CachedEngineFragmentBuilder#createArgs()}, call through to the super * method, then add the new properties as arguments in the {@link Bundle}. * </ol> * * Once a {@code CachedEngineFragmentBuilder} subclass is defined, the {@code FlutterFragment} * subclass can be instantiated as follows. {@code MyFlutterFragment f = new MyBuilder() * .someExistingProperty(...) .someNewProperty(...) .build<MyFlutterFragment>(); } */ public static class CachedEngineFragmentBuilder { private final Class<? extends FlutterFragment> fragmentClass; private final String engineId; private boolean destroyEngineWithFragment = false; private boolean handleDeeplinking = false; private RenderMode renderMode = RenderMode.surface; private TransparencyMode transparencyMode = TransparencyMode.transparent; private boolean shouldAttachEngineToActivity = true; private boolean shouldAutomaticallyHandleOnBackPressed = false; private boolean shouldDelayFirstAndroidViewDraw = false; private CachedEngineFragmentBuilder(@NonNull String engineId) { this(FlutterFragment.class, engineId); } public CachedEngineFragmentBuilder( @NonNull Class<? extends FlutterFragment> subclass, @NonNull String engineId) { this.fragmentClass = subclass; this.engineId = engineId; } /** * Pass {@code true} to destroy the cached {@link io.flutter.embedding.engine.FlutterEngine} * when this {@code FlutterFragment} is destroyed, or {@code false} for the cached {@link * io.flutter.embedding.engine.FlutterEngine} to outlive this {@code FlutterFragment}. */ @NonNull public CachedEngineFragmentBuilder destroyEngineWithFragment( boolean destroyEngineWithFragment) { this.destroyEngineWithFragment = destroyEngineWithFragment; return this; } /** * Render Flutter either as a {@link RenderMode#surface} or a {@link RenderMode#texture}. You * should use {@code surface} unless you have a specific reason to use {@code texture}. {@code * texture} comes with a significant performance impact, but {@code texture} can be displayed * beneath other Android {@code View}s and animated, whereas {@code surface} cannot. */ @NonNull public CachedEngineFragmentBuilder renderMode(@NonNull RenderMode renderMode) { this.renderMode = renderMode; return this; } /** * Support a {@link TransparencyMode#transparent} background within {@link * io.flutter.embedding.android.FlutterView}, or force an {@link TransparencyMode#opaque} * background. * * <p>See {@link TransparencyMode} for implications of this selection. */ @NonNull public CachedEngineFragmentBuilder transparencyMode( @NonNull TransparencyMode transparencyMode) { this.transparencyMode = transparencyMode; return this; } /** * Whether to handle the deeplinking from the {@code Intent} automatically if the {@code * getInitialRoute} returns null. */ @NonNull public CachedEngineFragmentBuilder handleDeeplinking(@NonNull Boolean handleDeeplinking) { this.handleDeeplinking = handleDeeplinking; return this; } /** * Whether or not this {@code FlutterFragment} should automatically attach its {@code Activity} * as a control surface for its {@link io.flutter.embedding.engine.FlutterEngine}. * * <p>Control surfaces are used to provide Android resources and lifecycle events to plugins * that are attached to the {@link io.flutter.embedding.engine.FlutterEngine}. If {@code * shouldAttachEngineToActivity} is true then this {@code FlutterFragment} will connect its * {@link io.flutter.embedding.engine.FlutterEngine} to the surrounding {@code Activity}, along * with any plugins that are registered with that {@link FlutterEngine}. This allows plugins to * access the {@code Activity}, as well as receive {@code Activity}-specific calls, e.g., {@link * android.app.Activity#onNewIntent(Intent)}. If {@code shouldAttachEngineToActivity} is false, * then this {@code FlutterFragment} will not automatically manage the connection between its * {@link io.flutter.embedding.engine.FlutterEngine} and the surrounding {@code Activity}. The * {@code Activity} will need to be manually connected to this {@code FlutterFragment}'s {@link * io.flutter.embedding.engine.FlutterEngine} by the app developer. See {@link * FlutterEngine#getActivityControlSurface()}. * * <p>One reason that a developer might choose to manually manage the relationship between the * {@code Activity} and {@link io.flutter.embedding.engine.FlutterEngine} is if the developer * wants to move the {@link FlutterEngine} somewhere else. For example, a developer might want * the {@link io.flutter.embedding.engine.FlutterEngine} to outlive the surrounding {@code * Activity} so that it can be used later in a different {@code Activity}. To accomplish this, * the {@link io.flutter.embedding.engine.FlutterEngine} will need to be disconnected from the * surrounding {@code Activity} at an unusual time, preventing this {@code FlutterFragment} from * correctly managing the relationship between the {@link * io.flutter.embedding.engine.FlutterEngine} and the surrounding {@code Activity}. * * <p>Another reason that a developer might choose to manually manage the relationship between * the {@code Activity} and {@link io.flutter.embedding.engine.FlutterEngine} is if the * developer wants to prevent, or explicitly control when the {@link * io.flutter.embedding.engine.FlutterEngine}'s plugins have access to the surrounding {@code * Activity}. For example, imagine that this {@code FlutterFragment} only takes up part of the * screen and the app developer wants to ensure that none of the Flutter plugins are able to * manipulate the surrounding {@code Activity}. In this case, the developer would not want the * {@link io.flutter.embedding.engine.FlutterEngine} to have access to the {@code Activity}, * which can be accomplished by setting {@code shouldAttachEngineToActivity} to {@code false}. */ @NonNull public CachedEngineFragmentBuilder shouldAttachEngineToActivity( boolean shouldAttachEngineToActivity) { this.shouldAttachEngineToActivity = shouldAttachEngineToActivity; return this; } /** * Whether or not this {@code FlutterFragment} should automatically receive {@link * #onBackPressed()} events, rather than requiring an explicit activity call through. Disabled * by default. * * <p>When enabled, the activity will automatically dispatch back-press events to the fragment's * {@link OnBackPressedCallback}, instead of requiring the activity to manually call {@link * #onBackPressed()} in client code. If enabled, do <b>not</b> invoke {@link #onBackPressed()} * manually. * * <p>Enabling this behavior relies on explicit behavior in {@link #popSystemNavigator()}. It's * not recommended to override that method when enabling this attribute, but if you do, you * should always fall back to calling {@code super.popSystemNavigator()} when not relying on * custom behavior. */ @NonNull public CachedEngineFragmentBuilder shouldAutomaticallyHandleOnBackPressed( boolean shouldAutomaticallyHandleOnBackPressed) { this.shouldAutomaticallyHandleOnBackPressed = shouldAutomaticallyHandleOnBackPressed; return this; } /** * Whether to delay the Android drawing pass till after the Flutter UI has been displayed. * * <p>See {#link FlutterActivityAndFragmentDelegate#onCreateView} for more details. */ @NonNull public CachedEngineFragmentBuilder shouldDelayFirstAndroidViewDraw( @NonNull boolean shouldDelayFirstAndroidViewDraw) { this.shouldDelayFirstAndroidViewDraw = shouldDelayFirstAndroidViewDraw; return this; } /** * Creates a {@link Bundle} of arguments that are assigned to the new {@code FlutterFragment}. * * <p>Subclasses should override this method to add new properties to the {@link Bundle}. * Subclasses must call through to the super method to collect all existing property values. */ @NonNull protected Bundle createArgs() { Bundle args = new Bundle(); args.putString(ARG_CACHED_ENGINE_ID, engineId); args.putBoolean(ARG_DESTROY_ENGINE_WITH_FRAGMENT, destroyEngineWithFragment); args.putBoolean(ARG_HANDLE_DEEPLINKING, handleDeeplinking); args.putString( ARG_FLUTTERVIEW_RENDER_MODE, renderMode != null ? renderMode.name() : RenderMode.surface.name()); args.putString( ARG_FLUTTERVIEW_TRANSPARENCY_MODE, transparencyMode != null ? transparencyMode.name() : TransparencyMode.transparent.name()); args.putBoolean(ARG_SHOULD_ATTACH_ENGINE_TO_ACTIVITY, shouldAttachEngineToActivity); args.putBoolean( ARG_SHOULD_AUTOMATICALLY_HANDLE_ON_BACK_PRESSED, shouldAutomaticallyHandleOnBackPressed); args.putBoolean(ARG_SHOULD_DELAY_FIRST_ANDROID_VIEW_DRAW, shouldDelayFirstAndroidViewDraw); return args; } /** * Constructs a new {@code FlutterFragment} (or a subclass) that is configured based on * properties set on this {@code CachedEngineFragmentBuilder}. */ @NonNull public <T extends FlutterFragment> T build() { try { @SuppressWarnings("unchecked") T frag = (T) fragmentClass.getDeclaredConstructor().newInstance(); if (frag == null) { throw new RuntimeException( "The FlutterFragment subclass sent in the constructor (" + fragmentClass.getCanonicalName() + ") does not match the expected return type."); } Bundle args = createArgs(); frag.setArguments(args); return frag; } catch (Exception e) { throw new RuntimeException( "Could not instantiate FlutterFragment subclass (" + fragmentClass.getName() + ")", e); } } } /** * Returns a {@link NewEngineInGroupFragmentBuilder} to create a {@code FlutterFragment} with a * cached {@link io.flutter.embedding.engine.FlutterEngineGroup} in {@link * io.flutter.embedding.engine.FlutterEngineGroupCache}. * * <p>An {@code IllegalStateException} will be thrown during the lifecycle of the {@code * FlutterFragment} if a cached {@link io.flutter.embedding.engine.FlutterEngineGroup} is * requested but does not exist in the {@link * io.flutter.embedding.engine.FlutterEngineGroupCache}. */ @NonNull public static NewEngineInGroupFragmentBuilder withNewEngineInGroup( @NonNull String engineGroupId) { return new NewEngineInGroupFragmentBuilder(engineGroupId); } /** * Builder that creates a new {@code FlutterFragment} that uses a cached {@link * io.flutter.embedding.engine.FlutterEngineGroup} to create a new {@link * io.flutter.embedding.engine.FlutterEngine} with {@code arguments} that correspond to the values * set on this {@code Builder}. * * <p>Subclasses of {@code FlutterFragment} that do not introduce any new arguments can use this * {@code Builder} to construct instances of the subclass without subclassing this {@code * Builder}. {@code MyFlutterFragment f = new * FlutterFragment.NewEngineInGroupFragmentBuilder(MyFlutterFragment.class, engineGroupId) * .someProperty(...) .someOtherProperty(...) .build<MyFlutterFragment>(); } * * <p>Subclasses of {@code FlutterFragment} that introduce new arguments should subclass this * {@code NewEngineInGroupFragmentBuilder} to add the new properties: * * <ol> * <li>Ensure the {@code FlutterFragment} subclass has a no-arg constructor. * <li>Subclass this {@code NewEngineInGroupFragmentBuilder}. * <li>Override the new {@code NewEngineInGroupFragmentBuilder}'s no-arg constructor and invoke * the super constructor to set the {@code FlutterFragment} subclass: {@code public * MyBuilder() { super(MyFlutterFragment.class); } } * <li>Add appropriate property methods for the new properties. * <li>Override {@link NewEngineInGroupFragmentBuilder#createArgs()}, call through to the super * method, then add the new properties as arguments in the {@link Bundle}. * </ol> * * Once a {@code NewEngineInGroupFragmentBuilder} subclass is defined, the {@code FlutterFragment} * subclass can be instantiated as follows. {@code MyFlutterFragment f = new MyBuilder() * .someExistingProperty(...) .someNewProperty(...) .build<MyFlutterFragment>(); } */ public static class NewEngineInGroupFragmentBuilder { private final Class<? extends FlutterFragment> fragmentClass; private final String cachedEngineGroupId; private @NonNull String dartEntrypoint = "main"; private @NonNull String initialRoute = "/"; private @NonNull boolean handleDeeplinking = false; private @NonNull RenderMode renderMode = RenderMode.surface; private @NonNull TransparencyMode transparencyMode = TransparencyMode.transparent; private boolean shouldAttachEngineToActivity = true; private boolean shouldAutomaticallyHandleOnBackPressed = false; private boolean shouldDelayFirstAndroidViewDraw = false; public NewEngineInGroupFragmentBuilder(@NonNull String engineGroupId) { this(FlutterFragment.class, engineGroupId); } public NewEngineInGroupFragmentBuilder( @NonNull Class<? extends FlutterFragment> fragmentClass, @NonNull String engineGroupId) { this.fragmentClass = fragmentClass; this.cachedEngineGroupId = engineGroupId; } /** The name of the initial Dart method to invoke, defaults to "main". */ @NonNull public NewEngineInGroupFragmentBuilder dartEntrypoint(@NonNull String dartEntrypoint) { this.dartEntrypoint = dartEntrypoint; return this; } /** * The initial route that a Flutter app will render in this {@link FlutterFragment}, defaults to * "/". */ @NonNull public NewEngineInGroupFragmentBuilder initialRoute(@NonNull String initialRoute) { this.initialRoute = initialRoute; return this; } /** * Whether to handle the deeplinking from the {@code Intent} automatically if the {@code * getInitialRoute} returns null. */ @NonNull public NewEngineInGroupFragmentBuilder handleDeeplinking(@NonNull boolean handleDeeplinking) { this.handleDeeplinking = handleDeeplinking; return this; } /** * Render Flutter either as a {@link RenderMode#surface} or a {@link RenderMode#texture}. You * should use {@code surface} unless you have a specific reason to use {@code texture}. {@code * texture} comes with a significant performance impact, but {@code texture} can be displayed * beneath other Android {@code View}s and animated, whereas {@code surface} cannot. */ @NonNull public NewEngineInGroupFragmentBuilder renderMode(@NonNull RenderMode renderMode) { this.renderMode = renderMode; return this; } /** * Support a {@link TransparencyMode#transparent} background within {@link * io.flutter.embedding.android.FlutterView}, or force an {@link TransparencyMode#opaque} * background. * * <p>See {@link TransparencyMode} for implications of this selection. */ @NonNull public NewEngineInGroupFragmentBuilder transparencyMode( @NonNull TransparencyMode transparencyMode) { this.transparencyMode = transparencyMode; return this; } /** * Whether or not this {@code FlutterFragment} should automatically attach its {@code Activity} * as a control surface for its {@link io.flutter.embedding.engine.FlutterEngine}. * * <p>Control surfaces are used to provide Android resources and lifecycle events to plugins * that are attached to the {@link io.flutter.embedding.engine.FlutterEngine}. If {@code * shouldAttachEngineToActivity} is true then this {@code FlutterFragment} will connect its * {@link io.flutter.embedding.engine.FlutterEngine} to the surrounding {@code Activity}, along * with any plugins that are registered with that {@link FlutterEngine}. This allows plugins to * access the {@code Activity}, as well as receive {@code Activity}-specific calls, e.g., {@link * android.app.Activity#onNewIntent(Intent)}. If {@code shouldAttachEngineToActivity} is false, * then this {@code FlutterFragment} will not automatically manage the connection between its * {@link io.flutter.embedding.engine.FlutterEngine} and the surrounding {@code Activity}. The * {@code Activity} will need to be manually connected to this {@code FlutterFragment}'s {@link * io.flutter.embedding.engine.FlutterEngine} by the app developer. See {@link * FlutterEngine#getActivityControlSurface()}. * * <p>One reason that a developer might choose to manually manage the relationship between the * {@code Activity} and {@link io.flutter.embedding.engine.FlutterEngine} is if the developer * wants to move the {@link FlutterEngine} somewhere else. For example, a developer might want * the {@link io.flutter.embedding.engine.FlutterEngine} to outlive the surrounding {@code * Activity} so that it can be used later in a different {@code Activity}. To accomplish this, * the {@link io.flutter.embedding.engine.FlutterEngine} will need to be disconnected from the * surrounding {@code Activity} at an unusual time, preventing this {@code FlutterFragment} from * correctly managing the relationship between the {@link * io.flutter.embedding.engine.FlutterEngine} and the surrounding {@code Activity}. * * <p>Another reason that a developer might choose to manually manage the relationship between * the {@code Activity} and {@link io.flutter.embedding.engine.FlutterEngine} is if the * developer wants to prevent, or explicitly control when the {@link * io.flutter.embedding.engine.FlutterEngine}'s plugins have access to the surrounding {@code * Activity}. For example, imagine that this {@code FlutterFragment} only takes up part of the * screen and the app developer wants to ensure that none of the Flutter plugins are able to * manipulate the surrounding {@code Activity}. In this case, the developer would not want the * {@link io.flutter.embedding.engine.FlutterEngine} to have access to the {@code Activity}, * which can be accomplished by setting {@code shouldAttachEngineToActivity} to {@code false}. */ @NonNull public NewEngineInGroupFragmentBuilder shouldAttachEngineToActivity( boolean shouldAttachEngineToActivity) { this.shouldAttachEngineToActivity = shouldAttachEngineToActivity; return this; } /** * Whether or not this {@code FlutterFragment} should automatically receive {@link * #onBackPressed()} events, rather than requiring an explicit activity call through. Disabled * by default. * * <p>When enabled, the activity will automatically dispatch back-press events to the fragment's * {@link OnBackPressedCallback}, instead of requiring the activity to manually call {@link * #onBackPressed()} in client code. If enabled, do <b>not</b> invoke {@link #onBackPressed()} * manually. * * <p>This behavior relies on the implementation of {@link #popSystemNavigator()}. It's not * recommended to override that method when enabling this attribute, but if you do, you should * always fall back to calling {@code super.popSystemNavigator()} when not relying on custom * behavior. */ @NonNull public NewEngineInGroupFragmentBuilder shouldAutomaticallyHandleOnBackPressed( boolean shouldAutomaticallyHandleOnBackPressed) { this.shouldAutomaticallyHandleOnBackPressed = shouldAutomaticallyHandleOnBackPressed; return this; } /** * Whether to delay the Android drawing pass till after the Flutter UI has been displayed. * * <p>See {#link FlutterActivityAndFragmentDelegate#onCreateView} for more details. */ @NonNull public NewEngineInGroupFragmentBuilder shouldDelayFirstAndroidViewDraw( @NonNull boolean shouldDelayFirstAndroidViewDraw) { this.shouldDelayFirstAndroidViewDraw = shouldDelayFirstAndroidViewDraw; return this; } /** * Creates a {@link Bundle} of arguments that are assigned to the new {@code FlutterFragment}. * * <p>Subclasses should override this method to add new properties to the {@link Bundle}. * Subclasses must call through to the super method to collect all existing property values. */ @NonNull protected Bundle createArgs() { Bundle args = new Bundle(); args.putString(ARG_CACHED_ENGINE_GROUP_ID, cachedEngineGroupId); args.putString(ARG_DART_ENTRYPOINT, dartEntrypoint); args.putString(ARG_INITIAL_ROUTE, initialRoute); args.putBoolean(ARG_HANDLE_DEEPLINKING, handleDeeplinking); args.putString( ARG_FLUTTERVIEW_RENDER_MODE, renderMode != null ? renderMode.name() : RenderMode.surface.name()); args.putString( ARG_FLUTTERVIEW_TRANSPARENCY_MODE, transparencyMode != null ? transparencyMode.name() : TransparencyMode.transparent.name()); args.putBoolean(ARG_SHOULD_ATTACH_ENGINE_TO_ACTIVITY, shouldAttachEngineToActivity); args.putBoolean(ARG_DESTROY_ENGINE_WITH_FRAGMENT, true); args.putBoolean( ARG_SHOULD_AUTOMATICALLY_HANDLE_ON_BACK_PRESSED, shouldAutomaticallyHandleOnBackPressed); args.putBoolean(ARG_SHOULD_DELAY_FIRST_ANDROID_VIEW_DRAW, shouldDelayFirstAndroidViewDraw); return args; } /** * Constructs a new {@code FlutterFragment} (or a subclass) that is configured based on * properties set on this {@code Builder}. */ @NonNull public <T extends FlutterFragment> T build() { try { @SuppressWarnings("unchecked") T frag = (T) fragmentClass.getDeclaredConstructor().newInstance(); if (frag == null) { throw new RuntimeException( "The FlutterFragment subclass sent in the constructor (" + fragmentClass.getCanonicalName() + ") does not match the expected return type."); } Bundle args = createArgs(); frag.setArguments(args); return frag; } catch (Exception e) { throw new RuntimeException( "Could not instantiate FlutterFragment subclass (" + fragmentClass.getName() + ")", e); } } } // Delegate that runs all lifecycle and OS hook logic that is common between // FlutterActivity and FlutterFragment. See the FlutterActivityAndFragmentDelegate // implementation for details about why it exists. @VisibleForTesting @Nullable /* package */ FlutterActivityAndFragmentDelegate delegate; @NonNull private FlutterActivityAndFragmentDelegate.DelegateFactory delegateFactory = this; /** Default delegate factory that creates a simple FlutterActivityAndFragmentDelegate instance. */ public FlutterActivityAndFragmentDelegate createDelegate( FlutterActivityAndFragmentDelegate.Host host) { return new FlutterActivityAndFragmentDelegate(host); } private final OnBackPressedCallback onBackPressedCallback = new OnBackPressedCallback(true) { @Override public void handleOnBackPressed() { onBackPressed(); } }; public FlutterFragment() { // Ensure that we at least have an empty Bundle of arguments so that we don't // need to continually check for null arguments before grabbing one. setArguments(new Bundle()); } /** * This method exists so that JVM tests can ensure that a delegate exists without putting this * Fragment through any lifecycle events, because JVM tests cannot handle executing any lifecycle * methods, at the time of writing this. * * <p>The testing infrastructure should be upgraded to make FlutterFragment tests easy to write * while exercising real lifecycle methods. At such a time, this method should be removed. */ // TODO(mattcarroll): remove this when tests allow for it // (https://github.com/flutter/flutter/issues/43798) @VisibleForTesting /* package */ void setDelegateFactory( @NonNull FlutterActivityAndFragmentDelegate.DelegateFactory delegateFactory) { this.delegateFactory = delegateFactory; delegate = delegateFactory.createDelegate(this); } /** * Returns the Android App Component exclusively attached to {@link * io.flutter.embedding.engine.FlutterEngine}. */ @Override public ExclusiveAppComponent<Activity> getExclusiveAppComponent() { return delegate; } @Override public void onAttach(@NonNull Context context) { super.onAttach(context); delegate = delegateFactory.createDelegate(this); delegate.onAttach(context); if (getArguments().getBoolean(ARG_SHOULD_AUTOMATICALLY_HANDLE_ON_BACK_PRESSED, false)) { requireActivity().getOnBackPressedDispatcher().addCallback(this, onBackPressedCallback); } context.registerComponentCallbacks(this); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); delegate.onRestoreInstanceState(savedInstanceState); } @Nullable @Override public View onCreateView( LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return delegate.onCreateView( inflater, container, savedInstanceState, /*flutterViewId=*/ FLUTTER_VIEW_ID, shouldDelayFirstAndroidViewDraw()); } @Override public void onStart() { super.onStart(); if (stillAttachedForEvent("onStart")) { delegate.onStart(); } } @Override public void onResume() { super.onResume(); if (stillAttachedForEvent("onResume")) { delegate.onResume(); } } // TODO(mattcarroll): determine why this can't be in onResume(). Comment reason, or move if // possible. @ActivityCallThrough public void onPostResume() { if (stillAttachedForEvent("onPostResume")) { delegate.onPostResume(); } } @Override public void onPause() { super.onPause(); if (stillAttachedForEvent("onPause")) { delegate.onPause(); } } @Override public void onStop() { super.onStop(); if (stillAttachedForEvent("onStop")) { delegate.onStop(); } } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); view.getViewTreeObserver().addOnWindowFocusChangeListener(onWindowFocusChangeListener); } @Override public void onDestroyView() { super.onDestroyView(); requireView() .getViewTreeObserver() .removeOnWindowFocusChangeListener(onWindowFocusChangeListener); if (stillAttachedForEvent("onDestroyView")) { delegate.onDestroyView(); } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (stillAttachedForEvent("onSaveInstanceState")) { delegate.onSaveInstanceState(outState); } } @Override public void detachFromFlutterEngine() { Log.w( TAG, "FlutterFragment " + this + " connection to the engine " + getFlutterEngine() + " evicted by another attaching activity"); if (delegate != null) { // Redundant calls are ok. delegate.onDestroyView(); delegate.onDetach(); } } @Override public void onDetach() { getContext().unregisterComponentCallbacks(this); super.onDetach(); if (delegate != null) { delegate.onDetach(); delegate.release(); delegate = null; } else { Log.v(TAG, "FlutterFragment " + this + " onDetach called after release."); } } /** * The result of a permission request has been received. * * <p>See {@link android.app.Activity#onRequestPermissionsResult(int, String[], int[])} * * <p> * * @param requestCode identifier passed with the initial permission request * @param permissions permissions that were requested * @param grantResults permission grants or denials */ @ActivityCallThrough public void onRequestPermissionsResult( int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (stillAttachedForEvent("onRequestPermissionsResult")) { delegate.onRequestPermissionsResult(requestCode, permissions, grantResults); } } /** * A new Intent was received by the {@link android.app.Activity} that currently owns this {@link * Fragment}. * * <p>See {@link android.app.Activity#onNewIntent(Intent)} * * <p> * * @param intent new Intent */ @ActivityCallThrough public void onNewIntent(@NonNull Intent intent) { if (stillAttachedForEvent("onNewIntent")) { delegate.onNewIntent(intent); } } /** * The hardware back button was pressed. * * <p>If the fragment uses {@code shouldAutomaticallyHandleOnBackPressed(true)}, this method * should not be called through. It will be called automatically instead. * * <p>See {@link android.app.Activity#onBackPressed()} */ @ActivityCallThrough public void onBackPressed() { if (stillAttachedForEvent("onBackPressed")) { delegate.onBackPressed(); } } /** * A result has been returned after an invocation of {@link * Fragment#startActivityForResult(Intent, int)}. * * <p> * * @param requestCode request code sent with {@link Fragment#startActivityForResult(Intent, int)} * @param resultCode code representing the result of the {@code Activity} that was launched * @param data any corresponding return data, held within an {@code Intent} */ @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (stillAttachedForEvent("onActivityResult")) { delegate.onActivityResult(requestCode, resultCode, data); } } /** * The {@link android.app.Activity} that owns this {@link Fragment} is about to go to the * background as the result of a user's choice/action, i.e., not as the result of an OS decision. * * <p>See {@link android.app.Activity#onUserLeaveHint()} */ @ActivityCallThrough public void onUserLeaveHint() { if (stillAttachedForEvent("onUserLeaveHint")) { delegate.onUserLeaveHint(); } } /** * Callback invoked when memory is low. * * <p>This implementation forwards a memory pressure warning to the running Flutter app. * * <p> * * @param level level */ @Override public void onTrimMemory(int level) { if (stillAttachedForEvent("onTrimMemory")) { delegate.onTrimMemory(level); } } /** * {@link FlutterActivityAndFragmentDelegate.Host} method that is used by {@link * FlutterActivityAndFragmentDelegate} to obtain Flutter shell arguments when initializing * Flutter. */ @Override @NonNull public FlutterShellArgs getFlutterShellArgs() { String[] flutterShellArgsArray = getArguments().getStringArray(ARG_FLUTTER_INITIALIZATION_ARGS); return new FlutterShellArgs( flutterShellArgsArray != null ? flutterShellArgsArray : new String[] {}); } /** * Returns the ID of a statically cached {@link io.flutter.embedding.engine.FlutterEngine} to use * within this {@code FlutterFragment}, or {@code null} if this {@code FlutterFragment} does not * want to use a cached {@link io.flutter.embedding.engine.FlutterEngine}. */ @Nullable @Override public String getCachedEngineId() { return getArguments().getString(ARG_CACHED_ENGINE_ID, null); } /** * Returns the ID of a statically cached {@link io.flutter.embedding.engine.FlutterEngineGroup} to * use within this {@code FlutterFragment}, or {@code null} if this {@code FlutterFragment} does * not want to use a cached {@link io.flutter.embedding.engine.FlutterEngineGroup}. */ @Override @Nullable public String getCachedEngineGroupId() { return getArguments().getString(ARG_CACHED_ENGINE_GROUP_ID, null); } /** * Returns true a {@code FlutterEngine} was explicitly created and injected into the {@code * FlutterFragment} rather than one that was created implicitly in the {@code FlutterFragment}. */ /* package */ boolean isFlutterEngineInjected() { return delegate.isFlutterEngineFromHost(); } /** * Returns false if the {@link io.flutter.embedding.engine.FlutterEngine} within this {@code * FlutterFragment} should outlive the {@code FlutterFragment}, itself. * * <p>Defaults to true if no custom {@link io.flutter.embedding.engine.FlutterEngine is provided}, * false if a custom {@link FlutterEngine} is provided. */ @Override public boolean shouldDestroyEngineWithHost() { boolean explicitDestructionRequested = getArguments().getBoolean(ARG_DESTROY_ENGINE_WITH_FRAGMENT, false); if (getCachedEngineId() != null || delegate.isFlutterEngineFromHost()) { // Only destroy a cached engine if explicitly requested by app developer. return explicitDestructionRequested; } else { // If this Fragment created the FlutterEngine, destroy it by default unless // explicitly requested not to. return getArguments().getBoolean(ARG_DESTROY_ENGINE_WITH_FRAGMENT, true); } } /** * Returns the name of the Dart method that this {@code FlutterFragment} should execute to start a * Flutter app. * * <p>Defaults to "main". * * <p>Used by this {@code FlutterFragment}'s {@link FlutterActivityAndFragmentDelegate.Host} */ @Override @NonNull public String getDartEntrypointFunctionName() { return getArguments().getString(ARG_DART_ENTRYPOINT, "main"); } /** * The Dart entrypoint arguments will be passed as a list of string to Dart's entrypoint function. * * <p>A value of null means do not pass any arguments to Dart's entrypoint function. * * <p>Subclasses may override this method to directly control the Dart entrypoint arguments. */ @Override @Nullable public List<String> getDartEntrypointArgs() { return getArguments().getStringArrayList(ARG_DART_ENTRYPOINT_ARGS); } /** * Returns the library URI of the Dart method that this {@code FlutterFragment} should execute to * start a Flutter app. * * <p>Defaults to null (example value: "package:foo/bar.dart"). * * <p>Used by this {@code FlutterFragment}'s {@link FlutterActivityAndFragmentDelegate.Host} */ @Override @Nullable public String getDartEntrypointLibraryUri() { return getArguments().getString(ARG_DART_ENTRYPOINT_URI); } /** * A custom path to the bundle that contains this Flutter app's resources, e.g., Dart code * snapshots. * * <p>When unspecified, the value is null, which defaults to the app bundle path defined in {@link * io.flutter.embedding.engine.loader.FlutterLoader#findAppBundlePath()}. * * <p>Used by this {@code FlutterFragment}'s {@link FlutterActivityAndFragmentDelegate.Host} */ @Override @NonNull public String getAppBundlePath() { return getArguments().getString(ARG_APP_BUNDLE_PATH); } /** * Returns the initial route that should be rendered within Flutter, once the Flutter app starts. * * <p>Defaults to {@code null}, which signifies a route of "/" in Flutter. * * <p>Used by this {@code FlutterFragment}'s {@link FlutterActivityAndFragmentDelegate.Host} */ @Override @Nullable public String getInitialRoute() { return getArguments().getString(ARG_INITIAL_ROUTE); } /** * Returns the desired {@link RenderMode} for the {@link io.flutter.embedding.android.FlutterView} * displayed in this {@code FlutterFragment}. * * <p>Defaults to {@link RenderMode#surface}. * * <p>Used by this {@code FlutterFragment}'s {@link FlutterActivityAndFragmentDelegate.Host} */ @Override @NonNull public RenderMode getRenderMode() { String renderModeName = getArguments().getString(ARG_FLUTTERVIEW_RENDER_MODE, RenderMode.surface.name()); return RenderMode.valueOf(renderModeName); } /** * Returns the desired {@link TransparencyMode} for the {@link * io.flutter.embedding.android.FlutterView} displayed in this {@code FlutterFragment}. * * <p>Defaults to {@link TransparencyMode#transparent}. * * <p>Used by this {@code FlutterFragment}'s {@link FlutterActivityAndFragmentDelegate.Host} */ @Override @NonNull public TransparencyMode getTransparencyMode() { String transparencyModeName = getArguments() .getString(ARG_FLUTTERVIEW_TRANSPARENCY_MODE, TransparencyMode.transparent.name()); return TransparencyMode.valueOf(transparencyModeName); } /** * Hook for subclasses to return a {@link io.flutter.embedding.engine.FlutterEngine} with whatever * configuration is desired. * * <p>By default this method defers to this {@code FlutterFragment}'s surrounding {@code * Activity}, if that {@code Activity} implements {@link * io.flutter.embedding.android.FlutterEngineProvider}. If this method is overridden, the * surrounding {@code Activity} will no longer be given an opportunity to provide a {@link * io.flutter.embedding.engine.FlutterEngine}, unless the subclass explicitly implements that * behavior. * * <p>Consider returning a cached {@link io.flutter.embedding.engine.FlutterEngine} instance from * this method to avoid the typical warm-up time that a new {@link * io.flutter.embedding.engine.FlutterEngine} instance requires. * * <p>If null is returned then a new default {@link io.flutter.embedding.engine.FlutterEngine} * will be created to back this {@code FlutterFragment}. * * <p>Used by this {@code FlutterFragment}'s {@link FlutterActivityAndFragmentDelegate.Host} */ @Override @Nullable public FlutterEngine provideFlutterEngine(@NonNull Context context) { // Defer to the FragmentActivity that owns us to see if it wants to provide a // FlutterEngine. FlutterEngine flutterEngine = null; FragmentActivity attachedActivity = getActivity(); if (attachedActivity instanceof FlutterEngineProvider) { // Defer to the Activity that owns us to provide a FlutterEngine. Log.v(TAG, "Deferring to attached Activity to provide a FlutterEngine."); FlutterEngineProvider flutterEngineProvider = (FlutterEngineProvider) attachedActivity; flutterEngine = flutterEngineProvider.provideFlutterEngine(getContext()); } return flutterEngine; } /** * Hook for subclasses to obtain a reference to the {@link * io.flutter.embedding.engine.FlutterEngine} that is owned by this {@code FlutterActivity}. */ @Nullable public FlutterEngine getFlutterEngine() { return delegate.getFlutterEngine(); } @Nullable @Override public PlatformPlugin providePlatformPlugin( @Nullable Activity activity, @NonNull FlutterEngine flutterEngine) { if (activity != null) { return new PlatformPlugin(getActivity(), flutterEngine.getPlatformChannel(), this); } else { return null; } } /** * Configures a {@link io.flutter.embedding.engine.FlutterEngine} after its creation. * * <p>This method is called after {@link #provideFlutterEngine(Context)}, and after the given * {@link io.flutter.embedding.engine.FlutterEngine} has been attached to the owning {@code * FragmentActivity}. See {@link * io.flutter.embedding.engine.plugins.activity.ActivityControlSurface#attachToActivity( * ExclusiveAppComponent, Lifecycle)}. * * <p>It is possible that the owning {@code FragmentActivity} opted not to connect itself as an * {@link io.flutter.embedding.engine.plugins.activity.ActivityControlSurface}. In that case, any * configuration, e.g., plugins, must not expect or depend upon an available {@code Activity} at * the time that this method is invoked. * * <p>The default behavior of this method is to defer to the owning {@code FragmentActivity} as a * {@link io.flutter.embedding.android.FlutterEngineConfigurator}. Subclasses can override this * method if the subclass needs to override the {@code FragmentActivity}'s behavior, or add to it. * * <p>Used by this {@code FlutterFragment}'s {@link FlutterActivityAndFragmentDelegate.Host} */ @Override public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) { FragmentActivity attachedActivity = getActivity(); if (attachedActivity instanceof FlutterEngineConfigurator) { ((FlutterEngineConfigurator) attachedActivity).configureFlutterEngine(flutterEngine); } } /** * Hook for the host to cleanup references that were established in {@link * #configureFlutterEngine(FlutterEngine)} before the host is destroyed or detached. * * <p>This method is called in {@link #onDetach()}. */ @Override public void cleanUpFlutterEngine(@NonNull FlutterEngine flutterEngine) { FragmentActivity attachedActivity = getActivity(); if (attachedActivity instanceof FlutterEngineConfigurator) { ((FlutterEngineConfigurator) attachedActivity).cleanUpFlutterEngine(flutterEngine); } } /** * See {@link NewEngineFragmentBuilder#shouldAttachEngineToActivity()} and {@link * CachedEngineFragmentBuilder#shouldAttachEngineToActivity()}. * * <p>Used by this {@code FlutterFragment}'s {@link FlutterActivityAndFragmentDelegate} */ @Override public boolean shouldAttachEngineToActivity() { return getArguments().getBoolean(ARG_SHOULD_ATTACH_ENGINE_TO_ACTIVITY); } /** * Whether to handle the deeplinking from the {@code Intent} automatically if the {@code * getInitialRoute} returns null. */ @Override public boolean shouldHandleDeeplinking() { return getArguments().getBoolean(ARG_HANDLE_DEEPLINKING); } @Override public void onFlutterSurfaceViewCreated(@NonNull FlutterSurfaceView flutterSurfaceView) { // Hook for subclasses. } @Override public void onFlutterTextureViewCreated(@NonNull FlutterTextureView flutterTextureView) { // Hook for subclasses. } /** * Invoked after the {@link io.flutter.embedding.android.FlutterView} within this {@code * FlutterFragment} starts rendering pixels to the screen. * * <p>This method forwards {@code onFlutterUiDisplayed()} to its attached {@code Activity}, if the * attached {@code Activity} implements {@link FlutterUiDisplayListener}. * * <p>Subclasses that override this method must call through to the {@code super} method. * * <p>Used by this {@code FlutterFragment}'s {@link FlutterActivityAndFragmentDelegate.Host} */ @Override public void onFlutterUiDisplayed() { FragmentActivity attachedActivity = getActivity(); if (attachedActivity instanceof FlutterUiDisplayListener) { ((FlutterUiDisplayListener) attachedActivity).onFlutterUiDisplayed(); } } /** * Invoked after the {@link io.flutter.embedding.android.FlutterView} within this {@code * FlutterFragment} stops rendering pixels to the screen. * * <p>This method forwards {@code onFlutterUiNoLongerDisplayed()} to its attached {@code * Activity}, if the attached {@code Activity} implements {@link FlutterUiDisplayListener}. * * <p>Subclasses that override this method must call through to the {@code super} method. * * <p>Used by this {@code FlutterFragment}'s {@link FlutterActivityAndFragmentDelegate.Host} */ @Override public void onFlutterUiNoLongerDisplayed() { FragmentActivity attachedActivity = getActivity(); if (attachedActivity instanceof FlutterUiDisplayListener) { ((FlutterUiDisplayListener) attachedActivity).onFlutterUiNoLongerDisplayed(); } } @Override public boolean shouldRestoreAndSaveState() { if (getArguments().containsKey(ARG_ENABLE_STATE_RESTORATION)) { return getArguments().getBoolean(ARG_ENABLE_STATE_RESTORATION); } if (getCachedEngineId() != null) { return false; } return true; } @Override public void updateSystemUiOverlays() { if (delegate != null) { delegate.updateSystemUiOverlays(); } } /** * Give the host application a chance to take control of the app lifecycle events. * * <p>Return {@code false} means the host application dispatches these app lifecycle events, while * return {@code true} means the engine dispatches these events. * * <p>Defaults to {@code true}. */ @Override public boolean shouldDispatchAppLifecycleState() { return true; } /** * Whether to automatically attach the {@link FlutterView} to the engine. * * <p>Returning {@code false} means that the task of attaching the {@link FlutterView} to the * engine will be taken over by the host application. * * <p>Defaults to {@code true}. */ @Override public boolean attachToEngineAutomatically() { return true; } /** * {@inheritDoc} * * <p>Avoid overriding this method when using {@code * shouldAutomaticallyHandleOnBackPressed(true)}. If you do, you must always {@code return * super.popSystemNavigator()} rather than {@code return false}. Otherwise the navigation behavior * will recurse infinitely between this method and {@link #onBackPressed()}, breaking navigation. */ @Override public boolean popSystemNavigator() { if (getArguments().getBoolean(ARG_SHOULD_AUTOMATICALLY_HANDLE_ON_BACK_PRESSED, false)) { FragmentActivity activity = getActivity(); if (activity != null) { // Unless we disable the callback, the dispatcher call will trigger it. This will then // trigger the fragment's onBackPressed() implementation, which will call through to the // dart side and likely call back through to this method, creating an infinite call loop. onBackPressedCallback.setEnabled(false); activity.getOnBackPressedDispatcher().onBackPressed(); onBackPressedCallback.setEnabled(true); return true; } } // Hook for subclass. No-op if returns false. return false; } @VisibleForTesting @NonNull boolean shouldDelayFirstAndroidViewDraw() { return getArguments().getBoolean(ARG_SHOULD_DELAY_FIRST_ANDROID_VIEW_DRAW); } private boolean stillAttachedForEvent(String event) { if (delegate == null) { Log.w(TAG, "FlutterFragment " + hashCode() + " " + event + " called after release."); return false; } if (!delegate.isAttached()) { Log.w(TAG, "FlutterFragment " + hashCode() + " " + event + " called after detach."); return false; } return true; } /** * Annotates methods in {@code FlutterFragment} that must be called by the containing {@code * Activity}. */ @interface ActivityCallThrough {} }
engine/shell/platform/android/io/flutter/embedding/android/FlutterFragment.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/embedding/android/FlutterFragment.java", "repo_id": "engine", "token_count": 24029 }
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. package io.flutter.embedding.engine; import android.content.Context; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.AssetManager; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import io.flutter.FlutterInjector; import io.flutter.Log; import io.flutter.embedding.engine.dart.DartExecutor; import io.flutter.embedding.engine.dart.DartExecutor.DartEntrypoint; import io.flutter.embedding.engine.deferredcomponents.DeferredComponentManager; import io.flutter.embedding.engine.loader.FlutterLoader; import io.flutter.embedding.engine.plugins.PluginRegistry; import io.flutter.embedding.engine.plugins.activity.ActivityControlSurface; import io.flutter.embedding.engine.plugins.broadcastreceiver.BroadcastReceiverControlSurface; import io.flutter.embedding.engine.plugins.contentprovider.ContentProviderControlSurface; import io.flutter.embedding.engine.plugins.service.ServiceControlSurface; import io.flutter.embedding.engine.plugins.util.GeneratedPluginRegister; import io.flutter.embedding.engine.renderer.FlutterRenderer; import io.flutter.embedding.engine.renderer.RenderSurface; import io.flutter.embedding.engine.systemchannels.AccessibilityChannel; import io.flutter.embedding.engine.systemchannels.DeferredComponentChannel; import io.flutter.embedding.engine.systemchannels.LifecycleChannel; import io.flutter.embedding.engine.systemchannels.LocalizationChannel; import io.flutter.embedding.engine.systemchannels.MouseCursorChannel; import io.flutter.embedding.engine.systemchannels.NavigationChannel; import io.flutter.embedding.engine.systemchannels.PlatformChannel; import io.flutter.embedding.engine.systemchannels.ProcessTextChannel; import io.flutter.embedding.engine.systemchannels.RestorationChannel; import io.flutter.embedding.engine.systemchannels.SettingsChannel; import io.flutter.embedding.engine.systemchannels.SpellCheckChannel; import io.flutter.embedding.engine.systemchannels.SystemChannel; import io.flutter.embedding.engine.systemchannels.TextInputChannel; import io.flutter.plugin.localization.LocalizationPlugin; import io.flutter.plugin.platform.PlatformViewsController; import io.flutter.plugin.text.ProcessTextPlugin; import io.flutter.util.ViewUtils; import java.util.HashSet; import java.util.List; import java.util.Set; /** * A single Flutter execution environment. * * <p>The {@code FlutterEngine} is the container through which Dart code can be run in an Android * application. * * <p>Dart code in a {@code FlutterEngine} can execute in the background, or it can be render to the * screen by using the accompanying {@link FlutterRenderer} and Dart code using the Flutter * framework on the Dart side. Rendering can be started and stopped, thus allowing a {@code * FlutterEngine} to move from UI interaction to data-only processing and then back to UI * interaction. * * <p>Multiple {@code FlutterEngine}s may exist, execute Dart code, and render UIs within a single * Android app. For better memory performance characteristics, construct multiple {@code * FlutterEngine}s via {@link io.flutter.embedding.engine.FlutterEngineGroup} rather than via {@code * FlutterEngine}'s constructor directly. * * <p>To start running Dart and/or Flutter within this {@code FlutterEngine}, get a reference to * this engine's {@link DartExecutor} and then use {@link * DartExecutor#executeDartEntrypoint(DartExecutor.DartEntrypoint)}. The {@link * DartExecutor#executeDartEntrypoint(DartExecutor.DartEntrypoint)} method must not be invoked twice * on the same {@code FlutterEngine}. * * <p>To start rendering Flutter content to the screen, use {@link #getRenderer()} to obtain a * {@link FlutterRenderer} and then attach a {@link RenderSurface}. Consider using a {@link * io.flutter.embedding.android.FlutterView} as a {@link RenderSurface}. * * <p>Instatiating the first {@code FlutterEngine} per process will also load the Flutter engine's * native library and start the Dart VM. Subsequent {@code FlutterEngine}s will run on the same VM * instance but will have their own Dart <a * href="https://api.dartlang.org/stable/dart-isolate/Isolate-class.html">Isolate</a> when the * {@link DartExecutor} is run. Each Isolate is a self-contained Dart environment and cannot * communicate with each other except via Isolate ports. */ public class FlutterEngine implements ViewUtils.DisplayUpdater { private static final String TAG = "FlutterEngine"; @NonNull private final FlutterJNI flutterJNI; @NonNull private final FlutterRenderer renderer; @NonNull private final DartExecutor dartExecutor; @NonNull private final FlutterEngineConnectionRegistry pluginRegistry; @NonNull private final LocalizationPlugin localizationPlugin; // System channels. @NonNull private final AccessibilityChannel accessibilityChannel; @NonNull private final DeferredComponentChannel deferredComponentChannel; @NonNull private final LifecycleChannel lifecycleChannel; @NonNull private final LocalizationChannel localizationChannel; @NonNull private final MouseCursorChannel mouseCursorChannel; @NonNull private final NavigationChannel navigationChannel; @NonNull private final RestorationChannel restorationChannel; @NonNull private final PlatformChannel platformChannel; @NonNull private final ProcessTextChannel processTextChannel; @NonNull private final SettingsChannel settingsChannel; @NonNull private final SpellCheckChannel spellCheckChannel; @NonNull private final SystemChannel systemChannel; @NonNull private final TextInputChannel textInputChannel; // Platform Views. @NonNull private final PlatformViewsController platformViewsController; // Engine Lifecycle. @NonNull private final Set<EngineLifecycleListener> engineLifecycleListeners = new HashSet<>(); @NonNull private final EngineLifecycleListener engineLifecycleListener = new EngineLifecycleListener() { @SuppressWarnings("unused") public void onPreEngineRestart() { Log.v(TAG, "onPreEngineRestart()"); for (EngineLifecycleListener lifecycleListener : engineLifecycleListeners) { lifecycleListener.onPreEngineRestart(); } platformViewsController.onPreEngineRestart(); restorationChannel.clearData(); } @Override public void onEngineWillDestroy() { // This inner implementation doesn't do anything since FlutterEngine sent this // notification in the first place. It's meant for external listeners. } }; /** * Constructs a new {@code FlutterEngine}. * * <p>A new {@code FlutterEngine} does not execute any Dart code automatically. See {@link * #getDartExecutor()} and {@link DartExecutor#executeDartEntrypoint(DartExecutor.DartEntrypoint)} * to begin executing Dart code within this {@code FlutterEngine}. * * <p>A new {@code FlutterEngine} will not display any UI until a {@link RenderSurface} is * registered. See {@link #getRenderer()} and {@link * FlutterRenderer#startRenderingToSurface(Surface, boolean)}. * * <p>A new {@code FlutterEngine} automatically attaches all plugins. See {@link #getPlugins()}. * * <p>A new {@code FlutterEngine} does come with all default system channels attached. * * <p>The first {@code FlutterEngine} instance constructed per process will also load the Flutter * native library and start a Dart VM. * * <p>In order to pass Dart VM initialization arguments (see {@link * io.flutter.embedding.engine.FlutterShellArgs}) when creating the VM, manually set the * initialization arguments by calling {@link * io.flutter.embedding.engine.loader.FlutterLoader#startInitialization(Context)} and {@link * io.flutter.embedding.engine.loader.FlutterLoader#ensureInitializationComplete(Context, * String[])} before constructing the engine. */ public FlutterEngine(@NonNull Context context) { this(context, null); } /** * Same as {@link #FlutterEngine(Context)} with added support for passing Dart VM arguments. * * <p>If the Dart VM has already started, the given arguments will have no effect. */ public FlutterEngine(@NonNull Context context, @Nullable String[] dartVmArgs) { this(context, /* flutterLoader */ null, /* flutterJNI */ null, dartVmArgs, true); } /** * Same as {@link #FlutterEngine(Context)} with added support for passing Dart VM arguments and * avoiding automatic plugin registration. * * <p>If the Dart VM has already started, the given arguments will have no effect. */ public FlutterEngine( @NonNull Context context, @Nullable String[] dartVmArgs, boolean automaticallyRegisterPlugins) { this( context, /* flutterLoader */ null, /* flutterJNI */ null, dartVmArgs, automaticallyRegisterPlugins); } /** * Same as {@link #FlutterEngine(Context, String[], boolean)} with added support for configuring * whether the engine will receive restoration data. * * <p>The {@code waitForRestorationData} flag controls whether the engine delays responding to * requests from the framework for restoration data until that data has been provided to the * engine via {@code RestorationChannel.setRestorationData(byte[] data)}. If the flag is false, * the framework may temporarily initialize itself to default values before the restoration data * has been made available to the engine. Setting {@code waitForRestorationData} to true avoids * this extra work by delaying initialization until the data is available. * * <p>When {@code waitForRestorationData} is set, {@code * RestorationChannel.setRestorationData(byte[] data)} must be called at a later point in time. If * it later turns out that no restoration data is available to restore the framework from, that * method must still be called with null as an argument to indicate "no data". * * <p>If the framework never requests the restoration data, this flag has no effect. */ public FlutterEngine( @NonNull Context context, @Nullable String[] dartVmArgs, boolean automaticallyRegisterPlugins, boolean waitForRestorationData) { this( context, /* flutterLoader */ null, /* flutterJNI */ null, new PlatformViewsController(), dartVmArgs, automaticallyRegisterPlugins, waitForRestorationData); } /** * Same as {@link #FlutterEngine(Context, FlutterLoader, FlutterJNI, String[], boolean)} but with * no Dart VM flags and automatically registers plugins. * * <p>{@code flutterJNI} should be a new instance that has never been attached to an engine * before. */ public FlutterEngine( @NonNull Context context, @Nullable FlutterLoader flutterLoader, @NonNull FlutterJNI flutterJNI) { this(context, flutterLoader, flutterJNI, null, true); } /** * Same as {@link #FlutterEngine(Context, FlutterLoader, FlutterJNI)}, plus Dart VM flags in * {@code dartVmArgs}, and control over whether plugins are automatically registered with this * {@code FlutterEngine} in {@code automaticallyRegisterPlugins}. If plugins are automatically * registered, then they are registered during the execution of this constructor. */ public FlutterEngine( @NonNull Context context, @Nullable FlutterLoader flutterLoader, @NonNull FlutterJNI flutterJNI, @Nullable String[] dartVmArgs, boolean automaticallyRegisterPlugins) { this( context, flutterLoader, flutterJNI, new PlatformViewsController(), dartVmArgs, automaticallyRegisterPlugins); } /** * Same as {@link #FlutterEngine(Context, FlutterLoader, FlutterJNI, String[], boolean)}, plus the * ability to provide a custom {@code PlatformViewsController}. */ public FlutterEngine( @NonNull Context context, @Nullable FlutterLoader flutterLoader, @NonNull FlutterJNI flutterJNI, @NonNull PlatformViewsController platformViewsController, @Nullable String[] dartVmArgs, boolean automaticallyRegisterPlugins) { this( context, flutterLoader, flutterJNI, platformViewsController, dartVmArgs, automaticallyRegisterPlugins, false); } /** Fully configurable {@code FlutterEngine} constructor. */ public FlutterEngine( @NonNull Context context, @Nullable FlutterLoader flutterLoader, @NonNull FlutterJNI flutterJNI, @NonNull PlatformViewsController platformViewsController, @Nullable String[] dartVmArgs, boolean automaticallyRegisterPlugins, boolean waitForRestorationData) { this( context, flutterLoader, flutterJNI, platformViewsController, dartVmArgs, automaticallyRegisterPlugins, waitForRestorationData, null); } @VisibleForTesting(otherwise = VisibleForTesting.PACKAGE_PRIVATE) public FlutterEngine( @NonNull Context context, @Nullable FlutterLoader flutterLoader, @NonNull FlutterJNI flutterJNI, @NonNull PlatformViewsController platformViewsController, @Nullable String[] dartVmArgs, boolean automaticallyRegisterPlugins, boolean waitForRestorationData, @Nullable FlutterEngineGroup group) { AssetManager assetManager; try { assetManager = context.createPackageContext(context.getPackageName(), 0).getAssets(); } catch (NameNotFoundException e) { assetManager = context.getAssets(); } FlutterInjector injector = FlutterInjector.instance(); if (flutterJNI == null) { flutterJNI = injector.getFlutterJNIFactory().provideFlutterJNI(); } this.flutterJNI = flutterJNI; this.dartExecutor = new DartExecutor(flutterJNI, assetManager); this.dartExecutor.onAttachedToJNI(); DeferredComponentManager deferredComponentManager = FlutterInjector.instance().deferredComponentManager(); accessibilityChannel = new AccessibilityChannel(dartExecutor, flutterJNI); deferredComponentChannel = new DeferredComponentChannel(dartExecutor); lifecycleChannel = new LifecycleChannel(dartExecutor); localizationChannel = new LocalizationChannel(dartExecutor); mouseCursorChannel = new MouseCursorChannel(dartExecutor); navigationChannel = new NavigationChannel(dartExecutor); platformChannel = new PlatformChannel(dartExecutor); processTextChannel = new ProcessTextChannel(dartExecutor, context.getPackageManager()); restorationChannel = new RestorationChannel(dartExecutor, waitForRestorationData); settingsChannel = new SettingsChannel(dartExecutor); spellCheckChannel = new SpellCheckChannel(dartExecutor); systemChannel = new SystemChannel(dartExecutor); textInputChannel = new TextInputChannel(dartExecutor); if (deferredComponentManager != null) { deferredComponentManager.setDeferredComponentChannel(deferredComponentChannel); } this.localizationPlugin = new LocalizationPlugin(context, localizationChannel); if (flutterLoader == null) { flutterLoader = injector.flutterLoader(); } if (!flutterJNI.isAttached()) { flutterLoader.startInitialization(context.getApplicationContext()); flutterLoader.ensureInitializationComplete(context, dartVmArgs); } flutterJNI.addEngineLifecycleListener(engineLifecycleListener); flutterJNI.setPlatformViewsController(platformViewsController); flutterJNI.setLocalizationPlugin(localizationPlugin); flutterJNI.setDeferredComponentManager(injector.deferredComponentManager()); // It should typically be a fresh, unattached JNI. But on a spawned engine, the JNI instance // is already attached to a native shell. In that case, the Java FlutterEngine is created around // an existing shell. if (!flutterJNI.isAttached()) { attachToJni(); } // TODO(mattcarroll): FlutterRenderer is temporally coupled to attach(). Remove that coupling if // possible. this.renderer = new FlutterRenderer(flutterJNI); this.platformViewsController = platformViewsController; this.platformViewsController.onAttachedToJNI(); this.pluginRegistry = new FlutterEngineConnectionRegistry( context.getApplicationContext(), this, flutterLoader, group); localizationPlugin.sendLocalesToFlutter(context.getResources().getConfiguration()); // Only automatically register plugins if both constructor parameter and // loaded AndroidManifest config turn this feature on. if (automaticallyRegisterPlugins && flutterLoader.automaticallyRegisterPlugins()) { GeneratedPluginRegister.registerGeneratedPlugins(this); } ViewUtils.calculateMaximumDisplayMetrics(context, this); ProcessTextPlugin processTextPlugin = new ProcessTextPlugin(this.getProcessTextChannel()); this.pluginRegistry.add(processTextPlugin); } private void attachToJni() { Log.v(TAG, "Attaching to JNI."); flutterJNI.attachToNative(); if (!isAttachedToJni()) { throw new RuntimeException("FlutterEngine failed to attach to its native Object reference."); } } @SuppressWarnings("BooleanMethodIsAlwaysInverted") private boolean isAttachedToJni() { return flutterJNI.isAttached(); } /** * Create a second {@link io.flutter.embedding.engine.FlutterEngine} based on this current one by * sharing as much resources together as possible to minimize startup latency and memory cost. * * @param context is a Context used to create the {@link * io.flutter.embedding.engine.FlutterEngine}. Could be the same Context as the current engine * or a different one. Generally, only an application Context is needed for the {@link * io.flutter.embedding.engine.FlutterEngine} and its dependencies. * @param dartEntrypoint specifies the {@link DartEntrypoint} the new engine should run. It * doesn't need to be the same entrypoint as the current engine but must be built in the same * AOT or snapshot. * @param initialRoute The name of the initial Flutter `Navigator` `Route` to load. If this is * null, it will default to the "/" route. * @param dartEntrypointArgs Arguments passed as a list of string to Dart's entrypoint function. * @return a new {@link io.flutter.embedding.engine.FlutterEngine}. */ @NonNull /*package*/ FlutterEngine spawn( @NonNull Context context, @NonNull DartEntrypoint dartEntrypoint, @Nullable String initialRoute, @Nullable List<String> dartEntrypointArgs, @Nullable PlatformViewsController platformViewsController, boolean automaticallyRegisterPlugins, boolean waitForRestorationData) { if (!isAttachedToJni()) { throw new IllegalStateException( "Spawn can only be called on a fully constructed FlutterEngine"); } FlutterJNI newFlutterJNI = flutterJNI.spawn( dartEntrypoint.dartEntrypointFunctionName, dartEntrypoint.dartEntrypointLibrary, initialRoute, dartEntrypointArgs); return new FlutterEngine( context, // Context. null, // FlutterLoader. A null value passed here causes the constructor to get it from the // FlutterInjector. newFlutterJNI, // FlutterJNI. platformViewsController, // PlatformViewsController. null, // String[]. The Dart VM has already started, this arguments will have no effect. automaticallyRegisterPlugins, // boolean. waitForRestorationData); // boolean } /** * Cleans up all components within this {@code FlutterEngine} and destroys the associated Dart * Isolate. All state held by the Dart Isolate, such as the Flutter Elements tree, is lost. * * <p>This {@code FlutterEngine} instance should be discarded after invoking this method. */ public void destroy() { Log.v(TAG, "Destroying."); for (EngineLifecycleListener listener : engineLifecycleListeners) { listener.onEngineWillDestroy(); } // The order that these things are destroyed is important. pluginRegistry.destroy(); platformViewsController.onDetachedFromJNI(); dartExecutor.onDetachedFromJNI(); flutterJNI.removeEngineLifecycleListener(engineLifecycleListener); flutterJNI.setDeferredComponentManager(null); flutterJNI.detachFromNativeAndReleaseResources(); if (FlutterInjector.instance().deferredComponentManager() != null) { FlutterInjector.instance().deferredComponentManager().destroy(); deferredComponentChannel.setDeferredComponentManager(null); } } /** * Adds a {@code listener} to be notified of Flutter engine lifecycle events, e.g., {@code * onPreEngineStart()}. */ public void addEngineLifecycleListener(@NonNull EngineLifecycleListener listener) { engineLifecycleListeners.add(listener); } /** * Removes a {@code listener} that was previously added with {@link * #addEngineLifecycleListener(EngineLifecycleListener)}. */ public void removeEngineLifecycleListener(@NonNull EngineLifecycleListener listener) { engineLifecycleListeners.remove(listener); } /** * The Dart execution context associated with this {@code FlutterEngine}. * * <p>The {@link DartExecutor} can be used to start executing Dart code from a given entrypoint. * See {@link DartExecutor#executeDartEntrypoint(DartExecutor.DartEntrypoint)}. * * <p>Use the {@link DartExecutor} to connect any desired message channels and method channels to * facilitate communication between Android and Dart/Flutter. */ @NonNull public DartExecutor getDartExecutor() { return dartExecutor; } /** * The rendering system associated with this {@code FlutterEngine}. * * <p>To render a Flutter UI that is produced by this {@code FlutterEngine}'s Dart code, attach a * {@link RenderSurface} to this {@link FlutterRenderer}. */ @NonNull public FlutterRenderer getRenderer() { return renderer; } /** System channel that sends accessibility requests and events from Flutter to Android. */ @NonNull public AccessibilityChannel getAccessibilityChannel() { return accessibilityChannel; } /** System channel that sends Android lifecycle events to Flutter. */ @NonNull public LifecycleChannel getLifecycleChannel() { return lifecycleChannel; } /** System channel that sends locale data from Android to Flutter. */ @NonNull public LocalizationChannel getLocalizationChannel() { return localizationChannel; } /** System channel that sends Flutter navigation commands from Android to Flutter. */ @NonNull public NavigationChannel getNavigationChannel() { return navigationChannel; } /** * System channel that sends platform-oriented requests and information to Flutter, e.g., requests * to play sounds, requests for haptics, system chrome settings, etc. */ @NonNull public PlatformChannel getPlatformChannel() { return platformChannel; } /** System channel that sends text processing requests from Flutter to Android. */ @NonNull public ProcessTextChannel getProcessTextChannel() { return processTextChannel; } /** * System channel to exchange restoration data between framework and engine. * * <p>The engine can obtain the current restoration data from the framework via this channel to * store it on disk and - when the app is relaunched - provide the stored data back to the * framework to recreate the original state of the app. */ @NonNull public RestorationChannel getRestorationChannel() { return restorationChannel; } /** * System channel that sends platform/user settings from Android to Flutter, e.g., time format, * scale factor, etc. */ @NonNull public SettingsChannel getSettingsChannel() { return settingsChannel; } /** System channel that allows manual installation and state querying of deferred components. */ @NonNull public DeferredComponentChannel getDeferredComponentChannel() { return deferredComponentChannel; } /** System channel that sends memory pressure warnings from Android to Flutter. */ @NonNull public SystemChannel getSystemChannel() { return systemChannel; } /** System channel that sends and receives text input requests and state. */ @NonNull public MouseCursorChannel getMouseCursorChannel() { return mouseCursorChannel; } /** System channel that sends and receives text input requests and state. */ @NonNull public TextInputChannel getTextInputChannel() { return textInputChannel; } /** System channel that sends and receives spell check requests and results. */ @NonNull public SpellCheckChannel getSpellCheckChannel() { return spellCheckChannel; } /** * Plugin registry, which registers plugins that want to be applied to this {@code FlutterEngine}. */ @NonNull public PluginRegistry getPlugins() { return pluginRegistry; } /** The LocalizationPlugin this FlutterEngine created. */ @NonNull public LocalizationPlugin getLocalizationPlugin() { return localizationPlugin; } /** * {@code PlatformViewsController}, which controls all platform views running within this {@code * FlutterEngine}. */ @NonNull public PlatformViewsController getPlatformViewsController() { return platformViewsController; } @NonNull public ActivityControlSurface getActivityControlSurface() { return pluginRegistry; } @NonNull public ServiceControlSurface getServiceControlSurface() { return pluginRegistry; } @NonNull public BroadcastReceiverControlSurface getBroadcastReceiverControlSurface() { return pluginRegistry; } @NonNull public ContentProviderControlSurface getContentProviderControlSurface() { return pluginRegistry; } /** Lifecycle callbacks for Flutter engine lifecycle events. */ public interface EngineLifecycleListener { /** Lifecycle callback invoked before a hot restart of the Flutter engine. */ void onPreEngineRestart(); /** * Lifecycle callback invoked before the Flutter engine is destroyed. * * <p>For the duration of the call, the Flutter engine is still valid. */ void onEngineWillDestroy(); } @Override public void updateDisplayMetrics(float width, float height, float density) { flutterJNI.updateDisplayMetrics(0 /* display ID */, width, height, density); } }
engine/shell/platform/android/io/flutter/embedding/engine/FlutterEngine.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/embedding/engine/FlutterEngine.java", "repo_id": "engine", "token_count": 8249 }
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. package io.flutter.embedding.engine.loader; import static io.flutter.Build.API_LEVELS; import android.app.ActivityManager; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.res.AssetManager; import android.hardware.display.DisplayManager; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.SystemClock; import android.util.DisplayMetrics; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.flutter.BuildConfig; import io.flutter.FlutterInjector; import io.flutter.Log; import io.flutter.embedding.engine.FlutterJNI; import io.flutter.util.HandlerCompat; import io.flutter.util.PathUtils; import io.flutter.util.TraceSection; import io.flutter.view.VsyncWaiter; import java.io.File; import java.util.*; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; /** Finds Flutter resources in an application APK and also loads Flutter's native library. */ public class FlutterLoader { private static final String TAG = "FlutterLoader"; private static final String OLD_GEN_HEAP_SIZE_META_DATA_KEY = "io.flutter.embedding.android.OldGenHeapSize"; private static final String ENABLE_IMPELLER_META_DATA_KEY = "io.flutter.embedding.android.EnableImpeller"; private static final String ENABLE_VULKAN_VALIDATION_META_DATA_KEY = "io.flutter.embedding.android.EnableVulkanValidation"; private static final String IMPELLER_BACKEND_META_DATA_KEY = "io.flutter.embedding.android.ImpellerBackend"; private static final String IMPELLER_OPENGL_GPU_TRACING_DATA_KEY = "io.flutter.embedding.android.EnableOpenGLGPUTracing"; private static final String IMPELLER_VULKAN_GPU_TRACING_DATA_KEY = "io.flutter.embedding.android.EnableVulkanGPUTracing"; /** * Set whether leave or clean up the VM after the last shell shuts down. It can be set from app's * meta-data in <application /> in AndroidManifest.xml. Set it to true in to leave the Dart VM, * set it to false to destroy VM. * * <p>If your want to let your app destroy the last shell and re-create shells more quickly, set * it to true, otherwise if you want to clean up the memory of the leak VM, set it to false. * * <p>TODO(eggfly): Should it be set to false by default? * https://github.com/flutter/flutter/issues/96843 */ private static final String LEAK_VM_META_DATA_KEY = "io.flutter.embedding.android.LeakVM"; // Must match values in flutter::switches static final String AOT_SHARED_LIBRARY_NAME = "aot-shared-library-name"; static final String AOT_VMSERVICE_SHARED_LIBRARY_NAME = "aot-vmservice-shared-library-name"; static final String SNAPSHOT_ASSET_PATH_KEY = "snapshot-asset-path"; static final String VM_SNAPSHOT_DATA_KEY = "vm-snapshot-data"; static final String ISOLATE_SNAPSHOT_DATA_KEY = "isolate-snapshot-data"; static final String FLUTTER_ASSETS_DIR_KEY = "flutter-assets-dir"; static final String AUTOMATICALLY_REGISTER_PLUGINS_KEY = "automatically-register-plugins"; // Resource names used for components of the precompiled snapshot. private static final String DEFAULT_LIBRARY = "libflutter.so"; private static final String DEFAULT_KERNEL_BLOB = "kernel_blob.bin"; private static final String VMSERVICE_SNAPSHOT_LIBRARY = "libvmservice_snapshot.so"; private static FlutterLoader instance; /** * Creates a {@code FlutterLoader} that uses a default constructed {@link FlutterJNI} and {@link * ExecutorService}. */ public FlutterLoader() { this(FlutterInjector.instance().getFlutterJNIFactory().provideFlutterJNI()); } /** * Creates a {@code FlutterLoader} that uses a default constructed {@link ExecutorService}. * * @param flutterJNI The {@link FlutterJNI} instance to use for loading the libflutter.so C++ * library, setting up the font manager, and calling into C++ initialization. */ public FlutterLoader(@NonNull FlutterJNI flutterJNI) { this(flutterJNI, FlutterInjector.instance().executorService()); } /** * Creates a {@code FlutterLoader} with the specified {@link FlutterJNI}. * * @param flutterJNI The {@link FlutterJNI} instance to use for loading the libflutter.so C++ * library, setting up the font manager, and calling into C++ initialization. * @param executorService The {@link ExecutorService} to use when creating new threads. */ public FlutterLoader(@NonNull FlutterJNI flutterJNI, @NonNull ExecutorService executorService) { this.flutterJNI = flutterJNI; this.executorService = executorService; } private boolean initialized = false; @Nullable private Settings settings; private long initStartTimestampMillis; private FlutterApplicationInfo flutterApplicationInfo; private FlutterJNI flutterJNI; private ExecutorService executorService; private static class InitResult { final String appStoragePath; final String engineCachesPath; final String dataDirPath; private InitResult(String appStoragePath, String engineCachesPath, String dataDirPath) { this.appStoragePath = appStoragePath; this.engineCachesPath = engineCachesPath; this.dataDirPath = dataDirPath; } } @Nullable Future<InitResult> initResultFuture; /** * Starts initialization of the native system. * * @param applicationContext The Android application context. */ public void startInitialization(@NonNull Context applicationContext) { startInitialization(applicationContext, new Settings()); } /** * Starts initialization of the native system. * * <p>This loads the Flutter engine's native library to enable subsequent JNI calls. This also * starts locating and unpacking Dart resources packaged in the app's APK. * * <p>Calling this method multiple times has no effect. * * @param applicationContext The Android application context. * @param settings Configuration settings. */ public void startInitialization(@NonNull Context applicationContext, @NonNull Settings settings) { // Do not run startInitialization more than once. if (this.settings != null) { return; } if (Looper.myLooper() != Looper.getMainLooper()) { throw new IllegalStateException("startInitialization must be called on the main thread"); } try (TraceSection e = TraceSection.scoped("FlutterLoader#startInitialization")) { // Ensure that the context is actually the application context. final Context appContext = applicationContext.getApplicationContext(); this.settings = settings; initStartTimestampMillis = SystemClock.uptimeMillis(); flutterApplicationInfo = ApplicationInfoLoader.load(appContext); final DisplayManager dm = (DisplayManager) appContext.getSystemService(Context.DISPLAY_SERVICE); VsyncWaiter waiter = VsyncWaiter.getInstance(dm, flutterJNI); waiter.init(); // Use a background thread for initialization tasks that require disk access. Callable<InitResult> initTask = new Callable<InitResult>() { @Override public InitResult call() { try (TraceSection e = TraceSection.scoped("FlutterLoader initTask")) { ResourceExtractor resourceExtractor = initResources(appContext); try { flutterJNI.loadLibrary(); } catch (UnsatisfiedLinkError unsatisfiedLinkError) { String couldntFindVersion = "couldn't find \"libflutter.so\""; String notFoundVersion = "dlopen failed: library \"libflutter.so\" not found"; if (unsatisfiedLinkError.toString().contains(couldntFindVersion) || unsatisfiedLinkError.toString().contains(notFoundVersion)) { // To gather more information for // https://github.com/flutter/flutter/issues/144291, // log the contents of the native libraries directory as well as the // cpu architecture. String cpuArch = System.getProperty("os.arch"); File nativeLibsDir = new File(flutterApplicationInfo.nativeLibraryDir); String[] nativeLibsContents = nativeLibsDir.list(); throw new UnsupportedOperationException( "Could not load libflutter.so this is possibly because the application" + " is running on an architecture that Flutter Android does not support (e.g. x86)" + " see https://docs.flutter.dev/deployment/android#what-are-the-supported-target-architectures" + " for more detail.\n" + "App is using cpu architecture: " + cpuArch + ", and the native libraries directory (with path " + nativeLibsDir.getAbsolutePath() + ") contains the following files: " + Arrays.toString(nativeLibsContents), unsatisfiedLinkError); } throw unsatisfiedLinkError; } flutterJNI.updateRefreshRate(); // Prefetch the default font manager as soon as possible on a background thread. // It helps to reduce time cost of engine setup that blocks the platform thread. executorService.execute(() -> flutterJNI.prefetchDefaultFontManager()); if (resourceExtractor != null) { resourceExtractor.waitForCompletion(); } return new InitResult( PathUtils.getFilesDir(appContext), PathUtils.getCacheDirectory(appContext), PathUtils.getDataDirectory(appContext)); } } }; initResultFuture = executorService.submit(initTask); } } private static boolean areValidationLayersOnByDefault() { if (BuildConfig.DEBUG && Build.VERSION.SDK_INT >= API_LEVELS.API_26) { return Build.SUPPORTED_ABIS[0].equals("arm64-v8a"); } return false; } /** * Blocks until initialization of the native system has completed. * * <p>Calling this method multiple times has no effect. * * @param applicationContext The Android application context. * @param args Flags sent to the Flutter runtime. */ public void ensureInitializationComplete( @NonNull Context applicationContext, @Nullable String[] args) { if (initialized) { return; } if (Looper.myLooper() != Looper.getMainLooper()) { throw new IllegalStateException( "ensureInitializationComplete must be called on the main thread"); } if (settings == null) { throw new IllegalStateException( "ensureInitializationComplete must be called after startInitialization"); } try (TraceSection e = TraceSection.scoped("FlutterLoader#ensureInitializationComplete")) { InitResult result = initResultFuture.get(); List<String> shellArgs = new ArrayList<>(); shellArgs.add("--icu-symbol-prefix=_binary_icudtl_dat"); shellArgs.add( "--icu-native-lib-path=" + flutterApplicationInfo.nativeLibraryDir + File.separator + DEFAULT_LIBRARY); if (args != null) { Collections.addAll(shellArgs, args); } String kernelPath = null; if (BuildConfig.DEBUG || BuildConfig.JIT_RELEASE) { String snapshotAssetPath = result.dataDirPath + File.separator + flutterApplicationInfo.flutterAssetsDir; kernelPath = snapshotAssetPath + File.separator + DEFAULT_KERNEL_BLOB; shellArgs.add("--" + SNAPSHOT_ASSET_PATH_KEY + "=" + snapshotAssetPath); shellArgs.add("--" + VM_SNAPSHOT_DATA_KEY + "=" + flutterApplicationInfo.vmSnapshotData); shellArgs.add( "--" + ISOLATE_SNAPSHOT_DATA_KEY + "=" + flutterApplicationInfo.isolateSnapshotData); } else { shellArgs.add( "--" + AOT_SHARED_LIBRARY_NAME + "=" + flutterApplicationInfo.aotSharedLibraryName); // Most devices can load the AOT shared library based on the library name // with no directory path. Provide a fully qualified path to the library // as a workaround for devices where that fails. shellArgs.add( "--" + AOT_SHARED_LIBRARY_NAME + "=" + flutterApplicationInfo.nativeLibraryDir + File.separator + flutterApplicationInfo.aotSharedLibraryName); // In profile mode, provide a separate library containing a snapshot for // launching the Dart VM service isolate. if (BuildConfig.PROFILE) { shellArgs.add( "--" + AOT_VMSERVICE_SHARED_LIBRARY_NAME + "=" + VMSERVICE_SNAPSHOT_LIBRARY); } } shellArgs.add("--cache-dir-path=" + result.engineCachesPath); if (flutterApplicationInfo.domainNetworkPolicy != null) { shellArgs.add("--domain-network-policy=" + flutterApplicationInfo.domainNetworkPolicy); } if (settings.getLogTag() != null) { shellArgs.add("--log-tag=" + settings.getLogTag()); } ApplicationInfo applicationInfo = applicationContext .getPackageManager() .getApplicationInfo( applicationContext.getPackageName(), PackageManager.GET_META_DATA); Bundle metaData = applicationInfo.metaData; int oldGenHeapSizeMegaBytes = metaData != null ? metaData.getInt(OLD_GEN_HEAP_SIZE_META_DATA_KEY) : 0; if (oldGenHeapSizeMegaBytes == 0) { // default to half of total memory. ActivityManager activityManager = (ActivityManager) applicationContext.getSystemService(Context.ACTIVITY_SERVICE); ActivityManager.MemoryInfo memInfo = new ActivityManager.MemoryInfo(); activityManager.getMemoryInfo(memInfo); oldGenHeapSizeMegaBytes = (int) (memInfo.totalMem / 1e6 / 2); } shellArgs.add("--old-gen-heap-size=" + oldGenHeapSizeMegaBytes); DisplayMetrics displayMetrics = applicationContext.getResources().getDisplayMetrics(); int screenWidth = displayMetrics.widthPixels; int screenHeight = displayMetrics.heightPixels; // This is the formula Android uses. // https://android.googlesource.com/platform/frameworks/base/+/39ae5bac216757bc201490f4c7b8c0f63006c6cd/libs/hwui/renderthread/CacheManager.cpp#45 int resourceCacheMaxBytesThreshold = screenWidth * screenHeight * 12 * 4; shellArgs.add("--resource-cache-max-bytes-threshold=" + resourceCacheMaxBytesThreshold); shellArgs.add("--prefetched-default-font-manager"); if (metaData != null) { if (metaData.getBoolean(ENABLE_IMPELLER_META_DATA_KEY, false)) { shellArgs.add("--enable-impeller"); } if (metaData.getBoolean( ENABLE_VULKAN_VALIDATION_META_DATA_KEY, areValidationLayersOnByDefault())) { shellArgs.add("--enable-vulkan-validation"); } if (metaData.getBoolean(IMPELLER_OPENGL_GPU_TRACING_DATA_KEY, false)) { shellArgs.add("--enable-opengl-gpu-tracing"); } if (metaData.getBoolean(IMPELLER_VULKAN_GPU_TRACING_DATA_KEY, false)) { shellArgs.add("--enable-vulkan-gpu-tracing"); } String backend = metaData.getString(IMPELLER_BACKEND_META_DATA_KEY); if (backend != null) { shellArgs.add("--impeller-backend=" + backend); } } final String leakVM = isLeakVM(metaData) ? "true" : "false"; shellArgs.add("--leak-vm=" + leakVM); long initTimeMillis = SystemClock.uptimeMillis() - initStartTimestampMillis; flutterJNI.init( applicationContext, shellArgs.toArray(new String[0]), kernelPath, result.appStoragePath, result.engineCachesPath, initTimeMillis); initialized = true; } catch (Exception e) { Log.e(TAG, "Flutter initialization failed.", e); throw new RuntimeException(e); } } private static boolean isLeakVM(@Nullable Bundle metaData) { final boolean leakVMDefaultValue = true; if (metaData == null) { return leakVMDefaultValue; } return metaData.getBoolean(LEAK_VM_META_DATA_KEY, leakVMDefaultValue); } /** * Same as {@link #ensureInitializationComplete(Context, String[])} but waiting on a background * thread, then invoking {@code callback} on the {@code callbackHandler}. */ public void ensureInitializationCompleteAsync( @NonNull Context applicationContext, @Nullable String[] args, @NonNull Handler callbackHandler, @NonNull Runnable callback) { if (Looper.myLooper() != Looper.getMainLooper()) { throw new IllegalStateException( "ensureInitializationComplete must be called on the main thread"); } if (settings == null) { throw new IllegalStateException( "ensureInitializationComplete must be called after startInitialization"); } if (initialized) { callbackHandler.post(callback); return; } executorService.execute( () -> { InitResult result; try { result = initResultFuture.get(); } catch (Exception e) { Log.e(TAG, "Flutter initialization failed.", e); throw new RuntimeException(e); } HandlerCompat.createAsyncHandler(Looper.getMainLooper()) .post( () -> { ensureInitializationComplete(applicationContext.getApplicationContext(), args); callbackHandler.post(callback); }); }); } /** Returns whether the FlutterLoader has finished loading the native library. */ public boolean initialized() { return initialized; } /** Extract assets out of the APK that need to be cached as uncompressed files on disk. */ private ResourceExtractor initResources(@NonNull Context applicationContext) { ResourceExtractor resourceExtractor = null; if (BuildConfig.DEBUG || BuildConfig.JIT_RELEASE) { final String dataDirPath = PathUtils.getDataDirectory(applicationContext); final String packageName = applicationContext.getPackageName(); final PackageManager packageManager = applicationContext.getPackageManager(); final AssetManager assetManager = applicationContext.getResources().getAssets(); resourceExtractor = new ResourceExtractor(dataDirPath, packageName, packageManager, assetManager); // In debug/JIT mode these assets will be written to disk and then // mapped into memory so they can be provided to the Dart VM. resourceExtractor .addResource(fullAssetPathFrom(flutterApplicationInfo.vmSnapshotData)) .addResource(fullAssetPathFrom(flutterApplicationInfo.isolateSnapshotData)) .addResource(fullAssetPathFrom(DEFAULT_KERNEL_BLOB)); resourceExtractor.start(); } return resourceExtractor; } @NonNull public String findAppBundlePath() { return flutterApplicationInfo.flutterAssetsDir; } /** * Returns the file name for the given asset. The returned file name can be used to access the * asset in the APK through the {@link android.content.res.AssetManager} API. * * @param asset the name of the asset. The name can be hierarchical * @return the filename to be used with {@link android.content.res.AssetManager} */ @NonNull public String getLookupKeyForAsset(@NonNull String asset) { return fullAssetPathFrom(asset); } /** * Returns the file name for the given asset which originates from the specified packageName. The * returned file name can be used to access the asset in the APK through the {@link * android.content.res.AssetManager} API. * * @param asset the name of the asset. The name can be hierarchical * @param packageName the name of the package from which the asset originates * @return the file name to be used with {@link android.content.res.AssetManager} */ @NonNull public String getLookupKeyForAsset(@NonNull String asset, @NonNull String packageName) { return getLookupKeyForAsset("packages" + File.separator + packageName + File.separator + asset); } /** Returns the configuration on whether flutter engine should automatically register plugins. */ @NonNull public boolean automaticallyRegisterPlugins() { return flutterApplicationInfo.automaticallyRegisterPlugins; } @NonNull private String fullAssetPathFrom(@NonNull String filePath) { return flutterApplicationInfo.flutterAssetsDir + File.separator + filePath; } public static class Settings { private String logTag; @Nullable public String getLogTag() { return logTag; } /** * Set the tag associated with Flutter app log messages. * * @param tag Log tag. */ public void setLogTag(String tag) { logTag = tag; } } }
engine/shell/platform/android/io/flutter/embedding/engine/loader/FlutterLoader.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/embedding/engine/loader/FlutterLoader.java", "repo_id": "engine", "token_count": 8031 }
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. package io.flutter.embedding.engine.plugins.service; import androidx.annotation.NonNull; /** * A {@link io.flutter.embedding.engine.plugins.FlutterPlugin} that wants to know when it is running * within a {@link android.app.Service}. */ public interface ServiceAware { /** * Callback triggered when a {@code ServiceAware} {@link * io.flutter.embedding.engine.plugins.FlutterPlugin} is associated with a {@link * android.app.Service}. */ void onAttachedToService(@NonNull ServicePluginBinding binding); /** * Callback triggered when a {@code ServiceAware} {@link * io.flutter.embedding.engine.plugins.FlutterPlugin} is detached from a {@link * android.app.Service}. * * <p>Any {@code Lifecycle} listeners that were registered in {@link * #onAttachedToService(ServicePluginBinding)} should be deregistered here to avoid a possible * memory leak and other side effects. */ void onDetachedFromService(); interface OnModeChangeListener { /** * Callback triggered when the associated {@link android.app.Service} goes from background * execution to foreground execution. */ void onMoveToForeground(); /** * Callback triggered when the associated {@link android.app.Service} goes from foreground * execution to background execution. */ void onMoveToBackground(); } }
engine/shell/platform/android/io/flutter/embedding/engine/plugins/service/ServiceAware.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/embedding/engine/plugins/service/ServiceAware.java", "repo_id": "engine", "token_count": 466 }
338
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.embedding.engine.systemchannels; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import io.flutter.Log; import io.flutter.embedding.engine.dart.DartExecutor; import io.flutter.plugin.common.JSONMethodCodec; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodChannel; import java.util.ArrayList; import java.util.List; import java.util.Locale; import org.json.JSONException; import org.json.JSONObject; /** Sends the platform's locales to Dart. */ public class LocalizationChannel { private static final String TAG = "LocalizationChannel"; @NonNull public final MethodChannel channel; @Nullable private LocalizationMessageHandler localizationMessageHandler; @NonNull @VisibleForTesting public final MethodChannel.MethodCallHandler handler = new MethodChannel.MethodCallHandler() { @Override public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) { if (localizationMessageHandler == null) { // If no explicit LocalizationMessageHandler has been registered then we don't // need to forward this call to an API. Return. return; } String method = call.method; switch (method) { case "Localization.getStringResource": JSONObject arguments = call.<JSONObject>arguments(); try { String key = arguments.getString("key"); String localeString = null; if (arguments.has("locale")) { localeString = arguments.getString("locale"); } result.success(localizationMessageHandler.getStringResource(key, localeString)); } catch (JSONException exception) { result.error("error", exception.getMessage(), null); } break; default: result.notImplemented(); break; } } }; public LocalizationChannel(@NonNull DartExecutor dartExecutor) { this.channel = new MethodChannel(dartExecutor, "flutter/localization", JSONMethodCodec.INSTANCE); channel.setMethodCallHandler(handler); } /** * Sets the {@link LocalizationMessageHandler} which receives all events and requests that are * parsed from the underlying platform channel. */ public void setLocalizationMessageHandler( @Nullable LocalizationMessageHandler localizationMessageHandler) { this.localizationMessageHandler = localizationMessageHandler; } /** Send the given {@code locales} to Dart. */ public void sendLocales(@NonNull List<Locale> locales) { Log.v(TAG, "Sending Locales to Flutter."); // Send the user's preferred locales. List<String> data = new ArrayList<>(); for (Locale locale : locales) { Log.v( TAG, "Locale (Language: " + locale.getLanguage() + ", Country: " + locale.getCountry() + ", Variant: " + locale.getVariant() + ")"); data.add(locale.getLanguage()); data.add(locale.getCountry()); data.add(locale.getScript()); data.add(locale.getVariant()); } channel.invokeMethod("setLocale", data); } /** * Handler that receives platform messages sent from Flutter to Android through a given {@link * PlatformChannel}. * * <p>To register a {@code LocalizationMessageHandler} with a {@link PlatformChannel}, see {@link * LocalizationChannel#setLocalizationMessageHandler(LocalizationMessageHandler)}. */ public interface LocalizationMessageHandler { /** * The Flutter application would like to obtain the string resource of given {@code key} in * {@code locale}. */ @NonNull String getStringResource(@NonNull String key, @NonNull String locale); } }
engine/shell/platform/android/io/flutter/embedding/engine/systemchannels/LocalizationChannel.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/embedding/engine/systemchannels/LocalizationChannel.java", "repo_id": "engine", "token_count": 1535 }
339
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugin.common; import androidx.annotation.Nullable; import androidx.annotation.UiThread; import io.flutter.BuildConfig; import io.flutter.Log; import io.flutter.plugin.common.BinaryMessenger.BinaryMessageHandler; import io.flutter.plugin.common.BinaryMessenger.BinaryReply; import java.nio.ByteBuffer; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; /** * A named channel for communicating with the Flutter application using asynchronous event streams. * * <p>Incoming requests for event stream setup are decoded from binary on receipt, and Java * responses and events are encoded into binary before being transmitted back to Flutter. The {@link * MethodCodec} used must be compatible with the one used by the Flutter application. This can be * achieved by creating an <a * href="https://api.flutter.dev/flutter/services/EventChannel-class.html">EventChannel</a> * counterpart of this channel on the Dart side. The Java type of stream configuration arguments, * events, and error details is {@code Object}, but only values supported by the specified {@link * MethodCodec} can be used. * * <p>The logical identity of the channel is given by its name. Identically named channels will * interfere with each other's communication. */ public final class EventChannel { private static final String TAG = "EventChannel#"; private final BinaryMessenger messenger; private final String name; private final MethodCodec codec; @Nullable private final BinaryMessenger.TaskQueue taskQueue; /** * Creates a new channel associated with the specified {@link BinaryMessenger} and with the * specified name and the standard {@link MethodCodec}. * * @param messenger a {@link BinaryMessenger}. * @param name a channel name String. */ public EventChannel(BinaryMessenger messenger, String name) { this(messenger, name, StandardMethodCodec.INSTANCE); } /** * Creates a new channel associated with the specified {@link BinaryMessenger} and with the * specified name and {@link MethodCodec}. * * @param messenger a {@link BinaryMessenger}. * @param name a channel name String. * @param codec a {@link MessageCodec}. */ public EventChannel(BinaryMessenger messenger, String name, MethodCodec codec) { this(messenger, name, codec, null); } /** * Creates a new channel associated with the specified {@link BinaryMessenger} and with the * specified name and {@link MethodCodec}. * * @param messenger a {@link BinaryMessenger}. * @param name a channel name String. * @param codec a {@link MessageCodec}. * @param taskQueue a {@link BinaryMessenger.TaskQueue} that specifies what thread will execute * the handler. Specifying null means execute on the platform thread. See also {@link * BinaryMessenger#makeBackgroundTaskQueue()}. */ public EventChannel( BinaryMessenger messenger, String name, MethodCodec codec, BinaryMessenger.TaskQueue taskQueue) { if (BuildConfig.DEBUG) { if (messenger == null) { Log.e(TAG, "Parameter messenger must not be null."); } if (name == null) { Log.e(TAG, "Parameter name must not be null."); } if (codec == null) { Log.e(TAG, "Parameter codec must not be null."); } } this.messenger = messenger; this.name = name; this.codec = codec; this.taskQueue = taskQueue; } /** * Registers a stream handler on this channel. * * <p>Overrides any existing handler registration for (the name of) this channel. * * <p>If no handler has been registered, any incoming stream setup requests will be handled * silently by providing an empty stream. * * @param handler a {@link StreamHandler}, or null to deregister. */ @UiThread public void setStreamHandler(final StreamHandler handler) { // We call the 2 parameter variant specifically to avoid breaking changes in // mock verify calls. // See https://github.com/flutter/flutter/issues/92582. if (taskQueue != null) { messenger.setMessageHandler( name, handler == null ? null : new IncomingStreamRequestHandler(handler), taskQueue); } else { messenger.setMessageHandler( name, handler == null ? null : new IncomingStreamRequestHandler(handler)); } } /** * Handler of stream setup and teardown requests. * * <p>Implementations must be prepared to accept sequences of alternating calls to {@link * #onListen(Object, EventChannel.EventSink)} and {@link #onCancel(Object)}. Implementations * should ideally consume no resources when the last such call is not {@code onListen}. In typical * situations, this means that the implementation should register itself with platform-specific * event sources {@code onListen} and deregister again {@code onCancel}. */ public interface StreamHandler { /** * Handles a request to set up an event stream. * * <p>Any uncaught exception thrown by this method will be caught by the channel implementation * and logged. An error result message will be sent back to Flutter. * * @param arguments stream configuration arguments, possibly null. * @param events an {@link EventSink} for emitting events to the Flutter receiver. */ void onListen(Object arguments, EventSink events); /** * Handles a request to tear down the most recently created event stream. * * <p>Any uncaught exception thrown by this method will be caught by the channel implementation * and logged. An error result message will be sent back to Flutter. * * <p>The channel implementation may call this method with null arguments to separate a pair of * two consecutive set up requests. Such request pairs may occur during Flutter hot restart. Any * uncaught exception thrown in this situation will be logged without notifying Flutter. * * @param arguments stream configuration arguments, possibly null. */ void onCancel(Object arguments); } /** * Event callback. Supports dual use: Producers of events to be sent to Flutter act as clients of * this interface for sending events. Consumers of events sent from Flutter implement this * interface for handling received events (the latter facility has not been implemented yet). */ public interface EventSink { /** * Consumes a successful event. * * @param event the event, possibly null. */ void success(Object event); /** * Consumes an error event. * * @param errorCode an error code String. * @param errorMessage a human-readable error message String, possibly null. * @param errorDetails error details, possibly null */ void error(String errorCode, String errorMessage, Object errorDetails); /** * Consumes end of stream. Ensuing calls to {@link #success(Object)} or {@link #error(String, * String, Object)}, if any, are ignored. */ void endOfStream(); } private final class IncomingStreamRequestHandler implements BinaryMessageHandler { private final StreamHandler handler; private final AtomicReference<EventSink> activeSink = new AtomicReference<>(null); IncomingStreamRequestHandler(StreamHandler handler) { this.handler = handler; } @Override public void onMessage(ByteBuffer message, final BinaryReply reply) { final MethodCall call = codec.decodeMethodCall(message); if (call.method.equals("listen")) { onListen(call.arguments, reply); } else if (call.method.equals("cancel")) { onCancel(call.arguments, reply); } else { reply.reply(null); } } private void onListen(Object arguments, BinaryReply callback) { final EventSink eventSink = new EventSinkImplementation(); final EventSink oldSink = activeSink.getAndSet(eventSink); if (oldSink != null) { // Repeated calls to onListen may happen during hot restart. // We separate them with a call to onCancel. try { handler.onCancel(null); } catch (RuntimeException e) { Log.e(TAG + name, "Failed to close existing event stream", e); } } try { handler.onListen(arguments, eventSink); callback.reply(codec.encodeSuccessEnvelope(null)); } catch (RuntimeException e) { activeSink.set(null); Log.e(TAG + name, "Failed to open event stream", e); callback.reply(codec.encodeErrorEnvelope("error", e.getMessage(), null)); } } private void onCancel(Object arguments, BinaryReply callback) { final EventSink oldSink = activeSink.getAndSet(null); if (oldSink != null) { try { handler.onCancel(arguments); callback.reply(codec.encodeSuccessEnvelope(null)); } catch (RuntimeException e) { Log.e(TAG + name, "Failed to close event stream", e); callback.reply(codec.encodeErrorEnvelope("error", e.getMessage(), null)); } } else { callback.reply(codec.encodeErrorEnvelope("error", "No active stream to cancel", null)); } } private final class EventSinkImplementation implements EventSink { final AtomicBoolean hasEnded = new AtomicBoolean(false); @Override @UiThread public void success(Object event) { if (hasEnded.get() || activeSink.get() != this) { return; } EventChannel.this.messenger.send(name, codec.encodeSuccessEnvelope(event)); } @Override @UiThread public void error(String errorCode, String errorMessage, Object errorDetails) { if (hasEnded.get() || activeSink.get() != this) { return; } EventChannel.this.messenger.send( name, codec.encodeErrorEnvelope(errorCode, errorMessage, errorDetails)); } @Override @UiThread public void endOfStream() { if (hasEnded.getAndSet(true) || activeSink.get() != this) { return; } EventChannel.this.messenger.send(name, null); } } } }
engine/shell/platform/android/io/flutter/plugin/common/EventChannel.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/plugin/common/EventChannel.java", "repo_id": "engine", "token_count": 3456 }
340
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugin.editing; import android.text.Editable; import android.text.Selection; import android.text.SpannableStringBuilder; import android.view.View; import android.view.inputmethod.BaseInputConnection; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.flutter.Log; import io.flutter.embedding.engine.systemchannels.TextInputChannel; import java.util.ArrayList; /// The current editing state (text, selection range, composing range) the text input plugin holds. /// /// As the name implies, this class also notifies its listeners when the editing state changes. When /// there're ongoing batch edits, change notifications will be deferred until all batch edits end /// (i.e. when the outermost batch edit ends). Listeners added during a batch edit will always be /// notified when all batch edits end, even if there's no real change. /// /// Adding/removing listeners or changing the editing state in a didChangeEditingState callback may /// cause unexpected behavior. // // Currently this class does not notify its listeners on spans-only changes (e.g., // Selection.setSelection). Wrap them in a batch edit to trigger a change notification. class ListenableEditingState extends SpannableStringBuilder { interface EditingStateWatcher { // Changing the editing state in a didChangeEditingState callback may cause unexpected // behavior. void didChangeEditingState( boolean textChanged, boolean selectionChanged, boolean composingRegionChanged); } private static final String TAG = "ListenableEditingState"; private int mBatchEditNestDepth = 0; // We don't support adding/removing listeners, or changing the editing state in a listener // callback for now. private int mChangeNotificationDepth = 0; private ArrayList<EditingStateWatcher> mListeners = new ArrayList<>(); private ArrayList<EditingStateWatcher> mPendingListeners = new ArrayList<>(); private ArrayList<TextEditingDelta> mBatchTextEditingDeltas = new ArrayList<>(); private String mToStringCache; private String mTextWhenBeginBatchEdit; private int mSelectionStartWhenBeginBatchEdit; private int mSelectionEndWhenBeginBatchEdit; private int mComposingStartWhenBeginBatchEdit; private int mComposingEndWhenBeginBatchEdit; private BaseInputConnection mDummyConnection; // The View is only used for creating a dummy BaseInputConnection for setComposingRegion. The View // needs to have a non-null Context. public ListenableEditingState( @Nullable TextInputChannel.TextEditState initialState, @NonNull View view) { super(); Editable self = this; mDummyConnection = new BaseInputConnection(view, true) { @Override public Editable getEditable() { return self; } }; if (initialState != null) { setEditingState(initialState); } } public ArrayList<TextEditingDelta> extractBatchTextEditingDeltas() { ArrayList<TextEditingDelta> currentBatchDeltas = new ArrayList<TextEditingDelta>(mBatchTextEditingDeltas); mBatchTextEditingDeltas.clear(); return currentBatchDeltas; } public void clearBatchDeltas() { mBatchTextEditingDeltas.clear(); } /// Starts a new batch edit during which change notifications will be put on hold until all batch /// edits end. /// /// Batch edits nest. public void beginBatchEdit() { mBatchEditNestDepth++; if (mChangeNotificationDepth > 0) { Log.e(TAG, "editing state should not be changed in a listener callback"); } if (mBatchEditNestDepth == 1 && !mListeners.isEmpty()) { mTextWhenBeginBatchEdit = toString(); mSelectionStartWhenBeginBatchEdit = getSelectionStart(); mSelectionEndWhenBeginBatchEdit = getSelectionEnd(); mComposingStartWhenBeginBatchEdit = getComposingStart(); mComposingEndWhenBeginBatchEdit = getComposingEnd(); } } /// Ends the current batch edit and flush pending change notifications if the current batch edit /// is not nested (i.e. it is the last ongoing batch edit). public void endBatchEdit() { if (mBatchEditNestDepth == 0) { Log.e(TAG, "endBatchEdit called without a matching beginBatchEdit"); return; } if (mBatchEditNestDepth == 1) { for (final EditingStateWatcher listener : mPendingListeners) { notifyListener(listener, true, true, true); } if (!mListeners.isEmpty()) { Log.v(TAG, "didFinishBatchEdit with " + String.valueOf(mListeners.size()) + " listener(s)"); final boolean textChanged = !toString().equals(mTextWhenBeginBatchEdit); final boolean selectionChanged = mSelectionStartWhenBeginBatchEdit != getSelectionStart() || mSelectionEndWhenBeginBatchEdit != getSelectionEnd(); final boolean composingRegionChanged = mComposingStartWhenBeginBatchEdit != getComposingStart() || mComposingEndWhenBeginBatchEdit != getComposingEnd(); notifyListenersIfNeeded(textChanged, selectionChanged, composingRegionChanged); } } mListeners.addAll(mPendingListeners); mPendingListeners.clear(); mBatchEditNestDepth--; } /// Update the composing region of the current editing state. /// /// If the range is invalid or empty, the current composing region will be removed. public void setComposingRange(int composingStart, int composingEnd) { if (composingStart < 0 || composingStart >= composingEnd) { BaseInputConnection.removeComposingSpans(this); } else { mDummyConnection.setComposingRegion(composingStart, composingEnd); } } /// Called when the framework sends updates to the text input plugin. /// /// This method will also update the composing region if it has changed. public void setEditingState(TextInputChannel.TextEditState newState) { beginBatchEdit(); replace(0, length(), newState.text); if (newState.hasSelection()) { Selection.setSelection(this, newState.selectionStart, newState.selectionEnd); } else { Selection.removeSelection(this); } setComposingRange(newState.composingStart, newState.composingEnd); // Updates from the framework should not have a delta created for it as they have already been // applied on the framework side. clearBatchDeltas(); endBatchEdit(); } public void addEditingStateListener(EditingStateWatcher listener) { if (mChangeNotificationDepth > 0) { Log.e(TAG, "adding a listener " + listener.toString() + " in a listener callback"); } // It is possible for a listener to get added during a batch edit. When that happens we always // notify the new listeners. // This does not check if the listener is already in the list of existing listeners. if (mBatchEditNestDepth > 0) { Log.w(TAG, "a listener was added to EditingState while a batch edit was in progress"); mPendingListeners.add(listener); } else { mListeners.add(listener); } } public void removeEditingStateListener(EditingStateWatcher listener) { if (mChangeNotificationDepth > 0) { Log.e(TAG, "removing a listener " + listener.toString() + " in a listener callback"); } mListeners.remove(listener); if (mBatchEditNestDepth > 0) { mPendingListeners.remove(listener); } } @Override public SpannableStringBuilder replace( int start, int end, CharSequence tb, int tbstart, int tbend) { if (mChangeNotificationDepth > 0) { Log.e(TAG, "editing state should not be changed in a listener callback"); } final CharSequence oldText = toString(); boolean textChanged = end - start != tbend - tbstart; for (int i = 0; i < end - start && !textChanged; i++) { textChanged |= charAt(start + i) != tb.charAt(tbstart + i); } if (textChanged) { mToStringCache = null; } final int selectionStart = getSelectionStart(); final int selectionEnd = getSelectionEnd(); final int composingStart = getComposingStart(); final int composingEnd = getComposingEnd(); final SpannableStringBuilder editable = super.replace(start, end, tb, tbstart, tbend); mBatchTextEditingDeltas.add( new TextEditingDelta( oldText, start, end, tb, getSelectionStart(), getSelectionEnd(), getComposingStart(), getComposingEnd())); if (mBatchEditNestDepth > 0) { return editable; } final boolean selectionChanged = getSelectionStart() != selectionStart || getSelectionEnd() != selectionEnd; final boolean composingRegionChanged = getComposingStart() != composingStart || getComposingEnd() != composingEnd; notifyListenersIfNeeded(textChanged, selectionChanged, composingRegionChanged); return editable; } private void notifyListener( EditingStateWatcher listener, boolean textChanged, boolean selectionChanged, boolean composingChanged) { mChangeNotificationDepth++; listener.didChangeEditingState(textChanged, selectionChanged, composingChanged); mChangeNotificationDepth--; } private void notifyListenersIfNeeded( boolean textChanged, boolean selectionChanged, boolean composingChanged) { if (textChanged || selectionChanged || composingChanged) { for (final EditingStateWatcher listener : mListeners) { notifyListener(listener, textChanged, selectionChanged, composingChanged); } } } public final int getSelectionStart() { return Selection.getSelectionStart(this); } public final int getSelectionEnd() { return Selection.getSelectionEnd(this); } public final int getComposingStart() { return BaseInputConnection.getComposingSpanStart(this); } public final int getComposingEnd() { return BaseInputConnection.getComposingSpanEnd(this); } @Override public void setSpan(Object what, int start, int end, int flags) { super.setSpan(what, start, end, flags); // Setting a span does not involve mutating the text value in the editing state. Here we create // a non text update delta with any updated selection and composing regions. mBatchTextEditingDeltas.add( new TextEditingDelta( toString(), getSelectionStart(), getSelectionEnd(), getComposingStart(), getComposingEnd())); } @Override public String toString() { return mToStringCache != null ? mToStringCache : (mToStringCache = super.toString()); } }
engine/shell/platform/android/io/flutter/plugin/editing/ListenableEditingState.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/plugin/editing/ListenableEditingState.java", "repo_id": "engine", "token_count": 3562 }
341
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugin.platform; import android.view.View; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.flutter.view.AccessibilityBridge; /** Facilitates interaction between the accessibility bridge and embedded platform views. */ public interface PlatformViewsAccessibilityDelegate { /** * Returns the root of the view hierarchy for the platform view with the requested id, or null if * there is no corresponding view. */ @Nullable View getPlatformViewById(int viewId); /** Returns true if the platform view uses virtual displays. */ boolean usesVirtualDisplay(int id); /** * Attaches an accessibility bridge for this platform views accessibility delegate. * * <p>Accessibility events originating in platform views belonging to this delegate will be * delegated to this accessibility bridge. */ void attachAccessibilityBridge(@NonNull AccessibilityBridge accessibilityBridge); /** * Detaches the current accessibility bridge. * * <p>Any accessibility events sent by platform views belonging to this delegate will be ignored * until a new accessibility bridge is attached. */ void detachAccessibilityBridge(); }
engine/shell/platform/android/io/flutter/plugin/platform/PlatformViewsAccessibilityDelegate.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/plugin/platform/PlatformViewsAccessibilityDelegate.java", "repo_id": "engine", "token_count": 345 }
342
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.view; import static io.flutter.Build.API_LEVELS; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.Activity; import android.content.ContentResolver; import android.content.Context; import android.content.res.Configuration; import android.database.ContentObserver; import android.graphics.Rect; import android.net.Uri; import android.opengl.Matrix; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.provider.Settings; import android.text.SpannableString; import android.text.TextUtils; import android.text.style.LocaleSpan; import android.text.style.TtsSpan; import android.view.MotionEvent; import android.view.View; import android.view.WindowInsets; import android.view.WindowManager; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityManager; import android.view.accessibility.AccessibilityNodeInfo; import android.view.accessibility.AccessibilityNodeProvider; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import androidx.annotation.VisibleForTesting; import io.flutter.BuildConfig; import io.flutter.Log; import io.flutter.embedding.engine.systemchannels.AccessibilityChannel; import io.flutter.plugin.platform.PlatformViewsAccessibilityDelegate; import io.flutter.util.Predicate; import io.flutter.util.ViewUtils; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.Charset; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Bridge between Android's OS accessibility system and Flutter's accessibility system. * * <p>An {@code AccessibilityBridge} requires: * * <ul> * <li>A real Android {@link View}, called the {@link #rootAccessibilityView}, which contains a * Flutter UI. The {@link #rootAccessibilityView} is required at the time of {@code * AccessibilityBridge}'s instantiation and is held for the duration of {@code * AccessibilityBridge}'s lifespan. {@code AccessibilityBridge} invokes various accessibility * methods on the {@link #rootAccessibilityView}, e.g., {@link * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. The {@link * #rootAccessibilityView} is expected to notify the {@code AccessibilityBridge} of relevant * interactions: {@link #onAccessibilityHoverEvent(MotionEvent)}, {@link #reset()}, {@link * #updateSemantics(ByteBuffer, String[], ByteBuffer[])}, and {@link * #updateCustomAccessibilityActions(ByteBuffer, String[])} * <li>An {@link AccessibilityChannel} that is connected to the running Flutter app. * <li>Android's {@link AccessibilityManager} to query and listen for accessibility settings. * <li>Android's {@link ContentResolver} to listen for changes to system animation settings. * </ul> * * The {@code AccessibilityBridge} causes Android to treat Flutter {@code SemanticsNode}s as if they * were accessible Android {@link View}s. Accessibility requests may be sent from a Flutter widget * to the Android OS, as if it were an Android {@link View}, and accessibility events may be * consumed by a Flutter widget, as if it were an Android {@link View}. {@code AccessibilityBridge} * refers to Flutter's accessible widgets as "virtual views" and identifies them with "virtual view * IDs". */ public class AccessibilityBridge extends AccessibilityNodeProvider { private static final String TAG = "AccessibilityBridge"; // Constants from higher API levels. // TODO(goderbauer): Get these from Android Support Library when // https://github.com/flutter/flutter/issues/11099 is resolved. private static final int ACTION_SHOW_ON_SCREEN = 16908342; // API level 23 private static final float SCROLL_EXTENT_FOR_INFINITY = 100000.0f; private static final float SCROLL_POSITION_CAP_FOR_INFINITY = 70000.0f; private static final int ROOT_NODE_ID = 0; private static final int SCROLLABLE_ACTIONS = Action.SCROLL_RIGHT.value | Action.SCROLL_LEFT.value | Action.SCROLL_UP.value | Action.SCROLL_DOWN.value; // Flags that make a node accessibilty focusable. private static final int FOCUSABLE_FLAGS = Flag.HAS_CHECKED_STATE.value | Flag.IS_CHECKED.value | Flag.IS_SELECTED.value | Flag.IS_TEXT_FIELD.value | Flag.IS_FOCUSED.value | Flag.HAS_ENABLED_STATE.value | Flag.IS_ENABLED.value | Flag.IS_IN_MUTUALLY_EXCLUSIVE_GROUP.value | Flag.HAS_TOGGLED_STATE.value | Flag.IS_TOGGLED.value | Flag.IS_FOCUSABLE.value | Flag.IS_SLIDER.value; // The minimal ID for an engine generated AccessibilityNodeInfo. // // The AccessibilityNodeInfo node IDs are generated by the framework for most Flutter semantic // nodes. // When embedding platform views, the framework does not have the accessibility information for // the embedded view; // in this case the engine generates AccessibilityNodeInfo that mirrors the a11y information // exposed by the platform // view. To avoid the need of synchronizing the framework and engine mechanisms for generating the // next ID, we split // the 32bit range of virtual node IDs into 2. The least significant 16 bits are used for // framework generated IDs // and the most significant 16 bits are used for engine generated IDs. private static final int MIN_ENGINE_GENERATED_NODE_ID = 1 << 16; // Font weight adjustment for bold text. FontWeight.Bold - FontWeight.Normal = w700 - w400 = 300. private static final int BOLD_TEXT_WEIGHT_ADJUSTMENT = 300; /// Value is derived from ACTION_TYPE_MASK in AccessibilityNodeInfo.java private static int FIRST_RESOURCE_ID = 267386881; // Real Android View, which internally holds a Flutter UI. @NonNull private final View rootAccessibilityView; // The accessibility communication API between Flutter's Android embedding and // the Flutter framework. @NonNull private final AccessibilityChannel accessibilityChannel; // Android's {@link AccessibilityManager}, which we can query to see if accessibility is // turned on, as well as listen for changes to accessibility's activation. @NonNull private final AccessibilityManager accessibilityManager; @NonNull private final AccessibilityViewEmbedder accessibilityViewEmbedder; // The delegate for interacting with embedded platform views. Used to embed accessibility data for // an embedded view in the accessibility tree. @NonNull private final PlatformViewsAccessibilityDelegate platformViewsAccessibilityDelegate; // Android's {@link ContentResolver}, which is used to observe the global // TRANSITION_ANIMATION_SCALE, // which determines whether Flutter's animations should be enabled or disabled for accessibility // purposes. @NonNull private final ContentResolver contentResolver; // The entire Flutter semantics tree of the running Flutter app, stored as a Map // from each SemanticsNode's ID to a Java representation of a Flutter SemanticsNode. // // Flutter's semantics tree is cached here because Android might ask for information about // a given SemanticsNode at any moment in time. Caching the tree allows for immediate // response to Android's request. // // The structure of flutterSemanticsTree may be 1 or 2 frames behind the Flutter app // due to the time required to communicate tree changes from Flutter to Android. // // See the Flutter docs on SemanticsNode: // https://api.flutter.dev/flutter/semantics/SemanticsNode-class.html @NonNull private final Map<Integer, SemanticsNode> flutterSemanticsTree = new HashMap<>(); // The set of all custom Flutter accessibility actions that are present in the running // Flutter app, stored as a Map from each action's ID to the definition of the custom // accessibility // action. // // Flutter and Android support a number of built-in accessibility actions. However, these // predefined actions are not always sufficient for a desired interaction. Android facilitates // custom accessibility actions, // https://developer.android.com/reference/android/view/accessibility/AccessibilityNodeInfo.AccessibilityAction. // Flutter supports custom accessibility actions via {@code customSemanticsActions} within // a {@code Semantics} widget, https://api.flutter.dev/flutter/widgets/Semantics-class.html. // {@code customAccessibilityActions} are an Android-side cache of all custom accessibility // types declared within the running Flutter app. // // Custom accessibility actions are comprised of only a few fields, and therefore it is likely // that a given app may define the same custom accessibility action many times. Identical // custom accessibility actions are de-duped such that {@code customAccessibilityActions} only // caches unique custom accessibility actions. // // See the Android documentation for custom accessibility actions: // https://developer.android.com/reference/android/view/accessibility/AccessibilityNodeInfo.AccessibilityAction // // See the Flutter documentation for the Semantics widget: // https://api.flutter.dev/flutter/widgets/Semantics-class.html @NonNull private final Map<Integer, CustomAccessibilityAction> customAccessibilityActions = new HashMap<>(); // The {@code SemanticsNode} within Flutter that currently has the focus of Android's // accessibility system. // // This is null when a node embedded by the AccessibilityViewEmbedder has the focus. @Nullable private SemanticsNode accessibilityFocusedSemanticsNode; // The virtual ID of the currently embedded node with accessibility focus. // // This is the ID of a node generated by the AccessibilityViewEmbedder if an embedded node is // focused, // null otherwise. private Integer embeddedAccessibilityFocusedNodeId; // The virtual ID of the currently embedded node with input focus. // // This is the ID of a node generated by the AccessibilityViewEmbedder if an embedded node is // focused, // null otherwise. private Integer embeddedInputFocusedNodeId; // The accessibility features that should currently be active within Flutter, represented as // a bitmask whose values comes from {@link AccessibilityFeature}. private int accessibilityFeatureFlags = 0; // The {@code SemanticsNode} within Flutter that currently has the focus of Android's input // system. // // Input focus is independent of accessibility focus. It is possible that accessibility focus // and input focus target the same {@code SemanticsNode}, but it is also possible that one // {@code SemanticsNode} has input focus while a different {@code SemanticsNode} has // accessibility focus. For example, a user may use a D-Pad to navigate to a text field, giving // it accessibility focus, and then enable input on that text field, giving it input focus. Then // the user moves the accessibility focus to a nearby label to get info about the label, while // maintaining input focus on the original text field. @Nullable private SemanticsNode inputFocusedSemanticsNode; // Keeps track of the last semantics node that had the input focus. // // This is used to determine if the input focus has changed since the last time the // {@code inputFocusSemanticsNode} has been set, so that we can send a {@code TYPE_VIEW_FOCUSED} // event when it changes. @Nullable private SemanticsNode lastInputFocusedSemanticsNode; // The widget within Flutter that currently sits beneath a cursor, e.g, // beneath a stylus or mouse cursor. @Nullable private SemanticsNode hoveredObject; @VisibleForTesting public int getHoveredObjectId() { return hoveredObject.id; } // A Java/Android cached representation of the Flutter app's navigation stack. The Flutter // navigation stack is tracked so that accessibility announcements can be made during Flutter's // navigation changes. // TODO(mattcarroll): take this cache into account for new routing solution so accessibility does // not get left behind. @NonNull private final List<Integer> flutterNavigationStack = new ArrayList<>(); // TODO(mattcarroll): why do we need previouseRouteId if we have flutterNavigationStack private int previousRouteId = ROOT_NODE_ID; // Tracks the left system inset of the screen because Flutter needs to manually adjust // accessibility positioning when in reverse-landscape. This is an Android bug that Flutter // is solving for itself. @NonNull private Integer lastLeftFrameInset = 0; @Nullable private OnAccessibilityChangeListener onAccessibilityChangeListener; // Whether the users are using assistive technologies to interact with the devices. // // The getter returns true when at least one of the assistive technologies is running: // TalkBack, SwitchAccess, or VoiceAccess. @VisibleForTesting public boolean getAccessibleNavigation() { return accessibleNavigation; } private boolean accessibleNavigation = false; private void setAccessibleNavigation(boolean value) { if (accessibleNavigation == value) { return; } accessibleNavigation = value; if (accessibleNavigation) { accessibilityFeatureFlags |= AccessibilityFeature.ACCESSIBLE_NAVIGATION.value; } else { accessibilityFeatureFlags &= ~AccessibilityFeature.ACCESSIBLE_NAVIGATION.value; } sendLatestAccessibilityFlagsToFlutter(); } // Set to true after {@code release} has been invoked. private boolean isReleased = false; // Handler for all messages received from Flutter via the {@code accessibilityChannel} private final AccessibilityChannel.AccessibilityMessageHandler accessibilityMessageHandler = new AccessibilityChannel.AccessibilityMessageHandler() { /** The Dart application would like the given {@code message} to be announced. */ @Override public void announce(@NonNull String message) { rootAccessibilityView.announceForAccessibility(message); } /** The user has tapped on the widget with the given {@code nodeId}. */ @Override public void onTap(int nodeId) { sendAccessibilityEvent(nodeId, AccessibilityEvent.TYPE_VIEW_CLICKED); } /** The user has long pressed on the widget with the given {@code nodeId}. */ @Override public void onLongPress(int nodeId) { sendAccessibilityEvent(nodeId, AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); } /** The framework has requested focus on the given {@code nodeId}. */ @Override public void onFocus(int nodeId) { sendAccessibilityEvent(nodeId, AccessibilityEvent.TYPE_VIEW_FOCUSED); } /** The user has opened a tooltip. */ @Override public void onTooltip(@NonNull String message) { // Native Android tooltip is no longer announced when it pops up after API 28 and is // handled by // AccessibilityNodeInfo.setTooltipText instead. // // To reproduce native behavior, see // https://developer.android.com/guide/topics/ui/tooltips. if (Build.VERSION.SDK_INT >= API_LEVELS.API_28) { return; } AccessibilityEvent e = obtainAccessibilityEvent(ROOT_NODE_ID, AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); e.getText().add(message); sendAccessibilityEvent(e); } /** New custom accessibility actions exist in Flutter. Update our Android-side cache. */ @Override public void updateCustomAccessibilityActions(ByteBuffer buffer, String[] strings) { buffer.order(ByteOrder.LITTLE_ENDIAN); AccessibilityBridge.this.updateCustomAccessibilityActions(buffer, strings); } /** Flutter's semantics tree has changed. Update our Android-side cache. */ @Override public void updateSemantics( ByteBuffer buffer, String[] strings, ByteBuffer[] stringAttributeArgs) { buffer.order(ByteOrder.LITTLE_ENDIAN); for (ByteBuffer args : stringAttributeArgs) { args.order(ByteOrder.LITTLE_ENDIAN); } AccessibilityBridge.this.updateSemantics(buffer, strings, stringAttributeArgs); } }; // Listener that is notified when accessibility is turned on/off. private final AccessibilityManager.AccessibilityStateChangeListener accessibilityStateChangeListener = new AccessibilityManager.AccessibilityStateChangeListener() { @Override public void onAccessibilityStateChanged(boolean accessibilityEnabled) { if (isReleased) { return; } if (accessibilityEnabled) { accessibilityChannel.setAccessibilityMessageHandler(accessibilityMessageHandler); accessibilityChannel.onAndroidAccessibilityEnabled(); } else { setAccessibleNavigation(false); accessibilityChannel.setAccessibilityMessageHandler(null); accessibilityChannel.onAndroidAccessibilityDisabled(); } if (onAccessibilityChangeListener != null) { onAccessibilityChangeListener.onAccessibilityChanged( accessibilityEnabled, accessibilityManager.isTouchExplorationEnabled()); } } }; // Listener that is notified when accessibility touch exploration is turned on/off. // This is guarded at instantiation time. private final AccessibilityManager.TouchExplorationStateChangeListener touchExplorationStateChangeListener; // Listener that is notified when the global TRANSITION_ANIMATION_SCALE. When this scale goes // to zero, we instruct Flutter to disable animations. private final ContentObserver animationScaleObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { this.onChange(selfChange, null); } @Override public void onChange(boolean selfChange, Uri uri) { if (isReleased) { return; } // Retrieve the current value of TRANSITION_ANIMATION_SCALE from the OS. String value = Settings.Global.getString( contentResolver, Settings.Global.TRANSITION_ANIMATION_SCALE); boolean shouldAnimationsBeDisabled = value != null && value.equals("0"); if (shouldAnimationsBeDisabled) { accessibilityFeatureFlags |= AccessibilityFeature.DISABLE_ANIMATIONS.value; } else { accessibilityFeatureFlags &= ~AccessibilityFeature.DISABLE_ANIMATIONS.value; } sendLatestAccessibilityFlagsToFlutter(); } }; public AccessibilityBridge( @NonNull View rootAccessibilityView, @NonNull AccessibilityChannel accessibilityChannel, @NonNull AccessibilityManager accessibilityManager, @NonNull ContentResolver contentResolver, @NonNull PlatformViewsAccessibilityDelegate platformViewsAccessibilityDelegate) { this( rootAccessibilityView, accessibilityChannel, accessibilityManager, contentResolver, new AccessibilityViewEmbedder(rootAccessibilityView, MIN_ENGINE_GENERATED_NODE_ID), platformViewsAccessibilityDelegate); } @VisibleForTesting public AccessibilityBridge( @NonNull View rootAccessibilityView, @NonNull AccessibilityChannel accessibilityChannel, @NonNull AccessibilityManager accessibilityManager, @NonNull ContentResolver contentResolver, @NonNull AccessibilityViewEmbedder accessibilityViewEmbedder, @NonNull PlatformViewsAccessibilityDelegate platformViewsAccessibilityDelegate) { this.rootAccessibilityView = rootAccessibilityView; this.accessibilityChannel = accessibilityChannel; this.accessibilityManager = accessibilityManager; this.contentResolver = contentResolver; this.accessibilityViewEmbedder = accessibilityViewEmbedder; this.platformViewsAccessibilityDelegate = platformViewsAccessibilityDelegate; // Tell Flutter whether accessibility is initially active or not. Then register a listener // to be notified of changes in the future. accessibilityStateChangeListener.onAccessibilityStateChanged(accessibilityManager.isEnabled()); this.accessibilityManager.addAccessibilityStateChangeListener(accessibilityStateChangeListener); // Tell Flutter whether touch exploration is initially active or not. Then register a listener // to be notified of changes in the future. touchExplorationStateChangeListener = new AccessibilityManager.TouchExplorationStateChangeListener() { @Override public void onTouchExplorationStateChanged(boolean isTouchExplorationEnabled) { if (isReleased) { return; } if (!isTouchExplorationEnabled) { setAccessibleNavigation(false); onTouchExplorationExit(); } if (onAccessibilityChangeListener != null) { onAccessibilityChangeListener.onAccessibilityChanged( accessibilityManager.isEnabled(), isTouchExplorationEnabled); } } }; touchExplorationStateChangeListener.onTouchExplorationStateChanged( accessibilityManager.isTouchExplorationEnabled()); this.accessibilityManager.addTouchExplorationStateChangeListener( touchExplorationStateChangeListener); // Tell Flutter whether animations should initially be enabled or disabled. Then register a // listener to be notified of changes in the future. animationScaleObserver.onChange(false); Uri transitionUri = Settings.Global.getUriFor(Settings.Global.TRANSITION_ANIMATION_SCALE); this.contentResolver.registerContentObserver(transitionUri, false, animationScaleObserver); // Tells Flutter whether the text should be bolded or not. If the user changes bold text // setting, the configuration will change and trigger a re-build of the accesibiltyBridge. if (Build.VERSION.SDK_INT >= API_LEVELS.API_31) { setBoldTextFlag(); } platformViewsAccessibilityDelegate.attachAccessibilityBridge(this); } /** * Disconnects any listeners and/or delegates that were initialized in {@code * AccessibilityBridge}'s constructor, or added after. * * <p>Do not use this instance after invoking {@code release}. The behavior of any method invoked * on this {@code AccessibilityBridge} after invoking {@code release()} is undefined. */ public void release() { isReleased = true; platformViewsAccessibilityDelegate.detachAccessibilityBridge(); setOnAccessibilityChangeListener(null); accessibilityManager.removeAccessibilityStateChangeListener(accessibilityStateChangeListener); accessibilityManager.removeTouchExplorationStateChangeListener( touchExplorationStateChangeListener); contentResolver.unregisterContentObserver(animationScaleObserver); accessibilityChannel.setAccessibilityMessageHandler(null); } /** Returns true if the Android OS currently has accessibility enabled, false otherwise. */ public boolean isAccessibilityEnabled() { return accessibilityManager.isEnabled(); } /** Returns true if the Android OS currently has touch exploration enabled, false otherwise. */ public boolean isTouchExplorationEnabled() { return accessibilityManager.isTouchExplorationEnabled(); } /** * Sets a listener on this {@code AccessibilityBridge}, which is notified whenever accessibility * activation, or touch exploration activation changes. */ public void setOnAccessibilityChangeListener(@Nullable OnAccessibilityChangeListener listener) { this.onAccessibilityChangeListener = listener; } /** Sends the current value of {@link #accessibilityFeatureFlags} to Flutter. */ private void sendLatestAccessibilityFlagsToFlutter() { accessibilityChannel.setAccessibilityFeatures(accessibilityFeatureFlags); } private boolean shouldSetCollectionInfo(final SemanticsNode semanticsNode) { // TalkBack expects a number of rows and/or columns greater than 0 to announce // in list and out of list. For an infinite or growing list, you have to // specify something > 0 to get "in list" announcements. // TalkBack will also only track one list at a time, so we only want to set this // for a list that contains the current a11y focused semanticsNode - otherwise, if there // are two lists or nested lists, we may end up with announcements for only the last // one that is currently available in the semantics tree. However, we also want // to set it if we're exiting a list to a non-list, so that we can get the "out of list" // announcement when A11y focus moves out of a list and not into another list. return semanticsNode.scrollChildren > 0 && (SemanticsNode.nullableHasAncestor( accessibilityFocusedSemanticsNode, o -> o == semanticsNode) || !SemanticsNode.nullableHasAncestor( accessibilityFocusedSemanticsNode, o -> o.hasFlag(Flag.HAS_IMPLICIT_SCROLLING))); } @TargetApi(API_LEVELS.API_31) @RequiresApi(API_LEVELS.API_31) private void setBoldTextFlag() { if (rootAccessibilityView == null || rootAccessibilityView.getResources() == null) { return; } int fontWeightAdjustment = rootAccessibilityView.getResources().getConfiguration().fontWeightAdjustment; boolean shouldBold = fontWeightAdjustment != Configuration.FONT_WEIGHT_ADJUSTMENT_UNDEFINED && fontWeightAdjustment >= BOLD_TEXT_WEIGHT_ADJUSTMENT; if (shouldBold) { accessibilityFeatureFlags |= AccessibilityFeature.BOLD_TEXT.value; } else { accessibilityFeatureFlags &= AccessibilityFeature.BOLD_TEXT.value; } sendLatestAccessibilityFlagsToFlutter(); } @VisibleForTesting public AccessibilityNodeInfo obtainAccessibilityNodeInfo(View rootView) { return AccessibilityNodeInfo.obtain(rootView); } @VisibleForTesting public AccessibilityNodeInfo obtainAccessibilityNodeInfo(View rootView, int virtualViewId) { return AccessibilityNodeInfo.obtain(rootView, virtualViewId); } /** * Returns {@link AccessibilityNodeInfo} for the view corresponding to the given {@code * virtualViewId}. * * <p>This method is invoked by Android's accessibility system when Android needs accessibility * info for a given view. * * <p>When a {@code virtualViewId} of {@link View#NO_ID} is requested, accessibility node info is * returned for our {@link #rootAccessibilityView}. Otherwise, Flutter's semantics tree, * represented by {@link #flutterSemanticsTree}, is searched for a {@link SemanticsNode} with the * given {@code virtualViewId}. If no such {@link SemanticsNode} is found, then this method * returns null. If the desired {@link SemanticsNode} is found, then an {@link * AccessibilityNodeInfo} is obtained from the {@link #rootAccessibilityView}, filled with * appropriate info, and then returned. * * <p>Depending on the type of Flutter {@code SemanticsNode} that is requested, the returned * {@link AccessibilityNodeInfo} pretends that the {@code SemanticsNode} in question comes from a * specialize Android view, e.g., {@link Flag#IS_TEXT_FIELD} maps to {@code * android.widget.EditText}, {@link Flag#IS_BUTTON} maps to {@code android.widget.Button}, and * {@link Flag#IS_IMAGE} maps to {@code android.widget.ImageView}. In the case that no specialized * view applies, the returned {@link AccessibilityNodeInfo} pretends that it represents a {@code * android.view.View}. */ @Override @SuppressWarnings("deprecation") // Suppressing Lint warning for new API, as we are version guarding all calls to newer APIs @SuppressLint("NewApi") public AccessibilityNodeInfo createAccessibilityNodeInfo(int virtualViewId) { setAccessibleNavigation(true); if (virtualViewId >= MIN_ENGINE_GENERATED_NODE_ID) { // The node is in the engine generated range, and is provided by the accessibility view // embedder. return accessibilityViewEmbedder.createAccessibilityNodeInfo(virtualViewId); } if (virtualViewId == View.NO_ID) { AccessibilityNodeInfo result = obtainAccessibilityNodeInfo(rootAccessibilityView); rootAccessibilityView.onInitializeAccessibilityNodeInfo(result); // TODO(mattcarroll): what does it mean for the semantics tree to contain or not contain // the root node ID? if (flutterSemanticsTree.containsKey(ROOT_NODE_ID)) { result.addChild(rootAccessibilityView, ROOT_NODE_ID); } if (Build.VERSION.SDK_INT >= API_LEVELS.API_24) { result.setImportantForAccessibility(false); } return result; } SemanticsNode semanticsNode = flutterSemanticsTree.get(virtualViewId); if (semanticsNode == null) { return null; } // Generate accessibility node for platform views using a virtual display. // // In this case, register the accessibility node in the view embedder, // so the accessibility tree can be mirrored as a subtree of the Flutter accessibility tree. // This is in constrast to hybrid composition where the embedded view is in the view hiearchy, // so it doesn't need to be mirrored. // // See the case down below for how hybrid composition is handled. if (semanticsNode.platformViewId != -1) { if (platformViewsAccessibilityDelegate.usesVirtualDisplay(semanticsNode.platformViewId)) { View embeddedView = platformViewsAccessibilityDelegate.getPlatformViewById(semanticsNode.platformViewId); if (embeddedView == null) { return null; } Rect bounds = semanticsNode.getGlobalRect(); return accessibilityViewEmbedder.getRootNode(embeddedView, semanticsNode.id, bounds); } } AccessibilityNodeInfo result = obtainAccessibilityNodeInfo(rootAccessibilityView, virtualViewId); // Accessibility Scanner uses isImportantForAccessibility to decide whether to check // or skip this node. if (Build.VERSION.SDK_INT >= API_LEVELS.API_24) { result.setImportantForAccessibility(isImportant(semanticsNode)); } // Work around for https://github.com/flutter/flutter/issues/21030 result.setViewIdResourceName(""); if (semanticsNode.identifier != null) { result.setViewIdResourceName(semanticsNode.identifier); } result.setPackageName(rootAccessibilityView.getContext().getPackageName()); result.setClassName("android.view.View"); result.setSource(rootAccessibilityView, virtualViewId); result.setFocusable(semanticsNode.isFocusable()); if (inputFocusedSemanticsNode != null) { result.setFocused(inputFocusedSemanticsNode.id == virtualViewId); } if (accessibilityFocusedSemanticsNode != null) { result.setAccessibilityFocused(accessibilityFocusedSemanticsNode.id == virtualViewId); } if (semanticsNode.hasFlag(Flag.IS_TEXT_FIELD)) { result.setPassword(semanticsNode.hasFlag(Flag.IS_OBSCURED)); if (!semanticsNode.hasFlag(Flag.IS_READ_ONLY)) { result.setClassName("android.widget.EditText"); } result.setEditable(!semanticsNode.hasFlag(Flag.IS_READ_ONLY)); if (semanticsNode.textSelectionBase != -1 && semanticsNode.textSelectionExtent != -1) { result.setTextSelection(semanticsNode.textSelectionBase, semanticsNode.textSelectionExtent); } // Text fields will always be created as a live region when they have input focus, // so that updates to the label trigger polite announcements. This makes it easy to // follow a11y guidelines for text fields on Android. if (accessibilityFocusedSemanticsNode != null && accessibilityFocusedSemanticsNode.id == virtualViewId) { result.setLiveRegion(View.ACCESSIBILITY_LIVE_REGION_POLITE); } // Cursor movements int granularities = 0; if (semanticsNode.hasAction(Action.MOVE_CURSOR_FORWARD_BY_CHARACTER)) { result.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); granularities |= AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER; } if (semanticsNode.hasAction(Action.MOVE_CURSOR_BACKWARD_BY_CHARACTER)) { result.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); granularities |= AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER; } if (semanticsNode.hasAction(Action.MOVE_CURSOR_FORWARD_BY_WORD)) { result.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); granularities |= AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD; } if (semanticsNode.hasAction(Action.MOVE_CURSOR_BACKWARD_BY_WORD)) { result.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); granularities |= AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD; } result.setMovementGranularities(granularities); if (semanticsNode.maxValueLength >= 0) { // Account for the fact that Flutter is counting Unicode scalar values and Android // is counting UTF16 words. final int length = semanticsNode.value == null ? 0 : semanticsNode.value.length(); int a = length - semanticsNode.currentValueLength + semanticsNode.maxValueLength; result.setMaxTextLength( length - semanticsNode.currentValueLength + semanticsNode.maxValueLength); } } // These are non-ops on older devices. Attempting to interact with the text will cause Talkback // to read the contents of the text box instead. if (semanticsNode.hasAction(Action.SET_SELECTION)) { result.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); } if (semanticsNode.hasAction(Action.COPY)) { result.addAction(AccessibilityNodeInfo.ACTION_COPY); } if (semanticsNode.hasAction(Action.CUT)) { result.addAction(AccessibilityNodeInfo.ACTION_CUT); } if (semanticsNode.hasAction(Action.PASTE)) { result.addAction(AccessibilityNodeInfo.ACTION_PASTE); } if (semanticsNode.hasAction(Action.SET_TEXT)) { result.addAction(AccessibilityNodeInfo.ACTION_SET_TEXT); } if (semanticsNode.hasFlag(Flag.IS_BUTTON) || semanticsNode.hasFlag(Flag.IS_LINK)) { result.setClassName("android.widget.Button"); } if (semanticsNode.hasFlag(Flag.IS_IMAGE)) { result.setClassName("android.widget.ImageView"); // TODO(jonahwilliams): Figure out a way conform to the expected id from TalkBack's // CustomLabelManager. talkback/src/main/java/labeling/CustomLabelManager.java#L525 } if (semanticsNode.hasAction(Action.DISMISS)) { result.setDismissable(true); result.addAction(AccessibilityNodeInfo.ACTION_DISMISS); } if (semanticsNode.parent != null) { if (BuildConfig.DEBUG && semanticsNode.id <= ROOT_NODE_ID) { Log.e(TAG, "Semantics node id is not > ROOT_NODE_ID."); } result.setParent(rootAccessibilityView, semanticsNode.parent.id); } else { if (BuildConfig.DEBUG && semanticsNode.id != ROOT_NODE_ID) { Log.e(TAG, "Semantics node id does not equal ROOT_NODE_ID."); } result.setParent(rootAccessibilityView); } if (semanticsNode.previousNodeId != -1 && Build.VERSION.SDK_INT >= API_LEVELS.API_22) { result.setTraversalAfter(rootAccessibilityView, semanticsNode.previousNodeId); } Rect bounds = semanticsNode.getGlobalRect(); if (semanticsNode.parent != null) { Rect parentBounds = semanticsNode.parent.getGlobalRect(); Rect boundsInParent = new Rect(bounds); boundsInParent.offset(-parentBounds.left, -parentBounds.top); result.setBoundsInParent(boundsInParent); } else { result.setBoundsInParent(bounds); } final Rect boundsInScreen = getBoundsInScreen(bounds); result.setBoundsInScreen(boundsInScreen); result.setVisibleToUser(true); result.setEnabled( !semanticsNode.hasFlag(Flag.HAS_ENABLED_STATE) || semanticsNode.hasFlag(Flag.IS_ENABLED)); if (semanticsNode.hasAction(Action.TAP)) { if (semanticsNode.onTapOverride != null) { result.addAction( new AccessibilityNodeInfo.AccessibilityAction( AccessibilityNodeInfo.ACTION_CLICK, semanticsNode.onTapOverride.hint)); result.setClickable(true); } else { result.addAction(AccessibilityNodeInfo.ACTION_CLICK); result.setClickable(true); } } if (semanticsNode.hasAction(Action.LONG_PRESS)) { if (semanticsNode.onLongPressOverride != null) { result.addAction( new AccessibilityNodeInfo.AccessibilityAction( AccessibilityNodeInfo.ACTION_LONG_CLICK, semanticsNode.onLongPressOverride.hint)); result.setLongClickable(true); } else { result.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); result.setLongClickable(true); } } if (semanticsNode.hasAction(Action.SCROLL_LEFT) || semanticsNode.hasAction(Action.SCROLL_UP) || semanticsNode.hasAction(Action.SCROLL_RIGHT) || semanticsNode.hasAction(Action.SCROLL_DOWN)) { result.setScrollable(true); // This tells Android's a11y to send scroll events when reaching the end of // the visible viewport of a scrollable, unless the node itself does not // allow implicit scrolling - then we leave the className as view.View. // // We should prefer setCollectionInfo to the class names, as this way we get "In List" // and "Out of list" announcements. But we don't always know the counts, so we // can fallback to the generic scroll view class names. // // On older APIs, we always fall back to the generic scroll view class names here. // // TODO(dnfield): We should add semantics properties for rows and columns in 2 dimensional // lists, e.g. // GridView. Right now, we're only supporting ListViews and only if they have scroll // children. if (semanticsNode.hasFlag(Flag.HAS_IMPLICIT_SCROLLING)) { if (semanticsNode.hasAction(Action.SCROLL_LEFT) || semanticsNode.hasAction(Action.SCROLL_RIGHT)) { if (shouldSetCollectionInfo(semanticsNode)) { result.setCollectionInfo( AccessibilityNodeInfo.CollectionInfo.obtain( 0, // rows semanticsNode.scrollChildren, // columns false // hierarchical )); } else { result.setClassName("android.widget.HorizontalScrollView"); } } else { if (shouldSetCollectionInfo(semanticsNode)) { result.setCollectionInfo( AccessibilityNodeInfo.CollectionInfo.obtain( semanticsNode.scrollChildren, // rows 0, // columns false // hierarchical )); } else { result.setClassName("android.widget.ScrollView"); } } } // TODO(ianh): Once we're on SDK v23+, call addAction to // expose AccessibilityAction.ACTION_SCROLL_LEFT, _RIGHT, // _UP, and _DOWN when appropriate. if (semanticsNode.hasAction(Action.SCROLL_LEFT) || semanticsNode.hasAction(Action.SCROLL_UP)) { result.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD); } if (semanticsNode.hasAction(Action.SCROLL_RIGHT) || semanticsNode.hasAction(Action.SCROLL_DOWN)) { result.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD); } } if (semanticsNode.hasAction(Action.INCREASE) || semanticsNode.hasAction(Action.DECREASE)) { // TODO(jonahwilliams): support AccessibilityAction.ACTION_SET_PROGRESS once SDK is // updated. result.setClassName("android.widget.SeekBar"); if (semanticsNode.hasAction(Action.INCREASE)) { result.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD); } if (semanticsNode.hasAction(Action.DECREASE)) { result.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD); } } if (semanticsNode.hasFlag(Flag.IS_LIVE_REGION)) { result.setLiveRegion(View.ACCESSIBILITY_LIVE_REGION_POLITE); } // Scopes routes are not focusable, only need to set the content // for non-scopes-routes semantics nodes. if (semanticsNode.hasFlag(Flag.IS_TEXT_FIELD)) { result.setText(semanticsNode.getValue()); if (Build.VERSION.SDK_INT >= API_LEVELS.API_28) { result.setHintText(semanticsNode.getTextFieldHint()); } } else if (!semanticsNode.hasFlag(Flag.SCOPES_ROUTE)) { CharSequence content = semanticsNode.getValueLabelHint(); if (Build.VERSION.SDK_INT < API_LEVELS.API_28) { if (semanticsNode.tooltip != null) { // For backward compatibility with Flutter SDK before Android API // level 28, the tooltip is appended at the end of content description. content = content != null ? content : ""; content = content + "\n" + semanticsNode.tooltip; } } if (content != null) { result.setContentDescription(content); } } if (Build.VERSION.SDK_INT >= API_LEVELS.API_28) { if (semanticsNode.tooltip != null) { result.setTooltipText(semanticsNode.tooltip); } } boolean hasCheckedState = semanticsNode.hasFlag(Flag.HAS_CHECKED_STATE); boolean hasToggledState = semanticsNode.hasFlag(Flag.HAS_TOGGLED_STATE); if (BuildConfig.DEBUG && (hasCheckedState && hasToggledState)) { Log.e(TAG, "Expected semanticsNode to have checked state and toggled state."); } result.setCheckable(hasCheckedState || hasToggledState); if (hasCheckedState) { result.setChecked(semanticsNode.hasFlag(Flag.IS_CHECKED)); if (semanticsNode.hasFlag(Flag.IS_IN_MUTUALLY_EXCLUSIVE_GROUP)) { result.setClassName("android.widget.RadioButton"); } else { result.setClassName("android.widget.CheckBox"); } } else if (hasToggledState) { result.setChecked(semanticsNode.hasFlag(Flag.IS_TOGGLED)); result.setClassName("android.widget.Switch"); } result.setSelected(semanticsNode.hasFlag(Flag.IS_SELECTED)); // Heading support if (Build.VERSION.SDK_INT >= API_LEVELS.API_28) { result.setHeading(semanticsNode.hasFlag(Flag.IS_HEADER)); } // Accessibility Focus if (accessibilityFocusedSemanticsNode != null && accessibilityFocusedSemanticsNode.id == virtualViewId) { result.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); } else { result.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); } // Actions on the local context menu if (semanticsNode.customAccessibilityActions != null) { for (CustomAccessibilityAction action : semanticsNode.customAccessibilityActions) { result.addAction( new AccessibilityNodeInfo.AccessibilityAction(action.resourceId, action.label)); } } for (SemanticsNode child : semanticsNode.childrenInTraversalOrder) { if (child.hasFlag(Flag.IS_HIDDEN)) { continue; } if (child.platformViewId != -1) { View embeddedView = platformViewsAccessibilityDelegate.getPlatformViewById(child.platformViewId); // Add the embedded view as a child of the current accessibility node if it's not // using a virtual display. // // In this case, the view is in the Activity's view hierarchy, so it doesn't need to be // mirrored. // // See the case above for how virtual displays are handled. if (!platformViewsAccessibilityDelegate.usesVirtualDisplay(child.platformViewId)) { result.addChild(embeddedView); continue; } } result.addChild(rootAccessibilityView, child.id); } return result; } private boolean isImportant(SemanticsNode node) { if (node.hasFlag(Flag.SCOPES_ROUTE)) { return false; } if (node.getValueLabelHint() != null) { return true; } // Return true if the node has had any user action (not including system actions) return (node.actions & ~systemAction) != 0; } /** * Get the bounds in screen with root FlutterView's offset. * * @param bounds the bounds in FlutterView * @return the bounds with offset */ private Rect getBoundsInScreen(Rect bounds) { Rect boundsInScreen = new Rect(bounds); int[] locationOnScreen = new int[2]; rootAccessibilityView.getLocationOnScreen(locationOnScreen); boundsInScreen.offset(locationOnScreen[0], locationOnScreen[1]); return boundsInScreen; } /** * Instructs the view represented by {@code virtualViewId} to carry out the desired {@code * accessibilityAction}, perhaps configured by additional {@code arguments}. * * <p>This method is invoked by Android's accessibility system. This method returns true if the * desired {@code SemanticsNode} was found and was capable of performing the desired action, false * otherwise. * * <p>In a traditional Android app, the given view ID refers to a {@link View} within an Android * {@link View} hierarchy. Flutter does not have an Android {@link View} hierarchy, therefore the * given view ID is a {@code virtualViewId} that refers to a {@code SemanticsNode} within a * Flutter app. The given arguments of this method are forwarded from Android to Flutter. */ @Override public boolean performAction( int virtualViewId, int accessibilityAction, @Nullable Bundle arguments) { if (virtualViewId >= MIN_ENGINE_GENERATED_NODE_ID) { // The node is in the engine generated range, and is handled by the accessibility view // embedder. boolean didPerform = accessibilityViewEmbedder.performAction(virtualViewId, accessibilityAction, arguments); if (didPerform && accessibilityAction == AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS) { embeddedAccessibilityFocusedNodeId = null; } return didPerform; } SemanticsNode semanticsNode = flutterSemanticsTree.get(virtualViewId); if (semanticsNode == null) { return false; } switch (accessibilityAction) { case AccessibilityNodeInfo.ACTION_CLICK: { // Note: TalkBack prior to Oreo doesn't use this handler and instead simulates a // click event at the center of the SemanticsNode. Other a11y services might go // through this handler though. accessibilityChannel.dispatchSemanticsAction(virtualViewId, Action.TAP); return true; } case AccessibilityNodeInfo.ACTION_LONG_CLICK: { // Note: TalkBack doesn't use this handler and instead simulates a long click event // at the center of the SemanticsNode. Other a11y services might go through this // handler though. accessibilityChannel.dispatchSemanticsAction(virtualViewId, Action.LONG_PRESS); return true; } case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: { if (semanticsNode.hasAction(Action.SCROLL_UP)) { accessibilityChannel.dispatchSemanticsAction(virtualViewId, Action.SCROLL_UP); } else if (semanticsNode.hasAction(Action.SCROLL_LEFT)) { // TODO(ianh): bidi support using textDirection accessibilityChannel.dispatchSemanticsAction(virtualViewId, Action.SCROLL_LEFT); } else if (semanticsNode.hasAction(Action.INCREASE)) { semanticsNode.value = semanticsNode.increasedValue; semanticsNode.valueAttributes = semanticsNode.increasedValueAttributes; // Event causes Android to read out the updated value. sendAccessibilityEvent(virtualViewId, AccessibilityEvent.TYPE_VIEW_SELECTED); accessibilityChannel.dispatchSemanticsAction(virtualViewId, Action.INCREASE); } else { return false; } return true; } case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: { if (semanticsNode.hasAction(Action.SCROLL_DOWN)) { accessibilityChannel.dispatchSemanticsAction(virtualViewId, Action.SCROLL_DOWN); } else if (semanticsNode.hasAction(Action.SCROLL_RIGHT)) { // TODO(ianh): bidi support using textDirection accessibilityChannel.dispatchSemanticsAction(virtualViewId, Action.SCROLL_RIGHT); } else if (semanticsNode.hasAction(Action.DECREASE)) { semanticsNode.value = semanticsNode.decreasedValue; semanticsNode.valueAttributes = semanticsNode.decreasedValueAttributes; // Event causes Android to read out the updated value. sendAccessibilityEvent(virtualViewId, AccessibilityEvent.TYPE_VIEW_SELECTED); accessibilityChannel.dispatchSemanticsAction(virtualViewId, Action.DECREASE); } else { return false; } return true; } case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { return performCursorMoveAction(semanticsNode, virtualViewId, arguments, false); } case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { return performCursorMoveAction(semanticsNode, virtualViewId, arguments, true); } case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { // Focused semantics node must be reset before sending the // TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED event. Otherwise, // TalkBack may think the node is still focused. if (accessibilityFocusedSemanticsNode != null && accessibilityFocusedSemanticsNode.id == virtualViewId) { accessibilityFocusedSemanticsNode = null; } if (embeddedAccessibilityFocusedNodeId != null && embeddedAccessibilityFocusedNodeId == virtualViewId) { embeddedAccessibilityFocusedNodeId = null; } accessibilityChannel.dispatchSemanticsAction( virtualViewId, Action.DID_LOSE_ACCESSIBILITY_FOCUS); sendAccessibilityEvent( virtualViewId, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); return true; } case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { if (accessibilityFocusedSemanticsNode == null) { // When Android focuses a node, it doesn't invalidate the view. // (It does when it sends ACTION_CLEAR_ACCESSIBILITY_FOCUS, so // we only have to worry about this when the focused node is null.) rootAccessibilityView.invalidate(); } // Focused semantics node must be set before sending the TYPE_VIEW_ACCESSIBILITY_FOCUSED // event. Otherwise, TalkBack may think the node is not focused yet. accessibilityFocusedSemanticsNode = semanticsNode; accessibilityChannel.dispatchSemanticsAction( virtualViewId, Action.DID_GAIN_ACCESSIBILITY_FOCUS); HashMap<String, Object> message = new HashMap<>(); message.put("type", "didGainFocus"); message.put("nodeId", semanticsNode.id); accessibilityChannel.channel.send(message); sendAccessibilityEvent(virtualViewId, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); if (semanticsNode.hasAction(Action.INCREASE) || semanticsNode.hasAction(Action.DECREASE)) { // SeekBars only announce themselves after this event. sendAccessibilityEvent(virtualViewId, AccessibilityEvent.TYPE_VIEW_SELECTED); } return true; } case ACTION_SHOW_ON_SCREEN: { accessibilityChannel.dispatchSemanticsAction(virtualViewId, Action.SHOW_ON_SCREEN); return true; } case AccessibilityNodeInfo.ACTION_SET_SELECTION: { final Map<String, Integer> selection = new HashMap<>(); final boolean hasSelection = arguments != null && arguments.containsKey( AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT) && arguments.containsKey(AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT); if (hasSelection) { selection.put( "base", arguments.getInt(AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT)); selection.put( "extent", arguments.getInt(AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT)); } else { // Clear the selection selection.put("base", semanticsNode.textSelectionExtent); selection.put("extent", semanticsNode.textSelectionExtent); } accessibilityChannel.dispatchSemanticsAction( virtualViewId, Action.SET_SELECTION, selection); // The voice access expects the semantics node to update immediately. We update the // semantics node based on prediction. If the result is incorrect, it will be updated in // the next frame. SemanticsNode node = flutterSemanticsTree.get(virtualViewId); node.textSelectionBase = selection.get("base"); node.textSelectionExtent = selection.get("extent"); return true; } case AccessibilityNodeInfo.ACTION_COPY: { accessibilityChannel.dispatchSemanticsAction(virtualViewId, Action.COPY); return true; } case AccessibilityNodeInfo.ACTION_CUT: { accessibilityChannel.dispatchSemanticsAction(virtualViewId, Action.CUT); return true; } case AccessibilityNodeInfo.ACTION_PASTE: { accessibilityChannel.dispatchSemanticsAction(virtualViewId, Action.PASTE); return true; } case AccessibilityNodeInfo.ACTION_DISMISS: { accessibilityChannel.dispatchSemanticsAction(virtualViewId, Action.DISMISS); return true; } case AccessibilityNodeInfo.ACTION_SET_TEXT: { return performSetText(semanticsNode, virtualViewId, arguments); } default: // might be a custom accessibility accessibilityAction. final int flutterId = accessibilityAction - FIRST_RESOURCE_ID; CustomAccessibilityAction contextAction = customAccessibilityActions.get(flutterId); if (contextAction != null) { accessibilityChannel.dispatchSemanticsAction( virtualViewId, Action.CUSTOM_ACTION, contextAction.id); return true; } } return false; } /** * Handles the responsibilities of {@link #performAction(int, int, Bundle)} for the specific * scenario of cursor movement. */ private boolean performCursorMoveAction( @NonNull SemanticsNode semanticsNode, int virtualViewId, @NonNull Bundle arguments, boolean forward) { final int granularity = arguments.getInt(AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); final boolean extendSelection = arguments.getBoolean(AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); // The voice access expects the semantics node to update immediately. We update the semantics // node based on prediction. If the result is incorrect, it will be updated in the next frame. final int previousTextSelectionBase = semanticsNode.textSelectionBase; final int previousTextSelectionExtent = semanticsNode.textSelectionExtent; predictCursorMovement(semanticsNode, granularity, forward, extendSelection); if (previousTextSelectionBase != semanticsNode.textSelectionBase || previousTextSelectionExtent != semanticsNode.textSelectionExtent) { final String value = semanticsNode.value != null ? semanticsNode.value : ""; final AccessibilityEvent selectionEvent = obtainAccessibilityEvent( semanticsNode.id, AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); selectionEvent.getText().add(value); selectionEvent.setFromIndex(semanticsNode.textSelectionBase); selectionEvent.setToIndex(semanticsNode.textSelectionExtent); selectionEvent.setItemCount(value.length()); sendAccessibilityEvent(selectionEvent); } switch (granularity) { case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { if (forward && semanticsNode.hasAction(Action.MOVE_CURSOR_FORWARD_BY_CHARACTER)) { accessibilityChannel.dispatchSemanticsAction( virtualViewId, Action.MOVE_CURSOR_FORWARD_BY_CHARACTER, extendSelection); return true; } if (!forward && semanticsNode.hasAction(Action.MOVE_CURSOR_BACKWARD_BY_CHARACTER)) { accessibilityChannel.dispatchSemanticsAction( virtualViewId, Action.MOVE_CURSOR_BACKWARD_BY_CHARACTER, extendSelection); return true; } break; } case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: if (forward && semanticsNode.hasAction(Action.MOVE_CURSOR_FORWARD_BY_WORD)) { accessibilityChannel.dispatchSemanticsAction( virtualViewId, Action.MOVE_CURSOR_FORWARD_BY_WORD, extendSelection); return true; } if (!forward && semanticsNode.hasAction(Action.MOVE_CURSOR_BACKWARD_BY_WORD)) { accessibilityChannel.dispatchSemanticsAction( virtualViewId, Action.MOVE_CURSOR_BACKWARD_BY_WORD, extendSelection); return true; } break; case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_LINE: case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PAGE: return true; } return false; } private void predictCursorMovement( @NonNull SemanticsNode node, int granularity, boolean forward, boolean extendSelection) { if (node.textSelectionExtent < 0 || node.textSelectionBase < 0) { return; } switch (granularity) { case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: if (forward && node.textSelectionExtent < node.value.length()) { node.textSelectionExtent += 1; } else if (!forward && node.textSelectionExtent > 0) { node.textSelectionExtent -= 1; } break; case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: if (forward && node.textSelectionExtent < node.value.length()) { Pattern pattern = Pattern.compile("\\p{L}(\\b)"); Matcher result = pattern.matcher(node.value.substring(node.textSelectionExtent)); // we discard the first result because we want to find the "next" word result.find(); if (result.find()) { node.textSelectionExtent += result.start(1); } else { node.textSelectionExtent = node.value.length(); } } else if (!forward && node.textSelectionExtent > 0) { // Finds last beginning of the word boundary. Pattern pattern = Pattern.compile("(?s:.*)(\\b)\\p{L}"); Matcher result = pattern.matcher(node.value.substring(0, node.textSelectionExtent)); if (result.find()) { node.textSelectionExtent = result.start(1); } } break; case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_LINE: if (forward && node.textSelectionExtent < node.value.length()) { // Finds the next new line. Pattern pattern = Pattern.compile("(?!^)(\\n)"); Matcher result = pattern.matcher(node.value.substring(node.textSelectionExtent)); if (result.find()) { node.textSelectionExtent += result.start(1); } else { node.textSelectionExtent = node.value.length(); } } else if (!forward && node.textSelectionExtent > 0) { // Finds the last new line. Pattern pattern = Pattern.compile("(?s:.*)(\\n)"); Matcher result = pattern.matcher(node.value.substring(0, node.textSelectionExtent)); if (result.find()) { node.textSelectionExtent = result.start(1); } else { node.textSelectionExtent = 0; } } break; case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PAGE: if (forward) { node.textSelectionExtent = node.value.length(); } else { node.textSelectionExtent = 0; } break; } if (!extendSelection) { node.textSelectionBase = node.textSelectionExtent; } } /** * Handles the responsibilities of {@link #performAction(int, int, Bundle)} for the specific * scenario of cursor movement. */ private boolean performSetText(SemanticsNode node, int virtualViewId, @NonNull Bundle arguments) { String newText = ""; if (arguments != null && arguments.containsKey(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE)) { newText = arguments.getString(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE); } accessibilityChannel.dispatchSemanticsAction(virtualViewId, Action.SET_TEXT, newText); // The voice access expects the semantics node to update immediately. Update the semantics // node based on prediction. If the result is incorrect, it will be updated in the next frame. node.value = newText; node.valueAttributes = null; return true; } // TODO(ianh): implement findAccessibilityNodeInfosByText() /** * Finds the view in a hierarchy that currently has the given type of {@code focus}. * * <p>This method is invoked by Android's accessibility system. * * <p>Flutter does not have an Android {@link View} hierarchy. Therefore, Flutter conceptually * handles this request by searching its semantics tree for the given {@code focus}, represented * by {@link #flutterSemanticsTree}. In practice, this {@code AccessibilityBridge} always caches * any active {@link #accessibilityFocusedSemanticsNode} and {@link #inputFocusedSemanticsNode}. * Therefore, no searching is necessary. This method directly inspects the given {@code focus} * type to return one of the cached nodes, null if the cached node is null, or null if a different * {@code focus} type is requested. */ @Override public AccessibilityNodeInfo findFocus(int focus) { switch (focus) { case AccessibilityNodeInfo.FOCUS_INPUT: { if (inputFocusedSemanticsNode != null) { return createAccessibilityNodeInfo(inputFocusedSemanticsNode.id); } if (embeddedInputFocusedNodeId != null) { return createAccessibilityNodeInfo(embeddedInputFocusedNodeId); } } // Fall through to check FOCUS_ACCESSIBILITY case AccessibilityNodeInfo.FOCUS_ACCESSIBILITY: { if (accessibilityFocusedSemanticsNode != null) { return createAccessibilityNodeInfo(accessibilityFocusedSemanticsNode.id); } if (embeddedAccessibilityFocusedNodeId != null) { return createAccessibilityNodeInfo(embeddedAccessibilityFocusedNodeId); } } } return null; } /** Returns the {@link SemanticsNode} at the root of Flutter's semantics tree. */ private SemanticsNode getRootSemanticsNode() { if (BuildConfig.DEBUG && !flutterSemanticsTree.containsKey(0)) { Log.e(TAG, "Attempted to getRootSemanticsNode without a root semantics node."); } return flutterSemanticsTree.get(0); } /** * Returns an existing {@link SemanticsNode} with the given {@code id}, if it exists within {@link * #flutterSemanticsTree}, or creates and returns a new {@link SemanticsNode} with the given * {@code id}, adding the new {@link SemanticsNode} to the {@link #flutterSemanticsTree}. * * <p>This method should only be invoked as a result of receiving new information from Flutter. * The {@link #flutterSemanticsTree} is an Android cache of the last known state of a Flutter * app's semantics tree, therefore, invoking this method in any other situation will result in a * corrupt cache of Flutter's semantics tree. */ private SemanticsNode getOrCreateSemanticsNode(int id) { SemanticsNode semanticsNode = flutterSemanticsTree.get(id); if (semanticsNode == null) { semanticsNode = new SemanticsNode(this); semanticsNode.id = id; flutterSemanticsTree.put(id, semanticsNode); } return semanticsNode; } /** * Returns an existing {@link CustomAccessibilityAction} with the given {@code id}, if it exists * within {@link #customAccessibilityActions}, or creates and returns a new {@link * CustomAccessibilityAction} with the given {@code id}, adding the new {@link * CustomAccessibilityAction} to the {@link #customAccessibilityActions}. * * <p>This method should only be invoked as a result of receiving new information from Flutter. * The {@link #customAccessibilityActions} is an Android cache of the last known state of a * Flutter app's registered custom accessibility actions, therefore, invoking this method in any * other situation will result in a corrupt cache of Flutter's accessibility actions. */ private CustomAccessibilityAction getOrCreateAccessibilityAction(int id) { CustomAccessibilityAction action = customAccessibilityActions.get(id); if (action == null) { action = new CustomAccessibilityAction(); action.id = id; action.resourceId = id + FIRST_RESOURCE_ID; customAccessibilityActions.put(id, action); } return action; } /** * A hover {@link MotionEvent} has occurred in the {@code View} that corresponds to this {@code * AccessibilityBridge}. * * <p>This method returns true if Flutter's accessibility system handled the hover event, false * otherwise. * * <p>This method should be invoked from the corresponding {@code View}'s {@link * View#onHoverEvent(MotionEvent)}. */ public boolean onAccessibilityHoverEvent(MotionEvent event) { return onAccessibilityHoverEvent(event, false); } /** * A hover {@link MotionEvent} has occurred in the {@code View} that corresponds to this {@code * AccessibilityBridge}. * * <p>If {@code ignorePlatformViews} is true, if hit testing for the event finds a platform view, * the event will not be handled. This is useful when handling accessibility events for views * overlaying platform views. See {@code PlatformOverlayView} for details. * * <p>This method returns true if Flutter's accessibility system handled the hover event, false * otherwise. * * <p>This method should be invoked from the corresponding {@code View}'s {@link * View#onHoverEvent(MotionEvent)}. */ public boolean onAccessibilityHoverEvent(MotionEvent event, boolean ignorePlatformViews) { if (!accessibilityManager.isTouchExplorationEnabled()) { return false; } if (flutterSemanticsTree.isEmpty()) { return false; } SemanticsNode semanticsNodeUnderCursor = getRootSemanticsNode() .hitTest(new float[] {event.getX(), event.getY(), 0, 1}, ignorePlatformViews); // semanticsNodeUnderCursor can be null when hovering over non-flutter UI such as // the Android navigation bar due to hitTest() bounds checking. if (semanticsNodeUnderCursor != null && semanticsNodeUnderCursor.platformViewId != -1) { if (ignorePlatformViews) { return false; } return accessibilityViewEmbedder.onAccessibilityHoverEvent( semanticsNodeUnderCursor.id, event); } if (event.getAction() == MotionEvent.ACTION_HOVER_ENTER || event.getAction() == MotionEvent.ACTION_HOVER_MOVE) { handleTouchExploration(event.getX(), event.getY(), ignorePlatformViews); } else if (event.getAction() == MotionEvent.ACTION_HOVER_EXIT) { onTouchExplorationExit(); } else { Log.d("flutter", "unexpected accessibility hover event: " + event); return false; } return true; } /** * This method should be invoked when a hover interaction has the cursor move off of a {@code * SemanticsNode}. * * <p>This method informs the Android accessibility system that a {@link * AccessibilityEvent#TYPE_VIEW_HOVER_EXIT} has occurred. */ private void onTouchExplorationExit() { if (hoveredObject != null) { sendAccessibilityEvent(hoveredObject.id, AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); hoveredObject = null; } } /** * This method should be invoked when a new hover interaction begins with a {@code SemanticsNode}, * or when an existing hover interaction sees a movement of the cursor. * * <p>This method checks to see if the cursor has moved from one {@code SemanticsNode} to another. * If it has, this method informs the Android accessibility system of the change by first sending * a {@link AccessibilityEvent#TYPE_VIEW_HOVER_ENTER} event for the new hover node, followed by a * {@link AccessibilityEvent#TYPE_VIEW_HOVER_EXIT} event for the old hover node. */ private void handleTouchExploration(float x, float y, boolean ignorePlatformViews) { if (flutterSemanticsTree.isEmpty()) { return; } SemanticsNode semanticsNodeUnderCursor = getRootSemanticsNode().hitTest(new float[] {x, y, 0, 1}, ignorePlatformViews); if (semanticsNodeUnderCursor != hoveredObject) { // sending ENTER before EXIT is how Android wants it if (semanticsNodeUnderCursor != null) { sendAccessibilityEvent( semanticsNodeUnderCursor.id, AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); } if (hoveredObject != null) { sendAccessibilityEvent(hoveredObject.id, AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); } hoveredObject = semanticsNodeUnderCursor; } } /** * Updates the Android cache of Flutter's currently registered custom accessibility actions. * * <p>The buffer received here is encoded by PlatformViewAndroid::UpdateSemantics, and the decode * logic here must be kept in sync with that method's encoding logic. */ // TODO(mattcarroll): Consider introducing ability to delete custom actions because they can // probably come and go in Flutter, so we may want to reflect that here in // the Android cache as well. void updateCustomAccessibilityActions(@NonNull ByteBuffer buffer, @NonNull String[] strings) { while (buffer.hasRemaining()) { int id = buffer.getInt(); CustomAccessibilityAction action = getOrCreateAccessibilityAction(id); action.overrideId = buffer.getInt(); int stringIndex = buffer.getInt(); action.label = stringIndex == -1 ? null : strings[stringIndex]; stringIndex = buffer.getInt(); action.hint = stringIndex == -1 ? null : strings[stringIndex]; } } /** * Updates {@link #flutterSemanticsTree} to reflect the latest state of Flutter's semantics tree. * * <p>The latest state of Flutter's semantics tree is encoded in the given {@code buffer}. The * buffer is encoded by PlatformViewAndroid::UpdateSemantics, and the decode logic must be kept in * sync with that method's encoding logic. */ void updateSemantics( @NonNull ByteBuffer buffer, @NonNull String[] strings, @NonNull ByteBuffer[] stringAttributeArgs) { ArrayList<SemanticsNode> updated = new ArrayList<>(); while (buffer.hasRemaining()) { int id = buffer.getInt(); SemanticsNode semanticsNode = getOrCreateSemanticsNode(id); semanticsNode.updateWith(buffer, strings, stringAttributeArgs); if (semanticsNode.hasFlag(Flag.IS_HIDDEN)) { continue; } if (semanticsNode.hasFlag(Flag.IS_FOCUSED)) { inputFocusedSemanticsNode = semanticsNode; } if (semanticsNode.hadPreviousConfig) { updated.add(semanticsNode); } if (semanticsNode.platformViewId != -1 && !platformViewsAccessibilityDelegate.usesVirtualDisplay(semanticsNode.platformViewId)) { View embeddedView = platformViewsAccessibilityDelegate.getPlatformViewById(semanticsNode.platformViewId); if (embeddedView != null) { embeddedView.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_AUTO); } } } Set<SemanticsNode> visitedObjects = new HashSet<>(); SemanticsNode rootObject = getRootSemanticsNode(); List<SemanticsNode> newRoutes = new ArrayList<>(); if (rootObject != null) { final float[] identity = new float[16]; Matrix.setIdentityM(identity, 0); // In Android devices API 23 and above, the system nav bar can be placed on the left side // of the screen in landscape mode. We must handle the translation ourselves for the // a11y nodes. if (Build.VERSION.SDK_INT >= API_LEVELS.API_23) { boolean needsToApplyLeftCutoutInset = true; // In Android devices API 28 and above, the `layoutInDisplayCutoutMode` window attribute // can be set to allow overlapping content within the cutout area. Query the attribute // to figure out whether the content overlaps with the cutout and decide whether to // apply cutout inset. if (Build.VERSION.SDK_INT >= API_LEVELS.API_28) { needsToApplyLeftCutoutInset = doesLayoutInDisplayCutoutModeRequireLeftInset(); } if (needsToApplyLeftCutoutInset) { WindowInsets insets = rootAccessibilityView.getRootWindowInsets(); if (insets != null) { if (!lastLeftFrameInset.equals(insets.getSystemWindowInsetLeft())) { rootObject.globalGeometryDirty = true; rootObject.inverseTransformDirty = true; } lastLeftFrameInset = insets.getSystemWindowInsetLeft(); Matrix.translateM(identity, 0, lastLeftFrameInset, 0, 0); } } } rootObject.updateRecursively(identity, visitedObjects, false); rootObject.collectRoutes(newRoutes); } // Dispatch a TYPE_WINDOW_STATE_CHANGED event if the most recent route id changed from the // previously cached route id. // Finds the last route that is not in the previous routes. SemanticsNode lastAdded = null; for (SemanticsNode semanticsNode : newRoutes) { if (!flutterNavigationStack.contains(semanticsNode.id)) { lastAdded = semanticsNode; } } // If all the routes are in the previous route, get the last route. if (lastAdded == null && newRoutes.size() > 0) { lastAdded = newRoutes.get(newRoutes.size() - 1); } // There are two cases if lastAdded != nil // 1. lastAdded is not in previous routes. In this case, // lastAdded.id != previousRouteId // 2. All new routes are in previous routes and // lastAdded = newRoutes.last. // In the first case, we need to announce new route. In the second case, // we need to announce if one list is shorter than the other. if (lastAdded != null && (lastAdded.id != previousRouteId || newRoutes.size() != flutterNavigationStack.size())) { previousRouteId = lastAdded.id; onWindowNameChange(lastAdded); } flutterNavigationStack.clear(); for (SemanticsNode semanticsNode : newRoutes) { flutterNavigationStack.add(semanticsNode.id); } Iterator<Map.Entry<Integer, SemanticsNode>> it = flutterSemanticsTree.entrySet().iterator(); while (it.hasNext()) { Map.Entry<Integer, SemanticsNode> entry = it.next(); SemanticsNode object = entry.getValue(); if (!visitedObjects.contains(object)) { willRemoveSemanticsNode(object); it.remove(); } } // TODO(goderbauer): Send this event only once (!) for changed subtrees, // see https://github.com/flutter/flutter/issues/14534 sendWindowContentChangeEvent(0); for (SemanticsNode object : updated) { if (object.didScroll()) { AccessibilityEvent event = obtainAccessibilityEvent(object.id, AccessibilityEvent.TYPE_VIEW_SCROLLED); // Android doesn't support unbound scrolling. So we pretend there is a large // bound (SCROLL_EXTENT_FOR_INFINITY), which you can never reach. float position = object.scrollPosition; float max = object.scrollExtentMax; if (Float.isInfinite(object.scrollExtentMax)) { max = SCROLL_EXTENT_FOR_INFINITY; if (position > SCROLL_POSITION_CAP_FOR_INFINITY) { position = SCROLL_POSITION_CAP_FOR_INFINITY; } } if (Float.isInfinite(object.scrollExtentMin)) { max += SCROLL_EXTENT_FOR_INFINITY; if (position < -SCROLL_POSITION_CAP_FOR_INFINITY) { position = -SCROLL_POSITION_CAP_FOR_INFINITY; } position += SCROLL_EXTENT_FOR_INFINITY; } else { max -= object.scrollExtentMin; position -= object.scrollExtentMin; } if (object.hadAction(Action.SCROLL_UP) || object.hadAction(Action.SCROLL_DOWN)) { event.setScrollY((int) position); event.setMaxScrollY((int) max); } else if (object.hadAction(Action.SCROLL_LEFT) || object.hadAction(Action.SCROLL_RIGHT)) { event.setScrollX((int) position); event.setMaxScrollX((int) max); } if (object.scrollChildren > 0) { // We don't need to add 1 to the scroll index because TalkBack does this automagically. event.setItemCount(object.scrollChildren); event.setFromIndex(object.scrollIndex); int visibleChildren = 0; // handle hidden children at the beginning and end of the list. for (SemanticsNode child : object.childrenInHitTestOrder) { if (!child.hasFlag(Flag.IS_HIDDEN)) { visibleChildren += 1; } } if (BuildConfig.DEBUG) { if (object.scrollIndex + visibleChildren > object.scrollChildren) { Log.e(TAG, "Scroll index is out of bounds."); } if (object.childrenInHitTestOrder.isEmpty()) { Log.e(TAG, "Had scrollChildren but no childrenInHitTestOrder"); } } // The setToIndex should be the index of the last visible child. Because we counted all // children, including the first index we need to subtract one. // // [0, 1, 2, 3, 4, 5] // ^ ^ // In the example above where 0 is the first visible index and 2 is the last, we will // count 3 total visible children. We then subtract one to get the correct last visible // index of 2. event.setToIndex(object.scrollIndex + visibleChildren - 1); } sendAccessibilityEvent(event); } if (object.hasFlag(Flag.IS_LIVE_REGION) && object.didChangeLabel()) { sendWindowContentChangeEvent(object.id); } if (accessibilityFocusedSemanticsNode != null && accessibilityFocusedSemanticsNode.id == object.id && !object.hadFlag(Flag.IS_SELECTED) && object.hasFlag(Flag.IS_SELECTED)) { AccessibilityEvent event = obtainAccessibilityEvent(object.id, AccessibilityEvent.TYPE_VIEW_SELECTED); event.getText().add(object.label); sendAccessibilityEvent(event); } // If the object is the input-focused node, then tell the reader about it, but only if // it has changed since the last update. if (inputFocusedSemanticsNode != null && inputFocusedSemanticsNode.id == object.id && (lastInputFocusedSemanticsNode == null || lastInputFocusedSemanticsNode.id != inputFocusedSemanticsNode.id)) { lastInputFocusedSemanticsNode = inputFocusedSemanticsNode; sendAccessibilityEvent( obtainAccessibilityEvent(object.id, AccessibilityEvent.TYPE_VIEW_FOCUSED)); } else if (inputFocusedSemanticsNode == null) { // There's no TYPE_VIEW_CLEAR_FOCUSED event, so if the current input focus becomes // null, then we just set the last one to null too, so that it sends the event again // when something regains focus. lastInputFocusedSemanticsNode = null; } if (inputFocusedSemanticsNode != null && inputFocusedSemanticsNode.id == object.id && object.hadFlag(Flag.IS_TEXT_FIELD) && object.hasFlag(Flag.IS_TEXT_FIELD) // If we have a TextField that has InputFocus, we should avoid announcing it if something // else we track has a11y focus. This needs to still work when, e.g., IME has a11y focus // or the "PASTE" popup is used though. // See more discussion at https://github.com/flutter/flutter/issues/23180 && (accessibilityFocusedSemanticsNode == null || (accessibilityFocusedSemanticsNode.id == inputFocusedSemanticsNode.id))) { String oldValue = object.previousValue != null ? object.previousValue : ""; String newValue = object.value != null ? object.value : ""; AccessibilityEvent event = createTextChangedEvent(object.id, oldValue, newValue); if (event != null) { sendAccessibilityEvent(event); } if (object.previousTextSelectionBase != object.textSelectionBase || object.previousTextSelectionExtent != object.textSelectionExtent) { AccessibilityEvent selectionEvent = obtainAccessibilityEvent( object.id, AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); selectionEvent.getText().add(newValue); selectionEvent.setFromIndex(object.textSelectionBase); selectionEvent.setToIndex(object.textSelectionExtent); selectionEvent.setItemCount(newValue.length()); sendAccessibilityEvent(selectionEvent); } } } } private AccessibilityEvent createTextChangedEvent(int id, String oldValue, String newValue) { AccessibilityEvent e = obtainAccessibilityEvent(id, AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED); e.setBeforeText(oldValue); e.getText().add(newValue); int i; for (i = 0; i < oldValue.length() && i < newValue.length(); ++i) { if (oldValue.charAt(i) != newValue.charAt(i)) { break; } } if (i >= oldValue.length() && i >= newValue.length()) { return null; // Text did not change } int firstDifference = i; e.setFromIndex(firstDifference); int oldIndex = oldValue.length() - 1; int newIndex = newValue.length() - 1; while (oldIndex >= firstDifference && newIndex >= firstDifference) { if (oldValue.charAt(oldIndex) != newValue.charAt(newIndex)) { break; } --oldIndex; --newIndex; } e.setRemovedCount(oldIndex - firstDifference + 1); e.setAddedCount(newIndex - firstDifference + 1); return e; } /** * Sends an accessibility event of the given {@code eventType} to Android's accessibility system * with the given {@code viewId} represented as the source of the event. * * <p>The given {@code viewId} may either belong to {@link #rootAccessibilityView}, or any Flutter * {@link SemanticsNode}. */ @VisibleForTesting public void sendAccessibilityEvent(int viewId, int eventType) { if (!accessibilityManager.isEnabled()) { return; } sendAccessibilityEvent(obtainAccessibilityEvent(viewId, eventType)); } /** * Sends the given {@link AccessibilityEvent} to Android's accessibility system for a given * Flutter {@link SemanticsNode}. * * <p>This method should only be called for a Flutter {@link SemanticsNode}, not a traditional * Android {@code View}, i.e., {@link #rootAccessibilityView}. */ private void sendAccessibilityEvent(@NonNull AccessibilityEvent event) { if (!accessibilityManager.isEnabled()) { return; } // See // https://developer.android.com/reference/android/view/View.html#sendAccessibilityEvent(int) // We just want the final part at this point, since the event parameter // has already been correctly populated. rootAccessibilityView.getParent().requestSendAccessibilityEvent(rootAccessibilityView, event); } /** * Informs the TalkBack user about window name changes. * * <p>This method sets accessibility panel title if the API level >= 28, otherwise, it creates a * {@link AccessibilityEvent#TYPE_WINDOW_STATE_CHANGED} and sends the event to Android's * accessibility system. In both cases, TalkBack announces the label of the route and re-addjusts * the accessibility focus. * * <p>The given {@code route} should be a {@link SemanticsNode} that represents a navigation route * in the Flutter app. */ private void onWindowNameChange(@NonNull SemanticsNode route) { String routeName = route.getRouteName(); if (routeName == null) { // The routeName will be null when there is no semantics node that represnets namesRoute in // the scopeRoute. The TYPE_WINDOW_STATE_CHANGED only works the route name is not null and not // empty. Gives it a whitespace will make it focus the first semantics node without // pronouncing any word. // // The other way to trigger a focus change is to send a TYPE_VIEW_FOCUSED to the // rootAccessibilityView. However, it is less predictable which semantics node it will focus // next. routeName = " "; } if (Build.VERSION.SDK_INT >= API_LEVELS.API_28) { setAccessibilityPaneTitle(routeName); } else { AccessibilityEvent event = obtainAccessibilityEvent(route.id, AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); event.getText().add(routeName); sendAccessibilityEvent(event); } } @TargetApi(API_LEVELS.API_28) @RequiresApi(API_LEVELS.API_28) private void setAccessibilityPaneTitle(String title) { rootAccessibilityView.setAccessibilityPaneTitle(title); } /** * Creates a {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} and sends the event to * Android's accessibility system. * * <p>It sets the content change types to {@link AccessibilityEvent#CONTENT_CHANGE_TYPE_SUBTREE} * when supported by the API level. * * <p>The given {@code virtualViewId} should be a {@link SemanticsNode} below which the content * has changed. */ private void sendWindowContentChangeEvent(int virtualViewId) { AccessibilityEvent event = obtainAccessibilityEvent(virtualViewId, AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); event.setContentChangeTypes(AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE); sendAccessibilityEvent(event); } /** * Factory method that creates a new {@link AccessibilityEvent} that is configured to represent * the Flutter {@link SemanticsNode} represented by the given {@code virtualViewId}, categorized * as the given {@code eventType}. * * <p>This method should *only* be called for Flutter {@link SemanticsNode}s. It should *not* be * invoked to create an {@link AccessibilityEvent} for the {@link #rootAccessibilityView}. */ private AccessibilityEvent obtainAccessibilityEvent(int virtualViewId, int eventType) { AccessibilityEvent event = obtainAccessibilityEvent(eventType); event.setPackageName(rootAccessibilityView.getContext().getPackageName()); event.setSource(rootAccessibilityView, virtualViewId); return event; } @VisibleForTesting public AccessibilityEvent obtainAccessibilityEvent(int eventType) { return AccessibilityEvent.obtain(eventType); } /** * Reads the {@code layoutInDisplayCutoutMode} value from the window attribute and returns whether * a left cutout inset is required. * * <p>The {@code layoutInDisplayCutoutMode} is added after API level 28. */ @TargetApi(API_LEVELS.API_28) @RequiresApi(API_LEVELS.API_28) private boolean doesLayoutInDisplayCutoutModeRequireLeftInset() { Context context = rootAccessibilityView.getContext(); Activity activity = ViewUtils.getActivity(context); if (activity == null || activity.getWindow() == null) { // The activity is not visible, it does not matter whether to apply left inset // or not. return false; } int layoutInDisplayCutoutMode = activity.getWindow().getAttributes().layoutInDisplayCutoutMode; return layoutInDisplayCutoutMode == WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_NEVER || layoutInDisplayCutoutMode == WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT; } /** * Hook called just before a {@link SemanticsNode} is removed from the Android cache of Flutter's * semantics tree. */ private void willRemoveSemanticsNode(SemanticsNode semanticsNodeToBeRemoved) { if (BuildConfig.DEBUG) { if (!flutterSemanticsTree.containsKey(semanticsNodeToBeRemoved.id)) { Log.e(TAG, "Attempted to remove a node that is not in the tree."); } if (flutterSemanticsTree.get(semanticsNodeToBeRemoved.id) != semanticsNodeToBeRemoved) { Log.e(TAG, "Flutter semantics tree failed to get expected node when searching by id."); } } // TODO(mattcarroll): should parent be set to "null" here? Changing the parent seems like the // behavior of a method called "removeSemanticsNode()". The same is true // for null'ing accessibilityFocusedSemanticsNode, inputFocusedSemanticsNode, // and hoveredObject. Is this a hook method or a command? semanticsNodeToBeRemoved.parent = null; if (semanticsNodeToBeRemoved.platformViewId != -1 && embeddedAccessibilityFocusedNodeId != null && accessibilityViewEmbedder.platformViewOfNode(embeddedAccessibilityFocusedNodeId) == platformViewsAccessibilityDelegate.getPlatformViewById( semanticsNodeToBeRemoved.platformViewId)) { // If the currently focused a11y node is within a platform view that is // getting removed: clear it's a11y focus. sendAccessibilityEvent( embeddedAccessibilityFocusedNodeId, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); embeddedAccessibilityFocusedNodeId = null; } if (semanticsNodeToBeRemoved.platformViewId != -1) { View embeddedView = platformViewsAccessibilityDelegate.getPlatformViewById( semanticsNodeToBeRemoved.platformViewId); if (embeddedView != null) { embeddedView.setImportantForAccessibility( View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); } } if (accessibilityFocusedSemanticsNode == semanticsNodeToBeRemoved) { sendAccessibilityEvent( accessibilityFocusedSemanticsNode.id, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); accessibilityFocusedSemanticsNode = null; } if (inputFocusedSemanticsNode == semanticsNodeToBeRemoved) { inputFocusedSemanticsNode = null; } if (hoveredObject == semanticsNodeToBeRemoved) { hoveredObject = null; } } /** * Resets the {@code AccessibilityBridge}: * * <ul> * <li>Clears {@link #flutterSemanticsTree}, the Android cache of Flutter's semantics tree * <li>Releases focus on any active {@link #accessibilityFocusedSemanticsNode} * <li>Clears any hovered {@code SemanticsNode} * <li>Sends a {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event * </ul> */ // TODO(mattcarroll): under what conditions is this method expected to be invoked? public void reset() { flutterSemanticsTree.clear(); if (accessibilityFocusedSemanticsNode != null) { sendAccessibilityEvent( accessibilityFocusedSemanticsNode.id, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); } accessibilityFocusedSemanticsNode = null; hoveredObject = null; sendWindowContentChangeEvent(0); } /** * Listener that can be set on a {@link AccessibilityBridge}, which is invoked any time * accessibility is turned on/off, or touch exploration is turned on/off. */ public interface OnAccessibilityChangeListener { void onAccessibilityChanged(boolean isAccessibilityEnabled, boolean isTouchExplorationEnabled); } // Must match SemanticsActions in semantics.dart // https://github.com/flutter/engine/blob/main/lib/ui/semantics.dart public enum Action { TAP(1 << 0), LONG_PRESS(1 << 1), SCROLL_LEFT(1 << 2), SCROLL_RIGHT(1 << 3), SCROLL_UP(1 << 4), SCROLL_DOWN(1 << 5), INCREASE(1 << 6), DECREASE(1 << 7), SHOW_ON_SCREEN(1 << 8), MOVE_CURSOR_FORWARD_BY_CHARACTER(1 << 9), MOVE_CURSOR_BACKWARD_BY_CHARACTER(1 << 10), SET_SELECTION(1 << 11), COPY(1 << 12), CUT(1 << 13), PASTE(1 << 14), DID_GAIN_ACCESSIBILITY_FOCUS(1 << 15), DID_LOSE_ACCESSIBILITY_FOCUS(1 << 16), CUSTOM_ACTION(1 << 17), DISMISS(1 << 18), MOVE_CURSOR_FORWARD_BY_WORD(1 << 19), MOVE_CURSOR_BACKWARD_BY_WORD(1 << 20), SET_TEXT(1 << 21); public final int value; Action(int value) { this.value = value; } } // Actions that are triggered by Android OS, as opposed to user-triggered actions. // // This int is intended to be use in a bitwise comparison. static int systemAction = Action.DID_GAIN_ACCESSIBILITY_FOCUS.value & Action.DID_LOSE_ACCESSIBILITY_FOCUS.value & Action.SHOW_ON_SCREEN.value; // Must match SemanticsFlag in semantics.dart // https://github.com/flutter/engine/blob/main/lib/ui/semantics.dart /* Package */ enum Flag { HAS_CHECKED_STATE(1 << 0), IS_CHECKED(1 << 1), IS_SELECTED(1 << 2), IS_BUTTON(1 << 3), IS_TEXT_FIELD(1 << 4), IS_FOCUSED(1 << 5), HAS_ENABLED_STATE(1 << 6), IS_ENABLED(1 << 7), IS_IN_MUTUALLY_EXCLUSIVE_GROUP(1 << 8), IS_HEADER(1 << 9), IS_OBSCURED(1 << 10), SCOPES_ROUTE(1 << 11), NAMES_ROUTE(1 << 12), IS_HIDDEN(1 << 13), IS_IMAGE(1 << 14), IS_LIVE_REGION(1 << 15), HAS_TOGGLED_STATE(1 << 16), IS_TOGGLED(1 << 17), HAS_IMPLICIT_SCROLLING(1 << 18), IS_MULTILINE(1 << 19), IS_READ_ONLY(1 << 20), IS_FOCUSABLE(1 << 21), IS_LINK(1 << 22), IS_SLIDER(1 << 23), IS_KEYBOARD_KEY(1 << 24), IS_CHECK_STATE_MIXED(1 << 25), HAS_EXPANDED_STATE(1 << 26), IS_EXPANDED(1 << 27); final int value; Flag(int value) { this.value = value; } } // Must match the enum defined in window.dart. private enum AccessibilityFeature { ACCESSIBLE_NAVIGATION(1 << 0), INVERT_COLORS(1 << 1), // NOT SUPPORTED DISABLE_ANIMATIONS(1 << 2), BOLD_TEXT(1 << 3), // NOT SUPPORTED REDUCE_MOTION(1 << 4), // NOT SUPPORTED HIGH_CONTRAST(1 << 5), // NOT SUPPORTED ON_OFF_SWITCH_LABELS(1 << 6); // NOT SUPPORTED final int value; AccessibilityFeature(int value) { this.value = value; } } private enum TextDirection { UNKNOWN, LTR, RTL; public static TextDirection fromInt(int value) { switch (value) { case 1: return RTL; case 2: return LTR; } return UNKNOWN; } } /** * Accessibility action that is defined within a given Flutter application, as opposed to the * standard accessibility actions that are available in the Flutter framework. * * <p>Flutter and Android support a number of built-in accessibility actions. However, these * predefined actions are not always sufficient for a desired interaction. Android facilitates * custom accessibility actions, * https://developer.android.com/reference/android/view/accessibility/AccessibilityNodeInfo.AccessibilityAction. * Flutter supports custom accessibility actions via {@code customSemanticsActions} within a * {@code Semantics} widget, https://api.flutter.dev/flutter/widgets/Semantics-class.html. * * <p>See the Android documentation for custom accessibility actions: * https://developer.android.com/reference/android/view/accessibility/AccessibilityNodeInfo.AccessibilityAction * * <p>See the Flutter documentation for the Semantics widget: * https://api.flutter.dev/flutter/widgets/Semantics-class.html */ private static class CustomAccessibilityAction { CustomAccessibilityAction() {} // The ID of the custom action plus a minimum value so that the identifier // does not collide with existing Android accessibility actions. This ID // represents and Android resource ID, not a Flutter ID. private int resourceId = -1; // The Flutter ID of this custom accessibility action. See Flutter's Semantics widget for // custom accessibility action definitions: // https://api.flutter.dev/flutter/widgets/Semantics-class.html private int id = -1; // The ID of the standard Flutter accessibility action that this {@code // CustomAccessibilityAction} // overrides with a custom {@code label} and/or {@code hint}. private int overrideId = -1; // The user presented value which is displayed in the local context menu. private String label; // The text used in overridden standard actions. private String hint; } // When adding a new StringAttributeType, the classes in these file must be // updated as well. // * engine/src/flutter/lib/ui/semantics.dart // * engine/src/flutter/lib/web_ui/lib/semantics.dart // * engine/src/flutter/lib/ui/semantics/string_attribute.h private enum StringAttributeType { SPELLOUT, LOCALE, } private static class StringAttribute { int start; int end; StringAttributeType type; } private static class SpellOutStringAttribute extends StringAttribute {} private static class LocaleStringAttribute extends StringAttribute { String locale; } /** * Flutter {@code SemanticsNode} represented in Java/Android. * * <p>Flutter maintains a semantics tree that is controlled by, but is independent of Flutter's * element tree, i.e., widgets/elements/render objects. Flutter's semantics tree must be cached on * the Android side so that Android can query any {@code SemanticsNode} at any time. This class * represents a single node in the semantics tree, and it is a Java representation of the * analogous concept within Flutter. * * <p>To see how this {@code SemanticsNode}'s fields correspond to Flutter's semantics system, see * semantics.dart: https://github.com/flutter/engine/blob/main/lib/ui/semantics.dart */ private static class SemanticsNode { private static boolean nullableHasAncestor( SemanticsNode target, Predicate<SemanticsNode> tester) { return target != null && target.getAncestor(tester) != null; } final AccessibilityBridge accessibilityBridge; // Flutter ID of this {@code SemanticsNode}. private int id = -1; private int flags; private int actions; private int maxValueLength; private int currentValueLength; private int textSelectionBase; private int textSelectionExtent; private int platformViewId; private int scrollChildren; private int scrollIndex; private float scrollPosition; private float scrollExtentMax; private float scrollExtentMin; private String identifier; private String label; private List<StringAttribute> labelAttributes; private String value; private List<StringAttribute> valueAttributes; private String increasedValue; private List<StringAttribute> increasedValueAttributes; private String decreasedValue; private List<StringAttribute> decreasedValueAttributes; private String hint; private List<StringAttribute> hintAttributes; // The textual description of the backing widget's tooltip. // // The tooltip is attached through AccessibilityNodeInfo.setTooltipText if // API level >= 28; otherwise, this is attached to the end of content description. @Nullable private String tooltip; // The id of the sibling node that is before this node in traversal // order. // // The child order alone does not guarantee the TalkBack focus traversal // order. The AccessibilityNodeInfo.setTraversalAfter must be called with // its previous sibling to determine the focus traversal order. // // This property is updated in AccessibilityBridge.updateRecursively, // which is called at the end of every semantics update, and it is used in // AccessibilityBridge.createAccessibilityNodeInfo to set the "traversal // after" of this node. private int previousNodeId = -1; // See Flutter's {@code SemanticsNode#textDirection}. private TextDirection textDirection; private boolean hadPreviousConfig = false; private int previousFlags; private int previousActions; private int previousTextSelectionBase; private int previousTextSelectionExtent; private float previousScrollPosition; private float previousScrollExtentMax; private float previousScrollExtentMin; private String previousValue; private String previousLabel; private float left; private float top; private float right; private float bottom; private float[] transform; private SemanticsNode parent; private List<SemanticsNode> childrenInTraversalOrder = new ArrayList<>(); private List<SemanticsNode> childrenInHitTestOrder = new ArrayList<>(); private List<CustomAccessibilityAction> customAccessibilityActions; private CustomAccessibilityAction onTapOverride; private CustomAccessibilityAction onLongPressOverride; private boolean inverseTransformDirty = true; private float[] inverseTransform; private boolean globalGeometryDirty = true; private float[] globalTransform; private Rect globalRect; SemanticsNode(@NonNull AccessibilityBridge accessibilityBridge) { this.accessibilityBridge = accessibilityBridge; } /** * Returns the ancestor of this {@code SemanticsNode} for which {@link Predicate#test(Object)} * returns true, or null if no such ancestor exists. */ private SemanticsNode getAncestor(Predicate<SemanticsNode> tester) { SemanticsNode nextAncestor = parent; while (nextAncestor != null) { if (tester.test(nextAncestor)) { return nextAncestor; } nextAncestor = nextAncestor.parent; } return null; } /** * Returns true if the given {@code action} is supported by this {@code SemanticsNode}. * * <p>This method only applies to this {@code SemanticsNode} and does not implicitly search its * children. */ private boolean hasAction(@NonNull Action action) { return (actions & action.value) != 0; } /** * Returns true if the given {@code action} was supported by the immediately previous version of * this {@code SemanticsNode}. */ private boolean hadAction(@NonNull Action action) { return (previousActions & action.value) != 0; } private boolean hasFlag(@NonNull Flag flag) { return (flags & flag.value) != 0; } private boolean hadFlag(@NonNull Flag flag) { if (BuildConfig.DEBUG && !hadPreviousConfig) { Log.e(TAG, "Attempted to check hadFlag but had no previous config."); } return (previousFlags & flag.value) != 0; } private boolean didScroll() { return !Float.isNaN(scrollPosition) && !Float.isNaN(previousScrollPosition) && previousScrollPosition != scrollPosition; } private boolean didChangeLabel() { if (label == null && previousLabel == null) { return false; } return label == null || previousLabel == null || !label.equals(previousLabel); } private void log(@NonNull String indent, boolean recursive) { if (BuildConfig.DEBUG) { Log.i( TAG, indent + "SemanticsNode id=" + id + " identifier=" + identifier + " label=" + label + " actions=" + actions + " flags=" + flags + "\n" + indent + " +-- textDirection=" + textDirection + "\n" + indent + " +-- rect.ltrb=(" + left + ", " + top + ", " + right + ", " + bottom + ")\n" + indent + " +-- transform=" + Arrays.toString(transform) + "\n"); if (recursive) { String childIndent = indent + " "; for (SemanticsNode child : childrenInTraversalOrder) { child.log(childIndent, recursive); } } } } private void updateWith( @NonNull ByteBuffer buffer, @NonNull String[] strings, @NonNull ByteBuffer[] stringAttributeArgs) { hadPreviousConfig = true; previousValue = value; previousLabel = label; previousFlags = flags; previousActions = actions; previousTextSelectionBase = textSelectionBase; previousTextSelectionExtent = textSelectionExtent; previousScrollPosition = scrollPosition; previousScrollExtentMax = scrollExtentMax; previousScrollExtentMin = scrollExtentMin; flags = buffer.getInt(); actions = buffer.getInt(); maxValueLength = buffer.getInt(); currentValueLength = buffer.getInt(); textSelectionBase = buffer.getInt(); textSelectionExtent = buffer.getInt(); platformViewId = buffer.getInt(); scrollChildren = buffer.getInt(); scrollIndex = buffer.getInt(); scrollPosition = buffer.getFloat(); scrollExtentMax = buffer.getFloat(); scrollExtentMin = buffer.getFloat(); int stringIndex = buffer.getInt(); identifier = stringIndex == -1 ? null : strings[stringIndex]; stringIndex = buffer.getInt(); label = stringIndex == -1 ? null : strings[stringIndex]; labelAttributes = getStringAttributesFromBuffer(buffer, stringAttributeArgs); stringIndex = buffer.getInt(); value = stringIndex == -1 ? null : strings[stringIndex]; valueAttributes = getStringAttributesFromBuffer(buffer, stringAttributeArgs); stringIndex = buffer.getInt(); increasedValue = stringIndex == -1 ? null : strings[stringIndex]; increasedValueAttributes = getStringAttributesFromBuffer(buffer, stringAttributeArgs); stringIndex = buffer.getInt(); decreasedValue = stringIndex == -1 ? null : strings[stringIndex]; decreasedValueAttributes = getStringAttributesFromBuffer(buffer, stringAttributeArgs); stringIndex = buffer.getInt(); hint = stringIndex == -1 ? null : strings[stringIndex]; hintAttributes = getStringAttributesFromBuffer(buffer, stringAttributeArgs); stringIndex = buffer.getInt(); tooltip = stringIndex == -1 ? null : strings[stringIndex]; textDirection = TextDirection.fromInt(buffer.getInt()); left = buffer.getFloat(); top = buffer.getFloat(); right = buffer.getFloat(); bottom = buffer.getFloat(); if (transform == null) { transform = new float[16]; } for (int i = 0; i < 16; ++i) { transform[i] = buffer.getFloat(); } inverseTransformDirty = true; globalGeometryDirty = true; final int childCount = buffer.getInt(); childrenInTraversalOrder.clear(); childrenInHitTestOrder.clear(); for (int i = 0; i < childCount; ++i) { SemanticsNode child = accessibilityBridge.getOrCreateSemanticsNode(buffer.getInt()); child.parent = this; childrenInTraversalOrder.add(child); } for (int i = 0; i < childCount; ++i) { SemanticsNode child = accessibilityBridge.getOrCreateSemanticsNode(buffer.getInt()); child.parent = this; childrenInHitTestOrder.add(child); } final int actionCount = buffer.getInt(); if (actionCount == 0) { customAccessibilityActions = null; } else { if (customAccessibilityActions == null) customAccessibilityActions = new ArrayList<>(actionCount); else customAccessibilityActions.clear(); for (int i = 0; i < actionCount; i++) { CustomAccessibilityAction action = accessibilityBridge.getOrCreateAccessibilityAction(buffer.getInt()); if (action.overrideId == Action.TAP.value) { onTapOverride = action; } else if (action.overrideId == Action.LONG_PRESS.value) { onLongPressOverride = action; } else { // If we receive a different overrideId it means that we were passed // a standard action to override that we don't yet support. if (BuildConfig.DEBUG && action.overrideId != -1) { Log.e(TAG, "Expected action.overrideId to be -1."); } customAccessibilityActions.add(action); } customAccessibilityActions.add(action); } } } private List<StringAttribute> getStringAttributesFromBuffer( @NonNull ByteBuffer buffer, @NonNull ByteBuffer[] stringAttributeArgs) { final int attributesCount = buffer.getInt(); if (attributesCount == -1) { return null; } final List<StringAttribute> result = new ArrayList<>(attributesCount); for (int i = 0; i < attributesCount; ++i) { final int start = buffer.getInt(); final int end = buffer.getInt(); final StringAttributeType type = StringAttributeType.values()[buffer.getInt()]; switch (type) { case SPELLOUT: { // Pops the -1 size. buffer.getInt(); SpellOutStringAttribute attribute = new SpellOutStringAttribute(); attribute.start = start; attribute.end = end; attribute.type = type; result.add(attribute); break; } case LOCALE: { final int argsIndex = buffer.getInt(); final ByteBuffer args = stringAttributeArgs[argsIndex]; LocaleStringAttribute attribute = new LocaleStringAttribute(); attribute.start = start; attribute.end = end; attribute.type = type; attribute.locale = Charset.forName("UTF-8").decode(args).toString(); result.add(attribute); break; } default: break; } } return result; } private void ensureInverseTransform() { if (!inverseTransformDirty) { return; } inverseTransformDirty = false; if (inverseTransform == null) { inverseTransform = new float[16]; } if (!Matrix.invertM(inverseTransform, 0, transform, 0)) { Arrays.fill(inverseTransform, 0); } } private Rect getGlobalRect() { if (BuildConfig.DEBUG && globalGeometryDirty) { Log.e(TAG, "Attempted to getGlobalRect with a dirty geometry."); } return globalRect; } /** * Hit tests {@code point} to find the deepest focusable node in the node tree at that point. * * @param point The point to hit test against this node. * @param stopAtPlatformView Whether to return a platform view if found, regardless of whether * or not it is focusable. * @return The found node, or null if no relevant node was found at the given point. */ private SemanticsNode hitTest(float[] point, boolean stopAtPlatformView) { final float w = point[3]; final float x = point[0] / w; final float y = point[1] / w; if (x < left || x >= right || y < top || y >= bottom) return null; final float[] transformedPoint = new float[4]; for (SemanticsNode child : childrenInHitTestOrder) { if (child.hasFlag(Flag.IS_HIDDEN)) { continue; } child.ensureInverseTransform(); Matrix.multiplyMV(transformedPoint, 0, child.inverseTransform, 0, point, 0); final SemanticsNode result = child.hitTest(transformedPoint, stopAtPlatformView); if (result != null) { return result; } } final boolean foundPlatformView = stopAtPlatformView && platformViewId != -1; return isFocusable() || foundPlatformView ? this : null; } // TODO(goderbauer): This should be decided by the framework once we have more information // about focusability there. private boolean isFocusable() { // We enforce in the framework that no other useful semantics are merged with these // nodes. if (hasFlag(Flag.SCOPES_ROUTE)) { return false; } if (hasFlag(Flag.IS_FOCUSABLE)) { return true; } // If not explicitly set as focusable, then use our legacy // algorithm. Once all focusable widgets have a Focus widget, then // this won't be needed. return (actions & ~SCROLLABLE_ACTIONS) != 0 || (flags & FOCUSABLE_FLAGS) != 0 || (label != null && !label.isEmpty()) || (value != null && !value.isEmpty()) || (hint != null && !hint.isEmpty()); } private void collectRoutes(List<SemanticsNode> edges) { if (hasFlag(Flag.SCOPES_ROUTE)) { edges.add(this); } for (SemanticsNode child : childrenInTraversalOrder) { child.collectRoutes(edges); } } private String getRouteName() { // Returns the first non-null and non-empty semantic label of a child // with an NamesRoute flag. Otherwise returns null. if (hasFlag(Flag.NAMES_ROUTE)) { if (label != null && !label.isEmpty()) { return label; } } for (SemanticsNode child : childrenInTraversalOrder) { String newName = child.getRouteName(); if (newName != null && !newName.isEmpty()) { return newName; } } return null; } private void updateRecursively( float[] ancestorTransform, Set<SemanticsNode> visitedObjects, boolean forceUpdate) { visitedObjects.add(this); if (globalGeometryDirty) { forceUpdate = true; } if (forceUpdate) { if (globalTransform == null) { globalTransform = new float[16]; } if (transform == null) { if (BuildConfig.DEBUG) { Log.e(TAG, "transform has not been initialized for id = " + id); accessibilityBridge.getRootSemanticsNode().log("Semantics tree:", true); } transform = new float[16]; } Matrix.multiplyMM(globalTransform, 0, ancestorTransform, 0, transform, 0); final float[] sample = new float[4]; sample[2] = 0; sample[3] = 1; final float[] point1 = new float[4]; final float[] point2 = new float[4]; final float[] point3 = new float[4]; final float[] point4 = new float[4]; sample[0] = left; sample[1] = top; transformPoint(point1, globalTransform, sample); sample[0] = right; sample[1] = top; transformPoint(point2, globalTransform, sample); sample[0] = right; sample[1] = bottom; transformPoint(point3, globalTransform, sample); sample[0] = left; sample[1] = bottom; transformPoint(point4, globalTransform, sample); if (globalRect == null) globalRect = new Rect(); globalRect.set( Math.round(min(point1[0], point2[0], point3[0], point4[0])), Math.round(min(point1[1], point2[1], point3[1], point4[1])), Math.round(max(point1[0], point2[0], point3[0], point4[0])), Math.round(max(point1[1], point2[1], point3[1], point4[1]))); globalGeometryDirty = false; } if (BuildConfig.DEBUG) { if (globalTransform == null) { Log.e(TAG, "Expected globalTransform to not be null."); } if (globalRect == null) { Log.e(TAG, "Expected globalRect to not be null."); } } int previousNodeId = -1; for (SemanticsNode child : childrenInTraversalOrder) { child.previousNodeId = previousNodeId; previousNodeId = child.id; child.updateRecursively(globalTransform, visitedObjects, forceUpdate); } } private void transformPoint(float[] result, float[] transform, float[] point) { Matrix.multiplyMV(result, 0, transform, 0, point, 0); final float w = result[3]; result[0] /= w; result[1] /= w; result[2] /= w; result[3] = 0; } private float min(float a, float b, float c, float d) { return Math.min(a, Math.min(b, Math.min(c, d))); } private float max(float a, float b, float c, float d) { return Math.max(a, Math.max(b, Math.max(c, d))); } private CharSequence getValue() { return createSpannableString(value, valueAttributes); } private CharSequence getLabel() { return createSpannableString(label, labelAttributes); } private CharSequence getHint() { return createSpannableString(hint, hintAttributes); } private CharSequence getValueLabelHint() { CharSequence[] array = new CharSequence[] {getValue(), getLabel(), getHint()}; CharSequence result = null; for (CharSequence word : array) { if (word != null && word.length() > 0) { if (result == null || result.length() == 0) { result = word; } else { result = TextUtils.concat(result, ", ", word); } } } return result; } private CharSequence getTextFieldHint() { CharSequence[] array = new CharSequence[] {getLabel(), getHint()}; CharSequence result = null; for (CharSequence word : array) { if (word != null && word.length() > 0) { if (result == null || result.length() == 0) { result = word; } else { result = TextUtils.concat(result, ", ", word); } } } return result; } private SpannableString createSpannableString(String string, List<StringAttribute> attributes) { if (string == null) { return null; } final SpannableString spannableString = new SpannableString(string); if (attributes != null) { for (StringAttribute attribute : attributes) { switch (attribute.type) { case SPELLOUT: { final TtsSpan ttsSpan = new TtsSpan.Builder<>(TtsSpan.TYPE_VERBATIM).build(); spannableString.setSpan(ttsSpan, attribute.start, attribute.end, 0); break; } case LOCALE: { LocaleStringAttribute localeAttribute = (LocaleStringAttribute) attribute; Locale locale = Locale.forLanguageTag(localeAttribute.locale); final LocaleSpan localeSpan = new LocaleSpan(locale); spannableString.setSpan(localeSpan, attribute.start, attribute.end, 0); break; } } } } return spannableString; } } /** * Delegates handling of {@link android.view.ViewParent#requestSendAccessibilityEvent} to the * accessibility bridge. * * <p>This is used by embedded platform views to propagate accessibility events from their view * hierarchy to the accessibility bridge. * * <p>As the embedded view doesn't have to be the only View in the embedded hierarchy (it can have * child views) and the event might have been originated from any view in this hierarchy, this * method gets both a reference to the embedded platform view, and a reference to the view from * its hierarchy that sent the event. * * @param embeddedView the embedded platform view for which the event is delegated * @param eventOrigin the view in the embedded view's hierarchy that sent the event. * @return True if the event was sent. */ // AccessibilityEvent has many irrelevant cases that would be confusing to list. @SuppressLint("SwitchIntDef") public boolean externalViewRequestSendAccessibilityEvent( View embeddedView, View eventOrigin, AccessibilityEvent event) { if (!accessibilityViewEmbedder.requestSendAccessibilityEvent( embeddedView, eventOrigin, event)) { return false; } Integer virtualNodeId = accessibilityViewEmbedder.getRecordFlutterId(embeddedView, event); if (virtualNodeId == null) { return false; } switch (event.getEventType()) { case AccessibilityEvent.TYPE_VIEW_HOVER_ENTER: hoveredObject = null; break; case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED: embeddedAccessibilityFocusedNodeId = virtualNodeId; accessibilityFocusedSemanticsNode = null; break; case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED: embeddedInputFocusedNodeId = null; embeddedAccessibilityFocusedNodeId = null; break; case AccessibilityEvent.TYPE_VIEW_FOCUSED: embeddedInputFocusedNodeId = virtualNodeId; inputFocusedSemanticsNode = null; break; } return true; } }
engine/shell/platform/android/io/flutter/view/AccessibilityBridge.java/0
{ "file_path": "engine/shell/platform/android/io/flutter/view/AccessibilityBridge.java", "repo_id": "engine", "token_count": 44765 }
343
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_ANDROID_PLATFORM_MESSAGE_HANDLER_ANDROID_H_ #define FLUTTER_SHELL_PLATFORM_ANDROID_PLATFORM_MESSAGE_HANDLER_ANDROID_H_ #include <jni.h> #include <memory> #include <mutex> #include <unordered_map> #include "flutter/lib/ui/window/platform_message.h" #include "flutter/shell/common/platform_message_handler.h" #include "flutter/shell/platform/android/jni/platform_view_android_jni.h" namespace flutter { class PlatformMessageHandlerAndroid : public PlatformMessageHandler { public: explicit PlatformMessageHandlerAndroid( const std::shared_ptr<PlatformViewAndroidJNI>& jni_facade); void HandlePlatformMessage(std::unique_ptr<PlatformMessage> message) override; bool DoesHandlePlatformMessageOnPlatformThread() const override { return false; } void InvokePlatformMessageResponseCallback( int response_id, std::unique_ptr<fml::Mapping> mapping) override; void InvokePlatformMessageEmptyResponseCallback(int response_id) override; private: const std::shared_ptr<PlatformViewAndroidJNI> jni_facade_; std::atomic<int> next_response_id_ = 1; std::unordered_map<int, fml::RefPtr<flutter::PlatformMessageResponse>> pending_responses_; std::mutex pending_responses_mutex_; }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_ANDROID_PLATFORM_MESSAGE_HANDLER_ANDROID_H_
engine/shell/platform/android/platform_message_handler_android.h/0
{ "file_path": "engine/shell/platform/android/platform_message_handler_android.h", "repo_id": "engine", "token_count": 518 }
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_ANDROID_SURFACE_ANDROID_SURFACE_H_ #define FLUTTER_SHELL_PLATFORM_ANDROID_SURFACE_ANDROID_SURFACE_H_ #include <memory> #include "flutter/flow/embedded_views.h" #include "flutter/flow/surface.h" #include "flutter/fml/macros.h" #include "flutter/shell/platform/android/context/android_context.h" #include "flutter/shell/platform/android/jni/platform_view_android_jni.h" #include "flutter/shell/platform/android/surface/android_native_window.h" #include "third_party/skia/include/core/SkSize.h" namespace impeller { class Context; } // namespace impeller namespace flutter { class AndroidExternalViewEmbedder; class AndroidSurface { public: virtual ~AndroidSurface(); virtual bool IsValid() const = 0; virtual void TeardownOnScreenContext() = 0; virtual std::unique_ptr<Surface> CreateGPUSurface( GrDirectContext* gr_context = nullptr) = 0; virtual bool OnScreenSurfaceResize(const SkISize& size) = 0; virtual bool ResourceContextMakeCurrent() = 0; virtual bool ResourceContextClearCurrent() = 0; virtual bool SetNativeWindow(fml::RefPtr<AndroidNativeWindow> window) = 0; virtual std::unique_ptr<Surface> CreateSnapshotSurface(); virtual std::shared_ptr<impeller::Context> GetImpellerContext(); protected: AndroidSurface(); }; class AndroidSurfaceFactory { public: AndroidSurfaceFactory() = default; virtual ~AndroidSurfaceFactory() = default; virtual std::unique_ptr<AndroidSurface> CreateSurface() = 0; }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_ANDROID_SURFACE_ANDROID_SURFACE_H_
engine/shell/platform/android/surface/android_surface.h/0
{ "file_path": "engine/shell/platform/android/surface/android_surface.h", "repo_id": "engine", "token_count": 580 }
345
package io.flutter.embedding.android; import static io.flutter.Build.API_LEVELS; import static io.flutter.embedding.android.FlutterActivityLaunchConfigs.HANDLE_DEEPLINKING_META_DATA_KEY; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.lifecycle.DefaultLifecycleObserver; import androidx.lifecycle.LifecycleOwner; import androidx.test.core.app.ApplicationProvider; import androidx.test.ext.junit.runners.AndroidJUnit4; import io.flutter.FlutterInjector; import io.flutter.embedding.android.FlutterActivityLaunchConfigs.BackgroundMode; import io.flutter.embedding.engine.FlutterEngine; import io.flutter.embedding.engine.FlutterEngineCache; import io.flutter.embedding.engine.FlutterJNI; import io.flutter.embedding.engine.loader.FlutterLoader; import io.flutter.embedding.engine.plugins.FlutterPlugin; import io.flutter.embedding.engine.plugins.activity.ActivityAware; import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding; import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding.OnSaveInstanceStateListener; import io.flutter.plugins.GeneratedPluginRegistrant; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.android.controller.ActivityController; import org.robolectric.annotation.Config; @Config(manifest = Config.NONE) @RunWith(AndroidJUnit4.class) public class FlutterActivityTest { private final Context ctx = ApplicationProvider.getApplicationContext(); boolean isDelegateAttached; @Before public void setUp() { FlutterInjector.reset(); GeneratedPluginRegistrant.clearRegisteredEngines(); FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); when(mockFlutterJNI.isAttached()).thenReturn(true); FlutterJNI.Factory mockFlutterJNIFactory = mock(FlutterJNI.Factory.class); when(mockFlutterJNIFactory.provideFlutterJNI()).thenReturn(mockFlutterJNI); FlutterInjector.setInstance( new FlutterInjector.Builder().setFlutterJNIFactory(mockFlutterJNIFactory).build()); } @After public void tearDown() { GeneratedPluginRegistrant.clearRegisteredEngines(); FlutterInjector.reset(); } @Test public void flutterViewHasId() { Intent intent = FlutterActivity.createDefaultIntent(ctx); ActivityController<FlutterActivity> activityController = Robolectric.buildActivity(FlutterActivity.class, intent); FlutterActivity activity = activityController.get(); activity.onCreate(null); assertNotNull(activity.findViewById(FlutterActivity.FLUTTER_VIEW_ID)); assertTrue(activity.findViewById(FlutterActivity.FLUTTER_VIEW_ID) instanceof FlutterView); } // TODO(garyq): Robolectric does not yet support android api 33 yet. Switch to a robolectric // test that directly exercises the OnBackInvoked APIs when API 33 is supported. @Test @TargetApi(API_LEVELS.API_33) public void itRegistersOnBackInvokedCallbackOnChangingFrameworkHandlesBack() { Intent intent = FlutterActivityWithReportFullyDrawn.createDefaultIntent(ctx); ActivityController<FlutterActivityWithReportFullyDrawn> activityController = Robolectric.buildActivity(FlutterActivityWithReportFullyDrawn.class, intent); FlutterActivityWithReportFullyDrawn activity = spy(activityController.get()); activity.onCreate(null); verify(activity, times(0)).registerOnBackInvokedCallback(); activity.setFrameworkHandlesBack(false); verify(activity, times(0)).registerOnBackInvokedCallback(); activity.setFrameworkHandlesBack(true); verify(activity, times(1)).registerOnBackInvokedCallback(); } // TODO(garyq): Robolectric does not yet support android api 33 yet. Switch to a robolectric // test that directly exercises the OnBackInvoked APIs when API 33 is supported. @Test @TargetApi(API_LEVELS.API_33) public void itUnregistersOnBackInvokedCallbackOnRelease() { Intent intent = FlutterActivityWithReportFullyDrawn.createDefaultIntent(ctx); ActivityController<FlutterActivityWithReportFullyDrawn> activityController = Robolectric.buildActivity(FlutterActivityWithReportFullyDrawn.class, intent); FlutterActivityWithReportFullyDrawn activity = spy(activityController.get()); activity.release(); verify(activity, times(1)).unregisterOnBackInvokedCallback(); } @Test public void itCreatesDefaultIntentWithExpectedDefaults() { Intent intent = FlutterActivity.createDefaultIntent(ctx); ActivityController<FlutterActivity> activityController = Robolectric.buildActivity(FlutterActivity.class, intent); FlutterActivity flutterActivity = activityController.get(); flutterActivity.setDelegate(new FlutterActivityAndFragmentDelegate(flutterActivity)); assertEquals("main", flutterActivity.getDartEntrypointFunctionName()); assertNull(flutterActivity.getDartEntrypointLibraryUri()); assertNull(flutterActivity.getDartEntrypointArgs()); assertEquals("/", flutterActivity.getInitialRoute()); assertArrayEquals(new String[] {}, flutterActivity.getFlutterShellArgs().toArray()); assertTrue(flutterActivity.shouldAttachEngineToActivity()); assertNull(flutterActivity.getCachedEngineId()); assertTrue(flutterActivity.shouldDestroyEngineWithHost()); assertEquals(BackgroundMode.opaque, flutterActivity.getBackgroundMode()); assertEquals(RenderMode.surface, flutterActivity.getRenderMode()); assertEquals(TransparencyMode.opaque, flutterActivity.getTransparencyMode()); } @Test public void itDestroysNewEngineWhenIntentIsMissingParameter() { // All clients should use the static members of FlutterActivity to construct an // Intent. Missing extras is an error. However, Flutter has number of tests that // don't seem to use the static members of FlutterActivity to construct the // launching Intent, so this test explicitly verifies that even illegal Intents // result in the automatic destruction of a non-cached FlutterEngine, which prevents // the breakage of memory usage benchmark tests. Intent intent = new Intent(ctx, FlutterActivity.class); ActivityController<FlutterActivity> activityController = Robolectric.buildActivity(FlutterActivity.class, intent); FlutterActivity flutterActivity = activityController.get(); flutterActivity.setDelegate(new FlutterActivityAndFragmentDelegate(flutterActivity)); assertTrue(flutterActivity.shouldDestroyEngineWithHost()); } @Test public void itDoesNotDestroyFlutterEngineWhenProvidedByHost() { Intent intent = new Intent(ctx, FlutterActivityWithProvidedEngine.class); ActivityController<FlutterActivityWithProvidedEngine> activityController = Robolectric.buildActivity(FlutterActivityWithProvidedEngine.class, intent); activityController.create(); FlutterActivityWithProvidedEngine flutterActivity = activityController.get(); assertFalse(flutterActivity.shouldDestroyEngineWithHost()); } @Test public void itCreatesNewEngineIntentWithRequestedSettings() { Intent intent = FlutterActivity.withNewEngine() .initialRoute("/custom/route") .dartEntrypointArgs(new ArrayList<String>(Arrays.asList("foo", "bar"))) .backgroundMode(BackgroundMode.transparent) .build(ctx); ActivityController<FlutterActivity> activityController = Robolectric.buildActivity(FlutterActivity.class, intent); FlutterActivity flutterActivity = activityController.get(); flutterActivity.setDelegate(new FlutterActivityAndFragmentDelegate(flutterActivity)); assertEquals("/custom/route", flutterActivity.getInitialRoute()); assertArrayEquals( new String[] {"foo", "bar"}, flutterActivity.getDartEntrypointArgs().toArray()); assertArrayEquals(new String[] {}, flutterActivity.getFlutterShellArgs().toArray()); assertTrue(flutterActivity.shouldAttachEngineToActivity()); assertNull(flutterActivity.getCachedEngineId()); assertTrue(flutterActivity.shouldDestroyEngineWithHost()); assertEquals(BackgroundMode.transparent, flutterActivity.getBackgroundMode()); assertEquals(RenderMode.texture, flutterActivity.getRenderMode()); assertEquals(TransparencyMode.transparent, flutterActivity.getTransparencyMode()); } @Test public void itCreatesNewEngineInGroupIntentWithRequestedSettings() { Intent intent = FlutterActivity.withNewEngineInGroup("my_cached_engine_group") .dartEntrypoint("custom_entrypoint") .initialRoute("/custom/route") .backgroundMode(BackgroundMode.transparent) .build(ctx); ActivityController<FlutterActivity> activityController = Robolectric.buildActivity(FlutterActivity.class, intent); FlutterActivity flutterActivity = activityController.get(); flutterActivity.setDelegate(new FlutterActivityAndFragmentDelegate(flutterActivity)); assertEquals("my_cached_engine_group", flutterActivity.getCachedEngineGroupId()); assertEquals("custom_entrypoint", flutterActivity.getDartEntrypointFunctionName()); assertEquals("/custom/route", flutterActivity.getInitialRoute()); assertArrayEquals(new String[] {}, flutterActivity.getFlutterShellArgs().toArray()); assertTrue(flutterActivity.shouldAttachEngineToActivity()); assertTrue(flutterActivity.shouldDestroyEngineWithHost()); assertNull(flutterActivity.getCachedEngineId()); assertEquals(BackgroundMode.transparent, flutterActivity.getBackgroundMode()); assertEquals(RenderMode.texture, flutterActivity.getRenderMode()); assertEquals(TransparencyMode.transparent, flutterActivity.getTransparencyMode()); } @Test public void itReturnsValueFromMetaDataWhenCallsShouldHandleDeepLinkingCase1() throws PackageManager.NameNotFoundException { Intent intent = FlutterActivity.withNewEngine().backgroundMode(BackgroundMode.transparent).build(ctx); ActivityController<FlutterActivity> activityController = Robolectric.buildActivity(FlutterActivity.class, intent); FlutterActivity flutterActivity = activityController.get(); Bundle bundle = new Bundle(); bundle.putBoolean(HANDLE_DEEPLINKING_META_DATA_KEY, true); FlutterActivity spyFlutterActivity = spy(flutterActivity); when(spyFlutterActivity.getMetaData()).thenReturn(bundle); assertTrue(spyFlutterActivity.shouldHandleDeeplinking()); } @Test public void itReturnsValueFromMetaDataWhenCallsShouldHandleDeepLinkingCase2() throws PackageManager.NameNotFoundException { Intent intent = FlutterActivity.withNewEngine().backgroundMode(BackgroundMode.transparent).build(ctx); ActivityController<FlutterActivity> activityController = Robolectric.buildActivity(FlutterActivity.class, intent); FlutterActivity flutterActivity = activityController.get(); Bundle bundle = new Bundle(); bundle.putBoolean(HANDLE_DEEPLINKING_META_DATA_KEY, false); FlutterActivity spyFlutterActivity = spy(flutterActivity); when(spyFlutterActivity.getMetaData()).thenReturn(bundle); assertFalse(spyFlutterActivity.shouldHandleDeeplinking()); } @Test public void itReturnsValueFromMetaDataWhenCallsShouldHandleDeepLinkingCase3() throws PackageManager.NameNotFoundException { Intent intent = FlutterActivity.withNewEngine().backgroundMode(BackgroundMode.transparent).build(ctx); ActivityController<FlutterActivity> activityController = Robolectric.buildActivity(FlutterActivity.class, intent); FlutterActivity flutterActivity = activityController.get(); // Creates an empty bundle. Bundle bundle = new Bundle(); FlutterActivity spyFlutterActivity = spy(flutterActivity); when(spyFlutterActivity.getMetaData()).thenReturn(bundle); // Empty bundle should return false. assertFalse(spyFlutterActivity.shouldHandleDeeplinking()); } @Test public void itCreatesCachedEngineIntentThatDoesNotDestroyTheEngine() { Intent intent = FlutterActivity.withCachedEngine("my_cached_engine") .destroyEngineWithActivity(false) .build(ctx); ActivityController<FlutterActivity> activityController = Robolectric.buildActivity(FlutterActivity.class, intent); FlutterActivity flutterActivity = activityController.get(); assertArrayEquals(new String[] {}, flutterActivity.getFlutterShellArgs().toArray()); assertTrue(flutterActivity.shouldAttachEngineToActivity()); assertEquals("my_cached_engine", flutterActivity.getCachedEngineId()); assertFalse(flutterActivity.shouldDestroyEngineWithHost()); } @Test public void itCreatesCachedEngineIntentThatDestroysTheEngine() { Intent intent = FlutterActivity.withCachedEngine("my_cached_engine") .destroyEngineWithActivity(true) .build(ctx); ActivityController<FlutterActivity> activityController = Robolectric.buildActivity(FlutterActivity.class, intent); FlutterActivity flutterActivity = activityController.get(); assertArrayEquals(new String[] {}, flutterActivity.getFlutterShellArgs().toArray()); assertTrue(flutterActivity.shouldAttachEngineToActivity()); assertEquals("my_cached_engine", flutterActivity.getCachedEngineId()); assertTrue(flutterActivity.shouldDestroyEngineWithHost()); } @Test public void itRegistersPluginsAtConfigurationTime() { Intent intent = FlutterActivity.createDefaultIntent(ctx); ActivityController<FlutterActivity> activityController = Robolectric.buildActivity(FlutterActivity.class, intent); FlutterActivity activity = activityController.get(); // This calls onAttach on FlutterActivityAndFragmentDelegate and subsequently // configureFlutterEngine which registers the plugins. activity.onCreate(null); List<FlutterEngine> registeredEngines = GeneratedPluginRegistrant.getRegisteredEngines(); assertEquals(1, registeredEngines.size()); assertEquals(activity.getFlutterEngine(), registeredEngines.get(0)); } @Test public void itCanBeDetachedFromTheEngineAndStopSendingFurtherEvents() { FlutterActivityAndFragmentDelegate mockDelegate = mock(FlutterActivityAndFragmentDelegate.class); FlutterEngine mockEngine = mock(FlutterEngine.class); FlutterEngineCache.getInstance().put("my_cached_engine", mockEngine); Intent intent = FlutterActivity.withCachedEngine("my_cached_engine").build(ctx); ActivityController<FlutterActivity> activityController = Robolectric.buildActivity(FlutterActivity.class, intent); FlutterActivity flutterActivity = activityController.get(); isDelegateAttached = true; when(mockDelegate.isAttached()).thenAnswer(invocation -> isDelegateAttached); doAnswer(invocation -> isDelegateAttached = false).when(mockDelegate).onDetach(); flutterActivity.setDelegate(mockDelegate); flutterActivity.onStart(); flutterActivity.onResume(); verify(mockDelegate, times(1)).onStart(); verify(mockDelegate, times(1)).onResume(); flutterActivity.onPause(); flutterActivity.detachFromFlutterEngine(); verify(mockDelegate, times(1)).onPause(); verify(mockDelegate, times(1)).onDestroyView(); verify(mockDelegate, times(1)).onDetach(); flutterActivity.onStop(); verify(mockDelegate, never()).onStop(); // Simulate the disconnected activity resuming again. flutterActivity.onStart(); flutterActivity.onResume(); // Shouldn't send more events to the delegates as before and shouldn't crash. verify(mockDelegate, times(1)).onStart(); verify(mockDelegate, times(1)).onResume(); flutterActivity.onDestroy(); // 1 time same as before. verify(mockDelegate, times(1)).onDestroyView(); verify(mockDelegate, times(1)).onDetach(); verify(mockDelegate, times(1)).release(); } @Test public void itReturnsExclusiveAppComponent() { Intent intent = FlutterActivity.createDefaultIntent(ctx); ActivityController<FlutterActivity> activityController = Robolectric.buildActivity(FlutterActivity.class, intent); FlutterActivity flutterActivity = activityController.get(); FlutterActivityAndFragmentDelegate delegate = new FlutterActivityAndFragmentDelegate(flutterActivity); flutterActivity.setDelegate(delegate); assertEquals(flutterActivity.getExclusiveAppComponent(), delegate); } @Test public void itDelaysDrawing() { Intent intent = FlutterActivity.createDefaultIntent(ctx); ActivityController<FlutterActivity> activityController = Robolectric.buildActivity(FlutterActivity.class, intent); FlutterActivity flutterActivity = activityController.get(); flutterActivity.onCreate(null); assertNotNull(flutterActivity.delegate.activePreDrawListener); } @Test public void itDoesNotDelayDrawingwhenUsingTextureRendering() { Intent intent = FlutterActivityWithTextureRendering.createDefaultIntent(ctx); ActivityController<FlutterActivityWithTextureRendering> activityController = Robolectric.buildActivity(FlutterActivityWithTextureRendering.class, intent); FlutterActivityWithTextureRendering flutterActivity = activityController.get(); flutterActivity.onCreate(null); assertNull(flutterActivity.delegate.activePreDrawListener); } @Test public void itRestoresPluginStateBeforePluginOnCreate() { FlutterLoader mockFlutterLoader = mock(FlutterLoader.class); FlutterJNI mockFlutterJni = mock(FlutterJNI.class); when(mockFlutterJni.isAttached()).thenReturn(true); FlutterEngine cachedEngine = new FlutterEngine(ctx, mockFlutterLoader, mockFlutterJni); FakeFlutterPlugin fakeFlutterPlugin = new FakeFlutterPlugin(); cachedEngine.getPlugins().add(fakeFlutterPlugin); FlutterEngineCache.getInstance().put("my_cached_engine", cachedEngine); Intent intent = FlutterActivity.withCachedEngine("my_cached_engine").build(ctx); Robolectric.buildActivity(FlutterActivity.class, intent).setup(); assertTrue( "Expected FakeFlutterPlugin onCreateCalled to be true", fakeFlutterPlugin.onCreateCalled); } @Test public void itDoesNotRegisterPluginsTwiceWhenUsingACachedEngine() { Intent intent = new Intent(ctx, FlutterActivityWithProvidedEngine.class); ActivityController<FlutterActivityWithProvidedEngine> activityController = Robolectric.buildActivity(FlutterActivityWithProvidedEngine.class, intent); activityController.create(); FlutterActivityWithProvidedEngine flutterActivity = activityController.get(); flutterActivity.configureFlutterEngine(flutterActivity.getFlutterEngine()); List<FlutterEngine> registeredEngines = GeneratedPluginRegistrant.getRegisteredEngines(); // This might cause the plugins to be registered twice, once by the FlutterEngine constructor, // and once by the default FlutterActivity.configureFlutterEngine implementation. // Test that it doesn't happen. assertEquals(1, registeredEngines.size()); } @Test public void itDoesNotReleaseEnginewhenDetachFromFlutterEngine() { FlutterActivityAndFragmentDelegate mockDelegate = mock(FlutterActivityAndFragmentDelegate.class); isDelegateAttached = true; when(mockDelegate.isAttached()).thenAnswer(invocation -> isDelegateAttached); doAnswer(invocation -> isDelegateAttached = false).when(mockDelegate).onDetach(); FlutterEngine mockEngine = mock(FlutterEngine.class); FlutterEngineCache.getInstance().put("my_cached_engine", mockEngine); Intent intent = FlutterActivity.withCachedEngine("my_cached_engine").build(ctx); ActivityController<FlutterActivity> activityController = Robolectric.buildActivity(FlutterActivity.class, intent); FlutterActivity flutterActivity = activityController.get(); flutterActivity.setDelegate(mockDelegate); flutterActivity.onStart(); flutterActivity.onResume(); flutterActivity.onPause(); assertTrue(mockDelegate.isAttached()); flutterActivity.detachFromFlutterEngine(); verify(mockDelegate, times(1)).onDetach(); verify(mockDelegate, never()).release(); assertFalse(mockDelegate.isAttached()); } @Test public void itReleaseEngineWhenOnDestroy() { FlutterActivityAndFragmentDelegate mockDelegate = mock(FlutterActivityAndFragmentDelegate.class); isDelegateAttached = true; when(mockDelegate.isAttached()).thenAnswer(invocation -> isDelegateAttached); doAnswer(invocation -> isDelegateAttached = false).when(mockDelegate).onDetach(); FlutterEngine mockEngine = mock(FlutterEngine.class); FlutterEngineCache.getInstance().put("my_cached_engine", mockEngine); Intent intent = FlutterActivity.withCachedEngine("my_cached_engine").build(ctx); ActivityController<FlutterActivity> activityController = Robolectric.buildActivity(FlutterActivity.class, intent); FlutterActivity flutterActivity = activityController.get(); flutterActivity.setDelegate(mockDelegate); flutterActivity.onStart(); flutterActivity.onResume(); flutterActivity.onPause(); assertTrue(mockDelegate.isAttached()); flutterActivity.onDestroy(); verify(mockDelegate, times(1)).onDetach(); verify(mockDelegate, times(1)).release(); assertFalse(mockDelegate.isAttached()); } @Test @Config(minSdk = API_LEVELS.API_21, maxSdk = API_LEVELS.API_28) public void fullyDrawn_beforeAndroidQ() { Intent intent = FlutterActivityWithReportFullyDrawn.createDefaultIntent(ctx); ActivityController<FlutterActivityWithReportFullyDrawn> activityController = Robolectric.buildActivity(FlutterActivityWithReportFullyDrawn.class, intent); FlutterActivityWithReportFullyDrawn flutterActivity = activityController.get(); // See https://github.com/flutter/flutter/issues/46172, and // https://github.com/flutter/flutter/issues/88767. flutterActivity.onFlutterUiDisplayed(); assertFalse("reportFullyDrawn isn't used", flutterActivity.isFullyDrawn()); } @Test @Config(minSdk = API_LEVELS.API_29) public void fullyDrawn_fromAndroidQ() { Intent intent = FlutterActivityWithReportFullyDrawn.createDefaultIntent(ctx); ActivityController<FlutterActivityWithReportFullyDrawn> activityController = Robolectric.buildActivity(FlutterActivityWithReportFullyDrawn.class, intent); FlutterActivityWithReportFullyDrawn flutterActivity = activityController.get(); flutterActivity.onFlutterUiDisplayed(); assertTrue("reportFullyDrawn is used", flutterActivity.isFullyDrawn()); flutterActivity.resetFullyDrawn(); } static class FlutterActivityWithProvidedEngine extends FlutterActivity { @Override @SuppressLint("MissingSuperCall") protected void onCreate(@Nullable Bundle savedInstanceState) { super.delegate = new FlutterActivityAndFragmentDelegate(this); super.delegate.setUpFlutterEngine(); } @Nullable @Override public FlutterEngine provideFlutterEngine(@NonNull Context context) { FlutterJNI flutterJNI = mock(FlutterJNI.class); FlutterLoader flutterLoader = mock(FlutterLoader.class); when(flutterJNI.isAttached()).thenReturn(true); when(flutterLoader.automaticallyRegisterPlugins()).thenReturn(true); return new FlutterEngine(context, flutterLoader, flutterJNI, new String[] {}, true); } } // This is just a compile time check to ensure that it's possible for FlutterActivity subclasses // to provide their own intent builders which builds their own runtime types. static class FlutterActivityWithIntentBuilders extends FlutterActivity { public static NewEngineIntentBuilder withNewEngine() { return new NewEngineIntentBuilder(FlutterActivityWithIntentBuilders.class); } public static CachedEngineIntentBuilder withCachedEngine(@NonNull String cachedEngineId) { return new CachedEngineIntentBuilder(FlutterActivityWithIntentBuilders.class, cachedEngineId); } } private static class FlutterActivityWithTextureRendering extends FlutterActivity { @Override public RenderMode getRenderMode() { return RenderMode.texture; } } private static class FlutterActivityWithReportFullyDrawn extends FlutterActivity { private boolean fullyDrawn = false; @Override public void reportFullyDrawn() { fullyDrawn = true; } public boolean isFullyDrawn() { return fullyDrawn; } public void resetFullyDrawn() { fullyDrawn = false; } } private class FlutterActivityWithMockBackInvokedHandling extends FlutterActivity { @Override public void registerOnBackInvokedCallback() {} @Override public void unregisterOnBackInvokedCallback() {} } private static final class FakeFlutterPlugin implements FlutterPlugin, ActivityAware, OnSaveInstanceStateListener, DefaultLifecycleObserver { private ActivityPluginBinding activityPluginBinding; private boolean stateRestored = false; private boolean onCreateCalled = false; @Override public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) {} @Override public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {} @Override public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) { activityPluginBinding = binding; binding.addOnSaveStateListener(this); ((FlutterActivity) binding.getActivity()).getLifecycle().addObserver(this); } @Override public void onDetachedFromActivityForConfigChanges() { onDetachedFromActivity(); } @Override public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding binding) { onAttachedToActivity(binding); } @Override public void onDetachedFromActivity() { ((FlutterActivity) activityPluginBinding.getActivity()).getLifecycle().removeObserver(this); activityPluginBinding.removeOnSaveStateListener(this); activityPluginBinding = null; } @Override public void onSaveInstanceState(@NonNull Bundle bundle) {} @Override public void onRestoreInstanceState(@Nullable Bundle bundle) { stateRestored = true; } @Override public void onCreate(@NonNull LifecycleOwner lifecycleOwner) { assertTrue("State was restored before onCreate", stateRestored); onCreateCalled = true; } } }
engine/shell/platform/android/test/io/flutter/embedding/android/FlutterActivityTest.java/0
{ "file_path": "engine/shell/platform/android/test/io/flutter/embedding/android/FlutterActivityTest.java", "repo_id": "engine", "token_count": 8624 }
346
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package test.io.flutter.embedding.engine; import static junit.framework.TestCase.assertEquals; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import androidx.annotation.NonNull; import androidx.test.core.app.ApplicationProvider; import androidx.test.ext.junit.runners.AndroidJUnit4; import io.flutter.embedding.engine.FlutterEngine; import io.flutter.embedding.engine.FlutterJNI; import io.flutter.embedding.engine.loader.FlutterLoader; import io.flutter.embedding.engine.plugins.FlutterPlugin; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.annotation.Config; @Config(manifest = Config.NONE) @RunWith(AndroidJUnit4.class) public class PluginComponentTest { boolean jniAttached; @Test public void pluginsCanAccessFlutterAssetPaths() { // Setup test. FlutterJNI mockFlutterJNI = mock(FlutterJNI.class); FlutterJNI flutterJNI = mock(FlutterJNI.class); jniAttached = false; when(flutterJNI.isAttached()).thenAnswer(invocation -> jniAttached); doAnswer(invocation -> jniAttached = true).when(flutterJNI).attachToNative(); FlutterLoader flutterLoader = new FlutterLoader(mockFlutterJNI); // Execute behavior under test. FlutterEngine flutterEngine = new FlutterEngine(ApplicationProvider.getApplicationContext(), flutterLoader, flutterJNI); // As soon as our plugin is registered it will look up asset paths and store them // for our verification. PluginThatAccessesAssets plugin = new PluginThatAccessesAssets(); flutterEngine.getPlugins().add(plugin); // Verify results. assertEquals("flutter_assets/fake_asset.jpg", plugin.getAssetPathBasedOnName()); assertEquals( "flutter_assets/packages/fakepackage/fake_asset.jpg", plugin.getAssetPathBasedOnNameAndPackage()); assertEquals("flutter_assets/some/path/fake_asset.jpg", plugin.getAssetPathBasedOnSubpath()); assertEquals( "flutter_assets/packages/fakepackage/some/path/fake_asset.jpg", plugin.getAssetPathBasedOnSubpathAndPackage()); } private static class PluginThatAccessesAssets implements FlutterPlugin { private String assetPathBasedOnName; private String assetPathBasedOnNameAndPackage; private String assetPathBasedOnSubpath; private String assetPathBasedOnSubpathAndPackage; public String getAssetPathBasedOnName() { return assetPathBasedOnName; } public String getAssetPathBasedOnNameAndPackage() { return assetPathBasedOnNameAndPackage; } public String getAssetPathBasedOnSubpath() { return assetPathBasedOnSubpath; } public String getAssetPathBasedOnSubpathAndPackage() { return assetPathBasedOnSubpathAndPackage; } @Override public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) { assetPathBasedOnName = binding.getFlutterAssets().getAssetFilePathByName("fake_asset.jpg"); assetPathBasedOnNameAndPackage = binding.getFlutterAssets().getAssetFilePathByName("fake_asset.jpg", "fakepackage"); assetPathBasedOnSubpath = binding.getFlutterAssets().getAssetFilePathByName("some/path/fake_asset.jpg"); assetPathBasedOnSubpathAndPackage = binding .getFlutterAssets() .getAssetFilePathByName("some/path/fake_asset.jpg", "fakepackage"); } @Override public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {} } }
engine/shell/platform/android/test/io/flutter/embedding/engine/PluginComponentTest.java/0
{ "file_path": "engine/shell/platform/android/test/io/flutter/embedding/engine/PluginComponentTest.java", "repo_id": "engine", "token_count": 1265 }
347
package io.flutter.embedding.engine.systemchannels; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import androidx.test.ext.junit.runners.AndroidJUnit4; import io.flutter.plugin.common.BasicMessageChannel; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.robolectric.annotation.Config; @Config(manifest = Config.NONE) @RunWith(AndroidJUnit4.class) public class LifecycleChannelTest { LifecycleChannel lifecycleChannel; BasicMessageChannel<String> mockChannel; @Before public void setUp() { mockChannel = mock(BasicMessageChannel.class); lifecycleChannel = new LifecycleChannel(mockChannel); } @Test public void lifecycleChannel_handlesResumed() { lifecycleChannel.appIsResumed(); ArgumentCaptor<String> stringArgumentCaptor = ArgumentCaptor.forClass(String.class); verify(mockChannel, times(1)).send(stringArgumentCaptor.capture()); assertEquals("AppLifecycleState.resumed", stringArgumentCaptor.getValue()); lifecycleChannel.noWindowsAreFocused(); stringArgumentCaptor = ArgumentCaptor.forClass(String.class); verify(mockChannel, times(2)).send(stringArgumentCaptor.capture()); assertEquals("AppLifecycleState.inactive", stringArgumentCaptor.getValue()); lifecycleChannel.aWindowIsFocused(); stringArgumentCaptor = ArgumentCaptor.forClass(String.class); verify(mockChannel, times(3)).send(stringArgumentCaptor.capture()); assertEquals("AppLifecycleState.resumed", stringArgumentCaptor.getValue()); // Stays inactive, so no event is sent. lifecycleChannel.appIsInactive(); verify(mockChannel, times(4)).send(any(String.class)); // Stays inactive, so no event is sent. lifecycleChannel.appIsResumed(); verify(mockChannel, times(5)).send(any(String.class)); lifecycleChannel.aWindowIsFocused(); stringArgumentCaptor = ArgumentCaptor.forClass(String.class); verify(mockChannel, times(5)).send(stringArgumentCaptor.capture()); assertEquals("AppLifecycleState.resumed", stringArgumentCaptor.getValue()); } @Test public void lifecycleChannel_handlesInactive() { lifecycleChannel.appIsInactive(); ArgumentCaptor<String> stringArgumentCaptor = ArgumentCaptor.forClass(String.class); verify(mockChannel, times(1)).send(stringArgumentCaptor.capture()); assertEquals("AppLifecycleState.inactive", stringArgumentCaptor.getValue()); // Stays inactive, so no event is sent. lifecycleChannel.aWindowIsFocused(); verify(mockChannel, times(1)).send(any(String.class)); // Stays inactive, so no event is sent. lifecycleChannel.noWindowsAreFocused(); verify(mockChannel, times(1)).send(any(String.class)); lifecycleChannel.appIsResumed(); lifecycleChannel.aWindowIsFocused(); stringArgumentCaptor = ArgumentCaptor.forClass(String.class); verify(mockChannel, times(2)).send(stringArgumentCaptor.capture()); assertEquals("AppLifecycleState.resumed", stringArgumentCaptor.getValue()); } @Test public void lifecycleChannel_handlesPaused() { // Stays inactive, so no event is sent. lifecycleChannel.appIsPaused(); ArgumentCaptor<String> stringArgumentCaptor = ArgumentCaptor.forClass(String.class); verify(mockChannel, times(1)).send(stringArgumentCaptor.capture()); assertEquals("AppLifecycleState.paused", stringArgumentCaptor.getValue()); // Stays paused, so no event is sent. lifecycleChannel.aWindowIsFocused(); verify(mockChannel, times(1)).send(any(String.class)); lifecycleChannel.noWindowsAreFocused(); verify(mockChannel, times(1)).send(any(String.class)); lifecycleChannel.appIsResumed(); stringArgumentCaptor = ArgumentCaptor.forClass(String.class); verify(mockChannel, times(2)).send(stringArgumentCaptor.capture()); assertEquals("AppLifecycleState.inactive", stringArgumentCaptor.getValue()); lifecycleChannel.aWindowIsFocused(); stringArgumentCaptor = ArgumentCaptor.forClass(String.class); verify(mockChannel, times(3)).send(stringArgumentCaptor.capture()); assertEquals("AppLifecycleState.resumed", stringArgumentCaptor.getValue()); } @Test public void lifecycleChannel_handlesDetached() { // Stays inactive, so no event is sent. lifecycleChannel.appIsDetached(); ArgumentCaptor<String> stringArgumentCaptor = ArgumentCaptor.forClass(String.class); verify(mockChannel, times(1)).send(stringArgumentCaptor.capture()); assertEquals("AppLifecycleState.detached", stringArgumentCaptor.getValue()); // Stays paused, so no event is sent. lifecycleChannel.aWindowIsFocused(); verify(mockChannel, times(1)).send(any(String.class)); lifecycleChannel.noWindowsAreFocused(); verify(mockChannel, times(1)).send(any(String.class)); lifecycleChannel.appIsResumed(); stringArgumentCaptor = ArgumentCaptor.forClass(String.class); verify(mockChannel, times(2)).send(stringArgumentCaptor.capture()); assertEquals("AppLifecycleState.inactive", stringArgumentCaptor.getValue()); lifecycleChannel.aWindowIsFocused(); stringArgumentCaptor = ArgumentCaptor.forClass(String.class); verify(mockChannel, times(3)).send(stringArgumentCaptor.capture()); assertEquals("AppLifecycleState.resumed", stringArgumentCaptor.getValue()); } }
engine/shell/platform/android/test/io/flutter/embedding/engine/systemchannels/LifecycleChannelTest.java/0
{ "file_path": "engine/shell/platform/android/test/io/flutter/embedding/engine/systemchannels/LifecycleChannelTest.java", "repo_id": "engine", "token_count": 1842 }
348
package io.flutter.plugin.localization; import static io.flutter.Build.API_LEVELS; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.annotation.TargetApi; import android.content.Context; import android.content.res.Configuration; import android.content.res.Resources; import android.os.LocaleList; import androidx.test.core.app.ApplicationProvider; import androidx.test.ext.junit.runners.AndroidJUnit4; import io.flutter.embedding.engine.FlutterJNI; import io.flutter.embedding.engine.dart.DartExecutor; import io.flutter.embedding.engine.systemchannels.LocalizationChannel; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodChannel; import java.util.Locale; import org.json.JSONException; import org.json.JSONObject; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.annotation.Config; @Config(manifest = Config.NONE) @RunWith(AndroidJUnit4.class) @TargetApi(API_LEVELS.API_24) // LocaleList and scriptCode are API 24+. public class LocalizationPluginTest { private final Context ctx = ApplicationProvider.getApplicationContext(); // This test should be synced with the version for API 24. @Test @Config(sdk = API_LEVELS.API_26) public void computePlatformResolvedLocaleAPI26() { // --- Test Setup --- FlutterJNI flutterJNI = new FlutterJNI(); Context context = mock(Context.class); Resources resources = mock(Resources.class); Configuration config = mock(Configuration.class); DartExecutor dartExecutor = mock(DartExecutor.class); LocaleList localeList = new LocaleList(new Locale("es", "MX"), new Locale("zh", "CN"), new Locale("en", "US")); when(context.getResources()).thenReturn(resources); when(resources.getConfiguration()).thenReturn(config); when(config.getLocales()).thenReturn(localeList); flutterJNI.setLocalizationPlugin( new LocalizationPlugin(context, new LocalizationChannel(dartExecutor))); // Empty supportedLocales. String[] supportedLocales = new String[] {}; String[] result = flutterJNI.computePlatformResolvedLocale(supportedLocales); assertEquals(result.length, 0); // Empty preferredLocales. supportedLocales = new String[] { "fr", "FR", "", "zh", "", "", "en", "CA", "" }; localeList = new LocaleList(); when(config.getLocales()).thenReturn(localeList); result = flutterJNI.computePlatformResolvedLocale(supportedLocales); // The first locale is default. assertEquals(result.length, 3); assertEquals(result[0], "fr"); assertEquals(result[1], "FR"); assertEquals(result[2], ""); // Example from https://developer.android.com/guide/topics/resources/multilingual-support#postN supportedLocales = new String[] { "en", "", "", "de", "DE", "", "es", "ES", "", "fr", "FR", "", "it", "IT", "" }; localeList = new LocaleList(new Locale("fr", "CH")); when(config.getLocales()).thenReturn(localeList); result = flutterJNI.computePlatformResolvedLocale(supportedLocales); // The call will use the new (> API 24) algorithm. assertEquals(result.length, 3); assertEquals(result[0], "fr"); assertEquals(result[1], "FR"); assertEquals(result[2], ""); supportedLocales = new String[] { "en", "", "", "de", "DE", "", "es", "ES", "", "fr", "FR", "", "fr", "", "", "it", "IT", "" }; localeList = new LocaleList(new Locale("fr", "CH")); when(config.getLocales()).thenReturn(localeList); result = flutterJNI.computePlatformResolvedLocale(supportedLocales); // The call will use the new (> API 24) algorithm. assertEquals(result.length, 3); assertEquals(result[0], "fr"); assertEquals(result[1], ""); assertEquals(result[2], ""); // Example from https://developer.android.com/guide/topics/resources/multilingual-support#postN supportedLocales = new String[] { "en", "", "", "de", "DE", "", "es", "ES", "", "it", "IT", "" }; localeList = new LocaleList(new Locale("fr", "CH"), new Locale("it", "CH")); when(config.getLocales()).thenReturn(localeList); result = flutterJNI.computePlatformResolvedLocale(supportedLocales); // The call will use the new (> API 24) algorithm. assertEquals(result.length, 3); assertEquals(result[0], "it"); assertEquals(result[1], "IT"); assertEquals(result[2], ""); supportedLocales = new String[] { "zh", "CN", "Hans", "zh", "HK", "Hant", }; localeList = new LocaleList(new Locale("zh", "CN")); when(config.getLocales()).thenReturn(localeList); result = flutterJNI.computePlatformResolvedLocale(supportedLocales); assertEquals(result.length, 3); assertEquals(result[0], "zh"); assertEquals(result[1], "CN"); assertEquals(result[2], "Hans"); } // This test should be synced with the version for API 26. @Test @Config(minSdk = API_LEVELS.API_24) public void computePlatformResolvedLocale_fromAndroidN() { // --- Test Setup --- FlutterJNI flutterJNI = new FlutterJNI(); Context context = mock(Context.class); Resources resources = mock(Resources.class); Configuration config = mock(Configuration.class); DartExecutor dartExecutor = mock(DartExecutor.class); LocaleList localeList = new LocaleList(new Locale("es", "MX"), new Locale("zh", "CN"), new Locale("en", "US")); when(context.getResources()).thenReturn(resources); when(resources.getConfiguration()).thenReturn(config); when(config.getLocales()).thenReturn(localeList); flutterJNI.setLocalizationPlugin( new LocalizationPlugin(context, new LocalizationChannel(dartExecutor))); // Empty supportedLocales. String[] supportedLocales = new String[] {}; String[] result = flutterJNI.computePlatformResolvedLocale(supportedLocales); assertEquals(result.length, 0); // Empty preferredLocales. supportedLocales = new String[] { "fr", "FR", "", "zh", "", "", "en", "CA", "" }; localeList = new LocaleList(); when(config.getLocales()).thenReturn(localeList); result = flutterJNI.computePlatformResolvedLocale(supportedLocales); // The first locale is default. assertEquals(result.length, 3); assertEquals(result[0], "fr"); assertEquals(result[1], "FR"); assertEquals(result[2], ""); // Example from https://developer.android.com/guide/topics/resources/multilingual-support#postN supportedLocales = new String[] { "en", "", "", "de", "DE", "", "es", "ES", "", "fr", "FR", "", "it", "IT", "" }; localeList = new LocaleList(new Locale("fr", "CH")); when(config.getLocales()).thenReturn(localeList); result = flutterJNI.computePlatformResolvedLocale(supportedLocales); // The call will use the new (> API 24) algorithm. assertEquals(result.length, 3); assertEquals(result[0], "fr"); assertEquals(result[1], "FR"); assertEquals(result[2], ""); supportedLocales = new String[] { "en", "", "", "de", "DE", "", "es", "ES", "", "fr", "FR", "", "fr", "", "", "it", "IT", "" }; localeList = new LocaleList(new Locale("fr", "CH")); when(config.getLocales()).thenReturn(localeList); result = flutterJNI.computePlatformResolvedLocale(supportedLocales); // The call will use the new (> API 24) algorithm. assertEquals(result.length, 3); assertEquals(result[0], "fr"); assertEquals(result[1], ""); assertEquals(result[2], ""); // Example from https://developer.android.com/guide/topics/resources/multilingual-support#postN supportedLocales = new String[] { "en", "", "", "de", "DE", "", "es", "ES", "", "it", "IT", "" }; localeList = new LocaleList(new Locale("fr", "CH"), new Locale("it", "CH")); when(config.getLocales()).thenReturn(localeList); result = flutterJNI.computePlatformResolvedLocale(supportedLocales); // The call will use the new (> API 24) algorithm. assertEquals(result.length, 3); assertEquals(result[0], "it"); assertEquals(result[1], "IT"); assertEquals(result[2], ""); } // Tests the legacy pre API 24 algorithm. @Test @Config(minSdk = API_LEVELS.API_21, maxSdk = API_LEVELS.API_23, qualifiers = "es-rMX") public void computePlatformResolvedLocale_emptySupportedLocales_beforeAndroidN() { FlutterJNI flutterJNI = new FlutterJNI(); DartExecutor dartExecutor = mock(DartExecutor.class); flutterJNI.setLocalizationPlugin( new LocalizationPlugin(ctx, new LocalizationChannel(dartExecutor))); String[] supportedLocales = new String[] {}; String[] result = flutterJNI.computePlatformResolvedLocale(supportedLocales); assertEquals(result.length, 0); } @Test @Config(minSdk = API_LEVELS.API_21, maxSdk = API_LEVELS.API_23, qualifiers = "") public void computePlatformResolvedLocale_selectFirstLocaleWhenNoUserSetting_beforeAndroidN() { FlutterJNI flutterJNI = new FlutterJNI(); DartExecutor dartExecutor = mock(DartExecutor.class); flutterJNI.setLocalizationPlugin( new LocalizationPlugin(ctx, new LocalizationChannel(dartExecutor))); String[] supportedLocales = new String[] { "fr", "FR", "", "zh", "", "", "en", "CA", "" }; String[] result = flutterJNI.computePlatformResolvedLocale(supportedLocales); assertEquals(result.length, 3); assertEquals(result[0], "fr"); assertEquals(result[1], "FR"); assertEquals(result[2], ""); } @Test @Config(minSdk = API_LEVELS.API_21, maxSdk = API_LEVELS.API_23, qualifiers = "fr-rCH") public void computePlatformResolvedLocale_selectFirstLocaleWhenNoExactMatch_beforeAndroidN() { FlutterJNI flutterJNI = new FlutterJNI(); DartExecutor dartExecutor = mock(DartExecutor.class); flutterJNI.setLocalizationPlugin( new LocalizationPlugin(ctx, new LocalizationChannel(dartExecutor))); // Example from https://developer.android.com/guide/topics/resources/multilingual-support#postN String[] supportedLocales = new String[] { "en", "", "", "de", "DE", "", "es", "ES", "", "fr", "FR", "", "it", "IT", "" }; String[] result = flutterJNI.computePlatformResolvedLocale(supportedLocales); assertEquals(result.length, 3); assertEquals(result[0], "en"); assertEquals(result[1], ""); assertEquals(result[2], ""); } @Test @Config(minSdk = API_LEVELS.API_21, maxSdk = API_LEVELS.API_23, qualifiers = "it-rIT") public void computePlatformResolvedLocale_selectExactMatchLocale_beforeAndroidN() { FlutterJNI flutterJNI = new FlutterJNI(); DartExecutor dartExecutor = mock(DartExecutor.class); flutterJNI.setLocalizationPlugin( new LocalizationPlugin(ctx, new LocalizationChannel(dartExecutor))); String[] supportedLocales = new String[] { "en", "", "", "de", "DE", "", "es", "ES", "", "fr", "FR", "", "it", "IT", "" }; String[] result = flutterJNI.computePlatformResolvedLocale(supportedLocales); assertEquals(result.length, 3); assertEquals(result[0], "it"); assertEquals(result[1], "IT"); assertEquals(result[2], ""); } @Test @Config(minSdk = API_LEVELS.API_21, maxSdk = API_LEVELS.API_23, qualifiers = "fr-rCH") public void computePlatformResolvedLocale_selectOnlyLanguageLocale_beforeAndroidN() { FlutterJNI flutterJNI = new FlutterJNI(); DartExecutor dartExecutor = mock(DartExecutor.class); flutterJNI.setLocalizationPlugin( new LocalizationPlugin(ctx, new LocalizationChannel(dartExecutor))); String[] supportedLocales = new String[] { "en", "", "", "de", "DE", "", "es", "ES", "", "fr", "FR", "", "fr", "", "", "it", "IT", "" }; String[] result = flutterJNI.computePlatformResolvedLocale(supportedLocales); assertEquals(result.length, 3); assertEquals(result[0], "fr"); assertEquals(result[1], ""); assertEquals(result[2], ""); } @Test public void localeFromString_languageOnly() { Locale locale = LocalizationPlugin.localeFromString("en"); assertEquals(locale, new Locale("en")); } @Test public void localeFromString_languageAndCountry() { Locale locale = LocalizationPlugin.localeFromString("en-US"); assertEquals(locale, new Locale("en", "US")); } @Test public void localeFromString_languageCountryAndVariant() { Locale locale = LocalizationPlugin.localeFromString("zh-Hans-CN"); assertEquals(locale, new Locale("zh", "CN", "Hans")); } @Test public void localeFromString_underscore() { Locale locale = LocalizationPlugin.localeFromString("zh_Hans_CN"); assertEquals(locale, new Locale("zh", "CN", "Hans")); } @Test public void localeFromString_additionalVariantsAreIgnored() { Locale locale = LocalizationPlugin.localeFromString("de-DE-u-co-phonebk"); assertEquals(locale, new Locale("de", "DE")); } @Test public void getStringResource_withoutLocale() throws JSONException { Context context = mock(Context.class); Resources resources = mock(Resources.class); DartExecutor dartExecutor = mock(DartExecutor.class); LocalizationChannel localizationChannel = new LocalizationChannel(dartExecutor); LocalizationPlugin plugin = new LocalizationPlugin(context, localizationChannel); MethodChannel.Result mockResult = mock(MethodChannel.Result.class); String fakePackageName = "package_name"; String fakeKey = "test_key"; int fakeId = 123; when(context.getPackageName()).thenReturn(fakePackageName); when(context.getResources()).thenReturn(resources); when(resources.getIdentifier(fakeKey, "string", fakePackageName)).thenReturn(fakeId); when(resources.getString(fakeId)).thenReturn("test_value"); JSONObject param = new JSONObject(); param.put("key", fakeKey); localizationChannel.handler.onMethodCall( new MethodCall("Localization.getStringResource", param), mockResult); verify(mockResult).success("test_value"); } @Test public void getStringResource_withLocale() throws JSONException { Context context = mock(Context.class); Context localContext = mock(Context.class); Resources resources = mock(Resources.class); Resources localResources = mock(Resources.class); Configuration configuration = new Configuration(); DartExecutor dartExecutor = mock(DartExecutor.class); LocalizationChannel localizationChannel = new LocalizationChannel(dartExecutor); LocalizationPlugin plugin = new LocalizationPlugin(context, localizationChannel); MethodChannel.Result mockResult = mock(MethodChannel.Result.class); String fakePackageName = "package_name"; String fakeKey = "test_key"; int fakeId = 123; when(context.getPackageName()).thenReturn(fakePackageName); when(context.createConfigurationContext(any())).thenReturn(localContext); when(context.getResources()).thenReturn(resources); when(localContext.getResources()).thenReturn(localResources); when(resources.getConfiguration()).thenReturn(configuration); when(localResources.getIdentifier(fakeKey, "string", fakePackageName)).thenReturn(fakeId); when(localResources.getString(fakeId)).thenReturn("test_value"); JSONObject param = new JSONObject(); param.put("key", fakeKey); param.put("locale", "en-US"); localizationChannel.handler.onMethodCall( new MethodCall("Localization.getStringResource", param), mockResult); verify(mockResult).success("test_value"); } @Test public void getStringResource_nonExistentKey() throws JSONException { Context context = mock(Context.class); Resources resources = mock(Resources.class); DartExecutor dartExecutor = mock(DartExecutor.class); LocalizationChannel localizationChannel = new LocalizationChannel(dartExecutor); LocalizationPlugin plugin = new LocalizationPlugin(context, localizationChannel); MethodChannel.Result mockResult = mock(MethodChannel.Result.class); String fakePackageName = "package_name"; String fakeKey = "test_key"; when(context.getPackageName()).thenReturn(fakePackageName); when(context.getResources()).thenReturn(resources); when(resources.getIdentifier(fakeKey, "string", fakePackageName)) .thenReturn(0); // 0 means not exist JSONObject param = new JSONObject(); param.put("key", fakeKey); localizationChannel.handler.onMethodCall( new MethodCall("Localization.getStringResource", param), mockResult); verify(mockResult).success(null); } }
engine/shell/platform/android/test/io/flutter/plugin/localization/LocalizationPluginTest.java/0
{ "file_path": "engine/shell/platform/android/test/io/flutter/plugin/localization/LocalizationPluginTest.java", "repo_id": "engine", "token_count": 6461 }
349
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.util; import static io.flutter.Build.API_LEVELS; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import android.content.Context; import android.os.Build; import java.io.File; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; @Config(manifest = Config.NONE) @RunWith(RobolectricTestRunner.class) public class PathUtilsTest { private static final String APP_DATA_PATH = "/data/data/package_name"; @Test public void canGetFilesDir() { Context context = mock(Context.class); when(context.getFilesDir()).thenReturn(new File(APP_DATA_PATH + "/files")); assertEquals(PathUtils.getFilesDir(context), APP_DATA_PATH + "/files"); } @Test public void canOnlyGetFilesPathWhenDiskFullAndFilesDirNotCreated() { Context context = mock(Context.class); when(context.getFilesDir()).thenReturn(null); if (Build.VERSION.SDK_INT >= API_LEVELS.API_24) { when(context.getDataDir()).thenReturn(new File(APP_DATA_PATH)); } else { when(context.getApplicationInfo().dataDir).thenReturn(APP_DATA_PATH); } assertEquals(PathUtils.getFilesDir(context), APP_DATA_PATH + "/files"); } @Test public void canGetFlutterDataDir() { Context context = mock(Context.class); when(context.getDir("flutter", Context.MODE_PRIVATE)) .thenReturn(new File(APP_DATA_PATH + "/app_flutter")); assertEquals(PathUtils.getDataDirectory(context), APP_DATA_PATH + "/app_flutter"); } @Test public void canOnlyGetFlutterDataPathWhenDiskFullAndFlutterDataDirNotCreated() { Context context = mock(Context.class); when(context.getDir("flutter", Context.MODE_PRIVATE)).thenReturn(null); if (Build.VERSION.SDK_INT >= API_LEVELS.API_24) { when(context.getDataDir()).thenReturn(new File(APP_DATA_PATH)); } else { when(context.getApplicationInfo().dataDir).thenReturn(APP_DATA_PATH); } assertEquals(PathUtils.getDataDirectory(context), APP_DATA_PATH + "/app_flutter"); } @Test public void canGetCacheDir() { Context context = mock(Context.class); when(context.getCacheDir()).thenReturn(new File(APP_DATA_PATH + "/cache")); if (Build.VERSION.SDK_INT >= API_LEVELS.API_21) { when(context.getCodeCacheDir()).thenReturn(new File(APP_DATA_PATH + "/code_cache")); } assertTrue(PathUtils.getCacheDirectory(context).startsWith(APP_DATA_PATH)); } @Test public void canOnlyGetCachePathWhenDiskFullAndCacheDirNotCreated() { Context context = mock(Context.class); when(context.getCacheDir()).thenReturn(null); if (Build.VERSION.SDK_INT >= API_LEVELS.API_21) { when(context.getCodeCacheDir()).thenReturn(null); } if (Build.VERSION.SDK_INT >= API_LEVELS.API_24) { when(context.getDataDir()).thenReturn(new File(APP_DATA_PATH)); } else { when(context.getApplicationInfo().dataDir).thenReturn(APP_DATA_PATH); } assertEquals(PathUtils.getCacheDirectory(context), APP_DATA_PATH + "/cache"); } }
engine/shell/platform/android/test/io/flutter/util/PathUtilsTest.java/0
{ "file_path": "engine/shell/platform/android/test/io/flutter/util/PathUtilsTest.java", "repo_id": "engine", "token_count": 1204 }
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 "alert_platform_node_delegate.h" namespace flutter { AlertPlatformNodeDelegate::AlertPlatformNodeDelegate( ui::AXPlatformNodeDelegate& parent_delegate) : parent_delegate_(parent_delegate) { data_.role = ax::mojom::Role::kAlert; data_.id = id_.Get(); } AlertPlatformNodeDelegate::~AlertPlatformNodeDelegate() {} gfx::AcceleratedWidget AlertPlatformNodeDelegate::GetTargetForNativeAccessibilityEvent() { return parent_delegate_.GetTargetForNativeAccessibilityEvent(); } gfx::NativeViewAccessible AlertPlatformNodeDelegate::GetParent() { return parent_delegate_.GetNativeViewAccessible(); } const ui::AXUniqueId& AlertPlatformNodeDelegate::GetUniqueId() const { return id_; } const ui::AXNodeData& AlertPlatformNodeDelegate::GetData() const { return data_; } void AlertPlatformNodeDelegate::SetText(const std::u16string& text) { data_.SetName(text); data_.SetDescription(text); data_.SetValue(text); } } // namespace flutter
engine/shell/platform/common/alert_platform_node_delegate.cc/0
{ "file_path": "engine/shell/platform/common/alert_platform_node_delegate.cc", "repo_id": "engine", "token_count": 353 }
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. #ifndef FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_ENCODABLE_VALUE_H_ #define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_ENCODABLE_VALUE_H_ #include <any> #include <cassert> #include <cstdint> #include <map> #include <string> #include <utility> #include <variant> #include <vector> // Unless overridden, attempt to detect the RTTI state from the compiler. #ifndef FLUTTER_ENABLE_RTTI #if defined(_MSC_VER) #ifdef _CPPRTTI #define FLUTTER_ENABLE_RTTI 1 #endif #elif defined(__clang__) #if __has_feature(cxx_rtti) #define FLUTTER_ENABLE_RTTI 1 #endif #elif defined(__GNUC__) #ifdef __GXX_RTTI #define FLUTTER_ENABLE_RTTI 1 #endif #endif #endif // #ifndef FLUTTER_ENABLE_RTTI namespace flutter { static_assert(sizeof(double) == 8, "EncodableValue requires a 64-bit double"); // A container for arbitrary types in EncodableValue. // // This is used in conjunction with StandardCodecExtension to allow using other // types with a StandardMethodCodec/StandardMessageCodec. It is implicitly // convertible to EncodableValue, so constructing an EncodableValue from a // custom type can generally be written as: // CustomEncodableValue(MyType(...)) // rather than: // EncodableValue(CustomEncodableValue(MyType(...))) // // For extracting received custom types, it is implicitly convertible to // std::any. For example: // const MyType& my_type_value = // std::any_cast<MyType>(std::get<CustomEncodableValue>(value)); // // If RTTI is enabled, different extension types can be checked with type(): // if (custom_value->type() == typeid(SomeData)) { ... } // Clients that wish to disable RTTI would need to decide on another approach // for distinguishing types (e.g., in StandardCodecExtension::WriteValueOfType) // if multiple custom types are needed. For instance, wrapping all of the // extension types in an EncodableValue-style variant, and only ever storing // that variant in CustomEncodableValue. class CustomEncodableValue { public: explicit CustomEncodableValue(const std::any& value) : value_(value) {} ~CustomEncodableValue() = default; // Allow implicit conversion to std::any to allow direct use of any_cast. // NOLINTNEXTLINE(google-explicit-constructor) operator std::any&() { return value_; } // NOLINTNEXTLINE(google-explicit-constructor) operator const std::any&() const { return value_; } #if defined(FLUTTER_ENABLE_RTTI) && FLUTTER_ENABLE_RTTI // Passthrough to std::any's type(). const std::type_info& type() const noexcept { return value_.type(); } #endif // This operator exists only to provide a stable ordering for use as a // std::map key, to satisfy the compiler requirements for EncodableValue. // It does not attempt to provide useful ordering semantics, and using a // custom value as a map key is not recommended. bool operator<(const CustomEncodableValue& other) const { return this < &other; } bool operator==(const CustomEncodableValue& other) const { return this == &other; } private: std::any value_; }; class EncodableValue; // Convenience type aliases. using EncodableList = std::vector<EncodableValue>; using EncodableMap = std::map<EncodableValue, EncodableValue>; namespace internal { // The base class for EncodableValue. Do not use this directly; it exists only // for EncodableValue to inherit from. // // Do not change the order or indexes of the items here; see the comment on // EncodableValue using EncodableValueVariant = std::variant<std::monostate, bool, int32_t, int64_t, double, std::string, std::vector<uint8_t>, std::vector<int32_t>, std::vector<int64_t>, std::vector<double>, EncodableList, EncodableMap, CustomEncodableValue, std::vector<float>>; } // namespace internal // An object that can contain any value or collection type supported by // Flutter's standard method codec. // // For details, see: // https://api.flutter.dev/flutter/services/StandardMessageCodec-class.html // // As an example, the following Dart structure: // { // 'flag': true, // 'name': 'Thing', // 'values': [1, 2.0, 4], // } // would correspond to: // EncodableValue(EncodableMap{ // {EncodableValue("flag"), EncodableValue(true)}, // {EncodableValue("name"), EncodableValue("Thing")}, // {EncodableValue("values"), EncodableValue(EncodableList{ // EncodableValue(1), // EncodableValue(2.0), // EncodableValue(4), // })}, // }) // // The primary API surface for this object is std::variant. For instance, // getting a string value from an EncodableValue, with type checking: // if (std::holds_alternative<std::string>(value)) { // std::string some_string = std::get<std::string>(value); // } // // The order/indexes of the variant types is part of the API surface, and is // guaranteed not to change. // // The variant types are mapped with Dart types in following ways: // std::monostate -> null // bool -> bool // int32_t -> int // int64_t -> int // double -> double // std::string -> String // std::vector<uint8_t> -> Uint8List // std::vector<int32_t> -> Int32List // std::vector<int64_t> -> Int64List // std::vector<float> -> Float32List // std::vector<double> -> Float64List // EncodableList -> List // EncodableMap -> Map class EncodableValue : public internal::EncodableValueVariant { public: // Rely on std::variant for most of the constructors/operators. using super = internal::EncodableValueVariant; using super::super; using super::operator=; explicit EncodableValue() = default; // Avoid the C++17 pitfall of conversion from char* to bool. Should not be // needed for C++20. explicit EncodableValue(const char* string) : super(std::string(string)) {} EncodableValue& operator=(const char* other) { *this = std::string(other); return *this; } // Allow implicit conversion from CustomEncodableValue; the only reason to // make a CustomEncodableValue (which can only be constructed explicitly) is // to use it with EncodableValue, so the risk of unintended conversions is // minimal, and it avoids the need for the verbose: // EncodableValue(CustomEncodableValue(...)). // NOLINTNEXTLINE(google-explicit-constructor) EncodableValue(const CustomEncodableValue& v) : super(v) {} // Override the conversion constructors from std::variant to make them // explicit, to avoid implicit conversion. // // While implicit conversion can be convenient in some cases, it can have very // surprising effects. E.g., calling a function that takes an EncodableValue // but accidentally passing an EncodableValue* would, instead of failing to // compile, go through a pointer->bool->EncodableValue(bool) chain and // silently call the function with a temp-constructed EncodableValue(true). template <class T> constexpr explicit EncodableValue(T&& t) noexcept : super(t) {} // Returns true if the value is null. Convenience wrapper since unlike the // other types, std::monostate uses aren't self-documenting. bool IsNull() const { return std::holds_alternative<std::monostate>(*this); } // Convenience method to simplify handling objects received from Flutter // where the values may be larger than 32-bit, since they have the same type // on the Dart side, but will be either 32-bit or 64-bit here depending on // the value. // // Calling this method if the value doesn't contain either an int32_t or an // int64_t will throw an exception. int64_t LongValue() const { if (std::holds_alternative<int32_t>(*this)) { return std::get<int32_t>(*this); } return std::get<int64_t>(*this); } // Explicitly provide operator<, delegating to std::variant's operator<. // There are issues with with the way the standard library-provided // < and <=> comparisons interact with classes derived from variant. friend bool operator<(const EncodableValue& lhs, const EncodableValue& rhs) { return static_cast<const super&>(lhs) < static_cast<const super&>(rhs); } }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_ENCODABLE_VALUE_H_
engine/shell/platform/common/client_wrapper/include/flutter/encodable_value.h/0
{ "file_path": "engine/shell/platform/common/client_wrapper/include/flutter/encodable_value.h", "repo_id": "engine", "token_count": 3402 }
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_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_STANDARD_METHOD_CODEC_H_ #define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_STANDARD_METHOD_CODEC_H_ #include <memory> #include "encodable_value.h" #include "method_call.h" #include "method_codec.h" #include "standard_codec_serializer.h" namespace flutter { // An implementation of MethodCodec that uses a binary serialization. class StandardMethodCodec : public MethodCodec<EncodableValue> { public: // Returns an instance of the codec, optionally using a custom serializer to // add support for more types. // // If provided, |serializer| must be long-lived. If no serializer is provided, // the default will be used. // // The instance returned for a given |extension| will be shared, and // any instance returned from this will be long-lived, and can be safely // passed to, e.g., channel constructors. static const StandardMethodCodec& GetInstance( const StandardCodecSerializer* serializer = nullptr); ~StandardMethodCodec(); // Prevent copying. StandardMethodCodec(StandardMethodCodec const&) = delete; StandardMethodCodec& operator=(StandardMethodCodec const&) = delete; protected: // |flutter::MethodCodec| std::unique_ptr<MethodCall<EncodableValue>> DecodeMethodCallInternal( const uint8_t* message, size_t message_size) const override; // |flutter::MethodCodec| std::unique_ptr<std::vector<uint8_t>> EncodeMethodCallInternal( const MethodCall<EncodableValue>& method_call) const override; // |flutter::MethodCodec| std::unique_ptr<std::vector<uint8_t>> EncodeSuccessEnvelopeInternal( const EncodableValue* result) const override; // |flutter::MethodCodec| std::unique_ptr<std::vector<uint8_t>> EncodeErrorEnvelopeInternal( const std::string& error_code, const std::string& error_message, const EncodableValue* error_details) const override; // |flutter::MethodCodec| bool DecodeAndProcessResponseEnvelopeInternal( const uint8_t* response, size_t response_size, MethodResult<EncodableValue>* result) const override; private: // Instances should be obtained via GetInstance. explicit StandardMethodCodec(const StandardCodecSerializer* serializer); const StandardCodecSerializer* serializer_; }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_INCLUDE_FLUTTER_STANDARD_METHOD_CODEC_H_
engine/shell/platform/common/client_wrapper/include/flutter/standard_method_codec.h/0
{ "file_path": "engine/shell/platform/common/client_wrapper/include/flutter/standard_method_codec.h", "repo_id": "engine", "token_count": 864 }
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 "flutter/shell/platform/common/client_wrapper/include/flutter/texture_registrar.h" #include <map> #include <memory> #include <vector> #include "flutter/fml/synchronization/waitable_event.h" #include "flutter/shell/platform/common/client_wrapper/include/flutter/plugin_registrar.h" #include "flutter/shell/platform/common/client_wrapper/testing/stub_flutter_api.h" #include "gtest/gtest.h" namespace flutter { namespace { // Stub implementation to validate calls to the API. class TestApi : public testing::StubFlutterApi { public: struct FakePixelBufferTexture { int64_t texture_id; int32_t mark_count; FlutterDesktopPixelBufferTextureCallback texture_callback; void* user_data; }; public: int64_t TextureRegistrarRegisterExternalTexture( const FlutterDesktopTextureInfo* info) override { last_texture_id_++; auto texture = std::make_unique<FakePixelBufferTexture>(); texture->texture_callback = info->pixel_buffer_config.callback; texture->user_data = info->pixel_buffer_config.user_data; texture->mark_count = 0; texture->texture_id = last_texture_id_; textures_[last_texture_id_] = std::move(texture); return last_texture_id_; } void TextureRegistrarUnregisterExternalTexture( int64_t texture_id, void (*callback)(void* user_data), void* user_data) override { auto it = textures_.find(texture_id); if (it != textures_.end()) { textures_.erase(it); } if (callback) { callback(user_data); } } bool TextureRegistrarMarkTextureFrameAvailable(int64_t texture_id) override { auto it = textures_.find(texture_id); if (it != textures_.end()) { it->second->mark_count++; return true; } return false; } FakePixelBufferTexture* GetFakeTexture(int64_t texture_id) { auto it = textures_.find(texture_id); if (it != textures_.end()) { return it->second.get(); } return nullptr; } int64_t last_texture_id() { return last_texture_id_; } size_t textures_size() { return textures_.size(); } private: int64_t last_texture_id_ = -1; std::map<int64_t, std::unique_ptr<FakePixelBufferTexture>> textures_; }; } // namespace // Tests thats textures can be registered and unregistered. TEST(TextureRegistrarTest, RegisterUnregisterTexture) { testing::ScopedStubFlutterApi scoped_api_stub(std::make_unique<TestApi>()); auto test_api = static_cast<TestApi*>(scoped_api_stub.stub()); auto dummy_registrar_handle = reinterpret_cast<FlutterDesktopPluginRegistrarRef>(1); PluginRegistrar registrar(dummy_registrar_handle); TextureRegistrar* textures = registrar.texture_registrar(); ASSERT_NE(textures, nullptr); EXPECT_EQ(test_api->last_texture_id(), -1); auto texture = test_api->GetFakeTexture(0); EXPECT_EQ(texture, nullptr); auto pixel_buffer_texture = std::make_unique<TextureVariant>( PixelBufferTexture([](size_t width, size_t height) { return nullptr; })); int64_t texture_id = textures->RegisterTexture(pixel_buffer_texture.get()); EXPECT_EQ(test_api->last_texture_id(), texture_id); EXPECT_EQ(test_api->textures_size(), static_cast<size_t>(1)); texture = test_api->GetFakeTexture(texture_id); EXPECT_EQ(texture->texture_id, texture_id); EXPECT_EQ(texture->user_data, std::get_if<PixelBufferTexture>(pixel_buffer_texture.get())); textures->MarkTextureFrameAvailable(texture_id); textures->MarkTextureFrameAvailable(texture_id); bool success = textures->MarkTextureFrameAvailable(texture_id); EXPECT_TRUE(success); EXPECT_EQ(texture->mark_count, 3); fml::AutoResetWaitableEvent unregister_latch; textures->UnregisterTexture(texture_id, [&]() { unregister_latch.Signal(); }); unregister_latch.Wait(); texture = test_api->GetFakeTexture(texture_id); EXPECT_EQ(texture, nullptr); EXPECT_EQ(test_api->textures_size(), static_cast<size_t>(0)); } // Tests that the unregister callback gets also invoked when attempting to // unregister a texture with an unknown id. TEST(TextureRegistrarTest, UnregisterInvalidTexture) { auto dummy_registrar_handle = reinterpret_cast<FlutterDesktopPluginRegistrarRef>(1); PluginRegistrar registrar(dummy_registrar_handle); TextureRegistrar* textures = registrar.texture_registrar(); fml::AutoResetWaitableEvent latch; textures->UnregisterTexture(42, [&]() { latch.Signal(); }); latch.Wait(); } // Tests that claiming a new frame being available for an unknown texture // returns false. TEST(TextureRegistrarTest, MarkFrameAvailableInvalidTexture) { auto dummy_registrar_handle = reinterpret_cast<FlutterDesktopPluginRegistrarRef>(1); PluginRegistrar registrar(dummy_registrar_handle); TextureRegistrar* textures = registrar.texture_registrar(); bool success = textures->MarkTextureFrameAvailable(42); EXPECT_FALSE(success); } } // namespace flutter
engine/shell/platform/common/client_wrapper/texture_registrar_unittests.cc/0
{ "file_path": "engine/shell/platform/common/client_wrapper/texture_registrar_unittests.cc", "repo_id": "engine", "token_count": 1730 }
354
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_COMMON_JSON_METHOD_CODEC_H_ #define FLUTTER_SHELL_PLATFORM_COMMON_JSON_METHOD_CODEC_H_ #include <rapidjson/document.h> #include "flutter/shell/platform/common/client_wrapper/include/flutter/method_call.h" #include "flutter/shell/platform/common/client_wrapper/include/flutter/method_codec.h" namespace flutter { // An implementation of MethodCodec that uses JSON strings as the serialization. class JsonMethodCodec : public MethodCodec<rapidjson::Document> { public: // Returns the shared instance of the codec. static const JsonMethodCodec& GetInstance(); ~JsonMethodCodec() = default; // Prevent copying. JsonMethodCodec(JsonMethodCodec const&) = delete; JsonMethodCodec& operator=(JsonMethodCodec const&) = delete; protected: // Instances should be obtained via GetInstance. JsonMethodCodec() = default; // |flutter::MethodCodec| std::unique_ptr<MethodCall<rapidjson::Document>> DecodeMethodCallInternal( const uint8_t* message, const size_t message_size) const override; // |flutter::MethodCodec| std::unique_ptr<std::vector<uint8_t>> EncodeMethodCallInternal( const MethodCall<rapidjson::Document>& method_call) const override; // |flutter::MethodCodec| std::unique_ptr<std::vector<uint8_t>> EncodeSuccessEnvelopeInternal( const rapidjson::Document* result) const override; // |flutter::MethodCodec| std::unique_ptr<std::vector<uint8_t>> EncodeErrorEnvelopeInternal( const std::string& error_code, const std::string& error_message, const rapidjson::Document* error_details) const override; // |flutter::MethodCodec| bool DecodeAndProcessResponseEnvelopeInternal( const uint8_t* response, const size_t response_size, MethodResult<rapidjson::Document>* result) const override; }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_COMMON_JSON_METHOD_CODEC_H_
engine/shell/platform/common/json_method_codec.h/0
{ "file_path": "engine/shell/platform/common/json_method_codec.h", "repo_id": "engine", "token_count": 699 }
355
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/common/text_input_model.h" #include <algorithm> #include <string> #include "flutter/fml/string_conversion.h" namespace flutter { namespace { // Returns true if |code_point| is a leading surrogate of a surrogate pair. bool IsLeadingSurrogate(char32_t code_point) { return (code_point & 0xFFFFFC00) == 0xD800; } // Returns true if |code_point| is a trailing surrogate of a surrogate pair. bool IsTrailingSurrogate(char32_t code_point) { return (code_point & 0xFFFFFC00) == 0xDC00; } } // namespace TextInputModel::TextInputModel() = default; TextInputModel::~TextInputModel() = default; bool TextInputModel::SetText(const std::string& text, const TextRange& selection, const TextRange& composing_range) { text_ = fml::Utf8ToUtf16(text); if (!text_range().Contains(selection) || !text_range().Contains(composing_range)) { return false; } selection_ = selection; composing_range_ = composing_range; composing_ = !composing_range.collapsed(); return true; } bool TextInputModel::SetSelection(const TextRange& range) { if (composing_ && !range.collapsed()) { return false; } if (!editable_range().Contains(range)) { return false; } selection_ = range; return true; } bool TextInputModel::SetComposingRange(const TextRange& range, size_t cursor_offset) { if (!composing_ || !text_range().Contains(range)) { return false; } composing_range_ = range; selection_ = TextRange(range.start() + cursor_offset); return true; } void TextInputModel::BeginComposing() { composing_ = true; composing_range_ = TextRange(selection_.start()); } void TextInputModel::UpdateComposingText(const std::u16string& text, const TextRange& selection) { // Preserve selection if we get a no-op update to the composing region. if (text.length() == 0 && composing_range_.collapsed()) { return; } const TextRange& rangeToDelete = composing_range_.collapsed() ? selection_ : composing_range_; text_.replace(rangeToDelete.start(), rangeToDelete.length(), text); composing_range_.set_end(composing_range_.start() + text.length()); selection_ = TextRange(selection.start() + composing_range_.start(), selection.extent() + composing_range_.start()); } void TextInputModel::UpdateComposingText(const std::u16string& text) { UpdateComposingText(text, TextRange(text.length())); } void TextInputModel::UpdateComposingText(const std::string& text) { UpdateComposingText(fml::Utf8ToUtf16(text)); } void TextInputModel::CommitComposing() { // Preserve selection if no composing text was entered. if (composing_range_.collapsed()) { return; } composing_range_ = TextRange(composing_range_.end()); selection_ = composing_range_; } void TextInputModel::EndComposing() { composing_ = false; composing_range_ = TextRange(0); } bool TextInputModel::DeleteSelected() { if (selection_.collapsed()) { return false; } size_t start = selection_.start(); text_.erase(start, selection_.length()); selection_ = TextRange(start); if (composing_) { // This occurs only immediately after composing has begun with a selection. composing_range_ = selection_; } return true; } void TextInputModel::AddCodePoint(char32_t c) { if (c <= 0xFFFF) { AddText(std::u16string({static_cast<char16_t>(c)})); } else { char32_t to_decompose = c - 0x10000; AddText(std::u16string({ // High surrogate. static_cast<char16_t>((to_decompose >> 10) + 0xd800), // Low surrogate. static_cast<char16_t>((to_decompose % 0x400) + 0xdc00), })); } } void TextInputModel::AddText(const std::u16string& text) { DeleteSelected(); if (composing_) { // Delete the current composing text, set the cursor to composing start. text_.erase(composing_range_.start(), composing_range_.length()); selection_ = TextRange(composing_range_.start()); composing_range_.set_end(composing_range_.start() + text.length()); } size_t position = selection_.position(); text_.insert(position, text); selection_ = TextRange(position + text.length()); } void TextInputModel::AddText(const std::string& text) { AddText(fml::Utf8ToUtf16(text)); } bool TextInputModel::Backspace() { if (DeleteSelected()) { return true; } // There is no selection. Delete the preceding codepoint. size_t position = selection_.position(); if (position != editable_range().start()) { int count = IsTrailingSurrogate(text_.at(position - 1)) ? 2 : 1; text_.erase(position - count, count); selection_ = TextRange(position - count); if (composing_) { composing_range_.set_end(composing_range_.end() - count); } return true; } return false; } bool TextInputModel::Delete() { if (DeleteSelected()) { return true; } // There is no selection. Delete the preceding codepoint. size_t position = selection_.position(); if (position < editable_range().end()) { int count = IsLeadingSurrogate(text_.at(position)) ? 2 : 1; text_.erase(position, count); if (composing_) { composing_range_.set_end(composing_range_.end() - count); } return true; } return false; } bool TextInputModel::DeleteSurrounding(int offset_from_cursor, int count) { size_t max_pos = editable_range().end(); size_t start = selection_.extent(); if (offset_from_cursor < 0) { for (int i = 0; i < -offset_from_cursor; i++) { // If requested start is before the available text then reduce the // number of characters to delete. if (start == editable_range().start()) { count = i; break; } start -= IsTrailingSurrogate(text_.at(start - 1)) ? 2 : 1; } } else { for (int i = 0; i < offset_from_cursor && start != max_pos; i++) { start += IsLeadingSurrogate(text_.at(start)) ? 2 : 1; } } auto end = start; for (int i = 0; i < count && end != max_pos; i++) { end += IsLeadingSurrogate(text_.at(start)) ? 2 : 1; } if (start == end) { return false; } auto deleted_length = end - start; text_.erase(start, deleted_length); // Cursor moves only if deleted area is before it. selection_ = TextRange(offset_from_cursor <= 0 ? start : selection_.start()); // Adjust composing range. if (composing_) { composing_range_.set_end(composing_range_.end() - deleted_length); } return true; } bool TextInputModel::MoveCursorToBeginning() { size_t min_pos = editable_range().start(); if (selection_.collapsed() && selection_.position() == min_pos) { return false; } selection_ = TextRange(min_pos); return true; } bool TextInputModel::MoveCursorToEnd() { size_t max_pos = editable_range().end(); if (selection_.collapsed() && selection_.position() == max_pos) { return false; } selection_ = TextRange(max_pos); return true; } bool TextInputModel::SelectToBeginning() { size_t min_pos = editable_range().start(); if (selection_.collapsed() && selection_.position() == min_pos) { return false; } selection_ = TextRange(selection_.base(), min_pos); return true; } bool TextInputModel::SelectToEnd() { size_t max_pos = editable_range().end(); if (selection_.collapsed() && selection_.position() == max_pos) { return false; } selection_ = TextRange(selection_.base(), max_pos); return true; } bool TextInputModel::MoveCursorForward() { // If there's a selection, move to the end of the selection. if (!selection_.collapsed()) { selection_ = TextRange(selection_.end()); return true; } // Otherwise, move the cursor forward. size_t position = selection_.position(); if (position != editable_range().end()) { int count = IsLeadingSurrogate(text_.at(position)) ? 2 : 1; selection_ = TextRange(position + count); return true; } return false; } bool TextInputModel::MoveCursorBack() { // If there's a selection, move to the beginning of the selection. if (!selection_.collapsed()) { selection_ = TextRange(selection_.start()); return true; } // Otherwise, move the cursor backward. size_t position = selection_.position(); if (position != editable_range().start()) { int count = IsTrailingSurrogate(text_.at(position - 1)) ? 2 : 1; selection_ = TextRange(position - count); return true; } return false; } std::string TextInputModel::GetText() const { return fml::Utf16ToUtf8(text_); } int TextInputModel::GetCursorOffset() const { // Measure the length of the current text up to the selection extent. // There is probably a much more efficient way of doing this. auto leading_text = text_.substr(0, selection_.extent()); return fml::Utf16ToUtf8(leading_text).size(); } } // namespace flutter
engine/shell/platform/common/text_input_model.cc/0
{ "file_path": "engine/shell/platform/common/text_input_model.cc", "repo_id": "engine", "token_count": 3193 }
356
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_HEADERS_FLUTTERBINARYMESSENGER_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_HEADERS_FLUTTERBINARYMESSENGER_H_ #import <Foundation/Foundation.h> #import "FlutterMacros.h" NS_ASSUME_NONNULL_BEGIN /** * A message reply callback. * * Used for submitting a binary reply back to a Flutter message sender. Also used * in for handling a binary message reply received from Flutter. * * @param reply The reply. */ typedef void (^FlutterBinaryReply)(NSData* _Nullable reply); /** * A strategy for handling incoming binary messages from Flutter and to send * asynchronous replies back to Flutter. * * @param message The message. * @param reply A callback for submitting an asynchronous reply to the sender. */ typedef void (^FlutterBinaryMessageHandler)(NSData* _Nullable message, FlutterBinaryReply reply); typedef int64_t FlutterBinaryMessengerConnection; @protocol FlutterTaskQueue <NSObject> @end /** * A facility for communicating with the Flutter side using asynchronous message * passing with binary messages. * * Implementated by: * - `FlutterBasicMessageChannel`, which supports communication using structured * messages. * - `FlutterMethodChannel`, which supports communication using asynchronous * method calls. * - `FlutterEventChannel`, which supports commuication using event streams. */ FLUTTER_DARWIN_EXPORT @protocol FlutterBinaryMessenger <NSObject> /// TODO(gaaclarke): Remove optional when macos supports Background Platform Channels. @optional - (NSObject<FlutterTaskQueue>*)makeBackgroundTaskQueue; - (FlutterBinaryMessengerConnection) setMessageHandlerOnChannel:(NSString*)channel binaryMessageHandler:(FlutterBinaryMessageHandler _Nullable)handler taskQueue:(NSObject<FlutterTaskQueue>* _Nullable)taskQueue; @required /** * Sends a binary message to the Flutter side on the specified channel, expecting * no reply. * * @param channel The channel name. * @param message The message. */ - (void)sendOnChannel:(NSString*)channel message:(NSData* _Nullable)message; /** * Sends a binary message to the Flutter side on the specified channel, expecting * an asynchronous reply. * * @param channel The channel name. * @param message The message. * @param callback A callback for receiving a reply. */ - (void)sendOnChannel:(NSString*)channel message:(NSData* _Nullable)message binaryReply:(FlutterBinaryReply _Nullable)callback; /** * Registers a message handler for incoming binary messages from the Flutter side * on the specified channel. * * Replaces any existing handler. Use a `nil` handler for unregistering the * existing handler. * * @param channel The channel name. * @param handler The message handler. * @return An identifier that represents the connection that was just created to the channel. */ - (FlutterBinaryMessengerConnection)setMessageHandlerOnChannel:(NSString*)channel binaryMessageHandler: (FlutterBinaryMessageHandler _Nullable)handler; /** * Clears out a channel's message handler if that handler is still the one that * was created as a result of * `setMessageHandlerOnChannel:binaryMessageHandler:`. * * @param connection The result from `setMessageHandlerOnChannel:binaryMessageHandler:`. */ - (void)cleanUpConnection:(FlutterBinaryMessengerConnection)connection; @end NS_ASSUME_NONNULL_END #endif // FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_HEADERS_FLUTTERBINARYMESSENGER_H_
engine/shell/platform/darwin/common/framework/Headers/FlutterBinaryMessenger.h/0
{ "file_path": "engine/shell/platform/darwin/common/framework/Headers/FlutterBinaryMessenger.h", "repo_id": "engine", "token_count": 1163 }
357
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_SOURCE_FLUTTERSTANDARDCODECHELPER_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_SOURCE_FLUTTERSTANDARDCODECHELPER_H_ #include <CoreFoundation/CoreFoundation.h> #include <stdbool.h> #include <stdint.h> #if defined(__cplusplus) extern "C" { #endif // NOLINTBEGIN(google-runtime-int) // Note: Update FlutterStandardFieldIsStandardType if this changes. typedef enum { // NOLINTBEGIN(readability-identifier-naming) FlutterStandardFieldNil, FlutterStandardFieldTrue, FlutterStandardFieldFalse, FlutterStandardFieldInt32, FlutterStandardFieldInt64, FlutterStandardFieldIntHex, FlutterStandardFieldFloat64, FlutterStandardFieldString, FlutterStandardFieldUInt8Data, FlutterStandardFieldInt32Data, FlutterStandardFieldInt64Data, FlutterStandardFieldFloat64Data, FlutterStandardFieldList, FlutterStandardFieldMap, FlutterStandardFieldFloat32Data, // NOLINTEND(readability-identifier-naming) } FlutterStandardField; static inline bool FlutterStandardFieldIsStandardType(uint8_t field) { return field <= FlutterStandardFieldFloat32Data && field >= FlutterStandardFieldNil; } typedef enum { // NOLINTBEGIN(readability-identifier-naming) FlutterStandardCodecObjcTypeNil, FlutterStandardCodecObjcTypeNSNumber, FlutterStandardCodecObjcTypeNSString, FlutterStandardCodecObjcTypeFlutterStandardTypedData, FlutterStandardCodecObjcTypeNSData, FlutterStandardCodecObjcTypeNSArray, FlutterStandardCodecObjcTypeNSDictionary, FlutterStandardCodecObjcTypeUnknown, // NOLINTEND(readability-identifier-naming) } FlutterStandardCodecObjcType; // NOLINTBEGIN(google-objc-function-naming) /////////////////////////////////////////////////////////////////////////////// ///\name Reader Helpers ///@{ void FlutterStandardCodecHelperReadAlignment(unsigned long* location, uint8_t alignment); void FlutterStandardCodecHelperReadBytes(unsigned long* location, unsigned long length, void* destination, CFDataRef data); uint8_t FlutterStandardCodecHelperReadByte(unsigned long* location, CFDataRef data); uint32_t FlutterStandardCodecHelperReadSize(unsigned long* location, CFDataRef data); CFStringRef FlutterStandardCodecHelperReadUTF8(unsigned long* location, CFDataRef data); CFTypeRef FlutterStandardCodecHelperReadValueOfType( unsigned long* location, CFDataRef data, uint8_t type, CFTypeRef (*ReadValue)(CFTypeRef), CFTypeRef (*ReadTypedDataOfType)(FlutterStandardField, CFTypeRef), CFTypeRef user_data); ///@} /////////////////////////////////////////////////////////////////////////////// ///\name Writer Helpers ///@{ void FlutterStandardCodecHelperWriteByte(CFMutableDataRef data, uint8_t value); void FlutterStandardCodecHelperWriteBytes(CFMutableDataRef data, const void* bytes, unsigned long length); void FlutterStandardCodecHelperWriteSize(CFMutableDataRef data, uint32_t size); void FlutterStandardCodecHelperWriteAlignment(CFMutableDataRef data, uint8_t alignment); void FlutterStandardCodecHelperWriteUTF8(CFMutableDataRef data, CFStringRef value); void FlutterStandardCodecHelperWriteData(CFMutableDataRef data, CFDataRef value); bool FlutterStandardCodecHelperWriteNumber(CFMutableDataRef data, CFNumberRef number); ///@} // NOLINTEND(google-objc-function-naming) // NOLINTEND(google-runtime-int) #if defined(__cplusplus) } #endif #endif // FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_SOURCE_FLUTTERSTANDARDCODECHELPER_H_
engine/shell/platform/darwin/common/framework/Source/FlutterStandardCodecHelper.h/0
{ "file_path": "engine/shell/platform/darwin/common/framework/Source/FlutterStandardCodecHelper.h", "repo_id": "engine", "token_count": 1728 }
358
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FLUTTER_TASK_QUEUE_DISPATCH_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FLUTTER_TASK_QUEUE_DISPATCH_H_ #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterBinaryMessenger.h" /// The private implementation of `FlutterTaskQueue` that has method /// declarations. /// /// `FlutterTaskQueue` doesn't have any methods publicly since it is supposed to /// be an opaque data structure. For Swift integration though `FlutterTaskQueue` /// is visible publicly with no methods. @protocol FlutterTaskQueueDispatch <FlutterTaskQueue> - (void)dispatch:(dispatch_block_t)block; @end #endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FLUTTER_TASK_QUEUE_DISPATCH_H_
engine/shell/platform/darwin/ios/flutter_task_queue_dispatch.h/0
{ "file_path": "engine/shell/platform/darwin/ios/flutter_task_queue_dispatch.h", "repo_id": "engine", "token_count": 298 }
359
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterCallbackCache_Internal.h" #include "flutter/fml/logging.h" #include "flutter/lib/ui/plugins/callback_cache.h" @implementation FlutterCallbackInformation - (void)dealloc { [_callbackName release]; [_callbackClassName release]; [_callbackLibraryPath release]; [super dealloc]; } @end @implementation FlutterCallbackCache + (FlutterCallbackInformation*)lookupCallbackInformation:(int64_t)handle { auto info = flutter::DartCallbackCache::GetCallbackInformation(handle); if (info == nullptr) { return nil; } FlutterCallbackInformation* new_info = [[[FlutterCallbackInformation alloc] init] autorelease]; new_info.callbackName = [NSString stringWithUTF8String:info->name.c_str()]; new_info.callbackClassName = [NSString stringWithUTF8String:info->class_name.c_str()]; new_info.callbackLibraryPath = [NSString stringWithUTF8String:info->library_path.c_str()]; return new_info; } + (void)setCachePath:(NSString*)path { FML_DCHECK(path != nil); flutter::DartCallbackCache::SetCachePath([path UTF8String]); NSString* cache_path = [NSString stringWithUTF8String:flutter::DartCallbackCache::GetCachePath().c_str()]; // Set the "Do Not Backup" flag to ensure that the cache isn't moved off disk in // low-memory situations. if (![[NSFileManager defaultManager] fileExistsAtPath:cache_path]) { [[NSFileManager defaultManager] createFileAtPath:cache_path contents:nil attributes:nil]; NSError* error = nil; NSURL* URL = [NSURL fileURLWithPath:cache_path]; BOOL success = [URL setResourceValue:[NSNumber numberWithBool:YES] forKey:NSURLIsExcludedFromBackupKey error:&error]; if (!success) { NSLog(@"Error excluding %@ from backup %@", [URL lastPathComponent], error); } } } @end
engine/shell/platform/darwin/ios/framework/Source/FlutterCallbackCache.mm/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterCallbackCache.mm", "repo_id": "engine", "token_count": 711 }
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 <memory> #define FML_USED_ON_EMBEDDER #import <OCMock/OCMock.h> #import <XCTest/XCTest.h> #include "flutter/fml/message_loop.h" #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Internal.h" #import "flutter/shell/platform/darwin/ios/platform_view_ios.h" FLUTTER_ASSERT_ARC namespace flutter { namespace { class FakeDelegate : 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<AssetResolver> updated_asset_resolver, AssetResolver::AssetResolverType type) override {} flutter::Settings settings_; }; } // namespace } // namespace flutter @interface FlutterEnginePlatformViewTest : XCTestCase @end @implementation FlutterEnginePlatformViewTest std::unique_ptr<flutter::PlatformViewIOS> platform_view; std::unique_ptr<fml::WeakPtrFactory<flutter::PlatformView>> weak_factory; flutter::FakeDelegate fake_delegate; - (void)setUp { fml::MessageLoop::EnsureInitializedForCurrentThread(); auto thread_task_runner = fml::MessageLoop::GetCurrent().GetTaskRunner(); auto sync_switch = std::make_shared<fml::SyncSwitch>(); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/fake_delegate, /*rendering_api=*/fake_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=*/sync_switch); weak_factory = std::make_unique<fml::WeakPtrFactory<flutter::PlatformView>>(platform_view.get()); } - (void)tearDown { weak_factory.reset(); platform_view.reset(); } - (fml::WeakPtr<flutter::PlatformView>)platformViewReplacement { return weak_factory->GetWeakPtr(); } - (void)testMsaaSampleCount { if (fake_delegate.settings_.enable_impeller) { // Default should be 4 for Impeller. XCTAssertEqual(platform_view->GetIosContext()->GetMsaaSampleCount(), MsaaSampleCount::kFour); } else { // Default should be 1 for Skia. XCTAssertEqual(platform_view->GetIosContext()->GetMsaaSampleCount(), MsaaSampleCount::kNone); } // Verify the platform view creates a new context with updated msaa_samples. // Need to use Metal, since this is ignored for Software/GL. fake_delegate.settings_.msaa_samples = 4; auto thread_task_runner = fml::MessageLoop::GetCurrent().GetTaskRunner(); auto sync_switch = std::make_shared<fml::SyncSwitch>(); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); auto msaa_4x_platform_view = std::make_unique<flutter::PlatformViewIOS>( /*delegate=*/fake_delegate, /*rendering_api=*/flutter::IOSRenderingAPI::kMetal, /*platform_views_controller=*/nil, /*task_runners=*/runners, /*worker_task_runner=*/nil, /*is_gpu_disabled_sync_switch=*/sync_switch); XCTAssertEqual(msaa_4x_platform_view->GetIosContext()->GetMsaaSampleCount(), MsaaSampleCount::kFour); } - (void)testCallsNotifyLowMemory { FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"tester"]; XCTAssertNotNil(engine); id mockEngine = OCMPartialMock(engine); OCMStub([mockEngine notifyLowMemory]); OCMStub([mockEngine iosPlatformView]).andReturn(platform_view.get()); [engine setViewController:nil]; OCMVerify([mockEngine notifyLowMemory]); OCMReject([mockEngine notifyLowMemory]); XCTNSNotificationExpectation* memoryExpectation = [[XCTNSNotificationExpectation alloc] initWithName:UIApplicationDidReceiveMemoryWarningNotification]; [[NSNotificationCenter defaultCenter] postNotificationName:UIApplicationDidReceiveMemoryWarningNotification object:nil]; [self waitForExpectations:@[ memoryExpectation ] timeout:5.0]; OCMVerify([mockEngine notifyLowMemory]); OCMReject([mockEngine notifyLowMemory]); XCTNSNotificationExpectation* backgroundExpectation = [[XCTNSNotificationExpectation alloc] initWithName:UIApplicationDidEnterBackgroundNotification]; [[NSNotificationCenter defaultCenter] postNotificationName:UIApplicationDidEnterBackgroundNotification object:nil]; [self waitForExpectations:@[ backgroundExpectation ] timeout:5.0]; OCMVerify([mockEngine notifyLowMemory]); } @end
engine/shell/platform/darwin/ios/framework/Source/FlutterEnginePlatformViewTest.mm/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterEnginePlatformViewTest.mm", "repo_id": "engine", "token_count": 2604 }
361
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTEROVERLAYVIEW_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTEROVERLAYVIEW_H_ #include <Metal/Metal.h> #include <UIKit/UIKit.h> #include <memory> #include "flutter/fml/memory/weak_ptr.h" #include "flutter/shell/common/shell.h" #import "flutter/shell/platform/darwin/ios/ios_surface.h" #include "fml/platform/darwin/cf_utils.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformViews_Internal.h" /// UIViews that are used by |FlutterPlatformViews| to present Flutter /// rendering on top of system compositor rendering (ex. a web view). /// /// When there is a view composited by the system compositor within a Flutter /// view hierarchy, instead of rendering into a single render target, Flutter /// renders into multiple render targets (depending on the number of /// interleaving levels between Flutter & non-Flutter contents). While the /// FlutterView contains the backing store for the root render target, the /// FlutterOverlay view contains the backing stores for the rest. The overlay /// views also handle touch propagation and the like for touches that occurs /// either on overlays or otherwise may be intercepted by the platform views. @interface FlutterOverlayView : UIView - (instancetype)initWithFrame:(CGRect)frame NS_UNAVAILABLE; - (instancetype)initWithCoder:(NSCoder*)aDecoder NS_UNAVAILABLE; - (instancetype)init NS_DESIGNATED_INITIALIZER; - (instancetype)initWithContentsScale:(CGFloat)contentsScale pixelFormat:(MTLPixelFormat)pixelFormat; @end #endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTEROVERLAYVIEW_H_
engine/shell/platform/darwin/ios/framework/Source/FlutterOverlayView.h/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterOverlayView.h", "repo_id": "engine", "token_count": 612 }
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. #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterSemanticsScrollView.h" #import "flutter/shell/platform/darwin/ios/framework/Source/SemanticsObject.h" @implementation FlutterSemanticsScrollView - (instancetype)initWithSemanticsObject:(SemanticsObject*)semanticsObject { self = [super initWithFrame:CGRectZero]; if (self) { _semanticsObject = semanticsObject; } return self; } - (UIView*)hitTest:(CGPoint)point withEvent:(UIEvent*)event { return nil; } // The following methods are explicitly forwarded to the wrapped SemanticsObject because the // forwarding logic above doesn't apply to them since they are also implemented in the // UIScrollView class, the base class. - (BOOL)isAccessibilityElement { if (![_semanticsObject isAccessibilityBridgeAlive]) { return NO; } if ([_semanticsObject isAccessibilityElement]) { return YES; } if (self.contentSize.width > self.frame.size.width || self.contentSize.height > self.frame.size.height) { // In SwitchControl or VoiceControl, the isAccessibilityElement must return YES // in order to use scroll actions. return ![_semanticsObject bridge]->isVoiceOverRunning(); } else { return NO; } } - (NSString*)accessibilityLabel { return [_semanticsObject accessibilityLabel]; } - (NSAttributedString*)accessibilityAttributedLabel { return [_semanticsObject accessibilityAttributedLabel]; } - (NSString*)accessibilityValue { return [_semanticsObject accessibilityValue]; } - (NSAttributedString*)accessibilityAttributedValue { return [_semanticsObject accessibilityAttributedValue]; } - (NSString*)accessibilityHint { return [_semanticsObject accessibilityHint]; } - (NSAttributedString*)accessibilityAttributedHint { return [_semanticsObject accessibilityAttributedHint]; } - (BOOL)accessibilityActivate { return [_semanticsObject accessibilityActivate]; } - (void)accessibilityIncrement { [_semanticsObject accessibilityIncrement]; } - (void)accessibilityDecrement { [_semanticsObject accessibilityDecrement]; } - (BOOL)accessibilityScroll:(UIAccessibilityScrollDirection)direction { return [_semanticsObject accessibilityScroll:direction]; } - (BOOL)accessibilityPerformEscape { return [_semanticsObject accessibilityPerformEscape]; } - (void)accessibilityElementDidBecomeFocused { [_semanticsObject accessibilityElementDidBecomeFocused]; } - (void)accessibilityElementDidLoseFocus { [_semanticsObject accessibilityElementDidLoseFocus]; } - (id)accessibilityContainer { return [_semanticsObject accessibilityContainer]; } - (NSInteger)accessibilityElementCount { return [[_semanticsObject children] count]; } @end
engine/shell/platform/darwin/ios/framework/Source/FlutterSemanticsScrollView.mm/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterSemanticsScrollView.mm", "repo_id": "engine", "token_count": 844 }
363
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERUNDOMANAGERPLUGIN_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERUNDOMANAGERPLUGIN_H_ #import <UIKit/UIKit.h> #import "flutter/fml/memory/weak_ptr.h" #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterChannels.h" #import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterViewController.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterUndoManagerDelegate.h" @interface FlutterUndoManagerPlugin : NSObject @property(nonatomic, assign) FlutterViewController* viewController; - (instancetype)init NS_UNAVAILABLE; + (instancetype)new NS_UNAVAILABLE; - (instancetype)initWithDelegate:(id<FlutterUndoManagerDelegate>)undoManagerDelegate NS_DESIGNATED_INITIALIZER; - (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result; @end #endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERUNDOMANAGERPLUGIN_H_
engine/shell/platform/darwin/ios/framework/Source/FlutterUndoManagerPlugin.h/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterUndoManagerPlugin.h", "repo_id": "engine", "token_count": 428 }
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_DARWIN_IOS_FRAMEWORK_SOURCE_SEMANTICSOBJECTTESTMOCKS_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_SEMANTICSOBJECTTESTMOCKS_H_ #import "flutter/shell/platform/darwin/ios/framework/Source/SemanticsObject.h" const CGRect kScreenSize = CGRectMake(0, 0, 600, 800); namespace flutter { namespace testing { class SemanticsActionObservation { public: SemanticsActionObservation(int32_t observed_id, SemanticsAction observed_action) : id(observed_id), action(observed_action) {} int32_t id; SemanticsAction action; }; class MockAccessibilityBridge : public AccessibilityBridgeIos { public: MockAccessibilityBridge() : observations({}) { view_ = [[UIView alloc] initWithFrame:kScreenSize]; window_ = [[UIWindow alloc] initWithFrame:kScreenSize]; [window_ addSubview:view_]; } bool isVoiceOverRunning() const override { return isVoiceOverRunningValue; } UIView* view() const override { return view_; } UIView<UITextInput>* textInputView() override { return nil; } void DispatchSemanticsAction(int32_t id, SemanticsAction action) override { SemanticsActionObservation observation(id, action); observations.push_back(observation); } void DispatchSemanticsAction(int32_t id, SemanticsAction action, fml::MallocMapping args) override { SemanticsActionObservation observation(id, action); observations.push_back(observation); } void AccessibilityObjectDidBecomeFocused(int32_t id) override {} void AccessibilityObjectDidLoseFocus(int32_t id) override {} std::shared_ptr<FlutterPlatformViewsController> GetPlatformViewsController() const override { return nil; } std::vector<SemanticsActionObservation> observations; bool isVoiceOverRunningValue; private: UIView* view_; UIWindow* window_; }; class MockAccessibilityBridgeNoWindow : public AccessibilityBridgeIos { public: MockAccessibilityBridgeNoWindow() : observations({}) { view_ = [[UIView alloc] initWithFrame:kScreenSize]; } bool isVoiceOverRunning() const override { return isVoiceOverRunningValue; } UIView* view() const override { return view_; } UIView<UITextInput>* textInputView() override { return nil; } void DispatchSemanticsAction(int32_t id, SemanticsAction action) override { SemanticsActionObservation observation(id, action); observations.push_back(observation); } void DispatchSemanticsAction(int32_t id, SemanticsAction action, fml::MallocMapping args) override { SemanticsActionObservation observation(id, action); observations.push_back(observation); } void AccessibilityObjectDidBecomeFocused(int32_t id) override {} void AccessibilityObjectDidLoseFocus(int32_t id) override {} std::shared_ptr<FlutterPlatformViewsController> GetPlatformViewsController() const override { return nil; } std::vector<SemanticsActionObservation> observations; bool isVoiceOverRunningValue; private: UIView* view_; }; } // namespace testing } // namespace flutter @interface SemanticsObject (Tests) - (BOOL)accessibilityScrollToVisible; - (BOOL)accessibilityScrollToVisibleWithChild:(id)child; - (id)_accessibilityHitTest:(CGPoint)point withEvent:(UIEvent*)event; @end #endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_SEMANTICSOBJECTTESTMOCKS_H_
engine/shell/platform/darwin/ios/framework/Source/SemanticsObjectTestMocks.h/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/SemanticsObjectTestMocks.h", "repo_id": "engine", "token_count": 1233 }
365
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "flutter/shell/platform/darwin/ios/framework/Source/platform_message_response_darwin.h" namespace flutter { PlatformMessageResponseDarwin::PlatformMessageResponseDarwin( PlatformMessageResponseCallback callback, fml::RefPtr<fml::TaskRunner> platform_task_runner) : callback_(callback, fml::scoped_policy::OwnershipPolicy::kRetain), platform_task_runner_(std::move(platform_task_runner)) {} PlatformMessageResponseDarwin::~PlatformMessageResponseDarwin() = default; void PlatformMessageResponseDarwin::Complete(std::unique_ptr<fml::Mapping> data) { fml::RefPtr<PlatformMessageResponseDarwin> self(this); platform_task_runner_->PostTask(fml::MakeCopyable([self, data = std::move(data)]() mutable { self->callback_.get()(CopyMappingPtrToNSData(std::move(data))); })); } void PlatformMessageResponseDarwin::CompleteEmpty() { fml::RefPtr<PlatformMessageResponseDarwin> self(this); platform_task_runner_->PostTask( fml::MakeCopyable([self]() mutable { self->callback_.get()(nil); })); } } // namespace flutter
engine/shell/platform/darwin/ios/framework/Source/platform_message_response_darwin.mm/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/platform_message_response_darwin.mm", "repo_id": "engine", "token_count": 381 }
366
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_DARWIN_IOS_IOS_EXTERNAL_VIEW_EMBEDDER_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_IOS_EXTERNAL_VIEW_EMBEDDER_H_ #include "flutter/flow/embedded_views.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformViews_Internal.h" namespace flutter { class IOSExternalViewEmbedder : public ExternalViewEmbedder { public: IOSExternalViewEmbedder(const std::shared_ptr<FlutterPlatformViewsController>& platform_views_controller, std::shared_ptr<IOSContext> context); // |ExternalViewEmbedder| virtual ~IOSExternalViewEmbedder() override; private: const std::shared_ptr<FlutterPlatformViewsController>& platform_views_controller_; std::shared_ptr<IOSContext> ios_context_; // |ExternalViewEmbedder| DlCanvas* GetRootCanvas() override; // |ExternalViewEmbedder| void CancelFrame() override; // |ExternalViewEmbedder| void BeginFrame(GrDirectContext* context, const fml::RefPtr<fml::RasterThreadMerger>& raster_thread_merger) override; // |ExternalViewEmbedder| void PrepareFlutterView(int64_t flutter_view_id, SkISize frame_size, double device_pixel_ratio) override; // |ExternalViewEmbedder| void PrerollCompositeEmbeddedView( int64_t view_id, std::unique_ptr<flutter::EmbeddedViewParams> params) override; // |ExternalViewEmbedder| PostPrerollResult PostPrerollAction( const fml::RefPtr<fml::RasterThreadMerger>& raster_thread_merger) override; // |ExternalViewEmbedder| DlCanvas* CompositeEmbeddedView(int64_t view_id) override; // |ExternalViewEmbedder| void SubmitFlutterView( GrDirectContext* context, const std::shared_ptr<impeller::AiksContext>& aiks_context, std::unique_ptr<SurfaceFrame> frame) override; // |ExternalViewEmbedder| void EndFrame(bool should_resubmit_frame, const fml::RefPtr<fml::RasterThreadMerger>& raster_thread_merger) override; // |ExternalViewEmbedder| bool SupportsDynamicThreadMerging() override; // |ExternalViewEmbedder| void PushFilterToVisitedPlatformViews( const std::shared_ptr<const DlImageFilter>& filter, const SkRect& filter_rect) override; // |ExternalViewEmbedder| void PushVisitedPlatformView(int64_t view_id) override; FML_DISALLOW_COPY_AND_ASSIGN(IOSExternalViewEmbedder); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_IOS_EXTERNAL_VIEW_EMBEDDER_H_
engine/shell/platform/darwin/ios/ios_external_view_embedder.h/0
{ "file_path": "engine/shell/platform/darwin/ios/ios_external_view_embedder.h", "repo_id": "engine", "token_count": 1098 }
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. #import "flutter/shell/platform/darwin/ios/rendering_api_selection.h" #include <Foundation/Foundation.h> #include <QuartzCore/CAEAGLLayer.h> #import <QuartzCore/CAMetalLayer.h> #if SHELL_ENABLE_METAL #include <Metal/Metal.h> #endif // SHELL_ENABLE_METAL #import <TargetConditionals.h> #include "flutter/fml/logging.h" #include "flutter/shell/platform/darwin/ios/framework/Source/FlutterMetalLayer.h" namespace flutter { #if SHELL_ENABLE_METAL bool ShouldUseMetalRenderer() { bool ios_version_supports_metal = false; if (@available(iOS METAL_IOS_VERSION_BASELINE, *)) { auto device = MTLCreateSystemDefaultDevice(); ios_version_supports_metal = [device supportsFeatureSet:MTLFeatureSet_iOS_GPUFamily1_v3]; [device release]; } return ios_version_supports_metal; } #endif // SHELL_ENABLE_METAL IOSRenderingAPI GetRenderingAPIForProcess(bool force_software) { #if TARGET_OS_SIMULATOR if (force_software) { return IOSRenderingAPI::kSoftware; } #else if (force_software) { FML_LOG(WARNING) << "The --enable-software-rendering is only supported on Simulator targets " "and will be ignored."; } #endif // TARGET_OS_SIMULATOR #if SHELL_ENABLE_METAL static bool should_use_metal = ShouldUseMetalRenderer(); if (should_use_metal) { return IOSRenderingAPI::kMetal; } #endif // SHELL_ENABLE_METAL // When Metal isn't available we use Skia software rendering since it performs // a little better than emulated OpenGL. Also, omitting an OpenGL backend // reduces binary footprint. #if TARGET_OS_SIMULATOR return IOSRenderingAPI::kSoftware; #else FML_CHECK(false) << "Metal may only be unavailable on simulators"; return IOSRenderingAPI::kSoftware; #endif // TARGET_OS_SIMULATOR } Class GetCoreAnimationLayerClassForRenderingAPI(IOSRenderingAPI rendering_api) { switch (rendering_api) { case IOSRenderingAPI::kSoftware: return [CALayer class]; case IOSRenderingAPI::kMetal: if (@available(iOS METAL_IOS_VERSION_BASELINE, *)) { if ([FlutterMetalLayer enabled]) { return [FlutterMetalLayer class]; } else { return [CAMetalLayer class]; } } FML_CHECK(false) << "Metal availability should already have been checked"; break; default: break; } FML_CHECK(false) << "Unknown client rendering API"; return [CALayer class]; } } // namespace flutter
engine/shell/platform/darwin/ios/rendering_api_selection.mm/0
{ "file_path": "engine/shell/platform/darwin/ios/rendering_api_selection.mm", "repo_id": "engine", "token_count": 954 }
368
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterAppDelegate.h" #import "flutter/testing/testing.h" #include "third_party/googletest/googletest/include/gtest/gtest.h" @interface AppDelegateNoopFlutterAppLifecycleDelegate : NSObject <FlutterAppLifecycleDelegate> @property(nonatomic, copy, nullable) NSArray<NSURL*>* receivedURLs; @end @implementation AppDelegateNoopFlutterAppLifecycleDelegate @end @interface AppDelegateTestFlutterAppLifecycleDelegate : NSObject <FlutterAppLifecycleDelegate> @property(nonatomic, copy, nullable) NSArray<NSURL*>* receivedURLs; @end @implementation AppDelegateTestFlutterAppLifecycleDelegate - (BOOL)handleOpenURLs:(NSArray<NSURL*>*)urls { self.receivedURLs = [urls copy]; return YES; } @end namespace flutter::testing { TEST(FlutterAppDelegateTest, DoesNotCallDelegatesWithoutHandler) { FlutterAppDelegate* appDelegate = [[FlutterAppDelegate alloc] init]; AppDelegateNoopFlutterAppLifecycleDelegate* noopDelegate = [[AppDelegateNoopFlutterAppLifecycleDelegate alloc] init]; [appDelegate addApplicationLifecycleDelegate:noopDelegate]; [appDelegate application:NSApplication.sharedApplication openURLs:@[]]; // No EXPECT, since the test is that the call doesn't throw due to calling without checking that // the method is implemented. } TEST(FlutterAppDelegateTest, ReceivesOpenURLs) { FlutterAppDelegate* appDelegate = [[FlutterAppDelegate alloc] init]; AppDelegateTestFlutterAppLifecycleDelegate* delegate = [[AppDelegateTestFlutterAppLifecycleDelegate alloc] init]; [appDelegate addApplicationLifecycleDelegate:delegate]; NSURL* URL = [NSURL URLWithString:@"https://flutter.dev"]; EXPECT_NE(URL, nil); NSArray<NSURL*>* URLs = @[ URL ]; [appDelegate application:NSApplication.sharedApplication openURLs:URLs]; EXPECT_EQ([delegate receivedURLs], URLs); } TEST(FlutterAppDelegateTest, OperURLsStopsAfterHandled) { FlutterAppDelegate* appDelegate = [[FlutterAppDelegate alloc] init]; AppDelegateTestFlutterAppLifecycleDelegate* firstDelegate = [[AppDelegateTestFlutterAppLifecycleDelegate alloc] init]; AppDelegateTestFlutterAppLifecycleDelegate* secondDelegate = [[AppDelegateTestFlutterAppLifecycleDelegate alloc] init]; [appDelegate addApplicationLifecycleDelegate:firstDelegate]; [appDelegate addApplicationLifecycleDelegate:secondDelegate]; NSURL* URL = [NSURL URLWithString:@"https://flutter.dev"]; EXPECT_NE(URL, nil); NSArray<NSURL*>* URLs = @[ URL ]; [appDelegate application:NSApplication.sharedApplication openURLs:URLs]; EXPECT_EQ([firstDelegate receivedURLs], URLs); EXPECT_EQ([secondDelegate receivedURLs], nil); } } // namespace flutter::testing
engine/shell/platform/darwin/macos/framework/Source/FlutterAppDelegateTest.mm/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterAppDelegateTest.mm", "repo_id": "engine", "token_count": 952 }
369
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterDisplayLink.h" #import <AppKit/AppKit.h> #include <numeric> #include "flutter/fml/synchronization/waitable_event.h" #include "flutter/testing/testing.h" @interface TestDisplayLinkDelegate : NSObject <FlutterDisplayLinkDelegate> { void (^_block)(CFTimeInterval timestamp, CFTimeInterval targetTimestamp); } - (instancetype)initWithBlock:(void (^)(CFTimeInterval timestamp, CFTimeInterval targetTimestamp))block; @end @implementation TestDisplayLinkDelegate - (instancetype)initWithBlock:(void (^__strong)(CFTimeInterval, CFTimeInterval))block { if (self = [super init]) { _block = block; } return self; } - (void)onDisplayLink:(CFTimeInterval)timestamp targetTimestamp:(CFTimeInterval)targetTimestamp { _block(timestamp, targetTimestamp); } @end TEST(FlutterDisplayLinkTest, ViewAddedToWindowFirst) { NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 100, 100) styleMask:NSWindowStyleMaskTitled backing:NSBackingStoreNonretained defer:NO]; NSView* view = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, 100, 100)]; [window setContentView:view]; auto event = std::make_shared<fml::AutoResetWaitableEvent>(); TestDisplayLinkDelegate* delegate = [[TestDisplayLinkDelegate alloc] initWithBlock:^(CFTimeInterval timestamp, CFTimeInterval targetTimestamp) { event->Signal(); }]; FlutterDisplayLink* displayLink = [FlutterDisplayLink displayLinkWithView:view]; displayLink.delegate = delegate; displayLink.paused = NO; event->Wait(); [displayLink invalidate]; } TEST(FlutterDisplayLinkTest, ViewAddedToWindowLater) { NSView* view = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, 100, 100)]; auto event = std::make_shared<fml::AutoResetWaitableEvent>(); TestDisplayLinkDelegate* delegate = [[TestDisplayLinkDelegate alloc] initWithBlock:^(CFTimeInterval timestamp, CFTimeInterval targetTimestamp) { event->Signal(); }]; FlutterDisplayLink* displayLink = [FlutterDisplayLink displayLinkWithView:view]; displayLink.delegate = delegate; displayLink.paused = NO; NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 100, 100) styleMask:NSWindowStyleMaskTitled backing:NSBackingStoreNonretained defer:NO]; [window setContentView:view]; event->Wait(); [displayLink invalidate]; } TEST(FlutterDisplayLinkTest, ViewRemovedFromWindow) { NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 100, 100) styleMask:NSWindowStyleMaskTitled backing:NSBackingStoreNonretained defer:NO]; NSView* view = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, 100, 100)]; [window setContentView:view]; auto event = std::make_shared<fml::AutoResetWaitableEvent>(); TestDisplayLinkDelegate* delegate = [[TestDisplayLinkDelegate alloc] initWithBlock:^(CFTimeInterval timestamp, CFTimeInterval targetTimestamp) { event->Signal(); }]; FlutterDisplayLink* displayLink = [FlutterDisplayLink displayLinkWithView:view]; displayLink.delegate = delegate; displayLink.paused = NO; event->Wait(); displayLink.paused = YES; event->Reset(); displayLink.paused = NO; [window setContentView:nil]; EXPECT_TRUE(event->WaitWithTimeout(fml::TimeDelta::FromMilliseconds(100))); EXPECT_FALSE(event->IsSignaledForTest()); [displayLink invalidate]; } TEST(FlutterDisplayLinkTest, WorkaroundForFB13482573) { NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 100, 100) styleMask:NSWindowStyleMaskTitled backing:NSBackingStoreNonretained defer:NO]; NSView* view = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, 100, 100)]; [window setContentView:view]; auto event = std::make_shared<fml::AutoResetWaitableEvent>(); TestDisplayLinkDelegate* delegate = [[TestDisplayLinkDelegate alloc] initWithBlock:^(CFTimeInterval timestamp, CFTimeInterval targetTimestamp) { event->Signal(); }]; FlutterDisplayLink* displayLink = [FlutterDisplayLink displayLinkWithView:view]; displayLink.delegate = delegate; displayLink.paused = NO; event->Wait(); displayLink.paused = YES; event->Reset(); [NSThread detachNewThreadWithBlock:^{ // Here pthread_self() will be same as pthread_self inside first invocation of // display link callback, causing CVDisplayLinkStart to return error. displayLink.paused = NO; }]; event->Wait(); [displayLink invalidate]; } TEST(FlutterDisplayLinkTest, CVDisplayLinkInterval) { CVDisplayLinkRef link; CVDisplayLinkCreateWithCGDisplay(CGMainDisplayID(), &link); __block CFTimeInterval last = 0; auto intervals = std::make_shared<std::vector<CFTimeInterval>>(); auto event = std::make_shared<fml::AutoResetWaitableEvent>(); CVDisplayLinkSetOutputHandler( link, ^(CVDisplayLinkRef displayLink, const CVTimeStamp* inNow, const CVTimeStamp* inOutputTime, CVOptionFlags flagsIn, CVOptionFlags* flagsOut) { if (last != 0) { intervals->push_back(CACurrentMediaTime() - last); } last = CACurrentMediaTime(); if (intervals->size() == 10) { event->Signal(); } return 0; }); CVDisplayLinkStart(link); event->Wait(); CVDisplayLinkStop(link); CVDisplayLinkRelease(link); CFTimeInterval average = std::reduce(intervals->begin(), intervals->end()) / intervals->size(); CFTimeInterval max = *std::max_element(intervals->begin(), intervals->end()); CFTimeInterval min = *std::min_element(intervals->begin(), intervals->end()); NSLog(@"CVDisplayLink Interval: Average: %fs, Max: %fs, Min: %fs", average, max, min); }
engine/shell/platform/darwin/macos/framework/Source/FlutterDisplayLinkTest.mm/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterDisplayLinkTest.mm", "repo_id": "engine", "token_count": 2604 }
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. #ifndef FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERKEYBOARDVIEWDELEGATE_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERKEYBOARDVIEWDELEGATE_H_ #import <Cocoa/Cocoa.h> #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterBinaryMessenger.h" #import "flutter/shell/platform/embedder/embedder.h" namespace flutter { // Signature used to notify that a keyboard layout has changed. typedef void (^KeyboardLayoutNotifier)(); // The printable result of a key under certain modifiers, used to derive key // mapping. typedef struct { // The printable character. // // If `isDeadKey` is true, then this is the character when pressing the same // dead key twice. uint32_t character; // Whether this character is a dead key. // // A dead key is a key that is not counted as text per se, but holds a // diacritics to be added to the next key. bool isDeadKey; } LayoutClue; } // namespace flutter /** * An interface for a class that can provides |FlutterKeyboardManager| with * platform-related features. * * This protocol is typically implemented by |FlutterViewController|. */ @protocol FlutterKeyboardViewDelegate @required /** * Get the next responder to dispatch events that the keyboard system * (including text input) do not handle. * * If the |nextResponder| is null, then those events will be discarded. */ @property(nonatomic, readonly, nullable) NSResponder* nextResponder; /** * Dispatch events to the framework to be processed by |HardwareKeyboard|. * * This method typically forwards events to * |FlutterEngine.sendKeyEvent:callback:userData:|. */ - (void)sendKeyEvent:(const FlutterKeyEvent&)event callback:(nullable FlutterKeyEventCallback)callback userData:(nullable void*)userData; /** * Get a binary messenger to send channel messages with. * * This method is used to create the key data channel and typically * forwards to |FlutterEngine.binaryMessenger|. */ - (nonnull id<FlutterBinaryMessenger>)getBinaryMessenger; /** * Dispatch events that are not handled by the keyboard event handlers * to the text input handler. * * This method typically forwards events to |TextInputPlugin.handleKeyEvent|. */ - (BOOL)onTextInputKeyEvent:(nonnull NSEvent*)event; /** * Add a listener that is called whenever the user changes keyboard layout. * * Only one listeners is supported. Adding new ones overwrites the current one. * Assigning nil unsubscribes. */ - (void)subscribeToKeyboardLayoutChange:(nullable flutter::KeyboardLayoutNotifier)callback; /** * Querying the printable result of a key under the given modifier state. */ - (flutter::LayoutClue)lookUpLayoutForKeyCode:(uint16_t)keyCode shift:(BOOL)shift; /** * Returns the keyboard pressed state. * * Returns the keyboard pressed state. The dictionary contains one entry per * pressed keys, mapping from the logical key to the physical key. */ - (nonnull NSDictionary*)getPressedState; @end #endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERKEYBOARDVIEWDELEGATE_H_
engine/shell/platform/darwin/macos/framework/Source/FlutterKeyboardViewDelegate.h/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterKeyboardViewDelegate.h", "repo_id": "engine", "token_count": 987 }
371
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERRENDERER_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERRENDERER_H_ #import <Cocoa/Cocoa.h> #import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterEngine.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterTextureRegistrar.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterView.h" #import "flutter/shell/platform/embedder/embedder.h" /** * Rendering backend agnostic FlutterRendererConfig provider to be used by the embedder API. */ @interface FlutterRenderer : FlutterTextureRegistrar <FlutterTextureRegistry, FlutterTextureRegistrarDelegate> /** * Interface to the system GPU. Used to issue all the rendering commands. */ @property(nonatomic, readonly, nonnull) id<MTLDevice> device; /** * Used to get the command buffers for the MTLDevice to render to. */ @property(nonatomic, readonly, nonnull) id<MTLCommandQueue> commandQueue; /** * Intializes the renderer with the given FlutterEngine. */ - (nullable instancetype)initWithFlutterEngine:(nonnull FlutterEngine*)flutterEngine; /** * Creates a FlutterRendererConfig that renders using the appropriate backend. */ - (FlutterRendererConfig)createRendererConfig; /** * Populates the texture registry with the provided metalTexture. */ - (BOOL)populateTextureWithIdentifier:(int64_t)textureID metalTexture:(nonnull FlutterMetalExternalTexture*)metalTexture; @end #endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERRENDERER_H_
engine/shell/platform/darwin/macos/framework/Source/FlutterRenderer.h/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterRenderer.h", "repo_id": "engine", "token_count": 600 }
372
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterThreadSynchronizer.h" #import <QuartzCore/QuartzCore.h> #include <mutex> #include <unordered_map> #include <vector> #import "flutter/fml/logging.h" #import "flutter/fml/synchronization/waitable_event.h" @interface FlutterThreadSynchronizer () { dispatch_queue_t _mainQueue; std::mutex _mutex; BOOL _shuttingDown; std::unordered_map<int64_t, CGSize> _contentSizes; std::vector<dispatch_block_t> _scheduledBlocks; BOOL _beginResizeWaiting; // Used to block [beginResize:]. std::condition_variable _condBlockBeginResize; } /** * Returns true if all existing views have a non-zero size. * * If there are no views, still returns true. */ - (BOOL)allViewsHaveFrame; /** * Returns true if there are any views that have a non-zero size. * * If there are no views, returns false. */ - (BOOL)someViewsHaveFrame; @end @implementation FlutterThreadSynchronizer - (instancetype)init { return [self initWithMainQueue:dispatch_get_main_queue()]; } - (instancetype)initWithMainQueue:(dispatch_queue_t)queue { self = [super init]; if (self != nil) { _mainQueue = queue; } return self; } - (BOOL)allViewsHaveFrame { for (auto const& [viewId, contentSize] : _contentSizes) { if (CGSizeEqualToSize(contentSize, CGSizeZero)) { return NO; } } return YES; } - (BOOL)someViewsHaveFrame { for (auto const& [viewId, contentSize] : _contentSizes) { if (!CGSizeEqualToSize(contentSize, CGSizeZero)) { return YES; } } return NO; } - (void)drain { dispatch_assert_queue(_mainQueue); [CATransaction begin]; [CATransaction setDisableActions:YES]; for (dispatch_block_t block : _scheduledBlocks) { block(); } [CATransaction commit]; _scheduledBlocks.clear(); } - (void)blockUntilFrameAvailable { std::unique_lock<std::mutex> lock(_mutex); [self drain]; _beginResizeWaiting = YES; while (![self someViewsHaveFrame] && !_shuttingDown) { _condBlockBeginResize.wait(lock); [self drain]; } _beginResizeWaiting = NO; } - (void)beginResizeForView:(int64_t)viewId size:(CGSize)size notify:(nonnull dispatch_block_t)notify { dispatch_assert_queue(_mainQueue); std::unique_lock<std::mutex> lock(_mutex); if (![self allViewsHaveFrame] || _shuttingDown) { // No blocking until framework produces at least one frame notify(); return; } [self drain]; notify(); _contentSizes[viewId] = CGSizeMake(-1, -1); _beginResizeWaiting = YES; while (true) { if (_shuttingDown) { break; } const CGSize& contentSize = _contentSizes[viewId]; if (CGSizeEqualToSize(contentSize, size) || CGSizeEqualToSize(contentSize, CGSizeZero)) { break; } _condBlockBeginResize.wait(lock); [self drain]; } _beginResizeWaiting = NO; } - (void)performCommitForView:(int64_t)viewId size:(CGSize)size notify:(nonnull dispatch_block_t)notify { dispatch_assert_queue_not(_mainQueue); fml::AutoResetWaitableEvent event; { std::unique_lock<std::mutex> lock(_mutex); if (_shuttingDown) { // Engine is shutting down, main thread may be blocked by the engine // waiting for raster thread to finish. return; } fml::AutoResetWaitableEvent& e = event; _scheduledBlocks.push_back(^{ notify(); _contentSizes[viewId] = size; e.Signal(); }); if (_beginResizeWaiting) { _condBlockBeginResize.notify_all(); } else { dispatch_async(_mainQueue, ^{ std::unique_lock<std::mutex> lock(_mutex); [self drain]; }); } } event.Wait(); } - (void)performOnPlatformThread:(nonnull dispatch_block_t)block { std::unique_lock<std::mutex> lock(_mutex); _scheduledBlocks.push_back(block); if (_beginResizeWaiting) { _condBlockBeginResize.notify_all(); } else { dispatch_async(_mainQueue, ^{ std::unique_lock<std::mutex> lock(_mutex); [self drain]; }); } } - (void)registerView:(int64_t)viewId { dispatch_assert_queue(_mainQueue); std::unique_lock<std::mutex> lock(_mutex); _contentSizes[viewId] = CGSizeZero; } - (void)deregisterView:(int64_t)viewId { dispatch_assert_queue(_mainQueue); std::unique_lock<std::mutex> lock(_mutex); _contentSizes.erase(viewId); } - (void)shutdown { dispatch_assert_queue(_mainQueue); std::unique_lock<std::mutex> lock(_mutex); _shuttingDown = YES; _condBlockBeginResize.notify_all(); [self drain]; } - (BOOL)isWaitingWhenMutexIsAvailable { std::unique_lock<std::mutex> lock(_mutex); return _beginResizeWaiting; } @end
engine/shell/platform/darwin/macos/framework/Source/FlutterThreadSynchronizer.mm/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterThreadSynchronizer.mm", "repo_id": "engine", "token_count": 1925 }
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. #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewEngineProvider.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h" @interface FlutterViewEngineProvider () { __weak FlutterEngine* _engine; } @end @implementation FlutterViewEngineProvider - (instancetype)initWithEngine:(FlutterEngine*)engine { self = [super init]; if (self != nil) { _engine = engine; } return self; } - (nullable FlutterView*)viewForId:(FlutterViewId)viewId { return [_engine viewControllerForId:viewId].flutterView; } @end
engine/shell/platform/darwin/macos/framework/Source/FlutterViewEngineProvider.mm/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterViewEngineProvider.mm", "repo_id": "engine", "token_count": 269 }
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. declare_args() { # By default, the dynamic library target exposing the embedder API is only # built for the host. The reasoning is that platforms that have target # definitions would not need an embedder API because an embedder # implementation is already provided for said target. This flag allows tbe # builder to obtain a shared library exposing the embedder API for alternative # embedder implementations. embedder_for_target = false }
engine/shell/platform/embedder/embedder.gni/0
{ "file_path": "engine/shell/platform/embedder/embedder.gni", "repo_id": "engine", "token_count": 148 }
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. #include "flutter/shell/platform/embedder/embedder.h" // This file is the same as embedder_include.c and ensures that static methods // don't end up in public API header. This will cause duplicate symbols when the // header in imported in the multiple translation units in the embedder.
engine/shell/platform/embedder/embedder_include2.c/0
{ "file_path": "engine/shell/platform/embedder/embedder_include2.c", "repo_id": "engine", "token_count": 114 }
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 "flutter/shell/platform/embedder/embedder_surface.h" namespace flutter { EmbedderSurface::EmbedderSurface() = default; EmbedderSurface::~EmbedderSurface() = default; std::shared_ptr<impeller::Context> EmbedderSurface::CreateImpellerContext() const { return nullptr; } sk_sp<GrDirectContext> EmbedderSurface::CreateResourceContext() const { return nullptr; } } // namespace flutter
engine/shell/platform/embedder/embedder_surface.cc/0
{ "file_path": "engine/shell/platform/embedder/embedder_surface.cc", "repo_id": "engine", "token_count": 183 }
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. #define FML_USED_ON_EMBEDDER #include "flutter/shell/platform/embedder/embedder_thread_host.h" #include <algorithm> #include "flutter/fml/message_loop.h" #include "flutter/shell/platform/embedder/embedder_struct_macros.h" namespace flutter { //------------------------------------------------------------------------------ /// @brief Attempts to create a task runner from an embedder task runner /// description. The first boolean in the pair indicate whether the /// embedder specified an invalid task runner description. In this /// case, engine launch must be aborted. If the embedder did not /// specify any task runner, an engine managed task runner and /// thread must be selected instead. /// /// @param[in] description The description /// /// @return A pair that returns if the embedder has specified a task runner /// (null otherwise) and whether to terminate further engine launch. /// static std::pair<bool, fml::RefPtr<EmbedderTaskRunner>> CreateEmbedderTaskRunner(const FlutterTaskRunnerDescription* description) { if (description == nullptr) { // This is not embedder error. The embedder API will just have to create a // plain old task runner (and create a thread for it) instead of using a // task runner provided to us by the embedder. return {true, {}}; } if (SAFE_ACCESS(description, runs_task_on_current_thread_callback, nullptr) == nullptr) { FML_LOG(ERROR) << "FlutterTaskRunnerDescription.runs_task_on_current_" "thread_callback was nullptr."; return {false, {}}; } if (SAFE_ACCESS(description, post_task_callback, nullptr) == nullptr) { FML_LOG(ERROR) << "FlutterTaskRunnerDescription.post_task_callback was nullptr."; return {false, {}}; } auto user_data = SAFE_ACCESS(description, user_data, nullptr); // ABI safety checks have been completed. auto post_task_callback_c = description->post_task_callback; auto runs_task_on_current_thread_callback_c = description->runs_task_on_current_thread_callback; EmbedderTaskRunner::DispatchTable task_runner_dispatch_table = { // .post_task_callback [post_task_callback_c, user_data](EmbedderTaskRunner* task_runner, uint64_t task_baton, fml::TimePoint target_time) -> void { FlutterTask task = { // runner reinterpret_cast<FlutterTaskRunner>(task_runner), // task task_baton, }; post_task_callback_c(task, target_time.ToEpochDelta().ToNanoseconds(), user_data); }, // runs_task_on_current_thread_callback [runs_task_on_current_thread_callback_c, user_data]() -> bool { return runs_task_on_current_thread_callback_c(user_data); }}; return {true, fml::MakeRefCounted<EmbedderTaskRunner>( task_runner_dispatch_table, SAFE_ACCESS(description, identifier, 0u))}; } std::unique_ptr<EmbedderThreadHost> EmbedderThreadHost::CreateEmbedderOrEngineManagedThreadHost( const FlutterCustomTaskRunners* custom_task_runners, const flutter::ThreadConfigSetter& config_setter) { { auto host = CreateEmbedderManagedThreadHost(custom_task_runners, config_setter); if (host && host->IsValid()) { return host; } } // Only attempt to create the engine managed host if the embedder did not // specify a custom configuration. Don't fallback to the engine managed // configuration if the embedder attempted to specify a configuration but // messed up with an incorrect configuration. if (custom_task_runners == nullptr) { auto host = CreateEngineManagedThreadHost(config_setter); if (host && host->IsValid()) { return host; } } return nullptr; } static fml::RefPtr<fml::TaskRunner> GetCurrentThreadTaskRunner() { fml::MessageLoop::EnsureInitializedForCurrentThread(); return fml::MessageLoop::GetCurrent().GetTaskRunner(); } constexpr const char* kFlutterThreadName = "io.flutter"; fml::Thread::ThreadConfig MakeThreadConfig( flutter::ThreadHost::Type type, fml::Thread::ThreadPriority priority) { return fml::Thread::ThreadConfig( flutter::ThreadHost::ThreadHostConfig::MakeThreadName(type, kFlutterThreadName), priority); } // static std::unique_ptr<EmbedderThreadHost> EmbedderThreadHost::CreateEmbedderManagedThreadHost( const FlutterCustomTaskRunners* custom_task_runners, const flutter::ThreadConfigSetter& config_setter) { if (custom_task_runners == nullptr) { return nullptr; } auto thread_host_config = ThreadHost::ThreadHostConfig(config_setter); // The UI and IO threads are always created by the engine and the embedder has // no opportunity to specify task runners for the same. // // If/when more task runners are exposed, this mask will need to be updated. thread_host_config.SetUIConfig(MakeThreadConfig( ThreadHost::Type::kUi, fml::Thread::ThreadPriority::kDisplay)); thread_host_config.SetIOConfig(MakeThreadConfig( ThreadHost::Type::kIo, fml::Thread::ThreadPriority::kBackground)); auto platform_task_runner_pair = CreateEmbedderTaskRunner( SAFE_ACCESS(custom_task_runners, platform_task_runner, nullptr)); auto render_task_runner_pair = CreateEmbedderTaskRunner( SAFE_ACCESS(custom_task_runners, render_task_runner, nullptr)); if (!platform_task_runner_pair.first || !render_task_runner_pair.first) { // User error while supplying a custom task runner. Return an invalid thread // host. This will abort engine initialization. Don't fallback to defaults // if the user wanted to specify a task runner but just messed up instead. return nullptr; } // If the embedder has not supplied a raster task runner, one needs to be // created. if (!render_task_runner_pair.second) { thread_host_config.SetRasterConfig(MakeThreadConfig( ThreadHost::Type::kRaster, fml::Thread::ThreadPriority::kRaster)); } // If both the platform task runner and the raster task runner are specified // and have the same identifier, store only one. if (platform_task_runner_pair.second && render_task_runner_pair.second) { if (platform_task_runner_pair.second->GetEmbedderIdentifier() == render_task_runner_pair.second->GetEmbedderIdentifier()) { render_task_runner_pair.second = platform_task_runner_pair.second; } } // Create a thread host with just the threads that need to be managed by the // engine. The embedder has provided the rest. ThreadHost thread_host(thread_host_config); // If the embedder has supplied a platform task runner, use that. If not, use // the current thread task runner. auto platform_task_runner = platform_task_runner_pair.second ? static_cast<fml::RefPtr<fml::TaskRunner>>( platform_task_runner_pair.second) : GetCurrentThreadTaskRunner(); // If the embedder has supplied a raster task runner, use that. If not, use // the one from our thread host. auto render_task_runner = render_task_runner_pair.second ? static_cast<fml::RefPtr<fml::TaskRunner>>( render_task_runner_pair.second) : thread_host.raster_thread->GetTaskRunner(); flutter::TaskRunners task_runners( kFlutterThreadName, platform_task_runner, // platform render_task_runner, // raster thread_host.ui_thread->GetTaskRunner(), // ui (always engine managed) thread_host.io_thread->GetTaskRunner() // io (always engine managed) ); if (!task_runners.IsValid()) { return nullptr; } std::set<fml::RefPtr<EmbedderTaskRunner>> embedder_task_runners; if (platform_task_runner_pair.second) { embedder_task_runners.insert(platform_task_runner_pair.second); } if (render_task_runner_pair.second) { embedder_task_runners.insert(render_task_runner_pair.second); } auto embedder_host = std::make_unique<EmbedderThreadHost>( std::move(thread_host), std::move(task_runners), std::move(embedder_task_runners)); if (embedder_host->IsValid()) { return embedder_host; } return nullptr; } // static std::unique_ptr<EmbedderThreadHost> EmbedderThreadHost::CreateEngineManagedThreadHost( const flutter::ThreadConfigSetter& config_setter) { // Crate a thraed host config, and specified the thread name and priority. auto thread_host_config = ThreadHost::ThreadHostConfig(config_setter); thread_host_config.SetUIConfig(MakeThreadConfig( flutter::ThreadHost::kUi, fml::Thread::ThreadPriority::kDisplay)); thread_host_config.SetRasterConfig(MakeThreadConfig( flutter::ThreadHost::kRaster, fml::Thread::ThreadPriority::kRaster)); thread_host_config.SetIOConfig(MakeThreadConfig( flutter::ThreadHost::kIo, fml::Thread::ThreadPriority::kBackground)); // Create a thread host with the current thread as the platform thread and all // other threads managed. ThreadHost thread_host(thread_host_config); // For embedder platforms that don't have native message loop interop, this // will reference a task runner that points to a null message loop // implementation. auto platform_task_runner = GetCurrentThreadTaskRunner(); flutter::TaskRunners task_runners( kFlutterThreadName, platform_task_runner, // platform thread_host.raster_thread->GetTaskRunner(), // raster thread_host.ui_thread->GetTaskRunner(), // ui thread_host.io_thread->GetTaskRunner() // io ); if (!task_runners.IsValid()) { return nullptr; } std::set<fml::RefPtr<EmbedderTaskRunner>> empty_embedder_task_runners; auto embedder_host = std::make_unique<EmbedderThreadHost>( std::move(thread_host), std::move(task_runners), empty_embedder_task_runners); if (embedder_host->IsValid()) { return embedder_host; } return nullptr; } EmbedderThreadHost::EmbedderThreadHost( ThreadHost host, const flutter::TaskRunners& runners, const std::set<fml::RefPtr<EmbedderTaskRunner>>& embedder_task_runners) : host_(std::move(host)), runners_(runners) { for (const auto& runner : embedder_task_runners) { runners_map_[reinterpret_cast<int64_t>(runner.get())] = runner; } } EmbedderThreadHost::~EmbedderThreadHost() = default; bool EmbedderThreadHost::IsValid() const { return runners_.IsValid(); } const flutter::TaskRunners& EmbedderThreadHost::GetTaskRunners() const { return runners_; } bool EmbedderThreadHost::PostTask(int64_t runner, uint64_t task) const { auto found = runners_map_.find(runner); if (found == runners_map_.end()) { return false; } return found->second->PostTask(task); } } // namespace flutter
engine/shell/platform/embedder/embedder_thread_host.cc/0
{ "file_path": "engine/shell/platform/embedder/embedder_thread_host.cc", "repo_id": "engine", "token_count": 4089 }
378
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Allow access to fml::MessageLoop::GetCurrent() in order to flush platform // thread tasks. #define FML_USED_ON_EMBEDDER #include <functional> #include "flutter/fml/macros.h" #include "flutter/fml/message_loop.h" #include "flutter/fml/synchronization/waitable_event.h" #include "flutter/lib/ui/semantics/semantics_node.h" #include "flutter/shell/platform/embedder/embedder.h" #include "flutter/shell/platform/embedder/tests/embedder_config_builder.h" #include "flutter/testing/testing.h" #include "third_party/tonic/converter/dart_converter.h" #include "gmock/gmock.h" // For EXPECT_THAT and matchers #include "gtest/gtest.h" // CREATE_NATIVE_ENTRY is leaky by design // NOLINTBEGIN(clang-analyzer-core.StackAddressEscape) namespace flutter { namespace testing { using EmbedderA11yTest = testing::EmbedderTest; using ::testing::ElementsAre; constexpr static char kTooltip[] = "tooltip"; TEST_F(EmbedderTest, CannotProvideMultipleSemanticsCallbacks) { { EmbedderConfigBuilder builder( GetEmbedderContext(EmbedderTestContextType::kSoftwareContext)); builder.SetSoftwareRendererConfig(); builder.GetProjectArgs().update_semantics_callback = [](const FlutterSemanticsUpdate* update, void* user_data) {}; builder.GetProjectArgs().update_semantics_callback2 = [](const FlutterSemanticsUpdate2* update, void* user_data) {}; auto engine = builder.InitializeEngine(); ASSERT_FALSE(engine.is_valid()); engine.reset(); } { EmbedderConfigBuilder builder( GetEmbedderContext(EmbedderTestContextType::kSoftwareContext)); builder.SetSoftwareRendererConfig(); builder.GetProjectArgs().update_semantics_callback2 = [](const FlutterSemanticsUpdate2* update, void* user_data) {}; builder.GetProjectArgs().update_semantics_node_callback = [](const FlutterSemanticsNode* update, void* user_data) {}; builder.GetProjectArgs().update_semantics_custom_action_callback = [](const FlutterSemanticsCustomAction* update, void* user_data) {}; auto engine = builder.InitializeEngine(); ASSERT_FALSE(engine.is_valid()); engine.reset(); } { EmbedderConfigBuilder builder( GetEmbedderContext(EmbedderTestContextType::kSoftwareContext)); builder.SetSoftwareRendererConfig(); builder.GetProjectArgs().update_semantics_callback = [](const FlutterSemanticsUpdate* update, void* user_data) {}; builder.GetProjectArgs().update_semantics_node_callback = [](const FlutterSemanticsNode* update, void* user_data) {}; builder.GetProjectArgs().update_semantics_custom_action_callback = [](const FlutterSemanticsCustomAction* update, void* user_data) {}; auto engine = builder.InitializeEngine(); ASSERT_FALSE(engine.is_valid()); engine.reset(); } { EmbedderConfigBuilder builder( GetEmbedderContext(EmbedderTestContextType::kSoftwareContext)); builder.SetSoftwareRendererConfig(); builder.GetProjectArgs().update_semantics_callback2 = [](const FlutterSemanticsUpdate2* update, void* user_data) {}; builder.GetProjectArgs().update_semantics_callback = [](const FlutterSemanticsUpdate* update, void* user_data) {}; builder.GetProjectArgs().update_semantics_node_callback = [](const FlutterSemanticsNode* update, void* user_data) {}; builder.GetProjectArgs().update_semantics_custom_action_callback = [](const FlutterSemanticsCustomAction* update, void* user_data) {}; auto engine = builder.InitializeEngine(); ASSERT_FALSE(engine.is_valid()); engine.reset(); } } TEST_F(EmbedderA11yTest, A11yTreeIsConsistentUsingV3Callbacks) { #if defined(OS_FUCHSIA) GTEST_SKIP() << "This test crashes on Fuchsia. https://fxbug.dev/87493 "; #else auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); fml::AutoResetWaitableEvent signal_native_latch; // Called by the Dart text fixture on the UI thread to signal that the C++ // unittest should resume. context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY(([&signal_native_latch](Dart_NativeArguments) { signal_native_latch.Signal(); }))); // Called by test fixture on UI thread to pass data back to this test. NativeEntry notify_semantics_enabled_callback; context.AddNativeCallback( "NotifySemanticsEnabled", CREATE_NATIVE_ENTRY( ([&notify_semantics_enabled_callback](Dart_NativeArguments args) { ASSERT_NE(notify_semantics_enabled_callback, nullptr); notify_semantics_enabled_callback(args); }))); NativeEntry notify_accessibility_features_callback; context.AddNativeCallback( "NotifyAccessibilityFeatures", CREATE_NATIVE_ENTRY(( [&notify_accessibility_features_callback](Dart_NativeArguments args) { ASSERT_NE(notify_accessibility_features_callback, nullptr); notify_accessibility_features_callback(args); }))); NativeEntry notify_semantics_action_callback; context.AddNativeCallback( "NotifySemanticsAction", CREATE_NATIVE_ENTRY( ([&notify_semantics_action_callback](Dart_NativeArguments args) { ASSERT_NE(notify_semantics_action_callback, nullptr); notify_semantics_action_callback(args); }))); fml::AutoResetWaitableEvent semantics_update_latch; context.SetSemanticsUpdateCallback2( [&](const FlutterSemanticsUpdate2* update) { ASSERT_EQ(size_t(4), update->node_count); ASSERT_EQ(size_t(1), update->custom_action_count); for (size_t i = 0; i < update->node_count; i++) { const FlutterSemanticsNode2* node = update->nodes[i]; ASSERT_EQ(1.0, node->transform.scaleX); ASSERT_EQ(2.0, node->transform.skewX); ASSERT_EQ(3.0, node->transform.transX); ASSERT_EQ(4.0, node->transform.skewY); ASSERT_EQ(5.0, node->transform.scaleY); ASSERT_EQ(6.0, node->transform.transY); ASSERT_EQ(7.0, node->transform.pers0); ASSERT_EQ(8.0, node->transform.pers1); ASSERT_EQ(9.0, node->transform.pers2); ASSERT_EQ(std::strncmp(kTooltip, node->tooltip, sizeof(kTooltip) - 1), 0); if (node->id == 128) { ASSERT_EQ(0x3f3, node->platform_view_id); } else { ASSERT_NE(kFlutterSemanticsNodeIdBatchEnd, node->id); ASSERT_EQ(0, node->platform_view_id); } } semantics_update_latch.Signal(); }); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); builder.SetDartEntrypoint("a11y_main"); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); // 1: Wait for initial notifySemanticsEnabled(false). fml::AutoResetWaitableEvent notify_semantics_enabled_latch; notify_semantics_enabled_callback = [&](Dart_NativeArguments args) { Dart_Handle exception = nullptr; bool enabled = ::tonic::DartConverter<bool>::FromArguments(args, 0, exception); ASSERT_FALSE(enabled); notify_semantics_enabled_latch.Signal(); }; notify_semantics_enabled_latch.Wait(); // Prepare notifyAccessibilityFeatures callback. fml::AutoResetWaitableEvent notify_features_latch; notify_accessibility_features_callback = [&](Dart_NativeArguments args) { Dart_Handle exception = nullptr; bool enabled = ::tonic::DartConverter<bool>::FromArguments(args, 0, exception); ASSERT_FALSE(enabled); notify_features_latch.Signal(); }; // 2: Enable semantics. Wait for notifySemanticsEnabled(true). fml::AutoResetWaitableEvent notify_semantics_enabled_latch_2; notify_semantics_enabled_callback = [&](Dart_NativeArguments args) { Dart_Handle exception = nullptr; bool enabled = ::tonic::DartConverter<bool>::FromArguments(args, 0, exception); ASSERT_TRUE(enabled); notify_semantics_enabled_latch_2.Signal(); }; auto result = FlutterEngineUpdateSemanticsEnabled(engine.get(), true); ASSERT_EQ(result, FlutterEngineResult::kSuccess); notify_semantics_enabled_latch_2.Wait(); // 3: Wait for notifyAccessibilityFeatures (reduce_motion == false) notify_features_latch.Wait(); // 4: Wait for notifyAccessibilityFeatures (reduce_motion == true) fml::AutoResetWaitableEvent notify_features_latch_2; notify_accessibility_features_callback = [&](Dart_NativeArguments args) { Dart_Handle exception = nullptr; bool enabled = ::tonic::DartConverter<bool>::FromArguments(args, 0, exception); ASSERT_TRUE(enabled); notify_features_latch_2.Signal(); }; result = FlutterEngineUpdateAccessibilityFeatures( engine.get(), kFlutterAccessibilityFeatureReduceMotion); ASSERT_EQ(result, FlutterEngineResult::kSuccess); notify_features_latch_2.Wait(); // 5: Wait for UpdateSemantics callback on platform (current) thread. signal_native_latch.Wait(); fml::MessageLoop::GetCurrent().RunExpiredTasksNow(); semantics_update_latch.Wait(); // 6: Dispatch a tap to semantics node 42. Wait for NotifySemanticsAction. fml::AutoResetWaitableEvent notify_semantics_action_latch; notify_semantics_action_callback = [&](Dart_NativeArguments args) { Dart_Handle exception = nullptr; int64_t node_id = ::tonic::DartConverter<int64_t>::FromArguments(args, 0, exception); ASSERT_EQ(42, node_id); int64_t action_id = ::tonic::DartConverter<int64_t>::FromArguments(args, 1, exception); ASSERT_EQ(static_cast<int32_t>(flutter::SemanticsAction::kTap), action_id); std::vector<int64_t> semantic_args = ::tonic::DartConverter<std::vector<int64_t>>::FromArguments(args, 2, exception); ASSERT_THAT(semantic_args, ElementsAre(2, 1)); notify_semantics_action_latch.Signal(); }; std::vector<uint8_t> bytes({2, 1}); result = FlutterEngineDispatchSemanticsAction( engine.get(), 42, kFlutterSemanticsActionTap, &bytes[0], bytes.size()); ASSERT_EQ(result, FlutterEngineResult::kSuccess); notify_semantics_action_latch.Wait(); // 7: Disable semantics. Wait for NotifySemanticsEnabled(false). fml::AutoResetWaitableEvent notify_semantics_enabled_latch_3; notify_semantics_enabled_callback = [&](Dart_NativeArguments args) { Dart_Handle exception = nullptr; bool enabled = ::tonic::DartConverter<bool>::FromArguments(args, 0, exception); ASSERT_FALSE(enabled); notify_semantics_enabled_latch_3.Signal(); }; result = FlutterEngineUpdateSemanticsEnabled(engine.get(), false); ASSERT_EQ(result, FlutterEngineResult::kSuccess); notify_semantics_enabled_latch_3.Wait(); #endif // OS_FUCHSIA } TEST_F(EmbedderA11yTest, A11yStringAttributes) { #if defined(OS_FUCHSIA) GTEST_SKIP() << "This test crashes on Fuchsia. https://fxbug.dev/87493 "; #else auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); fml::AutoResetWaitableEvent signal_native_latch; // Called by the Dart text fixture on the UI thread to signal that the C++ // unittest should resume. context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY(([&signal_native_latch](Dart_NativeArguments) { signal_native_latch.Signal(); }))); fml::AutoResetWaitableEvent semantics_update_latch; context.SetSemanticsUpdateCallback2( [&](const FlutterSemanticsUpdate2* update) { ASSERT_EQ(update->node_count, size_t(1)); ASSERT_EQ(update->custom_action_count, size_t(0)); auto node = update->nodes[0]; // Verify label { ASSERT_EQ(std::string(node->label), "What is the meaning of life?"); ASSERT_EQ(node->label_attribute_count, size_t(2)); ASSERT_EQ(node->label_attributes[0]->start, size_t(0)); ASSERT_EQ(node->label_attributes[0]->end, size_t(28)); ASSERT_EQ(node->label_attributes[0]->type, FlutterStringAttributeType::kLocale); ASSERT_EQ(std::string(node->label_attributes[0]->locale->locale), "en"); ASSERT_EQ(node->label_attributes[1]->start, size_t(0)); ASSERT_EQ(node->label_attributes[1]->end, size_t(1)); ASSERT_EQ(node->label_attributes[1]->type, FlutterStringAttributeType::kSpellOut); } // Verify hint { ASSERT_EQ(std::string(node->hint), "It's a number"); ASSERT_EQ(node->hint_attribute_count, size_t(2)); ASSERT_EQ(node->hint_attributes[0]->start, size_t(0)); ASSERT_EQ(node->hint_attributes[0]->end, size_t(1)); ASSERT_EQ(node->hint_attributes[0]->type, FlutterStringAttributeType::kLocale); ASSERT_EQ(std::string(node->hint_attributes[0]->locale->locale), "en"); ASSERT_EQ(node->hint_attributes[1]->start, size_t(2)); ASSERT_EQ(node->hint_attributes[1]->end, size_t(3)); ASSERT_EQ(node->hint_attributes[1]->type, FlutterStringAttributeType::kLocale); ASSERT_EQ(std::string(node->hint_attributes[1]->locale->locale), "fr"); } // Verify value { ASSERT_EQ(std::string(node->value), "42"); ASSERT_EQ(node->value_attribute_count, size_t(1)); ASSERT_EQ(node->value_attributes[0]->start, size_t(0)); ASSERT_EQ(node->value_attributes[0]->end, size_t(2)); ASSERT_EQ(node->value_attributes[0]->type, FlutterStringAttributeType::kLocale); ASSERT_EQ(std::string(node->value_attributes[0]->locale->locale), "en-US"); } // Verify increased value { ASSERT_EQ(std::string(node->increased_value), "43"); ASSERT_EQ(node->increased_value_attribute_count, size_t(2)); ASSERT_EQ(node->increased_value_attributes[0]->start, size_t(0)); ASSERT_EQ(node->increased_value_attributes[0]->end, size_t(1)); ASSERT_EQ(node->increased_value_attributes[0]->type, FlutterStringAttributeType::kSpellOut); ASSERT_EQ(node->increased_value_attributes[1]->start, size_t(1)); ASSERT_EQ(node->increased_value_attributes[1]->end, size_t(2)); ASSERT_EQ(node->increased_value_attributes[1]->type, FlutterStringAttributeType::kSpellOut); } // Verify decreased value { ASSERT_EQ(std::string(node->decreased_value), "41"); ASSERT_EQ(node->decreased_value_attribute_count, size_t(0)); ASSERT_EQ(node->decreased_value_attributes, nullptr); } semantics_update_latch.Signal(); }); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); builder.SetDartEntrypoint("a11y_string_attributes"); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); // 1: Enable semantics. auto result = FlutterEngineUpdateSemanticsEnabled(engine.get(), true); ASSERT_EQ(result, FlutterEngineResult::kSuccess); // 2: Wait for semantics update callback on platform (current) thread. signal_native_latch.Wait(); fml::MessageLoop::GetCurrent().RunExpiredTasksNow(); semantics_update_latch.Wait(); #endif // OS_FUCHSIA } TEST_F(EmbedderA11yTest, A11yTreeIsConsistentUsingV2Callbacks) { #if defined(OS_FUCHSIA) GTEST_SKIP() << "This test crashes on Fuchsia. https://fxbug.dev/87493 "; #else auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); fml::AutoResetWaitableEvent signal_native_latch; // Called by the Dart text fixture on the UI thread to signal that the C++ // unittest should resume. context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY(([&signal_native_latch](Dart_NativeArguments) { signal_native_latch.Signal(); }))); // Called by test fixture on UI thread to pass data back to this test. NativeEntry notify_semantics_enabled_callback; context.AddNativeCallback( "NotifySemanticsEnabled", CREATE_NATIVE_ENTRY( ([&notify_semantics_enabled_callback](Dart_NativeArguments args) { ASSERT_NE(notify_semantics_enabled_callback, nullptr); notify_semantics_enabled_callback(args); }))); NativeEntry notify_accessibility_features_callback; context.AddNativeCallback( "NotifyAccessibilityFeatures", CREATE_NATIVE_ENTRY(( [&notify_accessibility_features_callback](Dart_NativeArguments args) { ASSERT_NE(notify_accessibility_features_callback, nullptr); notify_accessibility_features_callback(args); }))); NativeEntry notify_semantics_action_callback; context.AddNativeCallback( "NotifySemanticsAction", CREATE_NATIVE_ENTRY( ([&notify_semantics_action_callback](Dart_NativeArguments args) { ASSERT_NE(notify_semantics_action_callback, nullptr); notify_semantics_action_callback(args); }))); fml::AutoResetWaitableEvent semantics_update_latch; context.SetSemanticsUpdateCallback([&](const FlutterSemanticsUpdate* update) { ASSERT_EQ(size_t(4), update->nodes_count); ASSERT_EQ(size_t(1), update->custom_actions_count); for (size_t i = 0; i < update->nodes_count; i++) { const FlutterSemanticsNode* node = update->nodes + i; ASSERT_EQ(1.0, node->transform.scaleX); ASSERT_EQ(2.0, node->transform.skewX); ASSERT_EQ(3.0, node->transform.transX); ASSERT_EQ(4.0, node->transform.skewY); ASSERT_EQ(5.0, node->transform.scaleY); ASSERT_EQ(6.0, node->transform.transY); ASSERT_EQ(7.0, node->transform.pers0); ASSERT_EQ(8.0, node->transform.pers1); ASSERT_EQ(9.0, node->transform.pers2); ASSERT_EQ(std::strncmp(kTooltip, node->tooltip, sizeof(kTooltip) - 1), 0); if (node->id == 128) { ASSERT_EQ(0x3f3, node->platform_view_id); } else { ASSERT_NE(kFlutterSemanticsNodeIdBatchEnd, node->id); ASSERT_EQ(0, node->platform_view_id); } } semantics_update_latch.Signal(); }); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); builder.SetDartEntrypoint("a11y_main"); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); // 1: Wait for initial notifySemanticsEnabled(false). fml::AutoResetWaitableEvent notify_semantics_enabled_latch; notify_semantics_enabled_callback = [&](Dart_NativeArguments args) { Dart_Handle exception = nullptr; bool enabled = ::tonic::DartConverter<bool>::FromArguments(args, 0, exception); ASSERT_FALSE(enabled); notify_semantics_enabled_latch.Signal(); }; notify_semantics_enabled_latch.Wait(); // Prepare notifyAccessibilityFeatures callback. fml::AutoResetWaitableEvent notify_features_latch; notify_accessibility_features_callback = [&](Dart_NativeArguments args) { Dart_Handle exception = nullptr; bool enabled = ::tonic::DartConverter<bool>::FromArguments(args, 0, exception); ASSERT_FALSE(enabled); notify_features_latch.Signal(); }; // 2: Enable semantics. Wait for notifySemanticsEnabled(true). fml::AutoResetWaitableEvent notify_semantics_enabled_latch_2; notify_semantics_enabled_callback = [&](Dart_NativeArguments args) { Dart_Handle exception = nullptr; bool enabled = ::tonic::DartConverter<bool>::FromArguments(args, 0, exception); ASSERT_TRUE(enabled); notify_semantics_enabled_latch_2.Signal(); }; auto result = FlutterEngineUpdateSemanticsEnabled(engine.get(), true); ASSERT_EQ(result, FlutterEngineResult::kSuccess); notify_semantics_enabled_latch_2.Wait(); // 3: Wait for notifyAccessibilityFeatures (reduce_motion == false) notify_features_latch.Wait(); // 4: Wait for notifyAccessibilityFeatures (reduce_motion == true) fml::AutoResetWaitableEvent notify_features_latch_2; notify_accessibility_features_callback = [&](Dart_NativeArguments args) { Dart_Handle exception = nullptr; bool enabled = ::tonic::DartConverter<bool>::FromArguments(args, 0, exception); ASSERT_TRUE(enabled); notify_features_latch_2.Signal(); }; result = FlutterEngineUpdateAccessibilityFeatures( engine.get(), kFlutterAccessibilityFeatureReduceMotion); ASSERT_EQ(result, FlutterEngineResult::kSuccess); notify_features_latch_2.Wait(); // 5: Wait for UpdateSemantics callback on platform (current) thread. signal_native_latch.Wait(); fml::MessageLoop::GetCurrent().RunExpiredTasksNow(); semantics_update_latch.Wait(); // 6: Dispatch a tap to semantics node 42. Wait for NotifySemanticsAction. fml::AutoResetWaitableEvent notify_semantics_action_latch; notify_semantics_action_callback = [&](Dart_NativeArguments args) { Dart_Handle exception = nullptr; int64_t node_id = ::tonic::DartConverter<int64_t>::FromArguments(args, 0, exception); ASSERT_EQ(42, node_id); int64_t action_id = ::tonic::DartConverter<int64_t>::FromArguments(args, 1, exception); ASSERT_EQ(static_cast<int32_t>(flutter::SemanticsAction::kTap), action_id); std::vector<int64_t> semantic_args = ::tonic::DartConverter<std::vector<int64_t>>::FromArguments(args, 2, exception); ASSERT_THAT(semantic_args, ElementsAre(2, 1)); notify_semantics_action_latch.Signal(); }; std::vector<uint8_t> bytes({2, 1}); result = FlutterEngineDispatchSemanticsAction( engine.get(), 42, kFlutterSemanticsActionTap, &bytes[0], bytes.size()); ASSERT_EQ(result, FlutterEngineResult::kSuccess); notify_semantics_action_latch.Wait(); // 7: Disable semantics. Wait for NotifySemanticsEnabled(false). fml::AutoResetWaitableEvent notify_semantics_enabled_latch_3; notify_semantics_enabled_callback = [&](Dart_NativeArguments args) { Dart_Handle exception = nullptr; bool enabled = ::tonic::DartConverter<bool>::FromArguments(args, 0, exception); ASSERT_FALSE(enabled); notify_semantics_enabled_latch_3.Signal(); }; result = FlutterEngineUpdateSemanticsEnabled(engine.get(), false); ASSERT_EQ(result, FlutterEngineResult::kSuccess); notify_semantics_enabled_latch_3.Wait(); #endif // OS_FUCHSIA } TEST_F(EmbedderA11yTest, A11yTreeIsConsistentUsingV1Callbacks) { auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); fml::AutoResetWaitableEvent signal_native_latch; // Called by the Dart text fixture on the UI thread to signal that the C++ // unittest should resume. context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY(([&signal_native_latch](Dart_NativeArguments) { signal_native_latch.Signal(); }))); // Called by test fixture on UI thread to pass data back to this test. NativeEntry notify_semantics_enabled_callback; context.AddNativeCallback( "NotifySemanticsEnabled", CREATE_NATIVE_ENTRY( ([&notify_semantics_enabled_callback](Dart_NativeArguments args) { ASSERT_NE(notify_semantics_enabled_callback, nullptr); notify_semantics_enabled_callback(args); }))); NativeEntry notify_accessibility_features_callback; context.AddNativeCallback( "NotifyAccessibilityFeatures", CREATE_NATIVE_ENTRY(( [&notify_accessibility_features_callback](Dart_NativeArguments args) { ASSERT_NE(notify_accessibility_features_callback, nullptr); notify_accessibility_features_callback(args); }))); NativeEntry notify_semantics_action_callback; context.AddNativeCallback( "NotifySemanticsAction", CREATE_NATIVE_ENTRY( ([&notify_semantics_action_callback](Dart_NativeArguments args) { ASSERT_NE(notify_semantics_action_callback, nullptr); notify_semantics_action_callback(args); }))); fml::AutoResetWaitableEvent semantics_node_latch; fml::AutoResetWaitableEvent semantics_action_latch; int node_batch_end_count = 0; int action_batch_end_count = 0; int node_count = 0; context.SetSemanticsNodeCallback([&](const FlutterSemanticsNode* node) { if (node->id == kFlutterSemanticsNodeIdBatchEnd) { ++node_batch_end_count; semantics_node_latch.Signal(); } else { // Batches should be completed after all nodes are received. ASSERT_EQ(0, node_batch_end_count); ASSERT_EQ(0, action_batch_end_count); ++node_count; ASSERT_EQ(1.0, node->transform.scaleX); ASSERT_EQ(2.0, node->transform.skewX); ASSERT_EQ(3.0, node->transform.transX); ASSERT_EQ(4.0, node->transform.skewY); ASSERT_EQ(5.0, node->transform.scaleY); ASSERT_EQ(6.0, node->transform.transY); ASSERT_EQ(7.0, node->transform.pers0); ASSERT_EQ(8.0, node->transform.pers1); ASSERT_EQ(9.0, node->transform.pers2); ASSERT_EQ(std::strncmp(kTooltip, node->tooltip, sizeof(kTooltip) - 1), 0); if (node->id == 128) { ASSERT_EQ(0x3f3, node->platform_view_id); } else { ASSERT_EQ(0, node->platform_view_id); } } }); int action_count = 0; context.SetSemanticsCustomActionCallback( [&](const FlutterSemanticsCustomAction* action) { if (action->id == kFlutterSemanticsCustomActionIdBatchEnd) { ++action_batch_end_count; semantics_action_latch.Signal(); } else { // Batches should be completed after all actions are received. ASSERT_EQ(0, node_batch_end_count); ASSERT_EQ(0, action_batch_end_count); ++action_count; } }); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); builder.SetDartEntrypoint("a11y_main"); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); // 1: Wait for initial notifySemanticsEnabled(false). fml::AutoResetWaitableEvent notify_semantics_enabled_latch; notify_semantics_enabled_callback = [&](Dart_NativeArguments args) { Dart_Handle exception = nullptr; bool enabled = ::tonic::DartConverter<bool>::FromArguments(args, 0, exception); ASSERT_FALSE(enabled); notify_semantics_enabled_latch.Signal(); }; notify_semantics_enabled_latch.Wait(); // Prepare notifyAccessibilityFeatures callback. fml::AutoResetWaitableEvent notify_features_latch; notify_accessibility_features_callback = [&](Dart_NativeArguments args) { Dart_Handle exception = nullptr; bool enabled = ::tonic::DartConverter<bool>::FromArguments(args, 0, exception); ASSERT_FALSE(enabled); notify_features_latch.Signal(); }; // 2: Enable semantics. Wait for notifySemanticsEnabled(true). fml::AutoResetWaitableEvent notify_semantics_enabled_latch_2; notify_semantics_enabled_callback = [&](Dart_NativeArguments args) { Dart_Handle exception = nullptr; bool enabled = ::tonic::DartConverter<bool>::FromArguments(args, 0, exception); ASSERT_TRUE(enabled); notify_semantics_enabled_latch_2.Signal(); }; auto result = FlutterEngineUpdateSemanticsEnabled(engine.get(), true); ASSERT_EQ(result, FlutterEngineResult::kSuccess); notify_semantics_enabled_latch_2.Wait(); // 3: Wait for notifyAccessibilityFeatures (reduce_motion == false) notify_features_latch.Wait(); // 4: Wait for notifyAccessibilityFeatures (reduce_motion == true) fml::AutoResetWaitableEvent notify_features_latch_2; notify_accessibility_features_callback = [&](Dart_NativeArguments args) { Dart_Handle exception = nullptr; bool enabled = ::tonic::DartConverter<bool>::FromArguments(args, 0, exception); ASSERT_TRUE(enabled); notify_features_latch_2.Signal(); }; result = FlutterEngineUpdateAccessibilityFeatures( engine.get(), kFlutterAccessibilityFeatureReduceMotion); ASSERT_EQ(result, FlutterEngineResult::kSuccess); notify_features_latch_2.Wait(); // 5: Wait for UpdateSemantics callback on platform (current) thread. signal_native_latch.Wait(); fml::MessageLoop::GetCurrent().RunExpiredTasksNow(); semantics_node_latch.Wait(); semantics_action_latch.Wait(); ASSERT_EQ(4, node_count); ASSERT_EQ(1, node_batch_end_count); ASSERT_EQ(1, action_count); ASSERT_EQ(1, action_batch_end_count); // 6: Dispatch a tap to semantics node 42. Wait for NotifySemanticsAction. fml::AutoResetWaitableEvent notify_semantics_action_latch; notify_semantics_action_callback = [&](Dart_NativeArguments args) { Dart_Handle exception = nullptr; int64_t node_id = ::tonic::DartConverter<int64_t>::FromArguments(args, 0, exception); ASSERT_EQ(42, node_id); int64_t action_id = ::tonic::DartConverter<int64_t>::FromArguments(args, 1, exception); ASSERT_EQ(static_cast<int32_t>(flutter::SemanticsAction::kTap), action_id); std::vector<int64_t> semantic_args = ::tonic::DartConverter<std::vector<int64_t>>::FromArguments(args, 2, exception); ASSERT_THAT(semantic_args, ElementsAre(2, 1)); notify_semantics_action_latch.Signal(); }; std::vector<uint8_t> bytes({2, 1}); result = FlutterEngineDispatchSemanticsAction( engine.get(), 42, kFlutterSemanticsActionTap, &bytes[0], bytes.size()); ASSERT_EQ(result, FlutterEngineResult::kSuccess); notify_semantics_action_latch.Wait(); // 7: Disable semantics. Wait for NotifySemanticsEnabled(false). fml::AutoResetWaitableEvent notify_semantics_enabled_latch_3; notify_semantics_enabled_callback = [&](Dart_NativeArguments args) { Dart_Handle exception = nullptr; bool enabled = ::tonic::DartConverter<bool>::FromArguments(args, 0, exception); ASSERT_FALSE(enabled); notify_semantics_enabled_latch_3.Signal(); }; result = FlutterEngineUpdateSemanticsEnabled(engine.get(), false); ASSERT_EQ(result, FlutterEngineResult::kSuccess); notify_semantics_enabled_latch_3.Wait(); } } // namespace testing } // namespace flutter // NOLINTEND(clang-analyzer-core.StackAddressEscape)
engine/shell/platform/embedder/tests/embedder_a11y_unittests.cc/0
{ "file_path": "engine/shell/platform/embedder/tests/embedder_a11y_unittests.cc", "repo_id": "engine", "token_count": 12073 }
379
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #define FML_USED_ON_EMBEDDER #include <string> #include <utility> #include <vector> #include "embedder.h" #include "embedder_engine.h" #include "flutter/common/constants.h" #include "flutter/flow/raster_cache.h" #include "flutter/fml/file.h" #include "flutter/fml/make_copyable.h" #include "flutter/fml/mapping.h" #include "flutter/fml/message_loop.h" #include "flutter/fml/paths.h" #include "flutter/fml/synchronization/count_down_latch.h" #include "flutter/fml/synchronization/waitable_event.h" #include "flutter/fml/task_runner.h" #include "flutter/fml/thread.h" #include "flutter/fml/time/time_delta.h" #include "flutter/fml/time/time_point.h" #include "flutter/runtime/dart_vm.h" #include "flutter/shell/platform/embedder/tests/embedder_assertions.h" #include "flutter/shell/platform/embedder/tests/embedder_config_builder.h" #include "flutter/shell/platform/embedder/tests/embedder_test.h" #include "flutter/shell/platform/embedder/tests/embedder_unittests_util.h" #include "flutter/testing/assertions_skia.h" #include "flutter/testing/testing.h" #include "third_party/skia/include/core/SkSurface.h" #include "third_party/tonic/converter/dart_converter.h" #if defined(FML_OS_MACOSX) #include <pthread.h> #endif // CREATE_NATIVE_ENTRY is leaky by design // NOLINTBEGIN(clang-analyzer-core.StackAddressEscape) namespace { static uint64_t NanosFromEpoch(int millis_from_now) { const auto now = fml::TimePoint::Now(); const auto delta = fml::TimeDelta::FromMilliseconds(millis_from_now); return (now + delta).ToEpochDelta().ToNanoseconds(); } } // namespace namespace flutter { namespace testing { using EmbedderTest = testing::EmbedderTest; TEST(EmbedderTestNoFixture, MustNotRunWithInvalidArgs) { EmbedderTestContextSoftware context; EmbedderConfigBuilder builder( context, EmbedderConfigBuilder::InitializationPreference::kNoInitialize); auto engine = builder.LaunchEngine(); ASSERT_FALSE(engine.is_valid()); } TEST_F(EmbedderTest, CanLaunchAndShutdownWithValidProjectArgs) { auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); fml::AutoResetWaitableEvent latch; context.AddIsolateCreateCallback([&latch]() { latch.Signal(); }); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); // Wait for the root isolate to launch. latch.Wait(); engine.reset(); } // TODO(41999): Disabled because flaky. TEST_F(EmbedderTest, DISABLED_CanLaunchAndShutdownMultipleTimes) { EmbedderConfigBuilder builder( GetEmbedderContext(EmbedderTestContextType::kSoftwareContext)); builder.SetSoftwareRendererConfig(); for (size_t i = 0; i < 3; ++i) { auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); FML_LOG(INFO) << "Engine launch count: " << i + 1; } } TEST_F(EmbedderTest, CanInvokeCustomEntrypoint) { auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); static fml::AutoResetWaitableEvent latch; Dart_NativeFunction entrypoint = [](Dart_NativeArguments args) { latch.Signal(); }; context.AddNativeCallback("SayHiFromCustomEntrypoint", entrypoint); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); builder.SetDartEntrypoint("customEntrypoint"); auto engine = builder.LaunchEngine(); latch.Wait(); ASSERT_TRUE(engine.is_valid()); } TEST_F(EmbedderTest, CanInvokeCustomEntrypointMacro) { auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); fml::AutoResetWaitableEvent latch1; fml::AutoResetWaitableEvent latch2; fml::AutoResetWaitableEvent latch3; // Can be defined separately. auto entry1 = [&latch1](Dart_NativeArguments args) { FML_LOG(INFO) << "In Callback 1"; latch1.Signal(); }; auto native_entry1 = CREATE_NATIVE_ENTRY(entry1); context.AddNativeCallback("SayHiFromCustomEntrypoint1", native_entry1); // Can be wrapped in the args. auto entry2 = [&latch2](Dart_NativeArguments args) { FML_LOG(INFO) << "In Callback 2"; latch2.Signal(); }; context.AddNativeCallback("SayHiFromCustomEntrypoint2", CREATE_NATIVE_ENTRY(entry2)); // Everything can be inline. context.AddNativeCallback( "SayHiFromCustomEntrypoint3", CREATE_NATIVE_ENTRY([&latch3](Dart_NativeArguments args) { FML_LOG(INFO) << "In Callback 3"; latch3.Signal(); })); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); builder.SetDartEntrypoint("customEntrypoint1"); auto engine = builder.LaunchEngine(); latch1.Wait(); latch2.Wait(); latch3.Wait(); ASSERT_TRUE(engine.is_valid()); } TEST_F(EmbedderTest, CanTerminateCleanly) { auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); builder.SetDartEntrypoint("terminateExitCodeHandler"); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); } TEST_F(EmbedderTest, ExecutableNameNotNull) { auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); // Supply a callback to Dart for the test fixture to pass Platform.executable // back to us. fml::AutoResetWaitableEvent latch; context.AddNativeCallback( "NotifyStringValue", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { const auto dart_string = tonic::DartConverter<std::string>::FromDart( Dart_GetNativeArgument(args, 0)); EXPECT_EQ("/path/to/binary", dart_string); latch.Signal(); })); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); builder.SetDartEntrypoint("executableNameNotNull"); builder.SetExecutableName("/path/to/binary"); auto engine = builder.LaunchEngine(); latch.Wait(); } TEST_F(EmbedderTest, ImplicitViewNotNull) { // TODO(loicsharma): Update this test when embedders can opt-out // of the implicit view. // See: https://github.com/flutter/flutter/issues/120306 auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); bool implicitViewNotNull = false; fml::AutoResetWaitableEvent latch; context.AddNativeCallback( "NotifyBoolValue", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { implicitViewNotNull = tonic::DartConverter<bool>::FromDart( Dart_GetNativeArgument(args, 0)); latch.Signal(); })); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); builder.SetDartEntrypoint("implicitViewNotNull"); auto engine = builder.LaunchEngine(); latch.Wait(); EXPECT_TRUE(implicitViewNotNull); } std::atomic_size_t EmbedderTestTaskRunner::sEmbedderTaskRunnerIdentifiers = {}; TEST_F(EmbedderTest, CanSpecifyCustomPlatformTaskRunner) { auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); fml::AutoResetWaitableEvent latch; // Run the test on its own thread with a message loop so that it can safely // pump its event loop while we wait for all the conditions to be checked. auto platform_task_runner = CreateNewThread("test_platform_thread"); static std::mutex engine_mutex; static bool signaled_once = false; UniqueEngine engine; EmbedderTestTaskRunner test_task_runner( platform_task_runner, [&](FlutterTask task) { std::scoped_lock lock(engine_mutex); if (!engine.is_valid()) { return; } // There may be multiple tasks posted but we only need to check // assertions once. if (signaled_once) { FlutterEngineRunTask(engine.get(), &task); return; } signaled_once = true; ASSERT_TRUE(engine.is_valid()); ASSERT_EQ(FlutterEngineRunTask(engine.get(), &task), kSuccess); latch.Signal(); }); platform_task_runner->PostTask([&]() { EmbedderConfigBuilder builder(context); const auto task_runner_description = test_task_runner.GetFlutterTaskRunnerDescription(); builder.SetSoftwareRendererConfig(); builder.SetPlatformTaskRunner(&task_runner_description); builder.SetDartEntrypoint("invokePlatformTaskRunner"); std::scoped_lock lock(engine_mutex); engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); }); // Signaled when all the assertions are checked. latch.Wait(); ASSERT_TRUE(engine.is_valid()); // Since the engine was started on its own thread, it must be killed there as // well. fml::AutoResetWaitableEvent kill_latch; platform_task_runner->PostTask(fml::MakeCopyable([&]() mutable { std::scoped_lock lock(engine_mutex); engine.reset(); // There may still be pending tasks on the platform thread that were queued // by the test_task_runner. Signal the latch after these tasks have been // consumed. platform_task_runner->PostTask([&kill_latch] { kill_latch.Signal(); }); })); kill_latch.Wait(); ASSERT_TRUE(signaled_once); signaled_once = false; } TEST(EmbedderTestNoFixture, CanGetCurrentTimeInNanoseconds) { auto point1 = fml::TimePoint::FromEpochDelta( fml::TimeDelta::FromNanoseconds(FlutterEngineGetCurrentTime())); auto point2 = fml::TimePoint::Now(); ASSERT_LT((point2 - point1), fml::TimeDelta::FromMilliseconds(1)); } TEST_F(EmbedderTest, CanReloadSystemFonts) { auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); auto result = FlutterEngineReloadSystemFonts(engine.get()); ASSERT_EQ(result, kSuccess); } TEST_F(EmbedderTest, IsolateServiceIdSent) { auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); fml::AutoResetWaitableEvent latch; fml::Thread thread; UniqueEngine engine; std::string isolate_message; thread.GetTaskRunner()->PostTask([&]() { EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); builder.SetDartEntrypoint("main"); builder.SetPlatformMessageCallback( [&](const FlutterPlatformMessage* message) { if (strcmp(message->channel, "flutter/isolate") == 0) { isolate_message = {reinterpret_cast<const char*>(message->message), message->message_size}; latch.Signal(); } }); engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); }); // Wait for the isolate ID message and check its format. latch.Wait(); ASSERT_EQ(isolate_message.find("isolates/"), 0ul); // Since the engine was started on its own thread, it must be killed there as // well. fml::AutoResetWaitableEvent kill_latch; thread.GetTaskRunner()->PostTask( fml::MakeCopyable([&engine, &kill_latch]() mutable { engine.reset(); kill_latch.Signal(); })); kill_latch.Wait(); } //------------------------------------------------------------------------------ /// Creates a platform message response callbacks, does NOT send them, and /// immediately collects the same. /// TEST_F(EmbedderTest, CanCreateAndCollectCallbacks) { auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); builder.SetDartEntrypoint("platform_messages_response"); context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY([](Dart_NativeArguments args) {})); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); FlutterPlatformMessageResponseHandle* response_handle = nullptr; auto callback = [](const uint8_t* data, size_t size, void* user_data) -> void {}; auto result = FlutterPlatformMessageCreateResponseHandle( engine.get(), callback, nullptr, &response_handle); ASSERT_EQ(result, kSuccess); ASSERT_NE(response_handle, nullptr); result = FlutterPlatformMessageReleaseResponseHandle(engine.get(), response_handle); ASSERT_EQ(result, kSuccess); } //------------------------------------------------------------------------------ /// Sends platform messages to Dart code than simply echoes the contents of the /// message back to the embedder. The embedder registers a native callback to /// intercept that message. /// TEST_F(EmbedderTest, PlatformMessagesCanReceiveResponse) { struct Captures { fml::AutoResetWaitableEvent latch; std::thread::id thread_id; }; Captures captures; CreateNewThread()->PostTask([&]() { captures.thread_id = std::this_thread::get_id(); auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); builder.SetDartEntrypoint("platform_messages_response"); fml::AutoResetWaitableEvent ready; context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY( [&ready](Dart_NativeArguments args) { ready.Signal(); })); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); static std::string kMessageData = "Hello from embedder."; FlutterPlatformMessageResponseHandle* response_handle = nullptr; auto callback = [](const uint8_t* data, size_t size, void* user_data) -> void { ASSERT_EQ(size, kMessageData.size()); ASSERT_EQ(strncmp(reinterpret_cast<const char*>(kMessageData.data()), reinterpret_cast<const char*>(data), size), 0); auto captures = reinterpret_cast<Captures*>(user_data); ASSERT_EQ(captures->thread_id, std::this_thread::get_id()); captures->latch.Signal(); }; auto result = FlutterPlatformMessageCreateResponseHandle( engine.get(), callback, &captures, &response_handle); ASSERT_EQ(result, kSuccess); FlutterPlatformMessage message = {}; message.struct_size = sizeof(FlutterPlatformMessage); message.channel = "test_channel"; message.message = reinterpret_cast<const uint8_t*>(kMessageData.data()); message.message_size = kMessageData.size(); message.response_handle = response_handle; ready.Wait(); result = FlutterEngineSendPlatformMessage(engine.get(), &message); ASSERT_EQ(result, kSuccess); result = FlutterPlatformMessageReleaseResponseHandle(engine.get(), response_handle); ASSERT_EQ(result, kSuccess); }); captures.latch.Wait(); } //------------------------------------------------------------------------------ /// Tests that a platform message can be sent with no response handle. Instead /// of the platform message integrity checked via a response handle, a native /// callback with the response is invoked to assert integrity. /// TEST_F(EmbedderTest, PlatformMessagesCanBeSentWithoutResponseHandles) { auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); builder.SetDartEntrypoint("platform_messages_no_response"); const std::string message_data = "Hello but don't call me back."; fml::AutoResetWaitableEvent ready, message; context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY( [&ready](Dart_NativeArguments args) { ready.Signal(); })); context.AddNativeCallback( "SignalNativeMessage", CREATE_NATIVE_ENTRY( ([&message, &message_data](Dart_NativeArguments args) { auto received_message = tonic::DartConverter<std::string>::FromDart( Dart_GetNativeArgument(args, 0)); ASSERT_EQ(received_message, message_data); message.Signal(); }))); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); ready.Wait(); FlutterPlatformMessage platform_message = {}; platform_message.struct_size = sizeof(FlutterPlatformMessage); platform_message.channel = "test_channel"; platform_message.message = reinterpret_cast<const uint8_t*>(message_data.data()); platform_message.message_size = message_data.size(); platform_message.response_handle = nullptr; // No response needed. auto result = FlutterEngineSendPlatformMessage(engine.get(), &platform_message); ASSERT_EQ(result, kSuccess); message.Wait(); } //------------------------------------------------------------------------------ /// Tests that a null platform message can be sent. /// TEST_F(EmbedderTest, NullPlatformMessagesCanBeSent) { auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); builder.SetDartEntrypoint("null_platform_messages"); fml::AutoResetWaitableEvent ready, message; context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY( [&ready](Dart_NativeArguments args) { ready.Signal(); })); context.AddNativeCallback( "SignalNativeMessage", CREATE_NATIVE_ENTRY(([&message](Dart_NativeArguments args) { auto received_message = tonic::DartConverter<std::string>::FromDart( Dart_GetNativeArgument(args, 0)); ASSERT_EQ("true", received_message); message.Signal(); }))); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); ready.Wait(); FlutterPlatformMessage platform_message = {}; platform_message.struct_size = sizeof(FlutterPlatformMessage); platform_message.channel = "test_channel"; platform_message.message = nullptr; platform_message.message_size = 0; platform_message.response_handle = nullptr; // No response needed. auto result = FlutterEngineSendPlatformMessage(engine.get(), &platform_message); ASSERT_EQ(result, kSuccess); message.Wait(); } //------------------------------------------------------------------------------ /// Tests that a null platform message cannot be send if the message_size /// isn't equals to 0. /// TEST_F(EmbedderTest, InvalidPlatformMessages) { auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); FlutterPlatformMessage platform_message = {}; platform_message.struct_size = sizeof(FlutterPlatformMessage); platform_message.channel = "test_channel"; platform_message.message = nullptr; platform_message.message_size = 1; platform_message.response_handle = nullptr; // No response needed. auto result = FlutterEngineSendPlatformMessage(engine.get(), &platform_message); ASSERT_EQ(result, kInvalidArguments); } //------------------------------------------------------------------------------ /// Tests that setting a custom log callback works as expected and defaults to /// using tag "flutter". TEST_F(EmbedderTest, CanSetCustomLogMessageCallback) { fml::AutoResetWaitableEvent callback_latch; auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); EmbedderConfigBuilder builder(context); builder.SetDartEntrypoint("custom_logger"); builder.SetSoftwareRendererConfig(); context.SetLogMessageCallback( [&callback_latch](const char* tag, const char* message) { EXPECT_EQ(std::string(tag), "flutter"); EXPECT_EQ(std::string(message), "hello world"); callback_latch.Signal(); }); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); callback_latch.Wait(); } //------------------------------------------------------------------------------ /// Tests that setting a custom log tag works. TEST_F(EmbedderTest, CanSetCustomLogTag) { fml::AutoResetWaitableEvent callback_latch; auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); EmbedderConfigBuilder builder(context); builder.SetDartEntrypoint("custom_logger"); builder.SetSoftwareRendererConfig(); builder.SetLogTag("butterfly"); context.SetLogMessageCallback( [&callback_latch](const char* tag, const char* message) { EXPECT_EQ(std::string(tag), "butterfly"); EXPECT_EQ(std::string(message), "hello world"); callback_latch.Signal(); }); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); callback_latch.Wait(); } //------------------------------------------------------------------------------ /// Asserts behavior of FlutterProjectArgs::shutdown_dart_vm_when_done (which is /// set to true by default in these unit-tests). /// TEST_F(EmbedderTest, VMShutsDownWhenNoEnginesInProcess) { auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); const auto launch_count = DartVM::GetVMLaunchCount(); { auto engine = builder.LaunchEngine(); ASSERT_EQ(launch_count + 1u, DartVM::GetVMLaunchCount()); } { auto engine = builder.LaunchEngine(); ASSERT_EQ(launch_count + 2u, DartVM::GetVMLaunchCount()); } } //------------------------------------------------------------------------------ /// TEST_F(EmbedderTest, DartEntrypointArgs) { auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); builder.AddDartEntrypointArgument("foo"); builder.AddDartEntrypointArgument("bar"); builder.SetDartEntrypoint("dart_entrypoint_args"); fml::AutoResetWaitableEvent callback_latch; std::vector<std::string> callback_args; auto nativeArgumentsCallback = [&callback_args, &callback_latch](Dart_NativeArguments args) { Dart_Handle exception = nullptr; callback_args = tonic::DartConverter<std::vector<std::string>>::FromArguments( args, 0, exception); callback_latch.Signal(); }; context.AddNativeCallback("NativeArgumentsCallback", CREATE_NATIVE_ENTRY(nativeArgumentsCallback)); auto engine = builder.LaunchEngine(); callback_latch.Wait(); ASSERT_EQ(callback_args[0], "foo"); ASSERT_EQ(callback_args[1], "bar"); } //------------------------------------------------------------------------------ /// These snapshots may be materialized from symbols and the size field may not /// be relevant. Since this information is redundant, engine launch should not /// be gated on a non-zero buffer size. /// TEST_F(EmbedderTest, VMAndIsolateSnapshotSizesAreRedundantInAOTMode) { if (!DartVM::IsRunningPrecompiledCode()) { GTEST_SKIP(); return; } auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); // The fixture sets this up correctly. Intentionally mess up the args. builder.GetProjectArgs().vm_snapshot_data_size = 0; builder.GetProjectArgs().vm_snapshot_instructions_size = 0; builder.GetProjectArgs().isolate_snapshot_data_size = 0; builder.GetProjectArgs().isolate_snapshot_instructions_size = 0; auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); } TEST_F(EmbedderTest, CanRenderImplicitView) { auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(SkISize::Make(800, 600)); builder.SetCompositor(); builder.SetDartEntrypoint("render_implicit_view"); builder.SetRenderTargetType( EmbedderTestBackingStoreProducer::RenderTargetType::kSoftwareBuffer); fml::AutoResetWaitableEvent latch; context.GetCompositor().SetNextPresentCallback( [&](FlutterViewId view_id, const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(view_id, kFlutterImplicitViewId); latch.Signal(); }); auto engine = builder.LaunchEngine(); FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 300; event.height = 200; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); latch.Wait(); } TEST_F(EmbedderTest, CanRenderImplicitViewUsingPresentLayersCallback) { auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(SkISize::Make(800, 600)); builder.SetCompositor(/* avoid_backing_store_cache = */ false, /* use_present_layers_callback = */ true); builder.SetDartEntrypoint("render_implicit_view"); builder.SetRenderTargetType( EmbedderTestBackingStoreProducer::RenderTargetType::kSoftwareBuffer); fml::AutoResetWaitableEvent latch; context.GetCompositor().SetNextPresentCallback( [&](FlutterViewId view_id, const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(view_id, kFlutterImplicitViewId); latch.Signal(); }); auto engine = builder.LaunchEngine(); FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 300; event.height = 200; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); latch.Wait(); } //------------------------------------------------------------------------------ /// Test the layer structure and pixels rendered when using a custom software /// compositor. /// // TODO(143940): Convert this test to use SkiaGold. #if FML_OS_MACOSX && FML_ARCH_CPU_ARM64 TEST_F(EmbedderTest, DISABLED_CompositorMustBeAbleToRenderKnownSceneWithSoftwareCompositor) { #else TEST_F(EmbedderTest, CompositorMustBeAbleToRenderKnownSceneWithSoftwareCompositor) { #endif // FML_OS_MACOSX && FML_ARCH_CPU_ARM64 auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(SkISize::Make(800, 600)); builder.SetCompositor(); builder.SetDartEntrypoint("can_composite_platform_views_with_known_scene"); builder.SetRenderTargetType( EmbedderTestBackingStoreProducer::RenderTargetType::kSoftwareBuffer); fml::CountDownLatch latch(5); auto scene_image = context.GetNextSceneImage(); context.GetCompositor().SetNextPresentCallback( [&](FlutterViewId view_id, const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 5u); // Layer Root { FlutterBackingStore backing_store = *layers[0]->backing_store; backing_store.type = kFlutterBackingStoreTypeSoftware; backing_store.did_update = true; backing_store.software.height = 600; FlutterRect paint_region_rects[] = { FlutterRectMakeLTRB(0, 0, 800, 600), }; FlutterRegion paint_region = { .struct_size = sizeof(FlutterRegion), .rects_count = 1, .rects = paint_region_rects, }; FlutterBackingStorePresentInfo present_info = { .struct_size = sizeof(FlutterBackingStorePresentInfo), .paint_region = &paint_region, }; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); layer.backing_store_present_info = &present_info; ASSERT_EQ(*layers[0], layer); } // Layer 1 { FlutterPlatformView platform_view = *layers[1]->platform_view; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 1; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; layer.size = FlutterSizeMake(50.0, 150.0); layer.offset = FlutterPointMake(20.0, 20.0); ASSERT_EQ(*layers[1], layer); } // Layer 2 { FlutterBackingStore backing_store = *layers[2]->backing_store; backing_store.type = kFlutterBackingStoreTypeSoftware; backing_store.did_update = true; backing_store.software.height = 600; FlutterRect paint_region_rects[] = { FlutterRectMakeLTRB(30, 30, 80, 180), }; FlutterRegion paint_region = { .struct_size = sizeof(FlutterRegion), .rects_count = 1, .rects = paint_region_rects, }; FlutterBackingStorePresentInfo present_info = { .struct_size = sizeof(FlutterBackingStorePresentInfo), .paint_region = &paint_region, }; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); layer.backing_store_present_info = &present_info; ASSERT_EQ(*layers[2], layer); } // Layer 3 { FlutterPlatformView platform_view = *layers[3]->platform_view; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 2; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; layer.size = FlutterSizeMake(50.0, 150.0); layer.offset = FlutterPointMake(40.0, 40.0); ASSERT_EQ(*layers[3], layer); } // Layer 4 { FlutterBackingStore backing_store = *layers[4]->backing_store; backing_store.type = kFlutterBackingStoreTypeSoftware; backing_store.did_update = true; backing_store.software.height = 600; FlutterRect paint_region_rects[] = { FlutterRectMakeLTRB(50, 50, 100, 200), }; FlutterRegion paint_region = { .struct_size = sizeof(FlutterRegion), .rects_count = 1, .rects = paint_region_rects, }; FlutterBackingStorePresentInfo present_info = { .struct_size = sizeof(FlutterBackingStorePresentInfo), .paint_region = &paint_region, }; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); layer.backing_store_present_info = &present_info; ASSERT_EQ(*layers[4], layer); } latch.CountDown(); }); context.GetCompositor().SetPlatformViewRendererCallback( [&](const FlutterLayer& layer, GrDirectContext* /* don't use because software compositor */) -> sk_sp<SkImage> { auto surface = CreateRenderSurface( layer, nullptr /* null because software compositor */); auto canvas = surface->getCanvas(); FML_CHECK(canvas != nullptr); switch (layer.platform_view->identifier) { case 1: { SkPaint paint; // See dart test for total order. paint.setColor(SK_ColorGREEN); paint.setAlpha(127); const auto& rect = SkRect::MakeWH(layer.size.width, layer.size.height); canvas->drawRect(rect, paint); latch.CountDown(); } break; case 2: { SkPaint paint; // See dart test for total order. paint.setColor(SK_ColorMAGENTA); paint.setAlpha(127); const auto& rect = SkRect::MakeWH(layer.size.width, layer.size.height); canvas->drawRect(rect, paint); latch.CountDown(); } break; default: // Asked to render an unknown platform view. FML_CHECK(false) << "Test was asked to composite an unknown platform view."; } return surface->makeImageSnapshot(); }); context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY( [&latch](Dart_NativeArguments args) { latch.CountDown(); })); auto engine = builder.LaunchEngine(); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; event.physical_view_inset_top = 0.0; event.physical_view_inset_right = 0.0; event.physical_view_inset_bottom = 0.0; event.physical_view_inset_left = 0.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); latch.Wait(); ASSERT_TRUE(ImageMatchesFixture("compositor_software.png", scene_image)); // There should no present calls on the root surface. ASSERT_EQ(context.GetSurfacePresentCount(), 0u); } //------------------------------------------------------------------------------ /// Test the layer structure and pixels rendered when using a custom software /// compositor, with a transparent overlay /// TEST_F(EmbedderTest, NoLayerCreatedForTransparentOverlayOnTopOfPlatformLayer) { auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(SkISize::Make(800, 600)); builder.SetCompositor(); builder.SetDartEntrypoint("can_composite_platform_views_transparent_overlay"); builder.SetRenderTargetType( EmbedderTestBackingStoreProducer::RenderTargetType::kSoftwareBuffer); fml::CountDownLatch latch(4); auto scene_image = context.GetNextSceneImage(); context.GetCompositor().SetNextPresentCallback( [&](FlutterViewId view_id, const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 2u); // Layer Root { FlutterBackingStore backing_store = *layers[0]->backing_store; backing_store.type = kFlutterBackingStoreTypeSoftware; backing_store.did_update = true; backing_store.software.height = 600; FlutterRect paint_region_rects[] = { FlutterRectMakeLTRB(0, 0, 800, 600), }; FlutterRegion paint_region = { .struct_size = sizeof(FlutterRegion), .rects_count = 1, .rects = paint_region_rects, }; FlutterBackingStorePresentInfo present_info = { .struct_size = sizeof(FlutterBackingStorePresentInfo), .paint_region = &paint_region, }; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); layer.backing_store_present_info = &present_info; ASSERT_EQ(*layers[0], layer); } // Layer 1 { FlutterPlatformView platform_view = *layers[1]->platform_view; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 1; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; layer.size = FlutterSizeMake(50.0, 150.0); layer.offset = FlutterPointMake(20.0, 20.0); ASSERT_EQ(*layers[1], layer); } latch.CountDown(); }); context.GetCompositor().SetPlatformViewRendererCallback( [&](const FlutterLayer& layer, GrDirectContext* /* don't use because software compositor */) -> sk_sp<SkImage> { auto surface = CreateRenderSurface( layer, nullptr /* null because software compositor */); auto canvas = surface->getCanvas(); FML_CHECK(canvas != nullptr); switch (layer.platform_view->identifier) { case 1: { SkPaint paint; // See dart test for total order. paint.setColor(SK_ColorGREEN); paint.setAlpha(127); const auto& rect = SkRect::MakeWH(layer.size.width, layer.size.height); canvas->drawRect(rect, paint); latch.CountDown(); } break; default: // Asked to render an unknown platform view. FML_CHECK(false) << "Test was asked to composite an unknown platform view."; } return surface->makeImageSnapshot(); }); context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY( [&latch](Dart_NativeArguments args) { latch.CountDown(); })); auto engine = builder.LaunchEngine(); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; event.physical_view_inset_top = 0.0; event.physical_view_inset_right = 0.0; event.physical_view_inset_bottom = 0.0; event.physical_view_inset_left = 0.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); latch.Wait(); // TODO(https://github.com/flutter/flutter/issues/53784): enable this on all // platforms. #if !defined(FML_OS_LINUX) GTEST_SKIP() << "Skipping golden tests on non-Linux OSes"; #endif // FML_OS_LINUX ASSERT_TRUE(ImageMatchesFixture( "compositor_platform_layer_with_no_overlay.png", scene_image)); // There should no present calls on the root surface. ASSERT_EQ(context.GetSurfacePresentCount(), 0u); } //------------------------------------------------------------------------------ /// Test the layer structure and pixels rendered when using a custom software /// compositor, with a no overlay /// TEST_F(EmbedderTest, NoLayerCreatedForNoOverlayOnTopOfPlatformLayer) { auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(SkISize::Make(800, 600)); builder.SetCompositor(); builder.SetDartEntrypoint("can_composite_platform_views_no_overlay"); builder.SetRenderTargetType( EmbedderTestBackingStoreProducer::RenderTargetType::kSoftwareBuffer); fml::CountDownLatch latch(4); auto scene_image = context.GetNextSceneImage(); context.GetCompositor().SetNextPresentCallback( [&](FlutterViewId view_id, const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 2u); // Layer Root { FlutterBackingStore backing_store = *layers[0]->backing_store; backing_store.type = kFlutterBackingStoreTypeSoftware; backing_store.did_update = true; backing_store.software.height = 600; FlutterRect paint_region_rects[] = { FlutterRectMakeLTRB(0, 0, 800, 600), }; FlutterRegion paint_region = { .struct_size = sizeof(FlutterRegion), .rects_count = 1, .rects = paint_region_rects, }; FlutterBackingStorePresentInfo present_info = { .struct_size = sizeof(FlutterBackingStorePresentInfo), .paint_region = &paint_region, }; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); layer.backing_store_present_info = &present_info; ASSERT_EQ(*layers[0], layer); } // Layer 1 { FlutterPlatformView platform_view = *layers[1]->platform_view; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 1; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; layer.size = FlutterSizeMake(50.0, 150.0); layer.offset = FlutterPointMake(20.0, 20.0); ASSERT_EQ(*layers[1], layer); } latch.CountDown(); }); context.GetCompositor().SetPlatformViewRendererCallback( [&](const FlutterLayer& layer, GrDirectContext* /* don't use because software compositor */) -> sk_sp<SkImage> { auto surface = CreateRenderSurface( layer, nullptr /* null because software compositor */); auto canvas = surface->getCanvas(); FML_CHECK(canvas != nullptr); switch (layer.platform_view->identifier) { case 1: { SkPaint paint; // See dart test for total order. paint.setColor(SK_ColorGREEN); paint.setAlpha(127); const auto& rect = SkRect::MakeWH(layer.size.width, layer.size.height); canvas->drawRect(rect, paint); latch.CountDown(); } break; default: // Asked to render an unknown platform view. FML_CHECK(false) << "Test was asked to composite an unknown platform view."; } return surface->makeImageSnapshot(); }); context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY( [&latch](Dart_NativeArguments args) { latch.CountDown(); })); auto engine = builder.LaunchEngine(); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; event.physical_view_inset_top = 0.0; event.physical_view_inset_right = 0.0; event.physical_view_inset_bottom = 0.0; event.physical_view_inset_left = 0.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); latch.Wait(); // TODO(https://github.com/flutter/flutter/issues/53784): enable this on all // platforms. #if !defined(FML_OS_LINUX) GTEST_SKIP() << "Skipping golden tests on non-Linux OSes"; #endif // FML_OS_LINUX ASSERT_TRUE(ImageMatchesFixture( "compositor_platform_layer_with_no_overlay.png", scene_image)); // There should no present calls on the root surface. ASSERT_EQ(context.GetSurfacePresentCount(), 0u); } //------------------------------------------------------------------------------ /// Test that an engine can be initialized but not run. /// TEST_F(EmbedderTest, CanCreateInitializedEngine) { EmbedderConfigBuilder builder( GetEmbedderContext(EmbedderTestContextType::kSoftwareContext)); builder.SetSoftwareRendererConfig(); auto engine = builder.InitializeEngine(); ASSERT_TRUE(engine.is_valid()); engine.reset(); } //------------------------------------------------------------------------------ /// Test that an initialized engine can be run exactly once. /// TEST_F(EmbedderTest, CanRunInitializedEngine) { EmbedderConfigBuilder builder( GetEmbedderContext(EmbedderTestContextType::kSoftwareContext)); builder.SetSoftwareRendererConfig(); auto engine = builder.InitializeEngine(); ASSERT_TRUE(engine.is_valid()); ASSERT_EQ(FlutterEngineRunInitialized(engine.get()), kSuccess); // Cannot re-run an already running engine. ASSERT_EQ(FlutterEngineRunInitialized(engine.get()), kInvalidArguments); engine.reset(); } //------------------------------------------------------------------------------ /// Test that an engine can be deinitialized. /// TEST_F(EmbedderTest, CanDeinitializeAnEngine) { EmbedderConfigBuilder builder( GetEmbedderContext(EmbedderTestContextType::kSoftwareContext)); builder.SetSoftwareRendererConfig(); auto engine = builder.InitializeEngine(); ASSERT_TRUE(engine.is_valid()); ASSERT_EQ(FlutterEngineRunInitialized(engine.get()), kSuccess); // Cannot re-run an already running engine. ASSERT_EQ(FlutterEngineRunInitialized(engine.get()), kInvalidArguments); ASSERT_EQ(FlutterEngineDeinitialize(engine.get()), kSuccess); // It is ok to deinitialize an engine multiple times. ASSERT_EQ(FlutterEngineDeinitialize(engine.get()), kSuccess); // Sending events to a deinitialized engine fails. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; event.physical_view_inset_top = 0.0; event.physical_view_inset_right = 0.0; event.physical_view_inset_bottom = 0.0; event.physical_view_inset_left = 0.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kInvalidArguments); engine.reset(); } TEST_F(EmbedderTest, CanRemoveView) { // TODO(loicsharma): We can't test this until views can be added! // https://github.com/flutter/flutter/issues/144806 } TEST_F(EmbedderTest, CannotRemoveImplicitView) { auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); FlutterRemoveViewInfo info = {}; info.struct_size = sizeof(FlutterRemoveViewInfo); info.view_id = kFlutterImplicitViewId; info.remove_view_callback = [](const FlutterRemoveViewResult* result) { FAIL(); }; ASSERT_EQ(FlutterEngineRemoveView(engine.get(), &info), kInvalidArguments); } TEST_F(EmbedderTest, CannotRemoveUnknownView) { auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); fml::AutoResetWaitableEvent latch; FlutterRemoveViewInfo info = {}; info.struct_size = sizeof(FlutterRemoveViewInfo); info.view_id = 123; info.user_data = &latch; info.remove_view_callback = [](const FlutterRemoveViewResult* result) { ASSERT_FALSE(result->removed); reinterpret_cast<fml::AutoResetWaitableEvent*>(result->user_data)->Signal(); }; ASSERT_EQ(FlutterEngineRemoveView(engine.get(), &info), kSuccess); latch.Wait(); } TEST_F(EmbedderTest, CanUpdateLocales) { auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); builder.SetDartEntrypoint("can_receive_locale_updates"); fml::AutoResetWaitableEvent latch; context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY( [&latch](Dart_NativeArguments args) { latch.Signal(); })); fml::AutoResetWaitableEvent check_latch; context.AddNativeCallback( "SignalNativeCount", CREATE_NATIVE_ENTRY([&check_latch](Dart_NativeArguments args) { ASSERT_EQ(tonic::DartConverter<int>::FromDart( Dart_GetNativeArgument(args, 0)), 2); check_latch.Signal(); })); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); // Wait for the application to attach the listener. latch.Wait(); FlutterLocale locale1 = {}; locale1.struct_size = sizeof(locale1); locale1.language_code = ""; // invalid locale1.country_code = "US"; locale1.script_code = ""; locale1.variant_code = nullptr; FlutterLocale locale2 = {}; locale2.struct_size = sizeof(locale2); locale2.language_code = "zh"; locale2.country_code = "CN"; locale2.script_code = "Hans"; locale2.variant_code = nullptr; std::vector<const FlutterLocale*> locales; locales.push_back(&locale1); locales.push_back(&locale2); ASSERT_EQ( FlutterEngineUpdateLocales(engine.get(), locales.data(), locales.size()), kInvalidArguments); // Fix the invalid code. locale1.language_code = "en"; ASSERT_EQ( FlutterEngineUpdateLocales(engine.get(), locales.data(), locales.size()), kSuccess); check_latch.Wait(); } TEST_F(EmbedderTest, LocalizationCallbacksCalled) { auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); fml::AutoResetWaitableEvent latch; context.AddIsolateCreateCallback([&latch]() { latch.Signal(); }); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); // Wait for the root isolate to launch. latch.Wait(); flutter::Shell& shell = ToEmbedderEngine(engine.get())->GetShell(); std::vector<std::string> supported_locales; supported_locales.push_back("es"); supported_locales.push_back("MX"); supported_locales.push_back(""); auto result = shell.GetPlatformView()->ComputePlatformResolvedLocales( supported_locales); ASSERT_EQ((*result).size(), supported_locales.size()); // 3 ASSERT_EQ((*result)[0], supported_locales[0]); ASSERT_EQ((*result)[1], supported_locales[1]); ASSERT_EQ((*result)[2], supported_locales[2]); engine.reset(); } TEST_F(EmbedderTest, CanQueryDartAOTMode) { ASSERT_EQ(FlutterEngineRunsAOTCompiledDartCode(), flutter::DartVM::IsRunningPrecompiledCode()); } TEST_F(EmbedderTest, VerifyB143464703WithSoftwareBackend) { auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(SkISize::Make(1024, 600)); builder.SetCompositor(); builder.SetDartEntrypoint("verify_b143464703"); builder.SetRenderTargetType( EmbedderTestBackingStoreProducer::RenderTargetType::kSoftwareBuffer); // setup the screenshot promise. auto rendered_scene = context.GetNextSceneImage(); fml::CountDownLatch latch(1); context.GetCompositor().SetNextPresentCallback( [&](FlutterViewId view_id, const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 2u); // Layer 0 (Root) { FlutterBackingStore backing_store = *layers[0]->backing_store; backing_store.type = kFlutterBackingStoreTypeSoftware; backing_store.did_update = true; FlutterRect paint_region_rects[] = { FlutterRectMakeLTRB(0, 0, 1024, 600), }; FlutterRegion paint_region = { .struct_size = sizeof(FlutterRegion), .rects_count = 1, .rects = paint_region_rects, }; FlutterBackingStorePresentInfo present_info = { .struct_size = sizeof(FlutterBackingStorePresentInfo), .paint_region = &paint_region, }; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(1024.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); layer.backing_store_present_info = &present_info; ASSERT_EQ(*layers[0], layer); } // Layer 1 { FlutterPlatformView platform_view = *layers[1]->platform_view; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 42; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; layer.size = FlutterSizeMake(1024.0, 540.0); layer.offset = FlutterPointMake(135.0, 60.0); ASSERT_EQ(*layers[1], layer); } latch.CountDown(); }); context.GetCompositor().SetPlatformViewRendererCallback( [](const FlutterLayer& layer, GrDirectContext* context) -> sk_sp<SkImage> { auto surface = CreateRenderSurface( layer, nullptr /* null because software compositor */); auto canvas = surface->getCanvas(); FML_CHECK(canvas != nullptr); switch (layer.platform_view->identifier) { case 42: { SkPaint paint; // See dart test for total order. paint.setColor(SK_ColorGREEN); paint.setAlpha(127); const auto& rect = SkRect::MakeWH(layer.size.width, layer.size.height); canvas->drawRect(rect, paint); } break; default: // Asked to render an unknown platform view. FML_CHECK(false) << "Test was asked to composite an unknown platform view."; } return surface->makeImageSnapshot(); }); auto engine = builder.LaunchEngine(); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 1024; event.height = 600; event.pixel_ratio = 1.0; event.physical_view_inset_top = 0.0; event.physical_view_inset_right = 0.0; event.physical_view_inset_bottom = 0.0; event.physical_view_inset_left = 0.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); // wait for scene to be rendered. latch.Wait(); // TODO(https://github.com/flutter/flutter/issues/53784): enable this on all // platforms. #if !defined(FML_OS_LINUX) GTEST_SKIP() << "Skipping golden tests on non-Linux OSes"; #endif // FML_OS_LINUX ASSERT_TRUE( ImageMatchesFixture("verifyb143464703_soft_noxform.png", rendered_scene)); } TEST_F(EmbedderTest, CanSendLowMemoryNotification) { auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); // TODO(chinmaygarde): The shell ought to have a mechanism for notification // dispatch that engine subsystems can register handlers to. This would allow // the raster cache and the secondary context caches to respond to // notifications. Once that is in place, this test can be updated to actually // ensure that the dispatched message is visible to engine subsystems. ASSERT_EQ(FlutterEngineNotifyLowMemoryWarning(engine.get()), kSuccess); } TEST_F(EmbedderTest, CanPostTaskToAllNativeThreads) { UniqueEngine engine; size_t worker_count = 0; fml::AutoResetWaitableEvent sync_latch; // One of the threads that the callback will be posted to is the platform // thread. So we cannot wait for assertions to complete on the platform // thread. Create a new thread to manage the engine instance and wait for // assertions on the test thread. auto platform_task_runner = CreateNewThread("platform_thread"); platform_task_runner->PostTask([&]() { auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); worker_count = ToEmbedderEngine(engine.get()) ->GetShell() .GetDartVM() ->GetConcurrentMessageLoop() ->GetWorkerCount(); sync_latch.Signal(); }); sync_latch.Wait(); const auto engine_threads_count = worker_count + 4u; struct Captures { // Waits the adequate number of callbacks to fire. fml::CountDownLatch latch; // This class will be accessed from multiple threads concurrently to track // thread specific information that is later checked. All updates to fields // in this struct must be made with this mutex acquired. std::mutex captures_mutex; // Ensures that the expect number of distinct threads were serviced. std::set<std::thread::id> thread_ids; size_t platform_threads_count = 0; size_t render_threads_count = 0; size_t ui_threads_count = 0; size_t worker_threads_count = 0; explicit Captures(size_t count) : latch(count) {} }; Captures captures(engine_threads_count); platform_task_runner->PostTask([&]() { ASSERT_EQ(FlutterEnginePostCallbackOnAllNativeThreads( engine.get(), [](FlutterNativeThreadType type, void* baton) { auto captures = reinterpret_cast<Captures*>(baton); { std::scoped_lock lock(captures->captures_mutex); switch (type) { case kFlutterNativeThreadTypeRender: captures->render_threads_count++; break; case kFlutterNativeThreadTypeWorker: captures->worker_threads_count++; break; case kFlutterNativeThreadTypeUI: captures->ui_threads_count++; break; case kFlutterNativeThreadTypePlatform: captures->platform_threads_count++; break; } captures->thread_ids.insert(std::this_thread::get_id()); } captures->latch.CountDown(); }, &captures), kSuccess); }); captures.latch.Wait(); ASSERT_EQ(captures.thread_ids.size(), engine_threads_count); ASSERT_EQ(captures.platform_threads_count, 1u); ASSERT_EQ(captures.render_threads_count, 1u); ASSERT_EQ(captures.ui_threads_count, 1u); ASSERT_EQ(captures.worker_threads_count, worker_count + 1u /* for IO */); platform_task_runner->PostTask([&]() { engine.reset(); sync_latch.Signal(); }); sync_latch.Wait(); // The engine should have already been destroyed on the platform task runner. ASSERT_FALSE(engine.is_valid()); } TEST_F(EmbedderTest, InvalidAOTDataSourcesMustReturnError) { if (!DartVM::IsRunningPrecompiledCode()) { GTEST_SKIP(); return; } FlutterEngineAOTDataSource data_in = {}; FlutterEngineAOTData data_out = nullptr; // Null source specified. ASSERT_EQ(FlutterEngineCreateAOTData(nullptr, &data_out), kInvalidArguments); ASSERT_EQ(data_out, nullptr); // Null data_out specified. ASSERT_EQ(FlutterEngineCreateAOTData(&data_in, nullptr), kInvalidArguments); // Invalid FlutterEngineAOTDataSourceType type specified. data_in.type = static_cast<FlutterEngineAOTDataSourceType>(-1); ASSERT_EQ(FlutterEngineCreateAOTData(&data_in, &data_out), kInvalidArguments); ASSERT_EQ(data_out, nullptr); // Invalid ELF path specified. data_in.type = kFlutterEngineAOTDataSourceTypeElfPath; data_in.elf_path = nullptr; ASSERT_EQ(FlutterEngineCreateAOTData(&data_in, &data_out), kInvalidArguments); ASSERT_EQ(data_in.type, kFlutterEngineAOTDataSourceTypeElfPath); ASSERT_EQ(data_in.elf_path, nullptr); ASSERT_EQ(data_out, nullptr); // Invalid ELF path specified. data_in.elf_path = ""; ASSERT_EQ(FlutterEngineCreateAOTData(&data_in, &data_out), kInvalidArguments); ASSERT_EQ(data_in.type, kFlutterEngineAOTDataSourceTypeElfPath); ASSERT_EQ(data_in.elf_path, ""); ASSERT_EQ(data_out, nullptr); // Could not find VM snapshot data. data_in.elf_path = "/bin/true"; ASSERT_EQ(FlutterEngineCreateAOTData(&data_in, &data_out), kInvalidArguments); ASSERT_EQ(data_in.type, kFlutterEngineAOTDataSourceTypeElfPath); ASSERT_EQ(data_in.elf_path, "/bin/true"); ASSERT_EQ(data_out, nullptr); } TEST_F(EmbedderTest, MustNotRunWithMultipleAOTSources) { if (!DartVM::IsRunningPrecompiledCode()) { GTEST_SKIP(); return; } auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); EmbedderConfigBuilder builder( context, EmbedderConfigBuilder::InitializationPreference::kMultiAOTInitialize); builder.SetSoftwareRendererConfig(); auto engine = builder.LaunchEngine(); ASSERT_FALSE(engine.is_valid()); } TEST_F(EmbedderTest, CanCreateAndCollectAValidElfSource) { if (!DartVM::IsRunningPrecompiledCode()) { GTEST_SKIP(); return; } FlutterEngineAOTDataSource data_in = {}; FlutterEngineAOTData data_out = nullptr; // Collecting a null object should be allowed ASSERT_EQ(FlutterEngineCollectAOTData(data_out), kSuccess); const auto elf_path = fml::paths::JoinPaths({GetFixturesPath(), kDefaultAOTAppELFFileName}); data_in.type = kFlutterEngineAOTDataSourceTypeElfPath; data_in.elf_path = elf_path.c_str(); ASSERT_EQ(FlutterEngineCreateAOTData(&data_in, &data_out), kSuccess); ASSERT_EQ(data_in.type, kFlutterEngineAOTDataSourceTypeElfPath); ASSERT_EQ(data_in.elf_path, elf_path.c_str()); ASSERT_NE(data_out, nullptr); ASSERT_EQ(FlutterEngineCollectAOTData(data_out), kSuccess); } TEST_F(EmbedderTest, CanLaunchAndShutdownWithAValidElfSource) { if (!DartVM::IsRunningPrecompiledCode()) { GTEST_SKIP(); return; } auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); fml::AutoResetWaitableEvent latch; context.AddIsolateCreateCallback([&latch]() { latch.Signal(); }); EmbedderConfigBuilder builder( context, EmbedderConfigBuilder::InitializationPreference::kAOTDataInitialize); builder.SetSoftwareRendererConfig(); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); // Wait for the root isolate to launch. latch.Wait(); engine.reset(); } #if defined(__clang_analyzer__) #define TEST_VM_SNAPSHOT_DATA nullptr #define TEST_VM_SNAPSHOT_INSTRUCTIONS nullptr #define TEST_ISOLATE_SNAPSHOT_DATA nullptr #define TEST_ISOLATE_SNAPSHOT_INSTRUCTIONS nullptr #endif //------------------------------------------------------------------------------ /// PopulateJITSnapshotMappingCallbacks should successfully change the callbacks /// of the snapshots in the engine's settings when JIT snapshots are explicitly /// defined. /// TEST_F(EmbedderTest, CanSuccessfullyPopulateSpecificJITSnapshotCallbacks) { // TODO(#107263): Inconsistent snapshot paths in the Linux Fuchsia FEMU test. #if defined(OS_FUCHSIA) GTEST_SKIP() << "Inconsistent paths in Fuchsia."; #else // This test is only relevant in JIT mode. if (DartVM::IsRunningPrecompiledCode()) { GTEST_SKIP(); return; } auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); // Construct the location of valid JIT snapshots. const std::string src_path = GetSourcePath(); const std::string vm_snapshot_data = fml::paths::JoinPaths({src_path, TEST_VM_SNAPSHOT_DATA}); const std::string vm_snapshot_instructions = fml::paths::JoinPaths({src_path, TEST_VM_SNAPSHOT_INSTRUCTIONS}); const std::string isolate_snapshot_data = fml::paths::JoinPaths({src_path, TEST_ISOLATE_SNAPSHOT_DATA}); const std::string isolate_snapshot_instructions = fml::paths::JoinPaths({src_path, TEST_ISOLATE_SNAPSHOT_INSTRUCTIONS}); // Explicitly define the locations of the JIT snapshots builder.GetProjectArgs().vm_snapshot_data = reinterpret_cast<const uint8_t*>(vm_snapshot_data.c_str()); builder.GetProjectArgs().vm_snapshot_instructions = reinterpret_cast<const uint8_t*>(vm_snapshot_instructions.c_str()); builder.GetProjectArgs().isolate_snapshot_data = reinterpret_cast<const uint8_t*>(isolate_snapshot_data.c_str()); builder.GetProjectArgs().isolate_snapshot_instructions = reinterpret_cast<const uint8_t*>(isolate_snapshot_instructions.c_str()); auto engine = builder.LaunchEngine(); flutter::Shell& shell = ToEmbedderEngine(engine.get())->GetShell(); const Settings settings = shell.GetSettings(); ASSERT_NE(settings.vm_snapshot_data(), nullptr); ASSERT_NE(settings.vm_snapshot_instr(), nullptr); ASSERT_NE(settings.isolate_snapshot_data(), nullptr); ASSERT_NE(settings.isolate_snapshot_instr(), nullptr); ASSERT_NE(settings.dart_library_sources_kernel(), nullptr); #endif // OS_FUCHSIA } //------------------------------------------------------------------------------ /// PopulateJITSnapshotMappingCallbacks should still be able to successfully /// change the callbacks of the snapshots in the engine's settings when JIT /// snapshots are explicitly defined. However, if those snapshot locations are /// invalid, the callbacks should return a nullptr. /// TEST_F(EmbedderTest, JITSnapshotCallbacksFailWithInvalidLocation) { // TODO(#107263): Inconsistent snapshot paths in the Linux Fuchsia FEMU test. #if defined(OS_FUCHSIA) GTEST_SKIP() << "Inconsistent paths in Fuchsia."; #else // This test is only relevant in JIT mode. if (DartVM::IsRunningPrecompiledCode()) { GTEST_SKIP(); return; } auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); // Explicitly define the locations of the invalid JIT snapshots builder.GetProjectArgs().vm_snapshot_data = reinterpret_cast<const uint8_t*>("invalid_vm_data"); builder.GetProjectArgs().vm_snapshot_instructions = reinterpret_cast<const uint8_t*>("invalid_vm_instructions"); builder.GetProjectArgs().isolate_snapshot_data = reinterpret_cast<const uint8_t*>("invalid_snapshot_data"); builder.GetProjectArgs().isolate_snapshot_instructions = reinterpret_cast<const uint8_t*>("invalid_snapshot_instructions"); auto engine = builder.LaunchEngine(); flutter::Shell& shell = ToEmbedderEngine(engine.get())->GetShell(); const Settings settings = shell.GetSettings(); ASSERT_EQ(settings.vm_snapshot_data(), nullptr); ASSERT_EQ(settings.vm_snapshot_instr(), nullptr); ASSERT_EQ(settings.isolate_snapshot_data(), nullptr); ASSERT_EQ(settings.isolate_snapshot_instr(), nullptr); #endif // OS_FUCHSIA } //------------------------------------------------------------------------------ /// The embedder must be able to run explicitly specified snapshots in JIT mode /// (i.e. when those are present in known locations). /// TEST_F(EmbedderTest, CanLaunchEngineWithSpecifiedJITSnapshots) { // This test is only relevant in JIT mode. if (DartVM::IsRunningPrecompiledCode()) { GTEST_SKIP(); return; } auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); // Construct the location of valid JIT snapshots. const std::string src_path = GetSourcePath(); const std::string vm_snapshot_data = fml::paths::JoinPaths({src_path, TEST_VM_SNAPSHOT_DATA}); const std::string vm_snapshot_instructions = fml::paths::JoinPaths({src_path, TEST_VM_SNAPSHOT_INSTRUCTIONS}); const std::string isolate_snapshot_data = fml::paths::JoinPaths({src_path, TEST_ISOLATE_SNAPSHOT_DATA}); const std::string isolate_snapshot_instructions = fml::paths::JoinPaths({src_path, TEST_ISOLATE_SNAPSHOT_INSTRUCTIONS}); // Explicitly define the locations of the JIT snapshots builder.GetProjectArgs().vm_snapshot_data = reinterpret_cast<const uint8_t*>(vm_snapshot_data.c_str()); builder.GetProjectArgs().vm_snapshot_instructions = reinterpret_cast<const uint8_t*>(vm_snapshot_instructions.c_str()); builder.GetProjectArgs().isolate_snapshot_data = reinterpret_cast<const uint8_t*>(isolate_snapshot_data.c_str()); builder.GetProjectArgs().isolate_snapshot_instructions = reinterpret_cast<const uint8_t*>(isolate_snapshot_instructions.c_str()); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); } //------------------------------------------------------------------------------ /// The embedder must be able to run in JIT mode when only some snapshots are /// specified. /// TEST_F(EmbedderTest, CanLaunchEngineWithSomeSpecifiedJITSnapshots) { // This test is only relevant in JIT mode. if (DartVM::IsRunningPrecompiledCode()) { GTEST_SKIP(); return; } auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); // Construct the location of valid JIT snapshots. const std::string src_path = GetSourcePath(); const std::string vm_snapshot_data = fml::paths::JoinPaths({src_path, TEST_VM_SNAPSHOT_DATA}); const std::string vm_snapshot_instructions = fml::paths::JoinPaths({src_path, TEST_VM_SNAPSHOT_INSTRUCTIONS}); // Explicitly define the locations of the JIT snapshots builder.GetProjectArgs().vm_snapshot_data = reinterpret_cast<const uint8_t*>(vm_snapshot_data.c_str()); builder.GetProjectArgs().vm_snapshot_instructions = reinterpret_cast<const uint8_t*>(vm_snapshot_instructions.c_str()); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); } //------------------------------------------------------------------------------ /// The embedder must be able to run in JIT mode even when the specfied /// snapshots are invalid. It should be able to resolve them as it would when /// the snapshots are not specified. /// TEST_F(EmbedderTest, CanLaunchEngineWithInvalidJITSnapshots) { // This test is only relevant in JIT mode. if (DartVM::IsRunningPrecompiledCode()) { GTEST_SKIP(); return; } auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); // Explicitly define the locations of the JIT snapshots builder.GetProjectArgs().isolate_snapshot_data = reinterpret_cast<const uint8_t*>("invalid_snapshot_data"); builder.GetProjectArgs().isolate_snapshot_instructions = reinterpret_cast<const uint8_t*>("invalid_snapshot_instructions"); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); ASSERT_EQ(FlutterEngineRunInitialized(engine.get()), kInvalidArguments); } //------------------------------------------------------------------------------ /// The embedder must be able to launch even when the snapshots are not /// explicitly defined in JIT mode. It must be able to resolve those snapshots. /// TEST_F(EmbedderTest, CanLaunchEngineWithUnspecifiedJITSnapshots) { // This test is only relevant in JIT mode. if (DartVM::IsRunningPrecompiledCode()) { GTEST_SKIP(); return; } auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); ASSERT_EQ(builder.GetProjectArgs().vm_snapshot_data, nullptr); ASSERT_EQ(builder.GetProjectArgs().vm_snapshot_instructions, nullptr); ASSERT_EQ(builder.GetProjectArgs().isolate_snapshot_data, nullptr); ASSERT_EQ(builder.GetProjectArgs().isolate_snapshot_instructions, nullptr); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); } TEST_F(EmbedderTest, InvalidFlutterWindowMetricsEvent) { auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 0.0; event.physical_view_inset_top = 0.0; event.physical_view_inset_right = 0.0; event.physical_view_inset_bottom = 0.0; event.physical_view_inset_left = 0.0; // Pixel ratio must be positive. ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kInvalidArguments); event.pixel_ratio = 1.0; event.physical_view_inset_top = -1.0; event.physical_view_inset_right = -1.0; event.physical_view_inset_bottom = -1.0; event.physical_view_inset_left = -1.0; // Physical view insets must be non-negative. ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kInvalidArguments); event.physical_view_inset_top = 700; event.physical_view_inset_right = 900; event.physical_view_inset_bottom = 700; event.physical_view_inset_left = 900; // Top/bottom insets cannot be greater than height. // Left/right insets cannot be greater than width. ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kInvalidArguments); } static void expectSoftwareRenderingOutputMatches( EmbedderTest& test, std::string entrypoint, FlutterSoftwarePixelFormat pixfmt, const std::vector<uint8_t>& bytes) { auto& context = test.GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); EmbedderConfigBuilder builder(context); fml::AutoResetWaitableEvent latch; bool matches = false; builder.SetSoftwareRendererConfig(); builder.SetCompositor(); builder.SetDartEntrypoint(std::move(entrypoint)); builder.SetRenderTargetType( EmbedderTestBackingStoreProducer::RenderTargetType::kSoftwareBuffer2, pixfmt); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); context.GetCompositor().SetNextPresentCallback( [&matches, &bytes, &latch](FlutterViewId view_id, const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers[0]->type, kFlutterLayerContentTypeBackingStore); ASSERT_EQ(layers[0]->backing_store->type, kFlutterBackingStoreTypeSoftware2); matches = SurfacePixelDataMatchesBytes( static_cast<SkSurface*>( layers[0]->backing_store->software2.user_data), bytes); latch.Signal(); }); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 1; event.height = 1; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); latch.Wait(); ASSERT_TRUE(matches); engine.reset(); } template <typename T> static void expectSoftwareRenderingOutputMatches( EmbedderTest& test, std::string entrypoint, FlutterSoftwarePixelFormat pixfmt, T pixelvalue) { uint8_t* bytes = reinterpret_cast<uint8_t*>(&pixelvalue); return expectSoftwareRenderingOutputMatches( test, std::move(entrypoint), pixfmt, std::vector<uint8_t>(bytes, bytes + sizeof(T))); } #define SW_PIXFMT_TEST_F(test_name, dart_entrypoint, pixfmt, matcher) \ TEST_F(EmbedderTest, SoftwareRenderingPixelFormats##test_name) { \ expectSoftwareRenderingOutputMatches(*this, #dart_entrypoint, pixfmt, \ matcher); \ } // Don't test the pixel formats that contain padding (so an X) and the // kFlutterSoftwarePixelFormatNative32 pixel format here, so we don't add any // flakiness. SW_PIXFMT_TEST_F(RedRGBA565xF800, draw_solid_red, kFlutterSoftwarePixelFormatRGB565, (uint16_t)0xF800); SW_PIXFMT_TEST_F(RedRGBA4444xF00F, draw_solid_red, kFlutterSoftwarePixelFormatRGBA4444, (uint16_t)0xF00F); SW_PIXFMT_TEST_F(RedRGBA8888xFFx00x00xFF, draw_solid_red, kFlutterSoftwarePixelFormatRGBA8888, (std::vector<uint8_t>{0xFF, 0x00, 0x00, 0xFF})); SW_PIXFMT_TEST_F(RedBGRA8888x00x00xFFxFF, draw_solid_red, kFlutterSoftwarePixelFormatBGRA8888, (std::vector<uint8_t>{0x00, 0x00, 0xFF, 0xFF})); SW_PIXFMT_TEST_F(RedGray8x36, draw_solid_red, kFlutterSoftwarePixelFormatGray8, (uint8_t)0x36); SW_PIXFMT_TEST_F(GreenRGB565x07E0, draw_solid_green, kFlutterSoftwarePixelFormatRGB565, (uint16_t)0x07E0); SW_PIXFMT_TEST_F(GreenRGBA4444x0F0F, draw_solid_green, kFlutterSoftwarePixelFormatRGBA4444, (uint16_t)0x0F0F); SW_PIXFMT_TEST_F(GreenRGBA8888x00xFFx00xFF, draw_solid_green, kFlutterSoftwarePixelFormatRGBA8888, (std::vector<uint8_t>{0x00, 0xFF, 0x00, 0xFF})); SW_PIXFMT_TEST_F(GreenBGRA8888x00xFFx00xFF, draw_solid_green, kFlutterSoftwarePixelFormatBGRA8888, (std::vector<uint8_t>{0x00, 0xFF, 0x00, 0xFF})); SW_PIXFMT_TEST_F(GreenGray8xB6, draw_solid_green, kFlutterSoftwarePixelFormatGray8, (uint8_t)0xB6); SW_PIXFMT_TEST_F(BlueRGB565x001F, draw_solid_blue, kFlutterSoftwarePixelFormatRGB565, (uint16_t)0x001F); SW_PIXFMT_TEST_F(BlueRGBA4444x00FF, draw_solid_blue, kFlutterSoftwarePixelFormatRGBA4444, (uint16_t)0x00FF); SW_PIXFMT_TEST_F(BlueRGBA8888x00x00xFFxFF, draw_solid_blue, kFlutterSoftwarePixelFormatRGBA8888, (std::vector<uint8_t>{0x00, 0x00, 0xFF, 0xFF})); SW_PIXFMT_TEST_F(BlueBGRA8888xFFx00x00xFF, draw_solid_blue, kFlutterSoftwarePixelFormatBGRA8888, (std::vector<uint8_t>{0xFF, 0x00, 0x00, 0xFF})); SW_PIXFMT_TEST_F(BlueGray8x12, draw_solid_blue, kFlutterSoftwarePixelFormatGray8, (uint8_t)0x12); //------------------------------------------------------------------------------ // Key Data //------------------------------------------------------------------------------ typedef struct { std::shared_ptr<fml::AutoResetWaitableEvent> latch; bool returned; } KeyEventUserData; // Convert `kind` in integer form to its enum form. // // It performs a revesed mapping from `_serializeKeyEventType` // in shell/platform/embedder/fixtures/main.dart. FlutterKeyEventType UnserializeKeyEventType(uint64_t kind) { switch (kind) { case 1: return kFlutterKeyEventTypeUp; case 2: return kFlutterKeyEventTypeDown; case 3: return kFlutterKeyEventTypeRepeat; default: FML_UNREACHABLE(); return kFlutterKeyEventTypeUp; } } // Convert `source` in integer form to its enum form. // // It performs a revesed mapping from `_serializeKeyEventDeviceType` // in shell/platform/embedder/fixtures/main.dart. FlutterKeyEventDeviceType UnserializeKeyEventDeviceType(uint64_t source) { switch (source) { case 1: return kFlutterKeyEventDeviceTypeKeyboard; case 2: return kFlutterKeyEventDeviceTypeDirectionalPad; case 3: return kFlutterKeyEventDeviceTypeGamepad; case 4: return kFlutterKeyEventDeviceTypeJoystick; case 5: return kFlutterKeyEventDeviceTypeHdmi; default: FML_UNREACHABLE(); return kFlutterKeyEventDeviceTypeKeyboard; } } // Checks the equality of two `FlutterKeyEvent` by each of their members except // for `character`. The `character` must be checked separately. void ExpectKeyEventEq(const FlutterKeyEvent& subject, const FlutterKeyEvent& baseline) { EXPECT_EQ(subject.timestamp, baseline.timestamp); EXPECT_EQ(subject.type, baseline.type); EXPECT_EQ(subject.physical, baseline.physical); EXPECT_EQ(subject.logical, baseline.logical); EXPECT_EQ(subject.synthesized, baseline.synthesized); EXPECT_EQ(subject.device_type, baseline.device_type); } TEST_F(EmbedderTest, KeyDataIsCorrectlySerialized) { auto message_latch = std::make_shared<fml::AutoResetWaitableEvent>(); uint64_t echoed_char; FlutterKeyEvent echoed_event; echoed_event.struct_size = sizeof(FlutterKeyEvent); auto native_echo_event = [&](Dart_NativeArguments args) { echoed_event.type = UnserializeKeyEventType(tonic::DartConverter<uint64_t>::FromDart( Dart_GetNativeArgument(args, 0))); echoed_event.timestamp = static_cast<double>(tonic::DartConverter<uint64_t>::FromDart( Dart_GetNativeArgument(args, 1))); echoed_event.physical = tonic::DartConverter<uint64_t>::FromDart( Dart_GetNativeArgument(args, 2)); echoed_event.logical = tonic::DartConverter<uint64_t>::FromDart( Dart_GetNativeArgument(args, 3)); echoed_char = tonic::DartConverter<uint64_t>::FromDart( Dart_GetNativeArgument(args, 4)); echoed_event.synthesized = tonic::DartConverter<bool>::FromDart(Dart_GetNativeArgument(args, 5)); echoed_event.device_type = UnserializeKeyEventDeviceType(tonic::DartConverter<uint64_t>::FromDart( Dart_GetNativeArgument(args, 6))); message_latch->Signal(); }; auto platform_task_runner = CreateNewThread("platform_thread"); UniqueEngine engine; fml::AutoResetWaitableEvent ready; platform_task_runner->PostTask([&]() { auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); builder.SetDartEntrypoint("key_data_echo"); builder.SetPlatformMessageCallback( [&](const FlutterPlatformMessage* message) { FlutterEngineSendPlatformMessageResponse( engine.get(), message->response_handle, nullptr, 0); }); context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY( [&ready](Dart_NativeArguments args) { ready.Signal(); })); context.AddNativeCallback("EchoKeyEvent", CREATE_NATIVE_ENTRY(native_echo_event)); engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); }); ready.Wait(); // A normal down event const FlutterKeyEvent down_event_upper_a{ .struct_size = sizeof(FlutterKeyEvent), .timestamp = 1, .type = kFlutterKeyEventTypeDown, .physical = 0x00070004, .logical = 0x00000000061, .character = "A", .synthesized = false, .device_type = kFlutterKeyEventDeviceTypeKeyboard, }; platform_task_runner->PostTask([&]() { FlutterEngineSendKeyEvent(engine.get(), &down_event_upper_a, nullptr, nullptr); }); message_latch->Wait(); ExpectKeyEventEq(echoed_event, down_event_upper_a); EXPECT_EQ(echoed_char, 0x41llu); // A repeat event with multi-byte character const FlutterKeyEvent repeat_event_wide_char{ .struct_size = sizeof(FlutterKeyEvent), .timestamp = 1000, .type = kFlutterKeyEventTypeRepeat, .physical = 0x00070005, .logical = 0x00000000062, .character = "∆", .synthesized = false, .device_type = kFlutterKeyEventDeviceTypeKeyboard, }; platform_task_runner->PostTask([&]() { FlutterEngineSendKeyEvent(engine.get(), &repeat_event_wide_char, nullptr, nullptr); }); message_latch->Wait(); ExpectKeyEventEq(echoed_event, repeat_event_wide_char); EXPECT_EQ(echoed_char, 0x2206llu); // An up event with no character, synthesized const FlutterKeyEvent up_event{ .struct_size = sizeof(FlutterKeyEvent), .timestamp = 1000000, .type = kFlutterKeyEventTypeUp, .physical = 0x00070006, .logical = 0x00000000063, .character = nullptr, .synthesized = true, .device_type = kFlutterKeyEventDeviceTypeKeyboard, }; platform_task_runner->PostTask([&]() { FlutterEngineSendKeyEvent(engine.get(), &up_event, nullptr, nullptr); }); message_latch->Wait(); ExpectKeyEventEq(echoed_event, up_event); EXPECT_EQ(echoed_char, 0llu); fml::AutoResetWaitableEvent shutdown_latch; platform_task_runner->PostTask([&]() { engine.reset(); shutdown_latch.Signal(); }); shutdown_latch.Wait(); } TEST_F(EmbedderTest, KeyDataAreBuffered) { auto message_latch = std::make_shared<fml::AutoResetWaitableEvent>(); std::vector<FlutterKeyEvent> echoed_events; auto native_echo_event = [&](Dart_NativeArguments args) { echoed_events.push_back(FlutterKeyEvent{ .timestamp = static_cast<double>(tonic::DartConverter<uint64_t>::FromDart( Dart_GetNativeArgument(args, 1))), .type = UnserializeKeyEventType(tonic::DartConverter<uint64_t>::FromDart( Dart_GetNativeArgument(args, 0))), .physical = tonic::DartConverter<uint64_t>::FromDart( Dart_GetNativeArgument(args, 2)), .logical = tonic::DartConverter<uint64_t>::FromDart( Dart_GetNativeArgument(args, 3)), .synthesized = tonic::DartConverter<bool>::FromDart( Dart_GetNativeArgument(args, 5)), .device_type = UnserializeKeyEventDeviceType( tonic::DartConverter<uint64_t>::FromDart( Dart_GetNativeArgument(args, 6))), }); message_latch->Signal(); }; auto platform_task_runner = CreateNewThread("platform_thread"); UniqueEngine engine; fml::AutoResetWaitableEvent ready; platform_task_runner->PostTask([&]() { auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); builder.SetDartEntrypoint("key_data_late_echo"); builder.SetPlatformMessageCallback( [&](const FlutterPlatformMessage* message) { FlutterEngineSendPlatformMessageResponse( engine.get(), message->response_handle, nullptr, 0); }); context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY( [&ready](Dart_NativeArguments args) { ready.Signal(); })); context.AddNativeCallback("EchoKeyEvent", CREATE_NATIVE_ENTRY(native_echo_event)); engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); }); ready.Wait(); FlutterKeyEvent sample_event{ .struct_size = sizeof(FlutterKeyEvent), .type = kFlutterKeyEventTypeDown, .physical = 0x00070004, .logical = 0x00000000061, .character = "A", .synthesized = false, .device_type = kFlutterKeyEventDeviceTypeKeyboard, }; // Send an event. sample_event.timestamp = 1.0l; platform_task_runner->PostTask([&]() { FlutterEngineSendKeyEvent(engine.get(), &sample_event, nullptr, nullptr); message_latch->Signal(); }); message_latch->Wait(); // Should not receive echos because the callback is not set yet. EXPECT_EQ(echoed_events.size(), 0u); // Send an empty message to 'test/starts_echo' to start echoing. FlutterPlatformMessageResponseHandle* response_handle = nullptr; FlutterPlatformMessageCreateResponseHandle( engine.get(), [](const uint8_t* data, size_t size, void* user_data) {}, nullptr, &response_handle); FlutterPlatformMessage message{ .struct_size = sizeof(FlutterPlatformMessage), .channel = "test/starts_echo", .message = nullptr, .message_size = 0, .response_handle = response_handle, }; platform_task_runner->PostTask([&]() { FlutterEngineResult result = FlutterEngineSendPlatformMessage(engine.get(), &message); ASSERT_EQ(result, kSuccess); FlutterPlatformMessageReleaseResponseHandle(engine.get(), response_handle); }); // message_latch->Wait(); message_latch->Wait(); // All previous events should be received now. EXPECT_EQ(echoed_events.size(), 1u); // Send a second event. sample_event.timestamp = 10.0l; platform_task_runner->PostTask([&]() { FlutterEngineSendKeyEvent(engine.get(), &sample_event, nullptr, nullptr); }); message_latch->Wait(); // The event should be echoed, too. EXPECT_EQ(echoed_events.size(), 2u); fml::AutoResetWaitableEvent shutdown_latch; platform_task_runner->PostTask([&]() { engine.reset(); shutdown_latch.Signal(); }); shutdown_latch.Wait(); } TEST_F(EmbedderTest, KeyDataResponseIsCorrectlyInvoked) { UniqueEngine engine; fml::AutoResetWaitableEvent sync_latch; fml::AutoResetWaitableEvent ready; // One of the threads that the key data callback will be posted to is the // platform thread. So we cannot wait for assertions to complete on the // platform thread. Create a new thread to manage the engine instance and wait // for assertions on the test thread. auto platform_task_runner = CreateNewThread("platform_thread"); platform_task_runner->PostTask([&]() { auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); builder.SetDartEntrypoint("key_data_echo"); context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY( [&ready](Dart_NativeArguments args) { ready.Signal(); })); context.AddNativeCallback( "EchoKeyEvent", CREATE_NATIVE_ENTRY([](Dart_NativeArguments args) {})); engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); sync_latch.Signal(); }); sync_latch.Wait(); ready.Wait(); // Dispatch a single event FlutterKeyEvent event{ .struct_size = sizeof(FlutterKeyEvent), .timestamp = 1000, .type = kFlutterKeyEventTypeDown, .physical = 0x00070005, .logical = 0x00000000062, .character = nullptr, .device_type = kFlutterKeyEventDeviceTypeKeyboard, }; KeyEventUserData user_data1{ .latch = std::make_shared<fml::AutoResetWaitableEvent>(), }; // Entrypoint `key_data_echo` returns `event.synthesized` as `handled`. event.synthesized = true; platform_task_runner->PostTask([&]() { // Test when the response callback is empty. // It should not cause a crash. FlutterEngineSendKeyEvent(engine.get(), &event, nullptr, nullptr); // Test when the response callback is non-empty. // It should be invoked (so that the latch can be unlocked.) FlutterEngineSendKeyEvent( engine.get(), &event, [](bool handled, void* untyped_user_data) { KeyEventUserData* user_data = reinterpret_cast<KeyEventUserData*>(untyped_user_data); EXPECT_EQ(handled, true); user_data->latch->Signal(); }, &user_data1); }); user_data1.latch->Wait(); fml::AutoResetWaitableEvent shutdown_latch; platform_task_runner->PostTask([&]() { engine.reset(); shutdown_latch.Signal(); }); shutdown_latch.Wait(); } TEST_F(EmbedderTest, BackToBackKeyEventResponsesCorrectlyInvoked) { UniqueEngine engine; fml::AutoResetWaitableEvent sync_latch; fml::AutoResetWaitableEvent ready; // One of the threads that the callback will be posted to is the platform // thread. So we cannot wait for assertions to complete on the platform // thread. Create a new thread to manage the engine instance and wait for // assertions on the test thread. auto platform_task_runner = CreateNewThread("platform_thread"); platform_task_runner->PostTask([&]() { auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); builder.SetDartEntrypoint("key_data_echo"); context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY( [&ready](Dart_NativeArguments args) { ready.Signal(); })); context.AddNativeCallback( "EchoKeyEvent", CREATE_NATIVE_ENTRY([](Dart_NativeArguments args) {})); engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); sync_latch.Signal(); }); sync_latch.Wait(); ready.Wait(); // Dispatch a single event FlutterKeyEvent event{ .struct_size = sizeof(FlutterKeyEvent), .timestamp = 1000, .type = kFlutterKeyEventTypeDown, .physical = 0x00070005, .logical = 0x00000000062, .character = nullptr, .synthesized = false, .device_type = kFlutterKeyEventDeviceTypeKeyboard, }; // Dispatch two events back to back, using the same callback on different // user_data KeyEventUserData user_data2{ .latch = std::make_shared<fml::AutoResetWaitableEvent>(), .returned = false, }; KeyEventUserData user_data3{ .latch = std::make_shared<fml::AutoResetWaitableEvent>(), .returned = false, }; auto callback23 = [](bool handled, void* untyped_user_data) { KeyEventUserData* user_data = reinterpret_cast<KeyEventUserData*>(untyped_user_data); EXPECT_EQ(handled, false); user_data->returned = true; user_data->latch->Signal(); }; platform_task_runner->PostTask([&]() { FlutterEngineSendKeyEvent(engine.get(), &event, callback23, &user_data2); FlutterEngineSendKeyEvent(engine.get(), &event, callback23, &user_data3); }); user_data2.latch->Wait(); user_data3.latch->Wait(); EXPECT_TRUE(user_data2.returned); EXPECT_TRUE(user_data3.returned); fml::AutoResetWaitableEvent shutdown_latch; platform_task_runner->PostTask([&]() { engine.reset(); shutdown_latch.Signal(); }); shutdown_latch.Wait(); } //------------------------------------------------------------------------------ // Vsync waiter //------------------------------------------------------------------------------ // This test schedules a frame for the future and asserts that vsync waiter // posts the event at the right frame start time (which is in the future). TEST_F(EmbedderTest, VsyncCallbackPostedIntoFuture) { UniqueEngine engine; fml::AutoResetWaitableEvent present_latch; fml::AutoResetWaitableEvent vsync_latch; // One of the threads that the callback (FlutterEngineOnVsync) will be posted // to is the platform thread. So we cannot wait for assertions to complete on // the platform thread. Create a new thread to manage the engine instance and // wait for assertions on the test thread. auto platform_task_runner = CreateNewThread("platform_thread"); platform_task_runner->PostTask([&]() { auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); context.SetVsyncCallback([&](intptr_t baton) { platform_task_runner->PostTask([baton = baton, &engine, &vsync_latch]() { FlutterEngineOnVsync(engine.get(), baton, NanosFromEpoch(16), NanosFromEpoch(32)); vsync_latch.Signal(); }); }); context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { present_latch.Signal(); })); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); builder.SetupVsyncCallback(); builder.SetDartEntrypoint("empty_scene"); engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); }); vsync_latch.Wait(); present_latch.Wait(); fml::AutoResetWaitableEvent shutdown_latch; platform_task_runner->PostTask([&]() { engine.reset(); shutdown_latch.Signal(); }); shutdown_latch.Wait(); } TEST_F(EmbedderTest, CanScheduleFrame) { auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); builder.SetDartEntrypoint("can_schedule_frame"); fml::AutoResetWaitableEvent latch; context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY( [&latch](Dart_NativeArguments args) { latch.Signal(); })); fml::AutoResetWaitableEvent check_latch; context.AddNativeCallback( "SignalNativeCount", CREATE_NATIVE_ENTRY( [&check_latch](Dart_NativeArguments args) { check_latch.Signal(); })); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); // Wait for the application to attach the listener. latch.Wait(); ASSERT_EQ(FlutterEngineScheduleFrame(engine.get()), kSuccess); check_latch.Wait(); } TEST_F(EmbedderTest, CanSetNextFrameCallback) { auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); builder.SetDartEntrypoint("draw_solid_red"); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); // Register the callback that is executed once the next frame is drawn. fml::AutoResetWaitableEvent callback_latch; VoidCallback callback = [](void* user_data) { fml::AutoResetWaitableEvent* callback_latch = static_cast<fml::AutoResetWaitableEvent*>(user_data); callback_latch->Signal(); }; auto result = FlutterEngineSetNextFrameCallback(engine.get(), callback, &callback_latch); ASSERT_EQ(result, kSuccess); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; event.physical_view_inset_top = 0.0; event.physical_view_inset_right = 0.0; event.physical_view_inset_bottom = 0.0; event.physical_view_inset_left = 0.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); callback_latch.Wait(); } #if defined(FML_OS_MACOSX) static void MockThreadConfigSetter(const fml::Thread::ThreadConfig& config) { pthread_t tid = pthread_self(); struct sched_param param; int policy = SCHED_OTHER; switch (config.priority) { case fml::Thread::ThreadPriority::kDisplay: param.sched_priority = 10; break; default: param.sched_priority = 1; } pthread_setschedparam(tid, policy, &param); } TEST_F(EmbedderTest, EmbedderThreadHostUseCustomThreadConfig) { auto thread_host = flutter::EmbedderThreadHost::CreateEmbedderOrEngineManagedThreadHost( nullptr, MockThreadConfigSetter); int ui_policy; struct sched_param ui_param; thread_host->GetTaskRunners().GetUITaskRunner()->PostTask([&] { pthread_t current_thread = pthread_self(); pthread_getschedparam(current_thread, &ui_policy, &ui_param); ASSERT_EQ(ui_param.sched_priority, 10); }); int io_policy; struct sched_param io_param; thread_host->GetTaskRunners().GetIOTaskRunner()->PostTask([&] { pthread_t current_thread = pthread_self(); pthread_getschedparam(current_thread, &io_policy, &io_param); ASSERT_EQ(io_param.sched_priority, 1); }); } #endif /// Send a pointer event to Dart and wait until the Dart code signals /// it received the event. TEST_F(EmbedderTest, CanSendPointer) { auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); builder.SetDartEntrypoint("pointer_data_packet"); fml::AutoResetWaitableEvent ready_latch, count_latch, message_latch; context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY( [&ready_latch](Dart_NativeArguments args) { ready_latch.Signal(); })); context.AddNativeCallback( "SignalNativeCount", CREATE_NATIVE_ENTRY([&count_latch](Dart_NativeArguments args) { int count = tonic::DartConverter<int>::FromDart( Dart_GetNativeArgument(args, 0)); ASSERT_EQ(count, 1); count_latch.Signal(); })); context.AddNativeCallback( "SignalNativeMessage", CREATE_NATIVE_ENTRY([&message_latch](Dart_NativeArguments args) { auto message = tonic::DartConverter<std::string>::FromDart( Dart_GetNativeArgument(args, 0)); ASSERT_EQ("PointerData(viewId: 0, x: 123.0, y: 456.0)", message); message_latch.Signal(); })); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); ready_latch.Wait(); FlutterPointerEvent pointer_event = {}; pointer_event.struct_size = sizeof(FlutterPointerEvent); pointer_event.phase = FlutterPointerPhase::kAdd; pointer_event.x = 123; pointer_event.y = 456; pointer_event.timestamp = static_cast<size_t>(1234567890); pointer_event.view_id = 0; FlutterEngineResult result = FlutterEngineSendPointerEvent(engine.get(), &pointer_event, 1); ASSERT_EQ(result, kSuccess); count_latch.Wait(); message_latch.Wait(); } /// Send a pointer event to Dart and wait until the Dart code echos with the /// view ID. TEST_F(EmbedderTest, CanSendPointerEventWithViewId) { auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); builder.SetDartEntrypoint("pointer_data_packet_view_id"); fml::AutoResetWaitableEvent ready_latch, count_latch, message_latch; context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY( [&ready_latch](Dart_NativeArguments args) { ready_latch.Signal(); })); context.AddNativeCallback( "SignalNativeMessage", CREATE_NATIVE_ENTRY([&message_latch](Dart_NativeArguments args) { auto message = tonic::DartConverter<std::string>::FromDart( Dart_GetNativeArgument(args, 0)); ASSERT_EQ("ViewID: 2", message); message_latch.Signal(); })); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); ready_latch.Wait(); FlutterPointerEvent pointer_event = {}; pointer_event.struct_size = sizeof(FlutterPointerEvent); pointer_event.phase = FlutterPointerPhase::kAdd; pointer_event.x = 123; pointer_event.y = 456; pointer_event.timestamp = static_cast<size_t>(1234567890); pointer_event.view_id = 2; FlutterEngineResult result = FlutterEngineSendPointerEvent(engine.get(), &pointer_event, 1); ASSERT_EQ(result, kSuccess); message_latch.Wait(); } TEST_F(EmbedderTest, WindowMetricsEventDefaultsToImplicitView) { auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); builder.SetDartEntrypoint("window_metrics_event_view_id"); fml::AutoResetWaitableEvent ready_latch, message_latch; context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY( [&ready_latch](Dart_NativeArguments args) { ready_latch.Signal(); })); context.AddNativeCallback( "SignalNativeMessage", CREATE_NATIVE_ENTRY([&message_latch](Dart_NativeArguments args) { auto message = tonic::DartConverter<std::string>::FromDart( Dart_GetNativeArgument(args, 0)); ASSERT_EQ("Changed: [0]", message); message_latch.Signal(); })); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); ready_latch.Wait(); FlutterWindowMetricsEvent event = {}; // Simulate an event that comes from an old version of embedder.h that doesn't // have the view_id field. event.struct_size = offsetof(FlutterWindowMetricsEvent, view_id); event.width = 200; event.height = 300; event.pixel_ratio = 1.5; // Skip assigning event.view_id here to test the default behavior. FlutterEngineResult result = FlutterEngineSendWindowMetricsEvent(engine.get(), &event); ASSERT_EQ(result, kSuccess); message_latch.Wait(); } TEST_F(EmbedderTest, IgnoresWindowMetricsEventForUnknownView) { auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); builder.SetDartEntrypoint("window_metrics_event_view_id"); fml::AutoResetWaitableEvent ready_latch, message_latch; context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY( [&ready_latch](Dart_NativeArguments args) { ready_latch.Signal(); })); context.AddNativeCallback( "SignalNativeMessage", CREATE_NATIVE_ENTRY([&message_latch](Dart_NativeArguments args) { auto message = tonic::DartConverter<std::string>::FromDart( Dart_GetNativeArgument(args, 0)); // Message latch should only be signaled once as the bad // view metric should be dropped by the engine. ASSERT_FALSE(message_latch.IsSignaledForTest()); ASSERT_EQ("Changed: [0]", message); message_latch.Signal(); })); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); ready_latch.Wait(); // Send a window metric for a nonexistent view, which should be dropped by the // engine. FlutterWindowMetricsEvent bad_event = {}; bad_event.struct_size = sizeof(FlutterWindowMetricsEvent); bad_event.width = 200; bad_event.height = 300; bad_event.pixel_ratio = 1.5; bad_event.view_id = 100; FlutterEngineResult result = FlutterEngineSendWindowMetricsEvent(engine.get(), &bad_event); ASSERT_EQ(result, kSuccess); // Send a window metric for a valid view. The engine notifies the Dart app. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(FlutterWindowMetricsEvent); event.width = 200; event.height = 300; event.pixel_ratio = 1.5; event.view_id = 0; result = FlutterEngineSendWindowMetricsEvent(engine.get(), &event); ASSERT_EQ(result, kSuccess); message_latch.Wait(); } TEST_F(EmbedderTest, RegisterChannelListener) { auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); fml::AutoResetWaitableEvent latch; fml::AutoResetWaitableEvent latch2; bool listening = false; context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments) { latch.Signal(); })); context.SetChannelUpdateCallback([&](const FlutterChannelUpdate* update) { EXPECT_STREQ(update->channel, "test/listen"); EXPECT_TRUE(update->listening); listening = true; latch2.Signal(); }); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); builder.SetDartEntrypoint("channel_listener_response"); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); latch.Wait(); // Drain tasks posted to platform thread task runner. fml::MessageLoop::GetCurrent().RunExpiredTasksNow(); latch2.Wait(); ASSERT_TRUE(listening); } } // namespace testing } // namespace flutter // NOLINTEND(clang-analyzer-core.StackAddressEscape)
engine/shell/platform/embedder/tests/embedder_unittests.cc/0
{ "file_path": "engine/shell/platform/embedder/tests/embedder_unittests.cc", "repo_id": "engine", "token_count": 40855 }
380
dart:zircon =========== These are the Dart bindings for the Zircon [kernel interface](https://fuchsia.googlesource.com/zircon/+/HEAD/docs/) This package exposes a `System` object with methods for may Zircon system calls, a `Handle` type representing a Zircon handle and a `HandleWaiter` type representing a wait on a handle. `Handle`s are returned by various methods on `System` and `HandleWaiter`s are returned by `handle.asyncWait(...)`.
engine/shell/platform/fuchsia/dart-pkg/zircon/README.md/0
{ "file_path": "engine/shell/platform/fuchsia/dart-pkg/zircon/README.md", "repo_id": "engine", "token_count": 132 }
381
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_SDK_EXT_HANDLE_WAITER_H_ #define FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_SDK_EXT_HANDLE_WAITER_H_ #include <lib/async/cpp/wait.h> #include <lib/zx/handle.h> #include "flutter/fml/memory/ref_counted.h" #include "third_party/tonic/dart_wrappable.h" namespace tonic { class DartLibraryNatives; } // namespace tonic namespace zircon { namespace dart { class Handle; class HandleWaiter : public fml::RefCountedThreadSafe<HandleWaiter>, public tonic::DartWrappable { DEFINE_WRAPPERTYPEINFO(); FML_FRIEND_REF_COUNTED_THREAD_SAFE(HandleWaiter); FML_FRIEND_MAKE_REF_COUNTED(HandleWaiter); public: static fml::RefPtr<HandleWaiter> Create(Handle* handle, zx_signals_t signals, Dart_Handle callback); void Cancel(); bool is_pending() { return wait_.is_pending(); } static void RegisterNatives(tonic::DartLibraryNatives* natives); private: explicit HandleWaiter(Handle* handle, zx_signals_t signals, Dart_Handle callback); ~HandleWaiter(); void OnWaitComplete(async_dispatcher_t* dispatcher, async::WaitBase* wait, zx_status_t status, const zx_packet_signal_t* signal); void RetainDartWrappableReference() const override { AddRef(); } void ReleaseDartWrappableReference() const override { Release(); } async::WaitMethod<HandleWaiter, &HandleWaiter::OnWaitComplete> wait_; Handle* handle_; tonic::DartPersistentValue callback_; }; } // namespace dart } // namespace zircon #endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_SDK_EXT_HANDLE_WAITER_H_
engine/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/handle_waiter.h/0
{ "file_path": "engine/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/handle_waiter.h", "repo_id": "engine", "token_count": 847 }
382
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "handle.h" #include "flutter/fml/logging.h" #include <iostream> #include <vector> #include <zircon/syscalls.h> static void HandleFree(void* isolate_callback_data, void* peer) { FML_CHECK(peer); zircon_dart_handle_t* handle = reinterpret_cast<zircon_dart_handle_t*>(peer); zircon_dart_handle_free(handle); } static void HandlePairFree(void* isolate_callback_data, void* peer) { FML_CHECK(peer); zircon_dart_handle_pair_t* handle_pair = reinterpret_cast<zircon_dart_handle_pair_t*>(peer); free(handle_pair); } void zircon_dart_handle_free(zircon_dart_handle_t* handle) { FML_CHECK(handle); if (handle->handle != ZX_HANDLE_INVALID) { zircon_dart_handle_close(handle); } free(handle); } int32_t zircon_dart_handle_close(zircon_dart_handle_t* handle) { FML_CHECK(handle->handle != ZX_HANDLE_INVALID); zx_status_t status = zx_handle_close(handle->handle); handle->handle = ZX_HANDLE_INVALID; if (status == ZX_OK) { return 1; } else { return 0; } } int32_t zircon_dart_handle_is_valid(zircon_dart_handle_t* handle) { if (!handle || (handle->handle == ZX_HANDLE_INVALID)) { return 0; } else { return 1; } } int zircon_dart_handle_attach_finalizer(Dart_Handle object, void* pointer, intptr_t external_allocation_size) { Dart_FinalizableHandle weak_handle = Dart_NewFinalizableHandle_DL( object, pointer, external_allocation_size, HandleFree); if (weak_handle == nullptr) { FML_LOG(ERROR) << "Unable to attach finalizer: " << std::hex << pointer; return -1; } return 1; } int zircon_dart_handle_pair_attach_finalizer( Dart_Handle object, void* pointer, intptr_t external_allocation_size) { Dart_FinalizableHandle weak_handle = Dart_NewFinalizableHandle_DL( object, pointer, external_allocation_size, HandlePairFree); if (weak_handle == nullptr) { FML_LOG(ERROR) << "Unable to attach finalizer: " << std::hex << pointer; return -1; } return 1; } // zircon handle list methods. using HandleVector = std::vector<zircon_dart_handle_t*>; using HandleVectorPtr = HandleVector*; zircon_dart_handle_list_t* zircon_dart_handle_list_create() { zircon_dart_handle_list_t* result = static_cast<zircon_dart_handle_list_t*>( malloc(sizeof(zircon_dart_handle_list_t))); result->size = 0; result->data = new HandleVector(); return result; } void zircon_dart_handle_list_append(zircon_dart_handle_list_t* list, zircon_dart_handle_t* handle) { FML_CHECK(list); FML_CHECK(handle); list->size++; auto data = reinterpret_cast<HandleVectorPtr>(list->data); data->push_back(handle); } void zircon_dart_handle_list_free(zircon_dart_handle_list_t* list) { auto data = reinterpret_cast<HandleVectorPtr>(list->data); data->clear(); delete data; free(list); }
engine/shell/platform/fuchsia/dart-pkg/zircon_ffi/handle.cc/0
{ "file_path": "engine/shell/platform/fuchsia/dart-pkg/zircon_ffi/handle.cc", "repo_id": "engine", "token_count": 1276 }
383
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "dart_test_component_controller.h" #include <fcntl.h> #include <fuchsia/test/cpp/fidl.h> #include <lib/async-loop/loop.h> #include <lib/async/cpp/task.h> #include <lib/async/default.h> #include <lib/fdio/directory.h> #include <lib/fdio/fd.h> #include <lib/fdio/namespace.h> #include <lib/fidl/cpp/string.h> #include <lib/fpromise/promise.h> #include <lib/sys/cpp/service_directory.h> #include <lib/zx/clock.h> #include <lib/zx/thread.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <zircon/status.h> #include <regex> #include <utility> #include "flutter/fml/logging.h" #include "runtime/dart/utils/files.h" #include "runtime/dart/utils/handle_exception.h" #include "runtime/dart/utils/inlines.h" #include "runtime/dart/utils/tempfs.h" #include "third_party/dart/runtime/include/dart_tools_api.h" #include "third_party/tonic/converter/dart_converter.h" #include "third_party/tonic/dart_message_handler.h" #include "third_party/tonic/dart_microtask_queue.h" #include "third_party/tonic/dart_state.h" #include "third_party/tonic/logging/dart_error.h" #include "third_party/tonic/logging/dart_invoke.h" #include "builtin_libraries.h" using tonic::ToDart; namespace dart_runner { namespace { constexpr char kTmpPath[] = "/tmp"; constexpr zx::duration kIdleWaitDuration = zx::sec(2); constexpr zx::duration kIdleNotifyDuration = zx::msec(500); constexpr zx::duration kIdleSlack = zx::sec(1); constexpr zx::duration kTestTimeout = zx::sec(60); void AfterTask(async_loop_t*, void*) { tonic::DartMicrotaskQueue* queue = tonic::DartMicrotaskQueue::GetForCurrentThread(); // Verify that the queue exists, as this method could have been called back as // part of the exit routine, after the destruction of the microtask queue. if (queue) { queue->RunMicrotasks(); } } constexpr async_loop_config_t kLoopConfig = { .default_accessors = { .getter = async_get_default_dispatcher, .setter = async_set_default_dispatcher, }, .make_default_for_current_thread = true, .epilogue = &AfterTask, }; // Find the last path of the component. // fuchsia-pkg://fuchsia.com/hello_dart#meta/hello_dart.cmx -> hello_dart.cmx std::string GetLabelFromUrl(const std::string& url) { for (size_t i = url.length() - 1; i > 0; i--) { if (url[i] == '/') { return url.substr(i + 1, url.length() - 1); } } return url; } // Find the name of the component. // fuchsia-pkg://fuchsia.com/hello_dart#meta/hello_dart.cm -> hello_dart std::string GetComponentNameFromUrl(const std::string& url) { const std::string label = GetLabelFromUrl(url); for (size_t i = 0; i < label.length(); ++i) { if (label[i] == '.') { return label.substr(0, i); } } return label; } } // namespace DartTestComponentController::DartTestComponentController( fuchsia::component::runner::ComponentStartInfo start_info, std::shared_ptr<sys::ServiceDirectory> runner_incoming_services, fidl::InterfaceRequest<fuchsia::component::runner::ComponentController> controller, DoneCallback done_callback) : loop_(new async::Loop(&kLoopConfig)), executor_(loop_->dispatcher()), label_(GetLabelFromUrl(start_info.resolved_url())), url_(std::move(start_info.resolved_url())), runner_incoming_services_(runner_incoming_services), start_info_(std::move(start_info)), binding_(this), done_callback_(std::move(done_callback)) { // TODO(fxb/84537): This data path is configured based how we build Flutter // applications in tree currently, but the way we build the Flutter // application may change. We should avoid assuming the data path and let the // CML file specify this data path instead. test_component_name_ = GetComponentNameFromUrl(url_); data_path_ = "pkg/data/" + test_component_name_; if (controller.is_valid()) { binding_.Bind(std::move(controller)); binding_.set_error_handler([this](zx_status_t status) { Kill(); }); } else { FML_LOG(ERROR) << "Fuchsia component controller endpoint is not valid."; } zx_status_t idle_timer_status = zx::timer::create(ZX_TIMER_SLACK_LATE, ZX_CLOCK_MONOTONIC, &idle_timer_); if (idle_timer_status != ZX_OK) { FML_LOG(INFO) << "Idle timer creation failed: " << zx_status_get_string(idle_timer_status); } else { idle_wait_.set_object(idle_timer_.get()); idle_wait_.set_trigger(ZX_TIMER_SIGNALED); idle_wait_.Begin(async_get_default_dispatcher()); } // Close the runtime_dir channel if we don't intend to serve it. Otherwise any // access to the runtime_dir will hang forever. start_info_.clear_runtime_dir(); } DartTestComponentController::~DartTestComponentController() { if (namespace_) { fdio_ns_destroy(namespace_); namespace_ = nullptr; } close(stdout_fd_); close(stderr_fd_); } void DartTestComponentController::SetUp() { // Name the thread after the url of the component being launched. zx::thread::self()->set_property(ZX_PROP_NAME, label_.c_str(), label_.size()); Dart_SetThreadName(label_.c_str()); if (!CreateAndBindNamespace()) { return; } if (SetUpFromAppSnapshot()) { FML_LOG(INFO) << url_ << " is running from an app snapshot"; } else if (SetUpFromKernel()) { FML_LOG(INFO) << url_ << " is running from kernel"; } else { FML_LOG(ERROR) << "Failed to set up component controller for " << url_; return; } // Serve |fuchsia::test::Suite| on outgoing directory. suite_context_ = sys::ComponentContext::Create(); suite_context_->outgoing()->AddPublicService(this->GetHandler()); suite_context_->outgoing()->Serve( std::move(*start_info_.mutable_outgoing_dir()), loop_->dispatcher()); loop_->Run(); } bool DartTestComponentController::CreateAndBindNamespace() { if (!start_info_.has_ns()) { FML_LOG(ERROR) << "Component start info does not have a namespace."; return false; } const zx_status_t ns_create_status = fdio_ns_create(&namespace_); if (ns_create_status != ZX_OK) { FML_LOG(ERROR) << "Failed to create namespace: " << zx_status_get_string(ns_create_status); } dart_utils::BindTemp(namespace_); // Bind each directory in start_info's namespace to the controller's namespace // instance. for (auto& ns_entry : *start_info_.mutable_ns()) { // TODO(akbiggs): Under what circumstances does a namespace entry not // have a path or directory? Should we log an error for these? if (!ns_entry.has_path() || !ns_entry.has_directory()) { continue; } if (ns_entry.path() == kTmpPath) { // /tmp is covered by a locally served virtual filesystem. continue; } // We move ownership of the directory & path since RAII is used to keep // the handle open. fidl::InterfaceHandle<::fuchsia::io::Directory> dir = std::move(*ns_entry.mutable_directory()); const std::string path = std::move(*ns_entry.mutable_path()); const zx_status_t ns_bind_status = fdio_ns_bind(namespace_, path.c_str(), dir.TakeChannel().release()); if (ns_bind_status != ZX_OK) { FML_LOG(ERROR) << "Failed to bind " << path << " to namespace: " << zx_status_get_string(ns_bind_status); return false; } } return true; } bool DartTestComponentController::SetUpFromKernel() { dart_utils::MappedResource manifest; if (!dart_utils::MappedResource::LoadFromNamespace( namespace_, data_path_ + "/app.dilplist", manifest)) { return false; } if (!dart_utils::MappedResource::LoadFromNamespace( nullptr, "/pkg/data/isolate_core_snapshot_data.bin", isolate_snapshot_data_)) { return false; } std::string str(reinterpret_cast<const char*>(manifest.address()), manifest.size()); Dart_Handle library = Dart_Null(); for (size_t start = 0; start < manifest.size();) { size_t end = str.find("\n", start); if (end == std::string::npos) { FML_LOG(ERROR) << "Malformed manifest"; return false; } std::string path = data_path_ + "/" + str.substr(start, end - start); start = end + 1; dart_utils::MappedResource kernel; if (!dart_utils::MappedResource::LoadFromNamespace(namespace_, path, kernel)) { FML_LOG(ERROR) << "Cannot load kernel from namespace: " << path; return false; } kernel_peices_.emplace_back(std::move(kernel)); } if (!CreateIsolate(isolate_snapshot_data_.address(), /*isolate_snapshot_instructions=*/nullptr)) { return false; } Dart_EnterScope(); for (const auto& kernel : kernel_peices_) { library = Dart_LoadLibraryFromKernel(kernel.address(), kernel.size()); if (Dart_IsError(library)) { FML_LOG(ERROR) << "Cannot load library from kernel: " << Dart_GetError(library); Dart_ExitScope(); return false; } } Dart_SetRootLibrary(library); Dart_Handle result = Dart_FinalizeLoading(false); if (Dart_IsError(result)) { FML_LOG(ERROR) << "Failed to FinalizeLoading: " << Dart_GetError(result); Dart_ExitScope(); return false; } return true; } bool DartTestComponentController::SetUpFromAppSnapshot() { #if !defined(AOT_RUNTIME) return false; #else // Load the ELF snapshot as available, and fall back to a blobs snapshot // otherwise. const uint8_t *isolate_data, *isolate_instructions; if (elf_snapshot_.Load(namespace_, data_path_ + "/app_aot_snapshot.so")) { isolate_data = elf_snapshot_.IsolateData(); isolate_instructions = elf_snapshot_.IsolateInstrs(); if (isolate_data == nullptr || isolate_instructions == nullptr) { return false; } } else { if (!dart_utils::MappedResource::LoadFromNamespace( namespace_, data_path_ + "/isolate_snapshot_data.bin", isolate_snapshot_data_)) { return false; } isolate_data = isolate_snapshot_data_.address(); isolate_instructions = nullptr; } return CreateIsolate(isolate_data, isolate_instructions); #endif // defined(AOT_RUNTIME) } bool DartTestComponentController::CreateIsolate( const uint8_t* isolate_snapshot_data, const uint8_t* isolate_snapshot_instructions) { // Create the isolate from the snapshot. char* error = nullptr; // TODO(dart_runner): Pass if we start using tonic's loader. intptr_t namespace_fd = -1; // Freed in IsolateShutdownCallback. auto state = new std::shared_ptr<tonic::DartState>(new tonic::DartState( namespace_fd, [this](Dart_Handle result) { MessageEpilogue(result); })); Dart_IsolateFlags isolate_flags; Dart_IsolateFlagsInitialize(&isolate_flags); isolate_flags.null_safety = true; isolate_ = Dart_CreateIsolateGroup( url_.c_str(), label_.c_str(), isolate_snapshot_data, isolate_snapshot_instructions, &isolate_flags, state, state, &error); if (!isolate_) { FML_LOG(ERROR) << "Dart_CreateIsolateGroup failed: " << error; return false; } state->get()->SetIsolate(isolate_); tonic::DartMessageHandler::TaskDispatcher dispatcher = [loop = loop_.get()](auto callback) { async::PostTask(loop->dispatcher(), std::move(callback)); }; state->get()->message_handler().Initialize(dispatcher); state->get()->SetReturnCodeCallback([this](uint32_t return_code) { return_code_ = return_code; auto ret_status = return_code == 0 ? fuchsia::test::Status::PASSED : fuchsia::test::Status::FAILED; fuchsia::test::Result result; result.set_status(ret_status); case_listener_->Finished(std::move(result)); }); return true; } // |fuchsia::test::CaseIterator| DartTestComponentController::CaseIterator::CaseIterator( fidl::InterfaceRequest<fuchsia::test::CaseIterator> request, async_dispatcher_t* dispatcher, std::string test_component_name, fit::function<void(CaseIterator*)> done_callback) : binding_(this, std::move(request), dispatcher), test_component_name_(test_component_name), done_callback_(std::move(done_callback)) {} // |fuchsia::test::CaseIterator| void DartTestComponentController::CaseIterator::GetNext( GetNextCallback callback) { // Dart test suites run as multiple tests behind one // test case. Flip flag once the one test case has been retrieved. if (first_case_) { fuchsia::test::Case test_case; test_case.set_name(test_component_name_); test_case.set_enabled(true); std::vector<fuchsia::test::Case> cases; cases.push_back(std::move(test_case)); callback(std::move(cases)); first_case_ = false; } else { // Return an pass an empty vector to the callback to indicate there // are no more tests to be executed. std::vector<fuchsia::test::Case> cases; callback(std::move(cases)); done_callback_(this); } } // |fuchsia::test::CaseIterator| std::unique_ptr<DartTestComponentController::CaseIterator> DartTestComponentController::RemoveCaseInterator(CaseIterator* case_iterator) { auto it = case_iterators_.find(case_iterator); std::unique_ptr<DartTestComponentController::CaseIterator> case_iterator_ptr; if (it != case_iterators_.end()) { case_iterator_ptr = std::move(it->second); case_iterators_.erase(it); } return case_iterator_ptr; } // |fuchsia::test::Suite| void DartTestComponentController::GetTests( fidl::InterfaceRequest<fuchsia::test::CaseIterator> iterator) { auto case_iterator = std::make_unique<CaseIterator>( std::move(iterator), loop_->dispatcher(), test_component_name_, [this](CaseIterator* case_iterator) { RemoveCaseInterator(case_iterator); }); case_iterators_.emplace(case_iterator.get(), std::move(case_iterator)); } // |fuchsia::test::Suite| void DartTestComponentController::Run( std::vector<fuchsia::test::Invocation> tests, fuchsia::test::RunOptions options, fidl::InterfaceHandle<fuchsia::test::RunListener> listener) { std::vector<std::string> args; if (options.has_arguments()) { args = std::move(*options.mutable_arguments()); } auto listener_proxy = listener.Bind(); // We expect 1 test that will run all other tests in the test suite (i.e. a // single main.dart that calls out to all of the dart tests). If the dart // implementation in-tree changes, iterating over the invocations like so // will be able to handle that. for (auto it = tests.begin(); it != tests.end(); it++) { auto invocation = std::move(*it); std::string test_case_name; if (invocation.has_name()) { test_case_name = invocation.name(); } // Create and out/err sockets and pass file descriptor for each to the // dart process so that logging can be forwarded to the test_manager. auto status = zx::socket::create(0, &out_, &out_client_); if (status != ZX_OK) { FML_LOG(FATAL) << "cannot create out socket: " << zx_status_get_string(status); } status = fdio_fd_create(out_.release(), &stdout_fd_); if (status != ZX_OK) { FML_LOG(FATAL) << "failed to extract output fd: " << zx_status_get_string(status); } status = zx::socket::create(0, &err_, &err_client_); if (status != ZX_OK) { FML_LOG(FATAL) << "cannot create error socket: " << zx_status_get_string(status); } status = fdio_fd_create(err_.release(), &stderr_fd_); if (status != ZX_OK) { FML_LOG(FATAL) << "failed to extract error fd: " << zx_status_get_string(status); } // Pass client end of out and err socket for test_manager to stream logs to // current terminal, via |fuchsia::test::StdHandles|. fuchsia::test::StdHandles std_handles; std_handles.set_out(std::move(out_client_)); std_handles.set_err(std::move(err_client_)); listener_proxy->OnTestCaseStarted(std::move(invocation), std::move(std_handles), case_listener_.NewRequest()); // Run dart main and wait until exit code has been set before notifying of // test completion. auto dart_main_promise = fpromise::make_promise([&] { RunDartMain(); }); auto dart_state = tonic::DartState::Current(); executor_.schedule_task(std::move(dart_main_promise)); while (!dart_state->has_set_return_code()) { loop_->Run(zx::deadline_after(kTestTimeout), true); } // Notify the test_manager that the test has completed. listener_proxy->OnFinished(); } if (binding_.is_bound()) { // From the documentation for ComponentController, ZX_OK should be sent when // the ComponentController receives a termination request. However, if the // component exited with a non-zero return code, we indicate this by sending // an INTERNAL epitaph instead. // // TODO(fxb/86666): Communicate return code from the ComponentController // once v2 has support. if (return_code_ == 0) { binding_.Close(ZX_OK); } else { binding_.Close(zx_status_t(fuchsia::component::Error::INTERNAL)); } } // Stop and kill the test component. Stop(); } fpromise::promise<> DartTestComponentController::RunDartMain() { FML_CHECK(namespace_ != nullptr); Dart_EnterScope(); tonic::DartMicrotaskQueue::StartForCurrentThread(); fidl::InterfaceRequest<fuchsia::io::Directory> outgoing_dir = std::move(*start_info_.mutable_outgoing_dir()); InitBuiltinLibrariesForIsolate(url_, namespace_, stdout_fd_, stderr_fd_, outgoing_dir.TakeChannel(), false /* service_isolate */); Dart_ExitScope(); Dart_ExitIsolate(); char* error = Dart_IsolateMakeRunnable(isolate_); if (error != nullptr) { Dart_EnterIsolate(isolate_); Dart_ShutdownIsolate(); FML_LOG(ERROR) << "Unable to make isolate runnable: " << error; free(error); return fpromise::make_error_promise(); } Dart_EnterIsolate(isolate_); Dart_EnterScope(); // TODO(fxb/88383): Support argument passing. Dart_Handle corelib = Dart_LookupLibrary(ToDart("dart:core")); Dart_Handle string_type = Dart_GetNonNullableType(corelib, ToDart("String"), 0, NULL); Dart_Handle dart_arguments = Dart_NewListOfTypeFilled(string_type, Dart_EmptyString(), 0); if (Dart_IsError(dart_arguments)) { FML_LOG(ERROR) << "Failed to allocate Dart arguments list: " << Dart_GetError(dart_arguments); Dart_ExitScope(); return fpromise::make_error_promise(); } Dart_Handle user_main = Dart_GetField(Dart_RootLibrary(), ToDart("main")); if (Dart_IsError(user_main)) { FML_LOG(ERROR) << "Failed to locate user_main in the root library: " << Dart_GetError(user_main); Dart_ExitScope(); return fpromise::make_error_promise(); } Dart_Handle fuchsia_lib = Dart_LookupLibrary(tonic::ToDart("dart:fuchsia")); if (Dart_IsError(fuchsia_lib)) { FML_LOG(ERROR) << "Failed to locate dart:fuchsia: " << Dart_GetError(fuchsia_lib); Dart_ExitScope(); return fpromise::make_error_promise(); } Dart_Handle main_result = tonic::DartInvokeField( fuchsia_lib, "_runUserMainForDartRunner", {user_main, dart_arguments}); if (Dart_IsError(main_result)) { auto dart_state = tonic::DartState::Current(); if (!dart_state->has_set_return_code()) { // The program hasn't set a return code meaning this exit is unexpected. FML_LOG(ERROR) << Dart_GetError(main_result); return_code_ = tonic::GetErrorExitCode(main_result); dart_utils::HandleIfException(runner_incoming_services_, url_, main_result); } Dart_ExitScope(); return fpromise::make_error_promise(); } Dart_ExitScope(); return fpromise::make_ok_promise(); } void DartTestComponentController::Kill() { done_callback_(this); close(stdout_fd_); close(stderr_fd_); suite_bindings_.CloseAll(); if (Dart_CurrentIsolate()) { tonic::DartMicrotaskQueue* queue = tonic::DartMicrotaskQueue::GetForCurrentThread(); if (queue) { queue->Destroy(); } loop_->Quit(); // TODO(rosswang): The docs warn of threading issues if doing this again, // but without this, attempting to shut down the isolate finalizes app // contexts that can't tell a shutdown is in progress and so fatal. Dart_SetMessageNotifyCallback(nullptr); Dart_ShutdownIsolate(); } } void DartTestComponentController::MessageEpilogue(Dart_Handle result) { auto dart_state = tonic::DartState::Current(); // If the Dart program has set a return code, then it is intending to shut // down by way of a fatal error, and so there is no need to override // return_code_. if (dart_state->has_set_return_code()) { Dart_ShutdownIsolate(); return; } dart_utils::HandleIfException(runner_incoming_services_, url_, result); // Otherwise, see if there was any other error. return_code_ = tonic::GetErrorExitCode(result); if (return_code_ != 0) { Dart_ShutdownIsolate(); return; } idle_start_ = zx::clock::get_monotonic(); zx_status_t status = idle_timer_.set(idle_start_ + kIdleWaitDuration, kIdleSlack); if (status != ZX_OK) { FML_LOG(INFO) << "Idle timer set failed: " << zx_status_get_string(status); } } void DartTestComponentController::Stop() { Kill(); } void DartTestComponentController::OnIdleTimer(async_dispatcher_t* dispatcher, async::WaitBase* wait, zx_status_t status, const zx_packet_signal* signal) { if ((status != ZX_OK) || !(signal->observed & ZX_TIMER_SIGNALED) || !Dart_CurrentIsolate()) { // Timer closed or isolate shutdown. return; } zx::time deadline = idle_start_ + kIdleWaitDuration; zx::time now = zx::clock::get_monotonic(); if (now >= deadline) { // No Dart message has been processed for kIdleWaitDuration: assume we'll // stay idle for kIdleNotifyDuration. Dart_NotifyIdle((now + kIdleNotifyDuration).get()); idle_start_ = zx::time(0); idle_timer_.cancel(); // De-assert signal. } else { // Early wakeup or message pushed idle time forward: reschedule. zx_status_t status = idle_timer_.set(deadline, kIdleSlack); if (status != ZX_OK) { FML_LOG(INFO) << "Idle timer set failed: " << zx_status_get_string(status); } } wait->Begin(dispatcher); // ignore errors } } // namespace dart_runner
engine/shell/platform/fuchsia/dart_runner/dart_test_component_controller.cc/0
{ "file_path": "engine/shell/platform/fuchsia/dart_runner/dart_test_component_controller.cc", "repo_id": "engine", "token_count": 8801 }
384
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. { use: [ // This is used by the Dart VM to communicate from Dart code to C++ code. { storage: "tmp", path: "/tmp", }, // This is used by the Dart VM to load i18n data. { directory: "config-data", rights: [ "r*" ], path: "/config/data", }, // The ICU time zone data, factored out of `config-data`. // See: // https://fuchsia.dev/fuchsia-src/concepts/process/namespaces?typical_directory_structure { directory: "tzdata-icu", rights: [ "r*" ], path: "/config/tzdata/icu", }, { protocol: [ "fuchsia.device.NameProvider", // For fdio uname() "fuchsia.feedback.CrashReporter", "fuchsia.inspect.InspectSink", // For inspect "fuchsia.intl.PropertyProvider", // For dartVM timezone support "fuchsia.logger.LogSink", // For syslog "fuchsia.net.name.Lookup", // For fdio sockets "fuchsia.posix.socket.Provider", // For fdio sockets ], from: "parent", }, { protocol: [ "fuchsia.tracing.provider.Registry", // For trace-provider ], from: "parent", availability: "optional", }, ] }
engine/shell/platform/fuchsia/dart_runner/meta/common.shard.cml/0
{ "file_path": "engine/shell/platform/fuchsia/dart_runner/meta/common.shard.cml", "repo_id": "engine", "token_count": 804 }
385
#!/usr/bin/env python3 # # Copyright 2013 The Flutter 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 argparse import subprocess import os import sys def main(): parser = argparse.ArgumentParser(description='Package a Flutter application') parser.add_argument('--flutter-root', type=str, required=True, help='The root of the Flutter SDK') parser.add_argument( '--flutter-tools', type=str, required=True, help='The executable for the Flutter tool' ) parser.add_argument( '--asset-dir', type=str, required=True, help='The directory where to put intermediate files' ) parser.add_argument('--app-dir', type=str, required=True, help='The root of the app') parser.add_argument('--packages', type=str, required=True, help='The package map to use') parser.add_argument('--manifest', type=str, help='The application manifest') parser.add_argument('--component-name', type=str, help='The name of the component') parser.add_argument( '--asset-manifest-out', type=str, help='Output path for the asset manifest used by the fuchsia packaging tool' ) args = parser.parse_args() env = os.environ.copy() env['FLUTTER_ROOT'] = args.flutter_root call_args = [ args.flutter_tools, '--asset-dir=%s' % args.asset_dir, '--packages=%s' % args.packages, ] if 'manifest' in args: call_args.append('--manifest=%s' % args.manifest) if args.asset_manifest_out: call_args.append('--asset-manifest-out=%s' % args.asset_manifest_out) if args.component_name: call_args.append('--component-name=%s' % args.component_name) result = subprocess.call(call_args, env=env, cwd=args.app_dir) return result if __name__ == '__main__': sys.exit(main())
engine/shell/platform/fuchsia/flutter/build/asset_package.py/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/build/asset_package.py", "repo_id": "engine", "token_count": 638 }
386
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_FLUTTER_RUNNER_FAKES_H_ #define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_FLUTTER_RUNNER_FAKES_H_ #include <fuchsia/accessibility/semantics/cpp/fidl.h> namespace flutter_runner_test { using fuchsia::accessibility::semantics::SemanticsManager; class MockSemanticsManager : public SemanticsManager, public fuchsia::accessibility::semantics::SemanticTree { public: MockSemanticsManager() : tree_binding_(this) {} // |fuchsia::accessibility::semantics::SemanticsManager|: void RegisterViewForSemantics( fuchsia::ui::views::ViewRef view_ref, fuchsia::accessibility::semantics::SemanticListenerHandle handle, fidl::InterfaceRequest<fuchsia::accessibility::semantics::SemanticTree> semantic_tree) override { tree_binding_.Bind(std::move(semantic_tree)); has_view_ref_ = true; } fidl::InterfaceRequestHandler<SemanticsManager> GetHandler( async_dispatcher_t* dispatcher) { return bindings_.GetHandler(this, dispatcher); } bool RegisterViewCalled() { return has_view_ref_; } void ResetTree() { update_count_ = 0; delete_count_ = 0; commit_count_ = 0; last_updated_nodes_.clear(); last_deleted_node_ids_.clear(); delete_overflowed_ = false; update_overflowed_ = false; } void UpdateSemanticNodes( std::vector<fuchsia::accessibility::semantics::Node> nodes) override { update_count_++; if (!update_overflowed_) { size_t size = 0; for (const auto& node : nodes) { size += sizeof(node); size += sizeof(node.attributes().label().size()); } update_overflowed_ = size > ZX_CHANNEL_MAX_MSG_BYTES; } last_updated_nodes_ = std::move(nodes); } void DeleteSemanticNodes(std::vector<uint32_t> node_ids) override { delete_count_++; if (!delete_overflowed_) { size_t size = sizeof(node_ids) + (node_ids.size() * flutter_runner::AccessibilityBridge::kNodeIdSize); delete_overflowed_ = size > ZX_CHANNEL_MAX_MSG_BYTES; } last_deleted_node_ids_ = std::move(node_ids); } const std::vector<uint32_t>& LastDeletedNodeIds() const { return last_deleted_node_ids_; } int DeleteCount() const { return delete_count_; } bool DeleteOverflowed() const { return delete_overflowed_; } int UpdateCount() const { return update_count_; } bool UpdateOverflowed() const { return update_overflowed_; } bool ShouldHoldCommitResponse() const { return should_hold_commit_response_; } void SetShouldHoldCommitResponse(bool value) { should_hold_commit_response_ = value; } void InvokeCommitCallback() { if (commit_callback_) { commit_callback_(); } } int CommitCount() const { return commit_count_; } const std::vector<fuchsia::accessibility::semantics::Node>& LastUpdatedNodes() const { return last_updated_nodes_; } void CommitUpdates(CommitUpdatesCallback callback) override { commit_count_++; if (should_hold_commit_response_) { commit_callback_ = std::move(callback); return; } callback(); } void SendSemanticEvent( fuchsia::accessibility::semantics::SemanticEvent semantic_event, SendSemanticEventCallback callback) override { last_events_.emplace_back(std::move(semantic_event)); callback(); } std::vector<fuchsia::accessibility::semantics::SemanticEvent>& GetLastEvents() { return last_events_; } private: bool has_view_ref_ = false; fidl::BindingSet<SemanticsManager> bindings_; fidl::Binding<SemanticTree> tree_binding_; std::vector<fuchsia::accessibility::semantics::Node> last_updated_nodes_; bool update_overflowed_; int update_count_; int delete_count_; bool delete_overflowed_; std::vector<uint32_t> last_deleted_node_ids_; bool should_hold_commit_response_ = false; CommitUpdatesCallback commit_callback_; int commit_count_; std::vector<fuchsia::accessibility::semantics::SemanticEvent> last_events_; }; } // namespace flutter_runner_test #endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_FLUTTER_RUNNER_FAKES_H_
engine/shell/platform/fuchsia/flutter/flutter_runner_fakes.h/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/flutter_runner_fakes.h", "repo_id": "engine", "token_count": 1599 }
387
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "pointer_injector_delegate.h" #include "flutter/fml/logging.h" namespace flutter_runner { using fup_Config = fuchsia::ui::pointerinjector::Config; using fup_Context = fuchsia::ui::pointerinjector::Context; using fup_Data = fuchsia::ui::pointerinjector::Data; using fup_DeviceType = fuchsia::ui::pointerinjector::DeviceType; using fup_DispatchPolicy = fuchsia::ui::pointerinjector::DispatchPolicy; using fup_Event = fuchsia::ui::pointerinjector::Event; using fup_EventPhase = fuchsia::ui::pointerinjector::EventPhase; using fup_PointerSample = fuchsia::ui::pointerinjector::PointerSample; using fup_Target = fuchsia::ui::pointerinjector::Target; using fup_Viewport = fuchsia::ui::pointerinjector::Viewport; using fuv_ViewRef = fuchsia::ui::views::ViewRef; const auto fup_MAX_INJECT = fuchsia::ui::pointerinjector::MAX_INJECT; namespace { // clang-format off static constexpr std::array<float, 9> kIdentityMatrix = { 1, 0, 0, // column one 0, 1, 0, // column two 0, 0, 1, // column three }; // clang-format on } // namespace bool PointerInjectorDelegate::HandlePlatformMessage( rapidjson::Value request, fml::RefPtr<flutter::PlatformMessageResponse> response) { if (!registry_->is_bound()) { FML_LOG(WARNING) << "Lost connection to fuchsia.ui.pointerinjector.Registry"; return false; } auto method = request.FindMember("method"); if (method == request.MemberEnd() || !method->value.IsString()) { FML_LOG(ERROR) << "No method found in platform message."; return false; } if (method->value != kPointerInjectorMethodPrefix) { FML_LOG(ERROR) << "Unexpected platform message method, expected " "View.pointerinjector.inject."; return false; } auto args_it = request.FindMember("args"); if (args_it == request.MemberEnd() || !args_it->value.IsObject()) { FML_LOG(ERROR) << "No arguments found in platform message's method"; return false; } const auto& args = args_it->value; auto view_id = args.FindMember("viewId"); if (!view_id->value.IsUint64()) { FML_LOG(ERROR) << "Argument 'viewId' is not a uint64"; return false; } auto id = view_id->value.GetUint64(); if (valid_views_.count(id) == 0) { // A child view can get destroyed bottom-up, so the parent view may continue // injecting until all view state processing "catches up". Until then, it's // okay to accept a request to inject into a view that no longer exists. // Doing so avoids log pollution regarding "MissingPluginException". Complete(std::move(response), "[0]"); return true; } auto phase = args.FindMember("phase"); if (!phase->value.IsInt()) { FML_LOG(ERROR) << "Argument 'phase' is not a int"; return false; } auto pointer_x = args.FindMember("x"); if (!pointer_x->value.IsFloat() && !pointer_x->value.IsInt()) { FML_LOG(ERROR) << "Argument 'Pointer.X' is not a float"; return false; } auto pointer_y = args.FindMember("y"); if (!pointer_y->value.IsFloat() && !pointer_y->value.IsInt()) { FML_LOG(ERROR) << "Argument 'Pointer.Y' is not a float"; return false; } auto pointer_id = args.FindMember("pointerId"); if (!pointer_id->value.IsUint()) { FML_LOG(ERROR) << "Argument 'pointerId' is not a uint32"; return false; } auto trace_flow_id = args.FindMember("traceFlowId"); if (!trace_flow_id->value.IsInt()) { FML_LOG(ERROR) << "Argument 'traceFlowId' is not a int"; return false; } auto width = args.FindMember("logicalWidth"); if (!width->value.IsFloat() && !width->value.IsInt()) { FML_LOG(ERROR) << "Argument 'logicalWidth' is not a float"; return false; } auto height = args.FindMember("logicalHeight"); if (!height->value.IsFloat() && !height->value.IsInt()) { FML_LOG(ERROR) << "Argument 'logicalHeight' is not a float"; return false; } auto timestamp = args.FindMember("timestamp"); if (!timestamp->value.IsInt() && !timestamp->value.IsUint64()) { FML_LOG(ERROR) << "Argument 'timestamp' is not a int"; return false; } PointerInjectorRequest event = { .x = pointer_x->value.GetFloat(), .y = pointer_y->value.GetFloat(), .pointer_id = pointer_id->value.GetUint(), .phase = static_cast<fup_EventPhase>(phase->value.GetInt()), .trace_flow_id = trace_flow_id->value.GetUint64(), .logical_size = {width->value.GetFloat(), height->value.GetFloat()}, .timestamp = timestamp->value.GetInt()}; // Inject the pointer event if the view has been created. valid_views_.at(id).InjectEvent(std::move(event)); Complete(std::move(response), "[0]"); return true; } void PointerInjectorDelegate::OnCreateView( uint64_t view_id, std::optional<fuv_ViewRef> view_ref) { FML_CHECK(valid_views_.count(view_id) == 0); auto [_, success] = valid_views_.try_emplace( view_id, registry_, host_view_ref_, std::move(view_ref)); FML_CHECK(success); } fup_Event PointerInjectorDelegate::ExtractPointerEvent( PointerInjectorRequest request) { fup_Event event; event.set_timestamp(request.timestamp); event.set_trace_flow_id(request.trace_flow_id); fup_PointerSample pointer_sample; pointer_sample.set_pointer_id(request.pointer_id); pointer_sample.set_phase(request.phase); pointer_sample.set_position_in_viewport({request.x, request.y}); fup_Data data; data.set_pointer_sample(std::move(pointer_sample)); event.set_data(std::move(data)); return event; } void PointerInjectorDelegate::Complete( fml::RefPtr<flutter::PlatformMessageResponse> response, std::string value) { if (response) { response->Complete(std::make_unique<fml::DataMapping>( std::vector<uint8_t>(value.begin(), value.end()))); } } void PointerInjectorDelegate::PointerInjectorEndpoint::InjectEvent( PointerInjectorRequest request) { if (!registered_) { RegisterInjector(request); } auto event = ExtractPointerEvent(std::move(request)); // Add the event to |injector_events_| and dispatch it to the view. EnqueueEvent(std::move(event)); DispatchPendingEvents(); } void PointerInjectorDelegate::PointerInjectorEndpoint::DispatchPendingEvents() { // Return if there is already a |fuchsia.ui.pointerinjector.Device.Inject| // call in flight. The new pointer events will be dispatched once the // in-progress call terminates. if (injection_in_flight_) { return; } // Dispatch the events present in |injector_events_|. Note that we recursively // call |DispatchPendingEvents| in the callback passed to the // |f.u.p.Device.Inject| call. This ensures that there is only one // |f.u.p.Device.Inject| call at a time. If a new pointer event comes when // there is a |f.u.p.Device.Inject| call in progress, it gets buffered in // |injector_events_| and is picked up later. if (!injector_events_.empty()) { auto events = std::move(injector_events_.front()); injector_events_.pop(); injection_in_flight_ = true; FML_CHECK(device_.is_bound()); FML_CHECK(events.size() <= fup_MAX_INJECT); device_->Inject(std::move(events), [weak = weak_factory_.GetWeakPtr()] { if (!weak) { FML_LOG(WARNING) << "Use after free attempted."; return; } weak->injection_in_flight_ = false; weak->DispatchPendingEvents(); }); } } void PointerInjectorDelegate::PointerInjectorEndpoint::EnqueueEvent( fup_Event event) { // Add |event| in |injector_events_| keeping in mind that the vector size does // not exceed |fup_MAX_INJECT|. if (!injector_events_.empty() && injector_events_.back().size() < fup_MAX_INJECT) { injector_events_.back().push_back(std::move(event)); } else { std::vector<fup_Event> vec; vec.reserve(fup_MAX_INJECT); vec.push_back(std::move(event)); injector_events_.push(std::move(vec)); } } void PointerInjectorDelegate::PointerInjectorEndpoint::RegisterInjector( const PointerInjectorRequest& request) { if (registered_) { return; } fup_Config config; config.set_device_id(1); config.set_device_type(fup_DeviceType::TOUCH); config.set_dispatch_policy(fup_DispatchPolicy::EXCLUSIVE_TARGET); fup_Context context; fuv_ViewRef context_clone; fidl::Clone(*host_view_ref_, &context_clone); context.set_view(std::move(context_clone)); config.set_context(std::move(context)); FML_CHECK(view_ref_.has_value()); fup_Target target; fuv_ViewRef target_clone; fidl::Clone(*view_ref_, &target_clone); target.set_view(std::move(target_clone)); config.set_target(std::move(target)); fup_Viewport viewport; viewport.set_viewport_to_context_transform(kIdentityMatrix); std::array<std::array<float, 2>, 2> extents{ {/*min*/ {0, 0}, /*max*/ {request.logical_size[0], request.logical_size[1]}}}; viewport.set_extents(std::move(extents)); config.set_viewport(std::move(viewport)); FML_CHECK(registry_->is_bound()); (*registry_)->Register(std::move(config), device_.NewRequest(), [] {}); registered_ = true; } void PointerInjectorDelegate::PointerInjectorEndpoint::Reset() { injection_in_flight_ = false; registered_ = false; injector_events_ = {}; } } // namespace flutter_runner
engine/shell/platform/fuchsia/flutter/pointer_injector_delegate.cc/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/pointer_injector_delegate.cc", "repo_id": "engine", "token_count": 3418 }
388
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "surface.h" #include <fcntl.h> #include <lib/fdio/watcher.h> #include <lib/zx/time.h> #include <unistd.h> #include "flutter/fml/unique_fd.h" namespace flutter_runner { Surface::Surface(std::string debug_label, std::shared_ptr<flutter::ExternalViewEmbedder> view_embedder, GrDirectContext* gr_context) : debug_label_(std::move(debug_label)), view_embedder_(view_embedder), gr_context_(gr_context) {} Surface::~Surface() = default; // |flutter::Surface| bool Surface::IsValid() { return true; } // |flutter::Surface| std::unique_ptr<flutter::SurfaceFrame> Surface::AcquireFrame( const SkISize& size) { flutter::SurfaceFrame::FramebufferInfo framebuffer_info; framebuffer_info.supports_readback = true; return std::make_unique<flutter::SurfaceFrame>( nullptr, std::move(framebuffer_info), [](const flutter::SurfaceFrame& surface_frame, flutter::DlCanvas* canvas) { return true; }, size); } // |flutter::Surface| GrDirectContext* Surface::GetContext() { return gr_context_; } // |flutter::Surface| SkMatrix Surface::GetRootTransformation() const { // This backend does not support delegating to the underlying platform to // query for root surface transformations. Just return identity. SkMatrix matrix; matrix.reset(); return matrix; } } // namespace flutter_runner
engine/shell/platform/fuchsia/flutter/surface.cc/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/surface.cc", "repo_id": "engine", "token_count": 556 }
389
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "fake_flatland_types.h" #include <lib/fidl/cpp/clone.h> #include <lib/zx/channel.h> #include <lib/zx/eventpair.h> #include "flutter/fml/logging.h" namespace flutter_runner::testing { namespace { using FakeTransformCache = std::unordered_map<const FakeTransform*, std::shared_ptr<FakeTransform>>; std::vector<std::shared_ptr<FakeTransform>> CloneFakeTransformVector( const std::vector<std::shared_ptr<FakeTransform>>& transforms, FakeTransformCache& transform_cache); std::shared_ptr<FakeContent> CloneFakeContent( const std::shared_ptr<FakeContent>& content) { if (content == nullptr) { return nullptr; } if (FakeViewport* viewport = std::get_if<FakeViewport>(content.get())) { return std::make_shared<FakeContent>(FakeViewport{ .id = viewport->id, .viewport_properties = fidl::Clone(viewport->viewport_properties), .viewport_token = viewport->viewport_token, .child_view_watcher = viewport->child_view_watcher, }); } else if (FakeImage* image = std::get_if<FakeImage>(content.get())) { return std::make_shared<FakeContent>(FakeImage{ .id = image->id, .image_properties = fidl::Clone(image->image_properties), .sample_region = image->sample_region, .destination_size = image->destination_size, .opacity = image->opacity, .blend_mode = image->blend_mode, .import_token = image->import_token, .vmo_index = image->vmo_index, }); } else { FML_UNREACHABLE(); } } std::shared_ptr<FakeTransform> CloneFakeTransform( const std::shared_ptr<FakeTransform>& transform, FakeTransformCache& transform_cache) { if (transform == nullptr) { return nullptr; } auto found_transform = transform_cache.find(transform.get()); if (found_transform != transform_cache.end()) { return found_transform->second; } auto [emplaced_transform, success] = transform_cache.emplace( transform.get(), std::make_shared<FakeTransform>(FakeTransform{ .id = transform->id, .translation = transform->translation, .scale = transform->scale, .orientation = transform->orientation, .clip_bounds = transform->clip_bounds, .opacity = transform->opacity, .children = CloneFakeTransformVector( transform->children, transform_cache), .content = CloneFakeContent(transform->content), .hit_regions = transform->hit_regions, })); FML_CHECK(success); return emplaced_transform->second; } std::vector<std::shared_ptr<FakeTransform>> CloneFakeTransformVector( const std::vector<std::shared_ptr<FakeTransform>>& transforms, FakeTransformCache& transform_cache) { std::vector<std::shared_ptr<FakeTransform>> clones; for (auto& transform : transforms) { clones.emplace_back(CloneFakeTransform(transform, transform_cache)); } return clones; } } // namespace ViewTokenPair ViewTokenPair::New() { ViewTokenPair token_pair; auto status = zx::channel::create(0u, &token_pair.view_token.value, &token_pair.viewport_token.value); FML_CHECK(status == ZX_OK); return token_pair; } BufferCollectionTokenPair BufferCollectionTokenPair::New() { BufferCollectionTokenPair token_pair; auto status = zx::eventpair::create(0u, &token_pair.export_token.value, &token_pair.import_token.value); FML_CHECK(status == ZX_OK); return token_pair; } bool FakeView::operator==(const FakeView& other) const { return view_token == other.view_token && view_ref == other.view_ref && view_ref_control == other.view_ref_control && view_ref_focused == other.view_ref_focused && focuser == other.focuser && touch_source == other.touch_source && mouse_source == other.mouse_source && parent_viewport_watcher == other.parent_viewport_watcher; } bool FakeViewport::operator==(const FakeViewport& other) const { return id == other.id && viewport_properties == other.viewport_properties && viewport_token == other.viewport_token && child_view_watcher == other.child_view_watcher; } bool FakeImage::operator==(const FakeImage& other) const { return id == other.id && image_properties == other.image_properties && sample_region == other.sample_region && destination_size == other.destination_size && opacity == other.opacity && blend_mode == other.blend_mode && import_token == other.import_token && vmo_index == other.vmo_index; } bool FakeTransform::operator==(const FakeTransform& other) const { return id == other.id && translation == other.translation && *clip_bounds == *other.clip_bounds && orientation == other.orientation && children == other.children && content == other.content && hit_regions == other.hit_regions; } bool FakeGraph::operator==(const FakeGraph& other) const { return transform_map == other.transform_map && content_map == other.content_map && root_transform == other.root_transform && view == other.view; } void FakeGraph::Clear() { view.reset(); root_transform.reset(); transform_map.clear(); content_map.clear(); } FakeGraph FakeGraph::Clone() const { FakeGraph clone; FakeTransformCache transform_cache; for (const auto& [transform_id, transform] : transform_map) { FML_CHECK(transform); clone.transform_map.emplace(transform_id, CloneFakeTransform(transform, transform_cache)); } for (const auto& [content_id, content] : content_map) { FML_CHECK(content); clone.content_map.emplace(content_id, CloneFakeContent(content)); } if (root_transform) { auto found_transform = transform_cache.find(root_transform.get()); FML_CHECK(found_transform != transform_cache.end()); clone.root_transform = found_transform->second; } if (view.has_value()) { clone.view.emplace(view.value()); } return clone; } } // namespace flutter_runner::testing
engine/shell/platform/fuchsia/flutter/tests/fakes/scenic/fake_flatland_types.cc/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/tests/fakes/scenic/fake_flatland_types.cc", "repo_id": "engine", "token_count": 2462 }
390
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:convert'; import 'dart:typed_data'; import 'dart:io'; import 'dart:ui'; import 'package:args/args.dart'; import 'package:vector_math/vector_math_64.dart' as vector_math_64; final _argsCsvFilePath = '/config/data/args.csv'; void main(List<String> args) async { print('parent-view: starting'); args = args + _GetArgsFromConfigFile(); final parser = ArgParser() ..addFlag('showOverlay', defaultsTo: false) ..addFlag('focusable', defaultsTo: true); final arguments = parser.parse(args); for (final option in arguments.options) { print('parent-view: $option: ${arguments[option]}'); } TestApp app; app = TestApp( ChildView(await _launchChildView()), showOverlay: arguments['showOverlay'], focusable: arguments['focusable'], ); app.run(); } class TestApp { static const _black = Color.fromARGB(255, 0, 0, 0); static const _blue = Color.fromARGB(255, 0, 0, 255); final ChildView childView; final bool showOverlay; final bool focusable; Color _backgroundColor = _blue; TestApp(this.childView, {this.showOverlay = false, this.focusable = true}) {} void run() { childView.create(focusable, (ByteData? reply) { // Set up window allbacks. window.onPointerDataPacket = (PointerDataPacket packet) { for (final data in packet.data) { if (data.change == PointerChange.down) { this._backgroundColor = _black; } } window.scheduleFrame(); }; 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) { final windowPhysicalBounds = Offset.zero & window.physicalSize; final pixelRatio = window.devicePixelRatio; final windowSize = window.physicalSize / pixelRatio; final windowBounds = Offset.zero & windowSize; final recorder = PictureRecorder(); final canvas = Canvas(recorder, windowPhysicalBounds); canvas.scale(pixelRatio); final paint = Paint()..color = this._backgroundColor; canvas.drawRect(windowBounds, paint); final picture = recorder.endRecording(); final sceneBuilder = SceneBuilder() ..pushClipRect(windowPhysicalBounds) ..addPicture(Offset.zero, picture); final childPhysicalSize = window.physicalSize * 0.33; // Alignment.center final windowCenter = windowSize.center(Offset.zero); final windowPhysicalCenter = window.physicalSize.center(Offset.zero); final childPhysicalOffset = windowPhysicalCenter - childPhysicalSize.center(Offset.zero); sceneBuilder ..pushTransform(vector_math_64.Matrix4.translationValues( childPhysicalOffset.dx, childPhysicalOffset.dy, 0.0) .storage) ..addPlatformView(childView.viewId, width: childPhysicalSize.width, height: childPhysicalSize.height) ..pop(); if (showOverlay) { final containerSize = windowSize * .66; // Alignment.center final containerOffset = windowCenter - containerSize.center(Offset.zero); final overlaySize = containerSize * 0.5; // Alignment.topRight final overlayOffset = Offset( containerOffset.dx + containerSize.width - overlaySize.width, containerOffset.dy); final overlayPhysicalSize = overlaySize * pixelRatio; final overlayPhysicalOffset = overlayOffset * pixelRatio; final overlayPhysicalBounds = overlayPhysicalOffset & overlayPhysicalSize; final recorder = PictureRecorder(); final overlayCullRect = Offset.zero & overlayPhysicalSize; // in canvas physical coordinates final canvas = Canvas(recorder, overlayCullRect); canvas.scale(pixelRatio); final paint = Paint()..color = Color.fromARGB(255, 0, 255, 0); canvas.drawRect(Offset.zero & overlaySize, paint); final overlayPicture = recorder.endRecording(); sceneBuilder ..pushClipRect(overlayPhysicalBounds) // in window physical coordinates ..addPicture(overlayPhysicalOffset, overlayPicture) ..pop(); } sceneBuilder.pop(); window.render(sceneBuilder.build()); } } class ChildView { final int viewId; ChildView(this.viewId); void create(bool focusable, PlatformMessageResponseCallback callback) { // Construct the dart:ui platform message to create the view, and when the // return callback is invoked, build the scene. At that point, it is safe // to embed the child-view2 in the scene. final viewOcclusionHint = Rect.zero; final Map<String, dynamic> args = <String, dynamic>{ 'viewId': viewId, // Flatland doesn't support disabling hit testing. 'hitTestable': true, 'focusable': focusable, 'viewOcclusionHintLTRB': <double>[ viewOcclusionHint.left, viewOcclusionHint.top, viewOcclusionHint.right, viewOcclusionHint.bottom ], }; final ByteData createViewMessage = ByteData.sublistView(utf8.encode(json.encode(<String, Object>{ 'method': 'View.create', 'args': args, }))); final platformViewsChannel = 'flutter/platform_views'; PlatformDispatcher.instance .sendPlatformMessage(platformViewsChannel, createViewMessage, callback); } } Future<int> _launchChildView() async { final message = Int8List.fromList([0x31]); final completer = new Completer<ByteData>(); PlatformDispatcher.instance.sendPlatformMessage( 'fuchsia/child_view', ByteData.sublistView(message), (ByteData? reply) { completer.complete(reply!); }); return int.parse( ascii.decode(((await completer.future).buffer.asUint8List()))); } List<String> _GetArgsFromConfigFile() { List<String> args; final f = File(_argsCsvFilePath); if (!f.existsSync()) { return List.empty(); } final fileContentCsv = f.readAsStringSync(); args = fileContentCsv.split('\n'); return args; }
engine/shell/platform/fuchsia/flutter/tests/integration/embedder/parent-view/lib/parent_view.dart/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/tests/integration/embedder/parent-view/lib/parent_view.dart", "repo_id": "engine", "token_count": 2273 }
391
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_INTEGRATION_UTILS_CHECK_VIEW_H_ #define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_INTEGRATION_UTILS_CHECK_VIEW_H_ #include <vector> #include <fuchsia/ui/observation/geometry/cpp/fidl.h> #include <zircon/status.h> namespace fuchsia_test_utils { /// Returns true if a view with the given |view_ref_koid| exists in a |snapshot| /// of the view tree, false otherwise. bool CheckViewExistsInSnapshot( const fuchsia::ui::observation::geometry::ViewTreeSnapshot& snapshot, zx_koid_t view_ref_koid); /// Returns true if any of the snapshots of the view tree in |updates| contain a /// view with the given |view_ref_koid|, false otherwise. bool CheckViewExistsInUpdates( const std::vector<fuchsia::ui::observation::geometry::ViewTreeSnapshot>& updates, zx_koid_t view_ref_koid); } // namespace fuchsia_test_utils #endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_INTEGRATION_UTILS_CHECK_VIEW_H_
engine/shell/platform/fuchsia/flutter/tests/integration/utils/check_view.h/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/tests/integration/utils/check_view.h", "repo_id": "engine", "token_count": 434 }
392
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_UNIQUE_FDIO_NS_H_ #define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_UNIQUE_FDIO_NS_H_ #include "flutter/fml/logging.h" #include "flutter/fml/unique_object.h" #include "lib/fdio/namespace.h" namespace flutter_runner { struct UniqueFDIONSTraits { static fdio_ns_t* InvalidValue() { return nullptr; } static bool IsValid(fdio_ns_t* ns) { return ns != InvalidValue(); } static void Free(fdio_ns_t* ns) { auto status = fdio_ns_destroy(ns); FML_DCHECK(status == ZX_OK); } }; using UniqueFDIONS = fml::UniqueObject<fdio_ns_t*, UniqueFDIONSTraits>; inline UniqueFDIONS UniqueFDIONSCreate() { fdio_ns_t* ns = nullptr; if (fdio_ns_create(&ns) == ZX_OK) { return UniqueFDIONS{ns}; } return UniqueFDIONS{nullptr}; } } // namespace flutter_runner #endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_UNIQUE_FDIO_NS_H_
engine/shell/platform/fuchsia/flutter/unique_fdio_ns.h/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/unique_fdio_ns.h", "repo_id": "engine", "token_count": 421 }
393
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "runtime/dart/utils/build_info.h" namespace dart_utils { const char* BuildInfo::DartSdkGitRevision() { return "{{DART_SDK_GIT_REVISION}}"; } const char* BuildInfo::DartSdkSemanticVersion() { return "{{DART_SDK_SEMANTIC_VERSION}}"; } const char* BuildInfo::FlutterEngineGitRevision() { return "{{FLUTTER_ENGINE_GIT_REVISION}}"; } const char* BuildInfo::FuchsiaSdkVersion() { return "{{FUCHSIA_SDK_VERSION}}"; } void BuildInfo::Dump(inspect::Node& node) { node.CreateString("dart_sdk_git_revision", DartSdkGitRevision(), RootInspectNode::GetInspector()); node.CreateString("dart_sdk_semantic_version", DartSdkSemanticVersion(), RootInspectNode::GetInspector()); node.CreateString("flutter_engine_git_revision", FlutterEngineGitRevision(), RootInspectNode::GetInspector()); node.CreateString("fuchsia_sdk_version", FuchsiaSdkVersion(), RootInspectNode::GetInspector()); } } // namespace dart_utils
engine/shell/platform/fuchsia/runtime/dart/utils/build_info_in.cc/0
{ "file_path": "engine/shell/platform/fuchsia/runtime/dart/utils/build_info_in.cc", "repo_id": "engine", "token_count": 464 }
394
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_VMO_H_ #define FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_VMO_H_ #include <string> #include <fuchsia/mem/cpp/fidl.h> namespace dart_utils { bool VmoFromFilename(const std::string& filename, bool executable, fuchsia::mem::Buffer* buffer); bool VmoFromFilenameAt(int dirfd, const std::string& filename, bool executable, fuchsia::mem::Buffer* buffer); zx_status_t IsSizeValid(const fuchsia::mem::Buffer& buffer, bool* is_valid); } // namespace dart_utils #endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_VMO_H_
engine/shell/platform/fuchsia/runtime/dart/utils/vmo.h/0
{ "file_path": "engine/shell/platform/fuchsia/runtime/dart/utils/vmo.h", "repo_id": "engine", "token_count": 392 }
395
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/glfw/client_wrapper/testing/stub_flutter_glfw_api.h" static flutter::testing::StubFlutterGlfwApi* s_stub_implementation; namespace flutter { namespace testing { // static void StubFlutterGlfwApi::SetTestStub(StubFlutterGlfwApi* stub) { s_stub_implementation = stub; } // static StubFlutterGlfwApi* StubFlutterGlfwApi::GetTestStub() { return s_stub_implementation; } ScopedStubFlutterGlfwApi::ScopedStubFlutterGlfwApi( std::unique_ptr<StubFlutterGlfwApi> stub) : stub_(std::move(stub)) { previous_stub_ = StubFlutterGlfwApi::GetTestStub(); StubFlutterGlfwApi::SetTestStub(stub_.get()); } ScopedStubFlutterGlfwApi::~ScopedStubFlutterGlfwApi() { StubFlutterGlfwApi::SetTestStub(previous_stub_); } } // namespace testing } // namespace flutter // Forwarding dummy implementations of the C API. bool FlutterDesktopInit() { if (s_stub_implementation) { s_stub_implementation->Init(); } return true; } void FlutterDesktopTerminate() { if (s_stub_implementation) { s_stub_implementation->Terminate(); } } FlutterDesktopWindowControllerRef FlutterDesktopCreateWindow( const FlutterDesktopWindowProperties& window_properties, const FlutterDesktopEngineProperties& engine_properties) { if (s_stub_implementation) { return s_stub_implementation->CreateWindow(window_properties, engine_properties); } return nullptr; } void FlutterDesktopDestroyWindow(FlutterDesktopWindowControllerRef controller) { if (s_stub_implementation) { s_stub_implementation->DestroyWindow(); } } void FlutterDesktopWindowSetHoverEnabled(FlutterDesktopWindowRef flutter_window, bool enabled) { if (s_stub_implementation) { s_stub_implementation->SetHoverEnabled(enabled); } } void FlutterDesktopWindowSetTitle(FlutterDesktopWindowRef flutter_window, const char* title) { if (s_stub_implementation) { s_stub_implementation->SetWindowTitle(title); } } void FlutterDesktopWindowSetIcon(FlutterDesktopWindowRef flutter_window, uint8_t* pixel_data, int width, int height) { if (s_stub_implementation) { s_stub_implementation->SetWindowIcon(pixel_data, width, height); } } void FlutterDesktopWindowGetFrame(FlutterDesktopWindowRef flutter_window, int* x, int* y, int* width, int* height) { if (s_stub_implementation) { s_stub_implementation->GetWindowFrame(x, y, width, height); } } void FlutterDesktopWindowSetFrame(FlutterDesktopWindowRef flutter_window, int x, int y, int width, int height) { if (s_stub_implementation) { s_stub_implementation->SetWindowFrame(x, y, width, height); } } void FlutterDesktopWindowSetSizeLimits(FlutterDesktopWindowRef flutter_window, FlutterDesktopSize minimum_size, FlutterDesktopSize maximum_size) { if (s_stub_implementation) { s_stub_implementation->SetSizeLimits(minimum_size, maximum_size); } } double FlutterDesktopWindowGetScaleFactor( FlutterDesktopWindowRef flutter_window) { if (s_stub_implementation) { return s_stub_implementation->GetWindowScaleFactor(); } return 1.0; } void FlutterDesktopWindowSetPixelRatioOverride( FlutterDesktopWindowRef flutter_window, double pixel_ratio) { if (s_stub_implementation) { return s_stub_implementation->SetPixelRatioOverride(pixel_ratio); } } bool FlutterDesktopRunWindowEventLoopWithTimeout( FlutterDesktopWindowControllerRef controller, uint32_t millisecond_timeout) { if (s_stub_implementation) { return s_stub_implementation->RunWindowEventLoopWithTimeout( millisecond_timeout); } return true; } FlutterDesktopEngineRef FlutterDesktopRunEngine( const FlutterDesktopEngineProperties& properties) { if (s_stub_implementation) { return s_stub_implementation->RunEngine(properties); } return nullptr; } void FlutterDesktopRunEngineEventLoopWithTimeout( FlutterDesktopEngineRef engine, uint32_t timeout_milliseconds) { if (s_stub_implementation) { s_stub_implementation->RunEngineEventLoopWithTimeout(timeout_milliseconds); } } bool FlutterDesktopShutDownEngine(FlutterDesktopEngineRef engine_ref) { if (s_stub_implementation) { return s_stub_implementation->ShutDownEngine(); } return true; } FlutterDesktopWindowRef FlutterDesktopGetWindow( FlutterDesktopWindowControllerRef controller) { // The stub ignores this, so just return an arbitrary non-zero value. return reinterpret_cast<FlutterDesktopWindowRef>(1); } FlutterDesktopEngineRef FlutterDesktopGetEngine( FlutterDesktopWindowControllerRef controller) { // The stub ignores this, so just return an arbitrary non-zero value. return reinterpret_cast<FlutterDesktopEngineRef>(3); } FlutterDesktopPluginRegistrarRef FlutterDesktopGetPluginRegistrar( FlutterDesktopEngineRef engine, const char* plugin_name) { // The stub ignores this, so just return an arbitrary non-zero value. return reinterpret_cast<FlutterDesktopPluginRegistrarRef>(2); } FlutterDesktopWindowRef FlutterDesktopPluginRegistrarGetWindow( FlutterDesktopPluginRegistrarRef registrar) { // The stub ignores this, so just return an arbitrary non-zero value. return reinterpret_cast<FlutterDesktopWindowRef>(3); } void FlutterDesktopPluginRegistrarEnableInputBlocking( FlutterDesktopPluginRegistrarRef registrar, const char* channel) { if (s_stub_implementation) { s_stub_implementation->PluginRegistrarEnableInputBlocking(channel); } }
engine/shell/platform/glfw/client_wrapper/testing/stub_flutter_glfw_api.cc/0
{ "file_path": "engine/shell/platform/glfw/client_wrapper/testing/stub_flutter_glfw_api.cc", "repo_id": "engine", "token_count": 2448 }
396
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/glfw/system_utils.h" #include <cstdlib> #include <sstream> namespace flutter { namespace { const char* GetLocaleStringFromEnvironment() { const char* retval; retval = getenv("LANGUAGE"); if ((retval != NULL) && (retval[0] != '\0')) { return retval; } retval = getenv("LC_ALL"); if ((retval != NULL) && (retval[0] != '\0')) { return retval; } retval = getenv("LC_MESSAGES"); if ((retval != NULL) && (retval[0] != '\0')) { return retval; } retval = getenv("LANG"); if ((retval != NULL) && (retval[0] != '\0')) { return retval; } return NULL; } // The least specific to most specific components of a locale. enum Component { kCodeset = 1 << 0, kTerritory = 1 << 1, kModifier = 1 << 2, }; // Construct a mask indicating which of the components in |info| are set. int ComputeVariantMask(const LanguageInfo& info) { int mask = 0; if (!info.territory.empty()) { mask |= kTerritory; } if (!info.codeset.empty()) { mask |= kCodeset; } if (!info.modifier.empty()) { mask |= kModifier; } return mask; } // Appends most specific to least specific variants of |info| to |languages|. // For example, "de_DE@euro" would append "de_DE@euro", "de@euro", "de_DE", // and "de". void AppendLocaleVariants(std::vector<LanguageInfo>& languages, const LanguageInfo& info) { int mask = ComputeVariantMask(info); for (int i = mask; i >= 0; --i) { if ((i & ~mask) == 0) { LanguageInfo variant; variant.language = info.language; if (i & kTerritory) { variant.territory = info.territory; } if (i & kCodeset) { variant.codeset = info.codeset; } if (i & kModifier) { variant.modifier = info.modifier; } languages.push_back(variant); } } } // Parses a locale into its components. LanguageInfo ParseLocale(const std::string& locale) { // Locales are of the form "language[_territory][.codeset][@modifier]" LanguageInfo result; std::string::size_type end = locale.size(); std::string::size_type modifier_pos = locale.rfind('@'); if (modifier_pos != std::string::npos) { result.modifier = locale.substr(modifier_pos + 1, end - modifier_pos - 1); end = modifier_pos; } std::string::size_type codeset_pos = locale.rfind('.', end); if (codeset_pos != std::string::npos) { result.codeset = locale.substr(codeset_pos + 1, end - codeset_pos - 1); end = codeset_pos; } std::string::size_type territory_pos = locale.rfind('_', end); if (territory_pos != std::string::npos) { result.territory = locale.substr(territory_pos + 1, end - territory_pos - 1); end = territory_pos; } result.language = locale.substr(0, end); return result; } } // namespace std::vector<LanguageInfo> GetPreferredLanguageInfo() { const char* locale_string; locale_string = GetLocaleStringFromEnvironment(); if (!locale_string || locale_string[0] == '\0') { // This is the default locale if none is specified according to ISO C. locale_string = "C"; } std::istringstream locales_stream(locale_string); std::vector<LanguageInfo> languages; std::string s; while (getline(locales_stream, s, ':')) { LanguageInfo info = ParseLocale(s); AppendLocaleVariants(languages, info); } return languages; } std::vector<FlutterLocale> ConvertToFlutterLocale( const std::vector<LanguageInfo>& languages) { std::vector<FlutterLocale> flutter_locales; flutter_locales.reserve(languages.size()); for (const auto& info : languages) { FlutterLocale locale = {}; locale.struct_size = sizeof(FlutterLocale); locale.language_code = info.language.c_str(); if (!info.territory.empty()) { locale.country_code = info.territory.c_str(); } if (!info.codeset.empty()) { locale.script_code = info.codeset.c_str(); } if (!info.modifier.empty()) { locale.variant_code = info.modifier.c_str(); } flutter_locales.push_back(locale); } return flutter_locales; } } // namespace flutter
engine/shell/platform/glfw/system_utils.cc/0
{ "file_path": "engine/shell/platform/glfw/system_utils.cc", "repo_id": "engine", "token_count": 1643 }
397
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Included first as it collides with the X11 headers. #include "gtest/gtest.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_basic_message_channel.h" #include "flutter/shell/platform/embedder/embedder.h" #include "flutter/shell/platform/embedder/test_utils/proc_table_replacement.h" #include "flutter/shell/platform/linux/fl_binary_messenger_private.h" #include "flutter/shell/platform/linux/fl_engine_private.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_message_codec.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_standard_message_codec.h" #include "flutter/shell/platform/linux/testing/fl_test.h" #include "flutter/shell/platform/linux/testing/mock_renderer.h" // Checks sending a message without a response works. // MOCK_ENGINE_PROC is leaky by design // NOLINTBEGIN(clang-analyzer-core.StackAddressEscape) TEST(FlBasicMessageChannelTest, SendMessageWithoutResponse) { g_autoptr(GMainLoop) loop = g_main_loop_new(nullptr, 0); g_autoptr(FlEngine) engine = make_mock_engine(); FlutterEngineProcTable* embedder_api = fl_engine_get_embedder_api(engine); bool called = false; FlutterEngineSendPlatformMessageFnPtr old_handler = embedder_api->SendPlatformMessage; embedder_api->SendPlatformMessage = MOCK_ENGINE_PROC( SendPlatformMessage, ([&called, old_handler](auto engine, const FlutterPlatformMessage* message) { if (strcmp(message->channel, "test") != 0) { return old_handler(engine, message); } called = true; EXPECT_EQ(message->response_handle, nullptr); g_autoptr(GBytes) message_bytes = g_bytes_new(message->message, message->message_size); g_autoptr(FlStandardMessageCodec) codec = fl_standard_message_codec_new(); FlValue* message_value = fl_message_codec_decode_message( FL_MESSAGE_CODEC(codec), message_bytes, nullptr); EXPECT_EQ(fl_value_get_type(message_value), FL_VALUE_TYPE_STRING); EXPECT_STREQ(fl_value_get_string(message_value), "Hello World!"); return kSuccess; })); FlBinaryMessenger* messenger = fl_binary_messenger_new(engine); g_autoptr(FlStandardMessageCodec) codec = fl_standard_message_codec_new(); g_autoptr(FlBasicMessageChannel) channel = fl_basic_message_channel_new(messenger, "test", FL_MESSAGE_CODEC(codec)); g_autoptr(FlValue) message = fl_value_new_string("Hello World!"); fl_basic_message_channel_send(channel, message, nullptr, nullptr, loop); EXPECT_TRUE(called); } // NOLINTEND(clang-analyzer-core.StackAddressEscape) // Called when the message response is received in the SendMessageWithResponse // test. static void echo_response_cb(GObject* object, GAsyncResult* result, gpointer user_data) { g_autoptr(GError) error = nullptr; g_autoptr(FlValue) message = fl_basic_message_channel_send_finish( FL_BASIC_MESSAGE_CHANNEL(object), result, &error); EXPECT_NE(message, nullptr); EXPECT_EQ(error, nullptr); EXPECT_EQ(fl_value_get_type(message), FL_VALUE_TYPE_STRING); EXPECT_STREQ(fl_value_get_string(message), "Hello World!"); g_main_loop_quit(static_cast<GMainLoop*>(user_data)); } // Checks sending a message with a response works. TEST(FlBasicMessageChannelTest, SendMessageWithResponse) { g_autoptr(GMainLoop) loop = g_main_loop_new(nullptr, 0); g_autoptr(FlEngine) engine = make_mock_engine(); FlBinaryMessenger* messenger = fl_binary_messenger_new(engine); g_autoptr(FlStandardMessageCodec) codec = fl_standard_message_codec_new(); g_autoptr(FlBasicMessageChannel) channel = fl_basic_message_channel_new( messenger, "test/echo", FL_MESSAGE_CODEC(codec)); g_autoptr(FlValue) message = fl_value_new_string("Hello World!"); fl_basic_message_channel_send(channel, message, nullptr, echo_response_cb, loop); // Blocks here until echo_response_cb is called. g_main_loop_run(loop); } // Called when the message response is received in the SendFailure test. static void failure_response_cb(GObject* object, GAsyncResult* result, gpointer user_data) { g_autoptr(GError) error = nullptr; g_autoptr(FlValue) message = fl_basic_message_channel_send_finish( FL_BASIC_MESSAGE_CHANNEL(object), result, &error); EXPECT_EQ(message, nullptr); EXPECT_NE(error, nullptr); g_main_loop_quit(static_cast<GMainLoop*>(user_data)); } // Checks the engine reporting a send failure is handled. TEST(FlBasicMessageChannelTest, SendFailure) { g_autoptr(GMainLoop) loop = g_main_loop_new(nullptr, 0); g_autoptr(FlEngine) engine = make_mock_engine(); FlBinaryMessenger* messenger = fl_binary_messenger_new(engine); g_autoptr(FlStandardMessageCodec) codec = fl_standard_message_codec_new(); g_autoptr(FlBasicMessageChannel) channel = fl_basic_message_channel_new( messenger, "test/failure", FL_MESSAGE_CODEC(codec)); g_autoptr(FlValue) message = fl_value_new_string("Hello World!"); fl_basic_message_channel_send(channel, message, nullptr, failure_response_cb, loop); // Blocks here until failure_response_cb is called. g_main_loop_run(loop); } // Called when a message is received from the engine in the ReceiveMessage test. static void message_cb(FlBasicMessageChannel* channel, FlValue* message, FlBasicMessageChannelResponseHandle* response_handle, gpointer user_data) { EXPECT_NE(message, nullptr); EXPECT_EQ(fl_value_get_type(message), FL_VALUE_TYPE_STRING); EXPECT_STREQ(fl_value_get_string(message), "Marco!"); g_autoptr(GError) error = nullptr; g_autoptr(FlValue) response = fl_value_new_string("Polo!"); EXPECT_TRUE(fl_basic_message_channel_respond(channel, response_handle, response, &error)); EXPECT_EQ(error, nullptr); } // Called when a the test engine notifies us what response we sent in the // ReceiveMessage test. static void response_cb(FlBasicMessageChannel* channel, FlValue* message, FlBasicMessageChannelResponseHandle* response_handle, gpointer user_data) { EXPECT_NE(message, nullptr); EXPECT_EQ(fl_value_get_type(message), FL_VALUE_TYPE_STRING); EXPECT_STREQ(fl_value_get_string(message), "Polo!"); fl_basic_message_channel_respond(channel, response_handle, nullptr, nullptr); g_main_loop_quit(static_cast<GMainLoop*>(user_data)); } // Checks the shell able to receive and respond to messages from the engine. TEST(FlBasicMessageChannelTest, ReceiveMessage) { g_autoptr(GMainLoop) loop = g_main_loop_new(nullptr, 0); g_autoptr(FlEngine) engine = make_mock_engine(); FlBinaryMessenger* messenger = fl_binary_messenger_new(engine); // Listen for messages from the engine. g_autoptr(FlStandardMessageCodec) codec = fl_standard_message_codec_new(); g_autoptr(FlBasicMessageChannel) messages_channel = fl_basic_message_channel_new(messenger, "test/messages", FL_MESSAGE_CODEC(codec)); fl_basic_message_channel_set_message_handler(messages_channel, message_cb, nullptr, nullptr); // Listen for response from the engine. g_autoptr(FlBasicMessageChannel) responses_channel = fl_basic_message_channel_new(messenger, "test/responses", FL_MESSAGE_CODEC(codec)); fl_basic_message_channel_set_message_handler(responses_channel, response_cb, loop, nullptr); // Triggger the engine to send a message. g_autoptr(FlBasicMessageChannel) control_channel = fl_basic_message_channel_new(messenger, "test/send-message", FL_MESSAGE_CODEC(codec)); g_autoptr(FlValue) message = fl_value_new_string("Marco!"); fl_basic_message_channel_send(control_channel, message, nullptr, nullptr, nullptr); // Blocks here until response_cb is called. g_main_loop_run(loop); } // Called when the message response is received in the // SendNullMessageWithResponse test. static void null_message_response_cb(GObject* object, GAsyncResult* result, gpointer user_data) { g_autoptr(GError) error = nullptr; g_autoptr(FlValue) message = fl_basic_message_channel_send_finish( FL_BASIC_MESSAGE_CHANNEL(object), result, &error); EXPECT_NE(message, nullptr); EXPECT_EQ(error, nullptr); EXPECT_EQ(fl_value_get_type(message), FL_VALUE_TYPE_NULL); g_main_loop_quit(static_cast<GMainLoop*>(user_data)); } // Checks sending a null message with a response works. TEST(FlBasicMessageChannelTest, SendNullMessageWithResponse) { g_autoptr(GMainLoop) loop = g_main_loop_new(nullptr, 0); g_autoptr(FlEngine) engine = make_mock_engine(); FlBinaryMessenger* messenger = fl_binary_messenger_new(engine); g_autoptr(FlStandardMessageCodec) codec = fl_standard_message_codec_new(); g_autoptr(FlBasicMessageChannel) channel = fl_basic_message_channel_new( messenger, "test/echo", FL_MESSAGE_CODEC(codec)); fl_basic_message_channel_send(channel, nullptr, nullptr, null_message_response_cb, loop); // Blocks here until null_message_response_cb is called. g_main_loop_run(loop); }
engine/shell/platform/linux/fl_basic_message_channel_test.cc/0
{ "file_path": "engine/shell/platform/linux/fl_basic_message_channel_test.cc", "repo_id": "engine", "token_count": 3947 }
398
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/linux/fl_gnome_settings.h" #include "flutter/shell/platform/linux/testing/fl_test.h" #include "flutter/shell/platform/linux/testing/mock_settings.h" #include "flutter/shell/platform/linux/testing/mock_signal_handler.h" #include "flutter/testing/testing.h" #include <gio/gio.h> #define G_SETTINGS_ENABLE_BACKEND #include <gio/gsettingsbackend.h> #include "gmock/gmock.h" #include "gtest/gtest.h" class FlGnomeSettingsTest : public ::testing::Test { protected: void SetUp() override { // force _g_io_modules_ensure_extension_points_registered() to get called g_settings_backend_get_default(); } }; static GSettings* create_settings(const gchar* name, const gchar* schema_id) { g_autofree gchar* path = g_build_filename(flutter::testing::GetFixturesPath(), name, nullptr); g_autoptr(GSettingsSchemaSource) source = g_settings_schema_source_new_from_directory(path, nullptr, false, nullptr); g_autoptr(GSettingsSchema) schema = g_settings_schema_source_lookup(source, schema_id, false); g_autoptr(GSettingsBackend) backend = g_memory_settings_backend_new(); return g_settings_new_full(schema, backend, nullptr); } TEST_F(FlGnomeSettingsTest, ClockFormat) { g_autoptr(GSettings) interface_settings = create_settings("ubuntu-20.04", "org.gnome.desktop.interface"); g_settings_set_string(interface_settings, "clock-format", "24h"); g_autoptr(FlSettings) settings = FL_SETTINGS( g_object_new(fl_gnome_settings_get_type(), "interface_settings", interface_settings, nullptr)); EXPECT_EQ(fl_settings_get_clock_format(settings), FL_CLOCK_FORMAT_24H); flutter::testing::MockSignalHandler settings_changed(settings, "changed"); EXPECT_SIGNAL(settings_changed).Times(1); g_settings_set_string(interface_settings, "clock-format", "12h"); EXPECT_EQ(fl_settings_get_clock_format(settings), FL_CLOCK_FORMAT_12H); } TEST_F(FlGnomeSettingsTest, GtkTheme) { g_autoptr(GSettings) interface_settings = create_settings("ubuntu-20.04", "org.gnome.desktop.interface"); g_settings_set_string(interface_settings, "gtk-theme", "Yaru"); g_autoptr(FlSettings) settings = FL_SETTINGS( g_object_new(fl_gnome_settings_get_type(), "interface_settings", interface_settings, nullptr)); EXPECT_EQ(fl_settings_get_color_scheme(settings), FL_COLOR_SCHEME_LIGHT); flutter::testing::MockSignalHandler settings_changed(settings, "changed"); EXPECT_SIGNAL(settings_changed).Times(1); g_settings_set_string(interface_settings, "gtk-theme", "Yaru-dark"); EXPECT_EQ(fl_settings_get_color_scheme(settings), FL_COLOR_SCHEME_DARK); } TEST_F(FlGnomeSettingsTest, EnableAnimations) { g_autoptr(FlSettings) settings = fl_gnome_settings_new(); EXPECT_TRUE(fl_settings_get_enable_animations(settings)); } TEST_F(FlGnomeSettingsTest, HighContrast) { g_autoptr(FlSettings) settings = fl_gnome_settings_new(); EXPECT_FALSE(fl_settings_get_high_contrast(settings)); } TEST_F(FlGnomeSettingsTest, TextScalingFactor) { g_autoptr(GSettings) interface_settings = create_settings("ubuntu-20.04", "org.gnome.desktop.interface"); g_settings_set_double(interface_settings, "text-scaling-factor", 1.0); g_autoptr(FlSettings) settings = FL_SETTINGS( g_object_new(fl_gnome_settings_get_type(), "interface_settings", interface_settings, nullptr)); EXPECT_EQ(fl_settings_get_text_scaling_factor(settings), 1.0); flutter::testing::MockSignalHandler settings_changed(settings, "changed"); EXPECT_SIGNAL(settings_changed).Times(1); g_settings_set_double(interface_settings, "text-scaling-factor", 1.5); EXPECT_EQ(fl_settings_get_text_scaling_factor(settings), 1.5); } TEST_F(FlGnomeSettingsTest, SignalHandlers) { g_autoptr(GSettings) interface_settings = create_settings("ubuntu-20.04", "org.gnome.desktop.interface"); g_autoptr(FlSettings) settings = FL_SETTINGS( g_object_new(fl_gnome_settings_get_type(), "interface_settings", interface_settings, nullptr)); flutter::testing::MockSignalHandler settings_changed(settings, "changed"); EXPECT_SIGNAL(settings_changed).Times(3); g_settings_set_string(interface_settings, "clock-format", "12h"); g_settings_set_string(interface_settings, "gtk-theme", "Yaru-dark"); g_settings_set_double(interface_settings, "text-scaling-factor", 1.5); EXPECT_SIGNAL(settings_changed).Times(0); g_clear_object(&settings); // destroyed FlSettings object must have disconnected its signal handlers g_settings_set_string(interface_settings, "clock-format", "24h"); g_settings_set_string(interface_settings, "gtk-theme", "Yaru"); g_settings_set_double(interface_settings, "text-scaling-factor", 2.0); }
engine/shell/platform/linux/fl_gnome_settings_test.cc/0
{ "file_path": "engine/shell/platform/linux/fl_gnome_settings_test.cc", "repo_id": "engine", "token_count": 1863 }
399
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/linux/fl_keyboard_manager.h" #include <array> #include <cinttypes> #include <memory> #include <string> #include "flutter/shell/platform/linux/fl_key_channel_responder.h" #include "flutter/shell/platform/linux/fl_key_embedder_responder.h" #include "flutter/shell/platform/linux/key_mapping.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_method_channel.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_standard_method_codec.h" // Turn on this flag to print complete layout data when switching IMEs. The data // is used in unit tests. #define DEBUG_PRINT_LAYOUT static constexpr char kChannelName[] = "flutter/keyboard"; static constexpr char kGetKeyboardStateMethod[] = "getKeyboardState"; /* Declarations of private classes */ G_DECLARE_FINAL_TYPE(FlKeyboardPendingEvent, fl_keyboard_pending_event, FL, KEYBOARD_PENDING_EVENT, GObject); #define FL_TYPE_KEYBOARD_MANAGER_USER_DATA \ fl_keyboard_manager_user_data_get_type() G_DECLARE_FINAL_TYPE(FlKeyboardManagerUserData, fl_keyboard_manager_user_data, FL, KEYBOARD_MANAGER_USER_DATA, GObject); /* End declarations */ namespace { // The maxiumum keycode in a derived layout. // // Although X supports higher keycodes, Flutter only cares about standard keys, // which are below this. constexpr size_t kLayoutSize = 128; // Describes the derived layout of a keyboard group. // // Maps from keycode to logical key. Value being 0 stands for empty. typedef std::array<uint64_t, kLayoutSize> DerivedGroupLayout; // Describes the derived layout of the entire keyboard. // // Maps from group ID to group layout. typedef std::map<guint8, DerivedGroupLayout> DerivedLayout; // Context variables for the foreach call used to dispatch events to responders. typedef struct { FlKeyEvent* event; uint64_t specified_logical_key; FlKeyboardManagerUserData* user_data; } DispatchToResponderLoopContext; bool is_eascii(uint16_t character) { return character < 256; } #ifdef DEBUG_PRINT_LAYOUT // Prints layout entries that will be parsed by `MockLayoutData`. void debug_format_layout_data(std::string& debug_layout_data, uint16_t keycode, uint16_t clue1, uint16_t clue2) { if (keycode % 4 == 0) { debug_layout_data.append(" "); } constexpr int kBufferSize = 30; char buffer[kBufferSize]; buffer[0] = 0; buffer[kBufferSize - 1] = 0; snprintf(buffer, kBufferSize, "0x%04x, 0x%04x, ", clue1, clue2); debug_layout_data.append(buffer); if (keycode % 4 == 3) { snprintf(buffer, kBufferSize, " // 0x%02x", keycode); debug_layout_data.append(buffer); } } #endif } // namespace static uint64_t get_logical_key_from_layout(const FlKeyEvent* event, const DerivedLayout& layout) { guint8 group = event->group; guint16 keycode = event->keycode; if (keycode >= kLayoutSize) { return 0; } auto found_group_layout = layout.find(group); if (found_group_layout != layout.end()) { return found_group_layout->second[keycode]; } return 0; } /* Define FlKeyboardPendingEvent */ /** * FlKeyboardPendingEvent: * A record for events that have been received by the manager, but * dispatched to other objects, whose results have yet to return. * * This object is used by both the "pending_responds" list and the * "pending_redispatches" list. */ struct _FlKeyboardPendingEvent { GObject parent_instance; // The target event. // // This is freed by #FlKeyboardPendingEvent if not null. std::unique_ptr<FlKeyEvent> event; // Self-incrementing ID attached to an event sent to the framework. // // Used to identify pending responds. uint64_t sequence_id; // The number of responders that haven't replied. size_t unreplied; // Whether any replied responders reported true (handled). bool any_handled; // A value calculated out of critical event information that can be used // to identify redispatched events. uint64_t hash; }; G_DEFINE_TYPE(FlKeyboardPendingEvent, fl_keyboard_pending_event, G_TYPE_OBJECT) static void fl_keyboard_pending_event_dispose(GObject* object) { // Redundant, but added so that we don't get a warning about unused function // for FL_IS_KEYBOARD_PENDING_EVENT. g_return_if_fail(FL_IS_KEYBOARD_PENDING_EVENT(object)); FlKeyboardPendingEvent* self = FL_KEYBOARD_PENDING_EVENT(object); if (self->event != nullptr) { fl_key_event_dispose(self->event.release()); } G_OBJECT_CLASS(fl_keyboard_pending_event_parent_class)->dispose(object); } static void fl_keyboard_pending_event_class_init( FlKeyboardPendingEventClass* klass) { G_OBJECT_CLASS(klass)->dispose = fl_keyboard_pending_event_dispose; } static void fl_keyboard_pending_event_init(FlKeyboardPendingEvent* self) {} // Calculates a unique ID for a given FlKeyEvent object to use for // identification of responses from the framework. static uint64_t fl_keyboard_manager_get_event_hash(FlKeyEvent* event) { // Combine the event timestamp, the type of event, and the hardware keycode // (scan code) of the event to come up with a unique id for this event that // can be derived solely from the event data itself, so that we can identify // whether or not we have seen this event already. guint64 type = static_cast<uint64_t>(event->is_press ? GDK_KEY_PRESS : GDK_KEY_RELEASE); guint64 keycode = static_cast<uint64_t>(event->keycode); return (event->time & 0xffffffff) | ((type & 0xffff) << 32) | ((keycode & 0xffff) << 48); } // Create a new FlKeyboardPendingEvent by providing the target event, // the sequence ID, and the number of responders that will reply. // // This will acquire the ownership of the event. static FlKeyboardPendingEvent* fl_keyboard_pending_event_new( std::unique_ptr<FlKeyEvent> event, uint64_t sequence_id, size_t to_reply) { FlKeyboardPendingEvent* self = FL_KEYBOARD_PENDING_EVENT( g_object_new(fl_keyboard_pending_event_get_type(), nullptr)); self->event = std::move(event); self->sequence_id = sequence_id; self->unreplied = to_reply; self->any_handled = false; self->hash = fl_keyboard_manager_get_event_hash(self->event.get()); return self; } /* Define FlKeyboardManagerUserData */ /** * FlKeyboardManagerUserData: * The user_data used when #FlKeyboardManager sends event to * responders. */ struct _FlKeyboardManagerUserData { GObject parent_instance; // A weak reference to the owner manager. FlKeyboardManager* manager; uint64_t sequence_id; }; G_DEFINE_TYPE(FlKeyboardManagerUserData, fl_keyboard_manager_user_data, G_TYPE_OBJECT) static void fl_keyboard_manager_user_data_dispose(GObject* object) { g_return_if_fail(FL_IS_KEYBOARD_MANAGER_USER_DATA(object)); FlKeyboardManagerUserData* self = FL_KEYBOARD_MANAGER_USER_DATA(object); if (self->manager != nullptr) { g_object_remove_weak_pointer(G_OBJECT(self->manager), reinterpret_cast<gpointer*>(&(self->manager))); self->manager = nullptr; } } static void fl_keyboard_manager_user_data_class_init( FlKeyboardManagerUserDataClass* klass) { G_OBJECT_CLASS(klass)->dispose = fl_keyboard_manager_user_data_dispose; } static void fl_keyboard_manager_user_data_init( FlKeyboardManagerUserData* self) {} // Creates a new FlKeyboardManagerUserData private class with all information. static FlKeyboardManagerUserData* fl_keyboard_manager_user_data_new( FlKeyboardManager* manager, uint64_t sequence_id) { FlKeyboardManagerUserData* self = FL_KEYBOARD_MANAGER_USER_DATA( g_object_new(fl_keyboard_manager_user_data_get_type(), nullptr)); self->manager = manager; // Add a weak pointer so we can know if the key event responder disappeared // while the framework was responding. g_object_add_weak_pointer(G_OBJECT(manager), reinterpret_cast<gpointer*>(&(self->manager))); self->sequence_id = sequence_id; return self; } /* Define FlKeyboardManager */ struct _FlKeyboardManager { GObject parent_instance; FlKeyboardViewDelegate* view_delegate; // An array of #FlKeyResponder. Elements are added with // #fl_keyboard_manager_add_responder immediately after initialization and are // automatically released on dispose. GPtrArray* responder_list; // An array of #FlKeyboardPendingEvent. // // Its elements are *not* unreferenced when removed. When FlKeyboardManager is // disposed, this array will be set with a free_func so that the elements are // unreferenced when removed. GPtrArray* pending_responds; // An array of #FlKeyboardPendingEvent. // // Its elements are unreferenced when removed. GPtrArray* pending_redispatches; // The last sequence ID used. Increased by 1 by every use. uint64_t last_sequence_id; // Record the derived layout. // // It is cleared when the platform reports a layout switch. Each entry, // which corresponds to a group, is only initialized on the arrival of the // first event for that group that has a goal keycode. std::unique_ptr<DerivedLayout> derived_layout; // A static map from keycodes to all layout goals. // // It is set up when the manager is initialized and is not changed ever after. std::unique_ptr<std::map<uint16_t, const LayoutGoal*>> keycode_to_goals; // A static map from logical keys to all mandatory layout goals. // // It is set up when the manager is initialized and is not changed ever after. std::unique_ptr<std::map<uint64_t, const LayoutGoal*>> logical_to_mandatory_goals; // The channel used by the framework to query the keyboard pressed state. FlMethodChannel* channel; }; G_DEFINE_TYPE(FlKeyboardManager, fl_keyboard_manager, G_TYPE_OBJECT); static void fl_keyboard_manager_dispose(GObject* object); static void fl_keyboard_manager_class_init(FlKeyboardManagerClass* klass) { G_OBJECT_CLASS(klass)->dispose = fl_keyboard_manager_dispose; } static void fl_keyboard_manager_init(FlKeyboardManager* self) { self->derived_layout = std::make_unique<DerivedLayout>(); self->keycode_to_goals = std::make_unique<std::map<uint16_t, const LayoutGoal*>>(); self->logical_to_mandatory_goals = std::make_unique<std::map<uint64_t, const LayoutGoal*>>(); for (const LayoutGoal& goal : layout_goals) { (*self->keycode_to_goals)[goal.keycode] = &goal; if (goal.mandatory) { (*self->logical_to_mandatory_goals)[goal.logical_key] = &goal; } } self->responder_list = g_ptr_array_new_with_free_func(g_object_unref); self->pending_responds = g_ptr_array_new(); self->pending_redispatches = g_ptr_array_new_with_free_func(g_object_unref); self->last_sequence_id = 1; } static void fl_keyboard_manager_dispose(GObject* object) { FlKeyboardManager* self = FL_KEYBOARD_MANAGER(object); if (self->view_delegate != nullptr) { fl_keyboard_view_delegate_subscribe_to_layout_change(self->view_delegate, nullptr); g_object_remove_weak_pointer( G_OBJECT(self->view_delegate), reinterpret_cast<gpointer*>(&(self->view_delegate))); self->view_delegate = nullptr; } self->derived_layout.reset(); self->keycode_to_goals.reset(); self->logical_to_mandatory_goals.reset(); g_ptr_array_free(self->responder_list, TRUE); g_ptr_array_set_free_func(self->pending_responds, g_object_unref); g_ptr_array_free(self->pending_responds, TRUE); g_ptr_array_free(self->pending_redispatches, TRUE); G_OBJECT_CLASS(fl_keyboard_manager_parent_class)->dispose(object); } /* Implement FlKeyboardManager */ // This is an exact copy of g_ptr_array_find_with_equal_func. Somehow CI // reports that can not find symbol g_ptr_array_find_with_equal_func, despite // the fact that it runs well locally. static gboolean g_ptr_array_find_with_equal_func1(GPtrArray* haystack, gconstpointer needle, GEqualFunc equal_func, guint* index_) { guint i; g_return_val_if_fail(haystack != NULL, FALSE); if (equal_func == NULL) { equal_func = g_direct_equal; } for (i = 0; i < haystack->len; i++) { if (equal_func(g_ptr_array_index(haystack, i), needle)) { if (index_ != NULL) { *index_ = i; } return TRUE; } } return FALSE; } // Compare a #FlKeyboardPendingEvent with the given sequence_id. The needle // should be a pointer to uint64_t sequence_id. static gboolean compare_pending_by_sequence_id( gconstpointer pending, gconstpointer needle_sequence_id) { uint64_t sequence_id = *reinterpret_cast<const uint64_t*>(needle_sequence_id); return static_cast<const FlKeyboardPendingEvent*>(pending)->sequence_id == sequence_id; } // Compare a #FlKeyboardPendingEvent with the given hash. The #needle should be // a pointer to uint64_t hash. static gboolean compare_pending_by_hash(gconstpointer pending, gconstpointer needle_hash) { uint64_t hash = *reinterpret_cast<const uint64_t*>(needle_hash); return static_cast<const FlKeyboardPendingEvent*>(pending)->hash == hash; } // Try to remove a pending event from `pending_redispatches` with the target // hash. // // Returns true if the event is found and removed. static bool fl_keyboard_manager_remove_redispatched(FlKeyboardManager* self, uint64_t hash) { guint result_index; gboolean found = g_ptr_array_find_with_equal_func1( self->pending_redispatches, static_cast<const uint64_t*>(&hash), compare_pending_by_hash, &result_index); if (found) { // The removed object is freed due to `pending_redispatches`'s free_func. g_ptr_array_remove_index_fast(self->pending_redispatches, result_index); return TRUE; } else { return FALSE; } } // The callback used by a responder after the event was dispatched. static void responder_handle_event_callback(bool handled, gpointer user_data_ptr) { g_return_if_fail(FL_IS_KEYBOARD_MANAGER_USER_DATA(user_data_ptr)); FlKeyboardManagerUserData* user_data = FL_KEYBOARD_MANAGER_USER_DATA(user_data_ptr); FlKeyboardManager* self = user_data->manager; g_return_if_fail(self->view_delegate != nullptr); guint result_index = -1; gboolean found = g_ptr_array_find_with_equal_func1( self->pending_responds, &user_data->sequence_id, compare_pending_by_sequence_id, &result_index); g_return_if_fail(found); FlKeyboardPendingEvent* pending = FL_KEYBOARD_PENDING_EVENT( g_ptr_array_index(self->pending_responds, result_index)); g_return_if_fail(pending != nullptr); g_return_if_fail(pending->unreplied > 0); pending->unreplied -= 1; pending->any_handled = pending->any_handled || handled; // All responders have replied. if (pending->unreplied == 0) { g_object_unref(user_data_ptr); gpointer removed = g_ptr_array_remove_index_fast(self->pending_responds, result_index); g_return_if_fail(removed == pending); bool should_redispatch = !pending->any_handled && !fl_keyboard_view_delegate_text_filter_key_press( self->view_delegate, pending->event.get()); if (should_redispatch) { g_ptr_array_add(self->pending_redispatches, pending); fl_keyboard_view_delegate_redispatch_event(self->view_delegate, std::move(pending->event)); } else { g_object_unref(pending); } } } static uint16_t convert_key_to_char(FlKeyboardViewDelegate* view_delegate, guint keycode, gint group, gint level) { GdkKeymapKey key = {keycode, group, level}; constexpr int kBmpMax = 0xD7FF; guint origin = fl_keyboard_view_delegate_lookup_key(view_delegate, &key); return origin < kBmpMax ? origin : 0xFFFF; } // Make sure that Flutter has derived the layout for the group of the event, // if the event contains a goal keycode. static void guarantee_layout(FlKeyboardManager* self, FlKeyEvent* event) { guint8 group = event->group; if (self->derived_layout->find(group) != self->derived_layout->end()) { return; } if (self->keycode_to_goals->find(event->keycode) == self->keycode_to_goals->end()) { return; } DerivedGroupLayout& layout = (*self->derived_layout)[group]; // Clone all mandatory goals. Each goal is removed from this cloned map when // fulfilled, and the remaining ones will be assigned to a default position. std::map<uint64_t, const LayoutGoal*> remaining_mandatory_goals = *self->logical_to_mandatory_goals; #ifdef DEBUG_PRINT_LAYOUT std::string debug_layout_data; for (uint16_t keycode = 0; keycode < 128; keycode += 1) { std::vector<uint16_t> this_key_clues = { convert_key_to_char(self->view_delegate, keycode, group, 0), convert_key_to_char(self->view_delegate, keycode, group, 1), // Shift }; debug_format_layout_data(debug_layout_data, keycode, this_key_clues[0], this_key_clues[1]); } #endif // It's important to only traverse layout goals instead of all keycodes. // Some key codes outside of the standard keyboard also gives alpha-numeric // letters, and will therefore take over mandatory goals from standard // keyboard keys if they come first. Example: French keyboard digit 1. for (const LayoutGoal& keycode_goal : layout_goals) { uint16_t keycode = keycode_goal.keycode; std::vector<uint16_t> this_key_clues = { convert_key_to_char(self->view_delegate, keycode, group, 0), convert_key_to_char(self->view_delegate, keycode, group, 1), // Shift }; // The logical key should be the first available clue from below: // // - Mandatory goal, if it matches any clue. This ensures that all alnum // keys can be found somewhere. // - US layout, if neither clue of the key is EASCII. This ensures that // there are no non-latin logical keys. // - A value derived on the fly from keycode & keyval. for (uint16_t clue : this_key_clues) { auto matching_goal = remaining_mandatory_goals.find(clue); if (matching_goal != remaining_mandatory_goals.end()) { // Found a key that produces a mandatory char. Use it. g_return_if_fail(layout[keycode] == 0); layout[keycode] = clue; remaining_mandatory_goals.erase(matching_goal); break; } } bool has_any_eascii = is_eascii(this_key_clues[0]) || is_eascii(this_key_clues[1]); // See if any produced char meets the requirement as a logical key. if (layout[keycode] == 0 && !has_any_eascii) { auto found_us_layout = self->keycode_to_goals->find(keycode); if (found_us_layout != self->keycode_to_goals->end()) { layout[keycode] = found_us_layout->second->logical_key; } } } // Ensure all mandatory goals are assigned. for (const auto mandatory_goal_iter : remaining_mandatory_goals) { const LayoutGoal* goal = mandatory_goal_iter.second; layout[goal->keycode] = goal->logical_key; } } // Returns the keyboard pressed state. FlMethodResponse* get_keyboard_state(FlKeyboardManager* self) { g_autoptr(FlValue) result = fl_value_new_map(); GHashTable* pressing_records = fl_keyboard_view_delegate_get_keyboard_state(self->view_delegate); g_hash_table_foreach( pressing_records, [](gpointer key, gpointer value, gpointer user_data) { int64_t physical_key = reinterpret_cast<int64_t>(key); int64_t logical_key = reinterpret_cast<int64_t>(value); FlValue* fl_value_map = reinterpret_cast<FlValue*>(user_data); fl_value_set_take(fl_value_map, fl_value_new_int(physical_key), fl_value_new_int(logical_key)); }, result); return FL_METHOD_RESPONSE(fl_method_success_response_new(result)); } // Called when a method call on flutter/keyboard is received from Flutter. static void method_call_handler(FlMethodChannel* channel, FlMethodCall* method_call, gpointer user_data) { FlKeyboardManager* self = FL_KEYBOARD_MANAGER(user_data); const gchar* method = fl_method_call_get_name(method_call); g_autoptr(FlMethodResponse) response = nullptr; if (strcmp(method, kGetKeyboardStateMethod) == 0) { response = get_keyboard_state(self); } 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); } } FlKeyboardManager* fl_keyboard_manager_new( FlBinaryMessenger* messenger, FlKeyboardViewDelegate* view_delegate) { g_return_val_if_fail(FL_IS_KEYBOARD_VIEW_DELEGATE(view_delegate), nullptr); FlKeyboardManager* self = FL_KEYBOARD_MANAGER( g_object_new(fl_keyboard_manager_get_type(), nullptr)); self->view_delegate = view_delegate; g_object_add_weak_pointer( G_OBJECT(view_delegate), reinterpret_cast<gpointer*>(&(self->view_delegate))); // The embedder responder must be added before the channel responder. g_ptr_array_add( self->responder_list, FL_KEY_RESPONDER(fl_key_embedder_responder_new( [](const FlutterKeyEvent* event, FlutterKeyEventCallback callback, void* callback_user_data, void* send_key_event_user_data) { FlKeyboardManager* self = FL_KEYBOARD_MANAGER(send_key_event_user_data); g_return_if_fail(self->view_delegate != nullptr); fl_keyboard_view_delegate_send_key_event( self->view_delegate, event, callback, callback_user_data); }, self))); g_ptr_array_add(self->responder_list, FL_KEY_RESPONDER(fl_key_channel_responder_new( fl_keyboard_view_delegate_get_messenger(view_delegate)))); fl_keyboard_view_delegate_subscribe_to_layout_change( self->view_delegate, [self]() { self->derived_layout->clear(); }); // Setup the flutter/keyboard channel. g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); self->channel = fl_method_channel_new(messenger, kChannelName, FL_METHOD_CODEC(codec)); fl_method_channel_set_method_call_handler(self->channel, method_call_handler, self, nullptr); return self; } // The loop body to dispatch an event to a responder. static void dispatch_to_responder(gpointer responder_data, gpointer foreach_data_ptr) { DispatchToResponderLoopContext* context = reinterpret_cast<DispatchToResponderLoopContext*>(foreach_data_ptr); FlKeyResponder* responder = FL_KEY_RESPONDER(responder_data); fl_key_responder_handle_event( responder, context->event, responder_handle_event_callback, context->user_data, context->specified_logical_key); } gboolean fl_keyboard_manager_handle_event(FlKeyboardManager* self, FlKeyEvent* event) { g_return_val_if_fail(FL_IS_KEYBOARD_MANAGER(self), FALSE); g_return_val_if_fail(event != nullptr, FALSE); g_return_val_if_fail(self->view_delegate != nullptr, FALSE); guarantee_layout(self, event); uint64_t incoming_hash = fl_keyboard_manager_get_event_hash(event); if (fl_keyboard_manager_remove_redispatched(self, incoming_hash)) { return FALSE; } FlKeyboardPendingEvent* pending = fl_keyboard_pending_event_new( std::unique_ptr<FlKeyEvent>(event), ++self->last_sequence_id, self->responder_list->len); g_ptr_array_add(self->pending_responds, pending); FlKeyboardManagerUserData* user_data = fl_keyboard_manager_user_data_new(self, pending->sequence_id); DispatchToResponderLoopContext data{ .event = event, .specified_logical_key = get_logical_key_from_layout(event, *self->derived_layout), .user_data = user_data, }; g_ptr_array_foreach(self->responder_list, dispatch_to_responder, &data); return TRUE; } gboolean fl_keyboard_manager_is_state_clear(FlKeyboardManager* self) { g_return_val_if_fail(FL_IS_KEYBOARD_MANAGER(self), FALSE); return self->pending_responds->len == 0 && self->pending_redispatches->len == 0; } void fl_keyboard_manager_sync_modifier_if_needed(FlKeyboardManager* self, guint state, double event_time) { g_return_if_fail(FL_IS_KEYBOARD_MANAGER(self)); // The embedder responder is the first element in // FlKeyboardManager.responder_list. FlKeyEmbedderResponder* responder = FL_KEY_EMBEDDER_RESPONDER(g_ptr_array_index(self->responder_list, 0)); fl_key_embedder_responder_sync_modifiers_if_needed(responder, state, event_time); } GHashTable* fl_keyboard_manager_get_pressed_state(FlKeyboardManager* self) { g_return_val_if_fail(FL_IS_KEYBOARD_MANAGER(self), nullptr); // The embedder responder is the first element in // FlKeyboardManager.responder_list. FlKeyEmbedderResponder* responder = FL_KEY_EMBEDDER_RESPONDER(g_ptr_array_index(self->responder_list, 0)); return fl_key_embedder_responder_get_pressed_state(responder); }
engine/shell/platform/linux/fl_keyboard_manager.cc/0
{ "file_path": "engine/shell/platform/linux/fl_keyboard_manager.cc", "repo_id": "engine", "token_count": 10241 }
400
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/linux/public/flutter_linux/fl_method_response.h" #include "gtest/gtest.h" TEST(FlMethodResponseTest, Success) { g_autoptr(FlValue) result = fl_value_new_int(42); g_autoptr(FlMethodSuccessResponse) response = fl_method_success_response_new(result); g_autoptr(FlValue) expected = fl_value_new_int(42); ASSERT_TRUE(fl_value_equal(fl_method_success_response_get_result(response), expected)); } TEST(FlMethodResponseTest, Error) { g_autoptr(FlMethodErrorResponse) response = fl_method_error_response_new("code", nullptr, nullptr); EXPECT_STREQ(fl_method_error_response_get_code(response), "code"); EXPECT_EQ(fl_method_error_response_get_message(response), nullptr); EXPECT_EQ(fl_method_error_response_get_details(response), nullptr); } TEST(FlMethodResponseTest, ErrorMessage) { g_autoptr(FlMethodErrorResponse) response = fl_method_error_response_new("code", "message", nullptr); EXPECT_STREQ(fl_method_error_response_get_code(response), "code"); EXPECT_STREQ(fl_method_error_response_get_message(response), "message"); EXPECT_EQ(fl_method_error_response_get_details(response), nullptr); } TEST(FlMethodResponseTest, ErrorDetails) { g_autoptr(FlValue) details = fl_value_new_int(42); g_autoptr(FlMethodErrorResponse) response = fl_method_error_response_new("code", nullptr, details); EXPECT_STREQ(fl_method_error_response_get_code(response), "code"); EXPECT_EQ(fl_method_error_response_get_message(response), nullptr); g_autoptr(FlValue) expected_details = fl_value_new_int(42); EXPECT_TRUE(fl_value_equal(fl_method_error_response_get_details(response), expected_details)); } TEST(FlMethodResponseTest, ErrorMessageAndDetails) { g_autoptr(FlValue) details = fl_value_new_int(42); g_autoptr(FlMethodErrorResponse) response = fl_method_error_response_new("code", "message", details); EXPECT_STREQ(fl_method_error_response_get_code(response), "code"); EXPECT_STREQ(fl_method_error_response_get_message(response), "message"); g_autoptr(FlValue) expected_details = fl_value_new_int(42); EXPECT_TRUE(fl_value_equal(fl_method_error_response_get_details(response), expected_details)); } TEST(FlMethodResponseTest, NotImplemented) { g_autoptr(FlMethodNotImplementedResponse) response = fl_method_not_implemented_response_new(); // Trivial check to stop the compiler deciding that 'response' is an unused // variable. EXPECT_TRUE(FL_IS_METHOD_NOT_IMPLEMENTED_RESPONSE(response)); } TEST(FlMethodResponseTest, SuccessGetResult) { g_autoptr(FlValue) r = fl_value_new_int(42); g_autoptr(FlMethodSuccessResponse) response = fl_method_success_response_new(r); g_autoptr(GError) error = nullptr; FlValue* result = fl_method_response_get_result(FL_METHOD_RESPONSE(response), &error); ASSERT_NE(result, nullptr); EXPECT_EQ(error, nullptr); g_autoptr(FlValue) expected = fl_value_new_int(42); ASSERT_TRUE(fl_value_equal(result, expected)); } TEST(FlMethodResponseTest, ErrorGetResult) { g_autoptr(FlMethodErrorResponse) response = fl_method_error_response_new("code", nullptr, nullptr); g_autoptr(GError) error = nullptr; g_autoptr(FlValue) result = fl_method_response_get_result(FL_METHOD_RESPONSE(response), &error); EXPECT_EQ(result, nullptr); EXPECT_TRUE(g_error_matches(error, FL_METHOD_RESPONSE_ERROR, FL_METHOD_RESPONSE_ERROR_REMOTE_ERROR)); } TEST(FlMethodResponseTest, NotImplementedGetResult) { g_autoptr(FlMethodNotImplementedResponse) response = fl_method_not_implemented_response_new(); g_autoptr(GError) error = nullptr; g_autoptr(FlValue) result = fl_method_response_get_result(FL_METHOD_RESPONSE(response), &error); EXPECT_EQ(result, nullptr); EXPECT_TRUE(g_error_matches(error, FL_METHOD_RESPONSE_ERROR, FL_METHOD_RESPONSE_ERROR_NOT_IMPLEMENTED)); }
engine/shell/platform/linux/fl_method_response_test.cc/0
{ "file_path": "engine/shell/platform/linux/fl_method_response_test.cc", "repo_id": "engine", "token_count": 1639 }
401
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_LINUX_FL_RENDERER_GDK_H_ #define FLUTTER_SHELL_PLATFORM_LINUX_FL_RENDERER_GDK_H_ #include "flutter/shell/platform/linux/fl_renderer.h" G_BEGIN_DECLS G_DECLARE_FINAL_TYPE(FlRendererGdk, fl_renderer_gdk, FL, RENDERER_GDK, FlRenderer) /** * FlRendererGdk: * * #FlRendererGdk is an implementation of #FlRenderer that renders by OpenGL ES. */ /** * fl_renderer_gdk_new: * @window: the window that is being rendered on. * * Creates an object that allows Flutter to render by OpenGL ES. * * Returns: a new #FlRendererGdk. */ FlRendererGdk* fl_renderer_gdk_new(GdkWindow* window); /** * fl_renderer_gdk_create_contexts: * @renderer: an #FlRendererGdk. * @error: (allow-none): #GError location to store the error occurring, or * %NULL to ignore. * * Create rendering contexts. * * Returns: %TRUE if contexts were created, %FALSE if there was an error. */ gboolean fl_renderer_gdk_create_contexts(FlRendererGdk* renderer, GError** error); /** * fl_renderer_gdk_get_context: * @renderer: an #FlRendererGdk. * * Returns: the main context used for rendering. */ GdkGLContext* fl_renderer_gdk_get_context(FlRendererGdk* renderer); G_END_DECLS #endif // FLUTTER_SHELL_PLATFORM_LINUX_FL_RENDERER_GDK_H_
engine/shell/platform/linux/fl_renderer_gdk.h/0
{ "file_path": "engine/shell/platform/linux/fl_renderer_gdk.h", "repo_id": "engine", "token_count": 670 }
402
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/linux/public/flutter_linux/fl_standard_message_codec.h" #include <gmodule.h> #include <cstring> // See lib/src/services/message_codecs.dart in Flutter source for description of // encoding. // Type values. static constexpr int kValueNull = 0; static constexpr int kValueTrue = 1; static constexpr int kValueFalse = 2; static constexpr int kValueInt32 = 3; static constexpr int kValueInt64 = 4; static constexpr int kValueFloat64 = 6; static constexpr int kValueString = 7; static constexpr int kValueUint8List = 8; static constexpr int kValueInt32List = 9; static constexpr int kValueInt64List = 10; static constexpr int kValueFloat64List = 11; static constexpr int kValueList = 12; static constexpr int kValueMap = 13; static constexpr int kValueFloat32List = 14; G_DEFINE_TYPE(FlStandardMessageCodec, fl_standard_message_codec, fl_message_codec_get_type()) // Functions to write standard C number types. static void write_uint8(GByteArray* buffer, uint8_t value) { g_byte_array_append(buffer, &value, sizeof(uint8_t)); } static void write_uint16(GByteArray* buffer, uint16_t value) { g_byte_array_append(buffer, reinterpret_cast<uint8_t*>(&value), sizeof(uint16_t)); } static void write_uint32(GByteArray* buffer, uint32_t value) { g_byte_array_append(buffer, reinterpret_cast<uint8_t*>(&value), sizeof(uint32_t)); } static void write_int32(GByteArray* buffer, int32_t value) { g_byte_array_append(buffer, reinterpret_cast<uint8_t*>(&value), sizeof(int32_t)); } static void write_int64(GByteArray* buffer, int64_t value) { g_byte_array_append(buffer, reinterpret_cast<uint8_t*>(&value), sizeof(int64_t)); } static void write_float64(GByteArray* buffer, double value) { g_byte_array_append(buffer, reinterpret_cast<uint8_t*>(&value), sizeof(double)); } // Write padding bytes to align to @align multiple of bytes. static void write_align(GByteArray* buffer, guint align) { while (buffer->len % align != 0) { write_uint8(buffer, 0); } } // Checks there is enough data in @buffer to be read. static gboolean check_size(GBytes* buffer, size_t offset, size_t required, GError** error) { if (offset + required > g_bytes_get_size(buffer)) { g_set_error(error, FL_MESSAGE_CODEC_ERROR, FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA, "Unexpected end of data"); return FALSE; } return TRUE; } // Skip bytes to align next read on @align multiple of bytes. static gboolean read_align(GBytes* buffer, size_t* offset, size_t align, GError** error) { if ((*offset) % align == 0) { return TRUE; } size_t required = align - (*offset) % align; if (!check_size(buffer, *offset, required, error)) { return FALSE; } (*offset) += required; return TRUE; } // Gets a pointer to the given offset in @buffer. static const uint8_t* get_data(GBytes* buffer, size_t* offset) { return static_cast<const uint8_t*>(g_bytes_get_data(buffer, nullptr)) + *offset; } // Reads an unsigned 8 bit number from @buffer and writes it to @value. // Returns TRUE if successful, otherwise sets an error. static gboolean read_uint8(GBytes* buffer, size_t* offset, uint8_t* value, GError** error) { if (!check_size(buffer, *offset, sizeof(uint8_t), error)) { return FALSE; } *value = get_data(buffer, offset)[0]; (*offset)++; return TRUE; } // Reads an unsigned 16 bit integer from @buffer and writes it to @value. // Returns TRUE if successful, otherwise sets an error. static gboolean read_uint16(GBytes* buffer, size_t* offset, uint16_t* value, GError** error) { if (!check_size(buffer, *offset, sizeof(uint16_t), error)) { return FALSE; } *value = reinterpret_cast<const uint16_t*>(get_data(buffer, offset))[0]; *offset += sizeof(uint16_t); return TRUE; } // Reads an unsigned 32 bit integer from @buffer and writes it to @value. // Returns TRUE if successful, otherwise sets an error. static gboolean read_uint32(GBytes* buffer, size_t* offset, uint32_t* value, GError** error) { if (!check_size(buffer, *offset, sizeof(uint32_t), error)) { return FALSE; } *value = reinterpret_cast<const uint32_t*>(get_data(buffer, offset))[0]; *offset += sizeof(uint32_t); return TRUE; } // Reads a #FL_VALUE_TYPE_INT stored as a signed 32 bit integer from @buffer. // Returns a new #FlValue of type #FL_VALUE_TYPE_INT if successful or %NULL on // error. static FlValue* read_int32_value(GBytes* buffer, size_t* offset, GError** error) { if (!check_size(buffer, *offset, sizeof(int32_t), error)) { return nullptr; } FlValue* value = fl_value_new_int( reinterpret_cast<const int32_t*>(get_data(buffer, offset))[0]); *offset += sizeof(int32_t); return value; } // Reads a #FL_VALUE_TYPE_INT stored as a signed 64 bit integer from @buffer. // Returns a new #FlValue of type #FL_VALUE_TYPE_INT if successful or %NULL on // error. static FlValue* read_int64_value(GBytes* buffer, size_t* offset, GError** error) { if (!check_size(buffer, *offset, sizeof(int64_t), error)) { return nullptr; } FlValue* value = fl_value_new_int( reinterpret_cast<const int64_t*>(get_data(buffer, offset))[0]); *offset += sizeof(int64_t); return value; } // Reads a 64 bit floating point number from @buffer and writes it to @value. // Returns a new #FlValue of type #FL_VALUE_TYPE_FLOAT if successful or %NULL on // error. static FlValue* read_float64_value(GBytes* buffer, size_t* offset, GError** error) { if (!read_align(buffer, offset, 8, error)) { return nullptr; } if (!check_size(buffer, *offset, sizeof(double), error)) { return nullptr; } FlValue* value = fl_value_new_float( reinterpret_cast<const double*>(get_data(buffer, offset))[0]); *offset += sizeof(double); return value; } // Reads an UTF-8 text string from @buffer in standard codec format. // Returns a new #FlValue of type #FL_VALUE_TYPE_STRING if successful or %NULL // on error. static FlValue* read_string_value(FlStandardMessageCodec* self, GBytes* buffer, size_t* offset, GError** error) { uint32_t length; if (!fl_standard_message_codec_read_size(self, buffer, offset, &length, error)) { return nullptr; } if (!check_size(buffer, *offset, length, error)) { return nullptr; } FlValue* value = fl_value_new_string_sized( reinterpret_cast<const gchar*>(get_data(buffer, offset)), length); *offset += length; return value; } // Reads an unsigned 8 bit list from @buffer in standard codec format. // Returns a new #FlValue of type #FL_VALUE_TYPE_UINT8_LIST if successful or // %NULL on error. static FlValue* read_uint8_list_value(FlStandardMessageCodec* self, GBytes* buffer, size_t* offset, GError** error) { uint32_t length; if (!fl_standard_message_codec_read_size(self, buffer, offset, &length, error)) { return nullptr; } if (!check_size(buffer, *offset, sizeof(uint8_t) * length, error)) { return nullptr; } FlValue* value = fl_value_new_uint8_list(get_data(buffer, offset), length); *offset += length; return value; } // Reads a signed 32 bit list from @buffer in standard codec format. // Returns a new #FlValue of type #FL_VALUE_TYPE_INT32_LIST if successful or // %NULL on error. static FlValue* read_int32_list_value(FlStandardMessageCodec* self, GBytes* buffer, size_t* offset, GError** error) { uint32_t length; if (!fl_standard_message_codec_read_size(self, buffer, offset, &length, error)) { return nullptr; } if (!read_align(buffer, offset, 4, error)) { return nullptr; } if (!check_size(buffer, *offset, sizeof(int32_t) * length, error)) { return nullptr; } FlValue* value = fl_value_new_int32_list( reinterpret_cast<const int32_t*>(get_data(buffer, offset)), length); *offset += sizeof(int32_t) * length; return value; } // Reads a signed 64 bit list from @buffer in standard codec format. // Returns a new #FlValue of type #FL_VALUE_TYPE_INT64_LIST if successful or // %NULL on error. static FlValue* read_int64_list_value(FlStandardMessageCodec* self, GBytes* buffer, size_t* offset, GError** error) { uint32_t length; if (!fl_standard_message_codec_read_size(self, buffer, offset, &length, error)) { return nullptr; } if (!read_align(buffer, offset, 8, error)) { return nullptr; } if (!check_size(buffer, *offset, sizeof(int64_t) * length, error)) { return nullptr; } FlValue* value = fl_value_new_int64_list( reinterpret_cast<const int64_t*>(get_data(buffer, offset)), length); *offset += sizeof(int64_t) * length; return value; } // Reads a 32 bit floating point number list from @buffer in standard codec // format. Returns a new #FlValue of type #FL_VALUE_TYPE_FLOAT32_LIST if // successful or %NULL on error. static FlValue* read_float32_list_value(FlStandardMessageCodec* self, GBytes* buffer, size_t* offset, GError** error) { uint32_t length; if (!fl_standard_message_codec_read_size(self, buffer, offset, &length, error)) { return nullptr; } if (!read_align(buffer, offset, 4, error)) { return nullptr; } if (!check_size(buffer, *offset, sizeof(float) * length, error)) { return nullptr; } FlValue* value = fl_value_new_float32_list( reinterpret_cast<const float*>(get_data(buffer, offset)), length); *offset += sizeof(float) * length; return value; } // Reads a floating point number list from @buffer in standard codec format. // Returns a new #FlValue of type #FL_VALUE_TYPE_FLOAT_LIST if successful or // %NULL on error. static FlValue* read_float64_list_value(FlStandardMessageCodec* self, GBytes* buffer, size_t* offset, GError** error) { uint32_t length; if (!fl_standard_message_codec_read_size(self, buffer, offset, &length, error)) { return nullptr; } if (!read_align(buffer, offset, 8, error)) { return nullptr; } if (!check_size(buffer, *offset, sizeof(double) * length, error)) { return nullptr; } FlValue* value = fl_value_new_float_list( reinterpret_cast<const double*>(get_data(buffer, offset)), length); *offset += sizeof(double) * length; return value; } // Reads a list from @buffer in standard codec format. // Returns a new #FlValue of type #FL_VALUE_TYPE_LIST if successful or %NULL on // error. static FlValue* read_list_value(FlStandardMessageCodec* self, GBytes* buffer, size_t* offset, GError** error) { uint32_t length; if (!fl_standard_message_codec_read_size(self, buffer, offset, &length, error)) { return nullptr; } g_autoptr(FlValue) list = fl_value_new_list(); for (size_t i = 0; i < length; i++) { g_autoptr(FlValue) child = fl_standard_message_codec_read_value(self, buffer, offset, error); if (child == nullptr) { return nullptr; } fl_value_append(list, child); } return fl_value_ref(list); } // Reads a map from @buffer in standard codec format. // Returns a new #FlValue of type #FL_VALUE_TYPE_MAP if successful or %NULL on // error. static FlValue* read_map_value(FlStandardMessageCodec* self, GBytes* buffer, size_t* offset, GError** error) { uint32_t length; if (!fl_standard_message_codec_read_size(self, buffer, offset, &length, error)) { return nullptr; } g_autoptr(FlValue) map = fl_value_new_map(); for (size_t i = 0; i < length; i++) { g_autoptr(FlValue) key = fl_standard_message_codec_read_value(self, buffer, offset, error); if (key == nullptr) { return nullptr; } g_autoptr(FlValue) value = fl_standard_message_codec_read_value(self, buffer, offset, error); if (value == nullptr) { return nullptr; } fl_value_set(map, key, value); } return fl_value_ref(map); } // Implements FlMessageCodec::encode_message. static GBytes* fl_standard_message_codec_encode_message(FlMessageCodec* codec, FlValue* message, GError** error) { FlStandardMessageCodec* self = reinterpret_cast<FlStandardMessageCodec*>(codec); g_autoptr(GByteArray) buffer = g_byte_array_new(); if (!fl_standard_message_codec_write_value(self, buffer, message, error)) { return nullptr; } return g_byte_array_free_to_bytes( static_cast<GByteArray*>(g_steal_pointer(&buffer))); } // Implements FlMessageCodec::decode_message. static FlValue* fl_standard_message_codec_decode_message(FlMessageCodec* codec, GBytes* message, GError** error) { if (g_bytes_get_size(message) == 0) { return fl_value_new_null(); } FlStandardMessageCodec* self = reinterpret_cast<FlStandardMessageCodec*>(codec); size_t offset = 0; g_autoptr(FlValue) value = fl_standard_message_codec_read_value(self, message, &offset, error); if (value == nullptr) { return nullptr; } if (offset != g_bytes_get_size(message)) { g_set_error(error, FL_MESSAGE_CODEC_ERROR, FL_MESSAGE_CODEC_ERROR_ADDITIONAL_DATA, "Unused %zi bytes after standard message", g_bytes_get_size(message) - offset); return nullptr; } return fl_value_ref(value); } // Implements FlStandardMessageCodec::write_value. static gboolean fl_standard_message_codec_real_write_value( FlStandardMessageCodec* self, GByteArray* buffer, FlValue* value, GError** error) { if (value == nullptr) { write_uint8(buffer, kValueNull); return TRUE; } switch (fl_value_get_type(value)) { case FL_VALUE_TYPE_NULL: write_uint8(buffer, kValueNull); return TRUE; case FL_VALUE_TYPE_BOOL: if (fl_value_get_bool(value)) { write_uint8(buffer, kValueTrue); } else { write_uint8(buffer, kValueFalse); } return TRUE; case FL_VALUE_TYPE_INT: { int64_t v = fl_value_get_int(value); if (v >= INT32_MIN && v <= INT32_MAX) { write_uint8(buffer, kValueInt32); write_int32(buffer, v); } else { write_uint8(buffer, kValueInt64); write_int64(buffer, v); } return TRUE; } case FL_VALUE_TYPE_FLOAT: write_uint8(buffer, kValueFloat64); write_align(buffer, 8); write_float64(buffer, fl_value_get_float(value)); return TRUE; case FL_VALUE_TYPE_STRING: { write_uint8(buffer, kValueString); const char* text = fl_value_get_string(value); size_t length = strlen(text); fl_standard_message_codec_write_size(self, buffer, length); g_byte_array_append(buffer, reinterpret_cast<const uint8_t*>(text), length); return TRUE; } case FL_VALUE_TYPE_UINT8_LIST: { write_uint8(buffer, kValueUint8List); size_t length = fl_value_get_length(value); fl_standard_message_codec_write_size(self, buffer, length); g_byte_array_append(buffer, fl_value_get_uint8_list(value), sizeof(uint8_t) * length); return TRUE; } case FL_VALUE_TYPE_INT32_LIST: { write_uint8(buffer, kValueInt32List); size_t length = fl_value_get_length(value); fl_standard_message_codec_write_size(self, buffer, length); write_align(buffer, 4); g_byte_array_append( buffer, reinterpret_cast<const uint8_t*>(fl_value_get_int32_list(value)), sizeof(int32_t) * length); return TRUE; } case FL_VALUE_TYPE_INT64_LIST: { write_uint8(buffer, kValueInt64List); size_t length = fl_value_get_length(value); fl_standard_message_codec_write_size(self, buffer, length); write_align(buffer, 8); g_byte_array_append( buffer, reinterpret_cast<const uint8_t*>(fl_value_get_int64_list(value)), sizeof(int64_t) * length); return TRUE; } case FL_VALUE_TYPE_FLOAT32_LIST: { write_uint8(buffer, kValueFloat32List); size_t length = fl_value_get_length(value); fl_standard_message_codec_write_size(self, buffer, length); write_align(buffer, 4); g_byte_array_append( buffer, reinterpret_cast<const uint8_t*>(fl_value_get_float32_list(value)), sizeof(float) * length); return TRUE; } case FL_VALUE_TYPE_FLOAT_LIST: { write_uint8(buffer, kValueFloat64List); size_t length = fl_value_get_length(value); fl_standard_message_codec_write_size(self, buffer, length); write_align(buffer, 8); g_byte_array_append( buffer, reinterpret_cast<const uint8_t*>(fl_value_get_float_list(value)), sizeof(double) * length); return TRUE; } case FL_VALUE_TYPE_LIST: write_uint8(buffer, kValueList); fl_standard_message_codec_write_size(self, buffer, fl_value_get_length(value)); for (size_t i = 0; i < fl_value_get_length(value); i++) { if (!fl_standard_message_codec_write_value( self, buffer, fl_value_get_list_value(value, i), error)) { return FALSE; } } return TRUE; case FL_VALUE_TYPE_MAP: write_uint8(buffer, kValueMap); fl_standard_message_codec_write_size(self, buffer, fl_value_get_length(value)); for (size_t i = 0; i < fl_value_get_length(value); i++) { if (!fl_standard_message_codec_write_value( self, buffer, fl_value_get_map_key(value, i), error) || !fl_standard_message_codec_write_value( self, buffer, fl_value_get_map_value(value, i), error)) { return FALSE; } } return TRUE; case FL_VALUE_TYPE_CUSTOM: g_set_error(error, FL_MESSAGE_CODEC_ERROR, FL_MESSAGE_CODEC_ERROR_UNSUPPORTED_TYPE, "Custom value not implemented"); return FALSE; } g_set_error(error, FL_MESSAGE_CODEC_ERROR, FL_MESSAGE_CODEC_ERROR_UNSUPPORTED_TYPE, "Unexpected FlValue type %d", fl_value_get_type(value)); return FALSE; } // Implements FlStandardMessageCodec::read_value_of_type. static FlValue* fl_standard_message_codec_read_value_of_type( FlStandardMessageCodec* self, GBytes* buffer, size_t* offset, int type, GError** error) { g_autoptr(FlValue) value = nullptr; if (type == kValueNull) { return fl_value_new_null(); } else if (type == kValueTrue) { return fl_value_new_bool(TRUE); } else if (type == kValueFalse) { return fl_value_new_bool(FALSE); } else if (type == kValueInt32) { value = read_int32_value(buffer, offset, error); } else if (type == kValueInt64) { value = read_int64_value(buffer, offset, error); } else if (type == kValueFloat64) { value = read_float64_value(buffer, offset, error); } else if (type == kValueString) { value = read_string_value(self, buffer, offset, error); } else if (type == kValueUint8List) { value = read_uint8_list_value(self, buffer, offset, error); } else if (type == kValueInt32List) { value = read_int32_list_value(self, buffer, offset, error); } else if (type == kValueInt64List) { value = read_int64_list_value(self, buffer, offset, error); } else if (type == kValueFloat32List) { value = read_float32_list_value(self, buffer, offset, error); } else if (type == kValueFloat64List) { value = read_float64_list_value(self, buffer, offset, error); } else if (type == kValueList) { value = read_list_value(self, buffer, offset, error); } else if (type == kValueMap) { value = read_map_value(self, buffer, offset, error); } else { g_set_error(error, FL_MESSAGE_CODEC_ERROR, FL_MESSAGE_CODEC_ERROR_UNSUPPORTED_TYPE, "Unexpected standard codec type %02x", type); return nullptr; } return value == nullptr ? nullptr : fl_value_ref(value); } static void fl_standard_message_codec_class_init( FlStandardMessageCodecClass* klass) { FL_MESSAGE_CODEC_CLASS(klass)->encode_message = fl_standard_message_codec_encode_message; FL_MESSAGE_CODEC_CLASS(klass)->decode_message = fl_standard_message_codec_decode_message; klass->write_value = fl_standard_message_codec_real_write_value; klass->read_value_of_type = fl_standard_message_codec_read_value_of_type; } static void fl_standard_message_codec_init(FlStandardMessageCodec* self) {} G_MODULE_EXPORT FlStandardMessageCodec* fl_standard_message_codec_new() { return static_cast<FlStandardMessageCodec*>( g_object_new(fl_standard_message_codec_get_type(), nullptr)); } G_MODULE_EXPORT void fl_standard_message_codec_write_size( FlStandardMessageCodec* codec, GByteArray* buffer, uint32_t size) { if (size < 254) { write_uint8(buffer, size); } else if (size <= 0xffff) { write_uint8(buffer, 254); write_uint16(buffer, size); } else { write_uint8(buffer, 255); write_uint32(buffer, size); } } G_MODULE_EXPORT gboolean fl_standard_message_codec_read_size( FlStandardMessageCodec* codec, GBytes* buffer, size_t* offset, uint32_t* value, GError** error) { uint8_t value8; if (!read_uint8(buffer, offset, &value8, error)) { return FALSE; } if (value8 == 255) { if (!read_uint32(buffer, offset, value, error)) { return FALSE; } } else if (value8 == 254) { uint16_t value16; if (!read_uint16(buffer, offset, &value16, error)) { return FALSE; } *value = value16; } else { *value = value8; } return TRUE; } G_MODULE_EXPORT gboolean fl_standard_message_codec_write_value( FlStandardMessageCodec* self, GByteArray* buffer, FlValue* value, GError** error) { return FL_STANDARD_MESSAGE_CODEC_GET_CLASS(self)->write_value(self, buffer, value, error); } G_MODULE_EXPORT FlValue* fl_standard_message_codec_read_value( FlStandardMessageCodec* self, GBytes* buffer, size_t* offset, GError** error) { uint8_t type; if (!read_uint8(buffer, offset, &type, error)) { return nullptr; } return FL_STANDARD_MESSAGE_CODEC_GET_CLASS(self)->read_value_of_type( self, buffer, offset, type, error); }
engine/shell/platform/linux/fl_standard_message_codec.cc/0
{ "file_path": "engine/shell/platform/linux/fl_standard_message_codec.cc", "repo_id": "engine", "token_count": 10927 }
403
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/linux/fl_texture_gl_private.h" #include "flutter/shell/platform/linux/fl_texture_private.h" #include "flutter/shell/platform/linux/fl_texture_registrar_private.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_texture.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_texture_registrar.h" #include "flutter/shell/platform/linux/testing/fl_test.h" #include "gtest/gtest.h" #include <epoxy/gl.h> static constexpr uint32_t kBufferWidth = 4u; static constexpr uint32_t kBufferHeight = 4u; static constexpr uint32_t kRealBufferWidth = 2u; static constexpr uint32_t kRealBufferHeight = 2u; G_DECLARE_FINAL_TYPE(FlTestTexture, fl_test_texture, FL, TEST_TEXTURE, FlTextureGL) /// A simple texture. struct _FlTestTexture { FlTextureGL parent_instance; }; G_DEFINE_TYPE(FlTestTexture, fl_test_texture, fl_texture_gl_get_type()) static gboolean fl_test_texture_populate(FlTextureGL* texture, uint32_t* target, uint32_t* name, uint32_t* width, uint32_t* height, GError** error) { EXPECT_TRUE(FL_IS_TEST_TEXTURE(texture)); EXPECT_EQ(*width, kBufferWidth); EXPECT_EQ(*height, kBufferHeight); *target = GL_TEXTURE_2D; *name = 1; *width = kRealBufferWidth; *height = kRealBufferHeight; return TRUE; } static void fl_test_texture_class_init(FlTestTextureClass* klass) { FL_TEXTURE_GL_CLASS(klass)->populate = fl_test_texture_populate; } static void fl_test_texture_init(FlTestTexture* self) {} static FlTestTexture* fl_test_texture_new() { return FL_TEST_TEXTURE(g_object_new(fl_test_texture_get_type(), nullptr)); } // Test that getting the texture ID works. TEST(FlTextureGLTest, TextureID) { g_autoptr(FlTexture) texture = FL_TEXTURE(fl_test_texture_new()); fl_texture_set_id(texture, 42); EXPECT_EQ(fl_texture_get_id(texture), static_cast<int64_t>(42)); } // Test that populating an OpenGL texture works. TEST(FlTextureGLTest, PopulateTexture) { g_autoptr(FlTextureGL) texture = FL_TEXTURE_GL(fl_test_texture_new()); FlutterOpenGLTexture opengl_texture = {0}; g_autoptr(GError) error = nullptr; EXPECT_TRUE(fl_texture_gl_populate(texture, kBufferWidth, kBufferHeight, &opengl_texture, &error)); EXPECT_EQ(error, nullptr); EXPECT_EQ(opengl_texture.width, kRealBufferWidth); EXPECT_EQ(opengl_texture.height, kRealBufferHeight); }
engine/shell/platform/linux/fl_texture_gl_test.cc/0
{ "file_path": "engine/shell/platform/linux/fl_texture_gl_test.cc", "repo_id": "engine", "token_count": 1227 }
404
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_BASIC_MESSAGE_CHANNEL_H_ #define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_BASIC_MESSAGE_CHANNEL_H_ #if !defined(__FLUTTER_LINUX_INSIDE__) && !defined(FLUTTER_LINUX_COMPILATION) #error "Only <flutter_linux/flutter_linux.h> can be included directly." #endif #include <gio/gio.h> #include <glib-object.h> #include <gmodule.h> #include "fl_binary_messenger.h" #include "fl_message_codec.h" G_BEGIN_DECLS G_MODULE_EXPORT G_DECLARE_FINAL_TYPE(FlBasicMessageChannel, fl_basic_message_channel, FL, BASIC_MESSAGE_CHANNEL, GObject) G_MODULE_EXPORT G_DECLARE_FINAL_TYPE(FlBasicMessageChannelResponseHandle, fl_basic_message_channel_response_handle, FL, BASIC_MESSAGE_CHANNEL_RESPONSE_HANDLE, GObject) /** * FlBasicMessageChannel: * * #FlBasicMessageChannel is an object that allows sending and receiving * messages to/from Dart code over platform channels. * * The following example shows how to send messages on a channel: * * |[<!-- language="C" --> * static FlBasicMessageChannel *channel = NULL; * * static void message_cb (FlBasicMessageChannel* channel, * FlValue* message, * FlBasicMessageChannelResponseHandle* response_handle, * gpointer user_data) { * g_autoptr(FlValue) response = handle_message (message); * g_autoptr(GError) error = NULL; * if (!fl_basic_message_channel_respond (channel, response_handle, response, * &error)) * g_warning ("Failed to send channel response: %s", error->message); * } * * static void message_response_cb (GObject *object, * GAsyncResult *result, * gpointer user_data) { * g_autoptr(GError) error = NULL; * g_autoptr(FlValue) response = * fl_basic_message_channel_send_finish (FL_BASIC_MESSAGE_CHANNEL (object), * result, &error); * if (response == NULL) { * g_warning ("Failed to send message: %s", error->message); * return; * } * * handle_response (response); * } * * static void setup_channel () { * g_autoptr(FlStandardMessageCodec) codec = fl_standard_message_codec_new (); * channel = fl_basic_message_channel_new (messenger, "flutter/foo", * FL_MESSAGE_CODEC (codec)); * fl_basic_message_channel_set_message_handler (channel, message_cb, NULL, * NULL); * * g_autoptr(FlValue) message = fl_value_new_string ("Hello World"); * fl_basic_message_channel_send (channel, message, NULL, * message_response_cb, NULL); * } * ]| * * #FlBasicMessageChannel matches the BasicMessageChannel class in the Flutter * services library. */ /** * FlBasicMessageChannelResponseHandle: * * #FlBasicMessageChannelResponseHandle is an object used to send responses * with. */ /** * FlBasicMessageChannelMessageHandler: * @channel: an #FlBasicMessageChannel. * @message: message received. * @response_handle: a handle to respond to the message with. * @user_data: (closure): data provided when registering this handler. * * Function called when a message is received. Call * fl_basic_message_channel_respond() to respond to this message. If the * response is not occurring in this callback take a reference to * @response_handle and release that once it has been responded to. Failing to * respond before the last reference to @response_handle is dropped is a * programming error. */ typedef void (*FlBasicMessageChannelMessageHandler)( FlBasicMessageChannel* channel, FlValue* message, FlBasicMessageChannelResponseHandle* response_handle, gpointer user_data); /** * fl_basic_message_channel_new: * @messenger: an #FlBinaryMessenger. * @name: a channel name. * @codec: the message codec. * * Creates a basic message channel. @codec must match the codec used on the Dart * end of the channel. * * Returns: a new #FlBasicMessageChannel. */ FlBasicMessageChannel* fl_basic_message_channel_new( FlBinaryMessenger* messenger, const gchar* name, FlMessageCodec* codec); /** * fl_basic_message_channel_set_message_handler: * @channel: an #FlBasicMessageChannel. * @handler: (allow-none): function to call when a message is received on this * channel or %NULL to disable the handler. * @user_data: (closure): user data to pass to @handler. * @destroy_notify: (allow-none): a function which gets called to free * @user_data, or %NULL. * * Sets the function called when a message is received from the Dart side of the * channel. See #FlBasicMessageChannelMessageHandler for details on how to * respond to messages. * * The handler is removed if the channel is closed or is replaced by another * handler, set @destroy_notify if you want to detect this. */ void fl_basic_message_channel_set_message_handler( FlBasicMessageChannel* channel, FlBasicMessageChannelMessageHandler handler, gpointer user_data, GDestroyNotify destroy_notify); /** * fl_basic_message_channel_respond: * @channel: an #FlBasicMessageChannel. * @response_handle: handle that was provided in a * #FlBasicMessageChannelMessageHandler. * @message: (allow-none): message response to send or %NULL for an empty * response. * @error: (allow-none): #GError location to store the error occurring, or %NULL * to ignore. * * Responds to a message. * * Returns: %TRUE on success. */ gboolean fl_basic_message_channel_respond( FlBasicMessageChannel* channel, FlBasicMessageChannelResponseHandle* response_handle, FlValue* message, GError** error); /** * fl_basic_message_channel_send: * @channel: an #FlBasicMessageChannel. * @message: (allow-none): message to send, must match what the #FlMessageCodec * supports. * @cancellable: (allow-none): a #GCancellable or %NULL. * @callback: (scope async): (allow-none): a #GAsyncReadyCallback to call when * the request is satisfied or %NULL to ignore the response. * @user_data: (closure): user data to pass to @callback. * * Asynchronously sends a message. */ void fl_basic_message_channel_send(FlBasicMessageChannel* channel, FlValue* message, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data); /** * fl_basic_message_channel_send_finish: * @channel: an #FlBasicMessageChannel. * @result: a #GAsyncResult. * @error: (allow-none): #GError location to store the error occurring, or %NULL * to ignore. * * Completes request started with fl_basic_message_channel_send(). * * Returns: message response on success or %NULL on error. */ FlValue* fl_basic_message_channel_send_finish(FlBasicMessageChannel* channel, GAsyncResult* result, GError** error); G_END_DECLS #endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_BASIC_MESSAGE_CHANNEL_H_
engine/shell/platform/linux/public/flutter_linux/fl_basic_message_channel.h/0
{ "file_path": "engine/shell/platform/linux/public/flutter_linux/fl_basic_message_channel.h", "repo_id": "engine", "token_count": 2881 }
405
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_STANDARD_MESSAGE_CODEC_H_ #define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_STANDARD_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 <gmodule.h> #include "fl_message_codec.h" G_BEGIN_DECLS G_MODULE_EXPORT G_DECLARE_DERIVABLE_TYPE(FlStandardMessageCodec, fl_standard_message_codec, FL, STANDARD_MESSAGE_CODEC, FlMessageCodec) /** * FlStandardMessageCodec: * * #FlStandardMessageCodec is an #FlMessageCodec that implements the Flutter * standard message encoding. This codec encodes and decodes #FlValue of type * #FL_VALUE_TYPE_NULL, #FL_VALUE_TYPE_BOOL, #FL_VALUE_TYPE_INT, * #FL_VALUE_TYPE_FLOAT, #FL_VALUE_TYPE_STRING, #FL_VALUE_TYPE_UINT8_LIST, * #FL_VALUE_TYPE_INT32_LIST, #FL_VALUE_TYPE_INT64_LIST, * #FL_VALUE_TYPE_FLOAT_LIST, #FL_VALUE_TYPE_LIST, and #FL_VALUE_TYPE_MAP. * * If other values types are required to be supported create a new subclass that * overrides write_value and read_value_of_type. * * #FlStandardMessageCodec matches the StandardCodec class in the Flutter * services library. */ struct _FlStandardMessageCodecClass { FlMessageCodecClass parent_class; /** * FlStandardMessageCodec::write_value: * @codec: an #FlStandardMessageCodec. * @buffer: a buffer to write into. * @value: (allow-none): value to write. * @error: (allow-none): #GError location to store the error occurring, or * %NULL. * * Virtual method to write an #FlValue in Flutter Standard encoding. * * If a codec needs to support custom #FlValue objects it must override this * method to encode those values. For non-custom values the parent method * should be called. * * Returns: %TRUE on success. */ gboolean (*write_value)(FlStandardMessageCodec* codec, GByteArray* buffer, FlValue* value, GError** error); /** * FlStandardMessageCodec::read_value_of_type: * @codec: an #FlStandardMessageCodec. * @buffer: buffer to read from. * @offset: (inout): read position in @buffer. * @type: the type of the value. * @error: (allow-none): #GError location to store the error occurring, or * %NULL. * * Virtual method to read an #FlValue in Flutter Standard encoding. * * If a codec needs to support custom #FlValue objects it must override this * method to decode those values. For non-custom values the parent method * should be called. * * Returns: an #FlValue or %NULL on error. */ FlValue* (*read_value_of_type)(FlStandardMessageCodec* codec, GBytes* buffer, size_t* offset, int type, GError** error); }; /* * fl_standard_message_codec_new: * * Creates an #FlStandardMessageCodec. * * Returns: a new #FlStandardMessageCodec. */ FlStandardMessageCodec* fl_standard_message_codec_new(); /** * fl_standard_message_codec_write_size: * @codec: an #FlStandardMessageCodec. * @buffer: buffer to write into. * @size: size value to write. * * Writes a size field in Flutter Standard encoding. */ void fl_standard_message_codec_write_size(FlStandardMessageCodec* codec, GByteArray* buffer, uint32_t size); /** * fl_standard_message_codec_read_size: * @codec: an #FlStandardMessageCodec. * @buffer: buffer to read from. * @offset: (inout): read position in @buffer. * @value: location to read size. * @error: (allow-none): #GError location to store the error occurring, or * %NULL. * * Reads a size field in Flutter Standard encoding. * * This method is intended for use by subclasses overriding * FlStandardMessageCodec::read_value_of_type. * * Returns: %TRUE on success. */ gboolean fl_standard_message_codec_read_size(FlStandardMessageCodec* codec, GBytes* buffer, size_t* offset, uint32_t* value, GError** error); /** * fl_standard_message_codec_write_value: * @codec: an #FlStandardMessageCodec. * @buffer: buffer to write into. * @value: (allow-none): value to write. * @error: (allow-none): #GError location to store the error occurring, or * %NULL. * * Writes an #FlValue in Flutter Standard encoding. * * This method is intended for use by subclasses overriding * FlStandardMessageCodec::write_value. * * Returns: %TRUE on success. */ gboolean fl_standard_message_codec_write_value(FlStandardMessageCodec* codec, GByteArray* buffer, FlValue* value, GError** error); /** * fl_standard_message_codec_read_value: * @codec: an #FlStandardMessageCodec. * @buffer: buffer to read from. * @offset: (inout): read position in @buffer. * @value: location to read size. * @error: (allow-none): #GError location to store the error occurring, or * %NULL. * * Reads an #FlValue in Flutter Standard encoding. * * This method is intended for use by subclasses overriding * FlStandardMessageCodec::read_value_of_type. * * Returns: a new #FlValue or %NULL on error. */ FlValue* fl_standard_message_codec_read_value(FlStandardMessageCodec* codec, GBytes* buffer, size_t* offset, GError** error); G_END_DECLS #endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_STANDARD_MESSAGE_CODEC_H_
engine/shell/platform/linux/public/flutter_linux/fl_standard_message_codec.h/0
{ "file_path": "engine/shell/platform/linux/public/flutter_linux/fl_standard_message_codec.h", "repo_id": "engine", "token_count": 2666 }
406
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_LINUX_TESTING_MOCK_BINARY_MESSENGER_H_ #define FLUTTER_SHELL_PLATFORM_LINUX_TESTING_MOCK_BINARY_MESSENGER_H_ #include <unordered_map> #include "flutter/shell/platform/linux/public/flutter_linux/fl_binary_messenger.h" #include "gmock/gmock.h" namespace flutter { namespace testing { // Mock for FlBinaryMessenger. class MockBinaryMessenger { public: MockBinaryMessenger(); ~MockBinaryMessenger(); // This was an existing use of operator overloading. It's against our style // guide but enabling clang tidy on header files is a higher priority than // fixing this. // NOLINTNEXTLINE(google-explicit-constructor) operator FlBinaryMessenger*(); MOCK_METHOD(void, fl_binary_messenger_set_message_handler_on_channel, (FlBinaryMessenger * messenger, const gchar* channel, FlBinaryMessengerMessageHandler handler, gpointer user_data, GDestroyNotify destroy_notify)); MOCK_METHOD(gboolean, fl_binary_messenger_send_response, (FlBinaryMessenger * messenger, FlBinaryMessengerResponseHandle* response_handle, GBytes* response, GError** error)); MOCK_METHOD(void, fl_binary_messenger_send_on_channel, (FlBinaryMessenger * messenger, const gchar* channel, GBytes* message, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer user_data)); MOCK_METHOD(GBytes*, fl_binary_messenger_send_on_channel_finish, (FlBinaryMessenger * messenger, GAsyncResult* result, GError** error)); MOCK_METHOD(void, fl_binary_messenger_resize_channel, (FlBinaryMessenger * messenger, const gchar* channel, int64_t new_size)); MOCK_METHOD(void, fl_binary_messenger_set_warns_on_channel_overflow, (FlBinaryMessenger * messenger, const gchar* channel, bool warns)); bool HasMessageHandler(const gchar* channel) const; void SetMessageHandler(const gchar* channel, FlBinaryMessengerMessageHandler handler, gpointer user_data); void ReceiveMessage(const gchar* channel, GBytes* message); private: FlBinaryMessenger* instance_ = nullptr; std::unordered_map<std::string, FlBinaryMessengerMessageHandler> message_handlers_; std::unordered_map<std::string, FlBinaryMessengerResponseHandle*> response_handles_; std::unordered_map<std::string, gpointer> user_datas_; }; } // namespace testing } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_LINUX_TESTING_MOCK_BINARY_MESSENGER_H_
engine/shell/platform/linux/testing/mock_binary_messenger.h/0
{ "file_path": "engine/shell/platform/linux/testing/mock_binary_messenger.h", "repo_id": "engine", "token_count": 1313 }
407
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_LINUX_TESTING_MOCK_TEXT_INPUT_PLUGIN_H_ #define FLUTTER_SHELL_PLATFORM_LINUX_TESTING_MOCK_TEXT_INPUT_PLUGIN_H_ #include <gdk/gdk.h> #include "flutter/shell/platform/linux/fl_text_input_plugin.h" G_BEGIN_DECLS G_DECLARE_FINAL_TYPE(FlMockTextInputPlugin, fl_mock_text_input_plugin, FL, MOCK_TEXT_INPUT_PLUGIN, FlTextInputPlugin) FlMockTextInputPlugin* fl_mock_text_input_plugin_new( gboolean (*filter_keypress)(FlTextInputPlugin* self, FlKeyEvent* event)); G_END_DECLS #endif // FLUTTER_SHELL_PLATFORM_LINUX_TESTING_MOCK_TEXT_INPUT_PLUGIN_H_
engine/shell/platform/linux/testing/mock_text_input_plugin.h/0
{ "file_path": "engine/shell/platform/linux/testing/mock_text_input_plugin.h", "repo_id": "engine", "token_count": 388 }
408
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "include/flutter/flutter_view_controller.h" #include <algorithm> #include <iostream> namespace flutter { FlutterViewController::FlutterViewController(int width, int height, const DartProject& project) { engine_ = std::make_unique<FlutterEngine>(project); controller_ = FlutterDesktopViewControllerCreate(width, height, engine_->RelinquishEngine()); if (!controller_) { std::cerr << "Failed to create view controller." << std::endl; return; } view_ = std::make_unique<FlutterView>( FlutterDesktopViewControllerGetView(controller_)); } FlutterViewController::~FlutterViewController() { if (controller_) { FlutterDesktopViewControllerDestroy(controller_); } } FlutterViewId FlutterViewController::view_id() const { auto view_id = FlutterDesktopViewControllerGetViewId(controller_); return static_cast<FlutterViewId>(view_id); } void FlutterViewController::ForceRedraw() { FlutterDesktopViewControllerForceRedraw(controller_); } std::optional<LRESULT> FlutterViewController::HandleTopLevelWindowProc( HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) { LRESULT result; bool handled = FlutterDesktopViewControllerHandleTopLevelWindowProc( controller_, hwnd, message, wparam, lparam, &result); return handled ? result : std::optional<LRESULT>(std::nullopt); } } // namespace flutter
engine/shell/platform/windows/client_wrapper/flutter_view_controller.cc/0
{ "file_path": "engine/shell/platform/windows/client_wrapper/flutter_view_controller.cc", "repo_id": "engine", "token_count": 627 }
409
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_WINDOWS_COMPOSITOR_SOFTWARE_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_COMPOSITOR_SOFTWARE_H_ #include "flutter/shell/platform/embedder/embedder.h" #include "flutter/shell/platform/windows/compositor.h" #include "flutter/shell/platform/windows/flutter_windows_engine.h" namespace flutter { // Enables the Flutter engine to render content on Windows using software // rasterization and bitmaps. class CompositorSoftware : public Compositor { public: CompositorSoftware(FlutterWindowsEngine* engine); /// |Compositor| bool CreateBackingStore(const FlutterBackingStoreConfig& config, FlutterBackingStore* result) override; /// |Compositor| bool CollectBackingStore(const FlutterBackingStore* store) override; /// |Compositor| bool Present(FlutterViewId view_id, const FlutterLayer** layers, size_t layers_count) override; private: FlutterWindowsEngine* engine_; }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_COMPOSITOR_SOFTWARE_H_
engine/shell/platform/windows/compositor_software.h/0
{ "file_path": "engine/shell/platform/windows/compositor_software.h", "repo_id": "engine", "token_count": 423 }
410
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_WINDOWS_EGL_MANAGER_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_EGL_MANAGER_H_ // OpenGL ES and EGL includes #include <EGL/egl.h> #include <EGL/eglext.h> #include <EGL/eglplatform.h> #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> // Windows platform specific includes #include <d3d11.h> #include <windows.h> #include <wrl/client.h> #include <memory> #include "flutter/fml/macros.h" #include "flutter/shell/platform/windows/egl/context.h" #include "flutter/shell/platform/windows/egl/surface.h" #include "flutter/shell/platform/windows/egl/window_surface.h" namespace flutter { namespace egl { // A manager for initializing ANGLE correctly and using it to create and // destroy surfaces class Manager { public: static std::unique_ptr<Manager> Create(bool enable_impeller); virtual ~Manager(); // Whether the manager is currently valid. bool IsValid() const; // Creates an EGL surface that can be used to render a Flutter view into a // win32 HWND. // // After the surface is created, |WindowSurface::SetVSyncEnabled| should be // called on a thread that can make the surface current. // // HWND is the window backing the surface. Width and height are the surface's // physical pixel dimensions. // // Returns nullptr on failure. virtual std::unique_ptr<WindowSurface> CreateWindowSurface(HWND hwnd, size_t width, size_t height); // Check if the current thread has a context bound. bool HasContextCurrent(); // Creates a |EGLSurface| from the provided handle. EGLSurface CreateSurfaceFromHandle(EGLenum handle_type, EGLClientBuffer handle, const EGLint* attributes) const; // Gets the |EGLDisplay|. EGLDisplay egl_display() const { return display_; }; // Gets the |ID3D11Device| chosen by ANGLE. bool GetDevice(ID3D11Device** device); // Get the EGL context used to render Flutter views. virtual Context* render_context() const; // Get the EGL context used for async texture uploads. virtual Context* resource_context() const; protected: // Creates a new surface manager retaining reference to the passed-in target // for the lifetime of the manager. explicit Manager(bool enable_impeller); private: // Number of active instances of Manager static int instance_count_; // Initialize the EGL display. bool InitializeDisplay(); // Initialize the EGL configs. bool InitializeConfig(bool enable_impeller); // Initialize the EGL render and resource contexts. bool InitializeContexts(); // Initialize the D3D11 device. bool InitializeDevice(); void CleanUp(); // Whether the manager was initialized successfully. bool is_valid_ = false; // EGL representation of native display. EGLDisplay display_ = EGL_NO_DISPLAY; // EGL framebuffer configuration. EGLConfig config_ = nullptr; // The EGL context used to render Flutter views. std::unique_ptr<Context> render_context_; // The EGL context used for async texture uploads. std::unique_ptr<Context> resource_context_; // The current D3D device. Microsoft::WRL::ComPtr<ID3D11Device> resolved_device_ = nullptr; FML_DISALLOW_COPY_AND_ASSIGN(Manager); }; } // namespace egl } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_EGL_MANAGER_H_
engine/shell/platform/windows/egl/manager.h/0
{ "file_path": "engine/shell/platform/windows/egl/manager.h", "repo_id": "engine", "token_count": 1267 }
411