text
stringlengths
6
1.82M
id
stringlengths
12
200
metadata
dict
__index_level_0__
int64
0
784
// Copyright 2014 The Flutter 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:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; // There's also some duplicate GlobalKey tests in the framework_test.dart file. void main() { testWidgets('GlobalKey children of one node', (WidgetTester tester) async { // This is actually a test of the regular duplicate key logic, which // happens before the duplicate GlobalKey logic. await tester.pumpWidget(const Stack(children: <Widget>[ DummyWidget(key: GlobalObjectKey(0)), DummyWidget(key: GlobalObjectKey(0)), ])); final dynamic error = tester.takeException(); expect(error, isFlutterError); expect(error.toString(), startsWith('Duplicate keys found.\n')); expect(error.toString(), contains('Stack')); expect(error.toString(), contains('[GlobalObjectKey ${describeIdentity(0)}]')); }); testWidgets('GlobalKey children of two nodes - A', (WidgetTester tester) async { await tester.pumpWidget(const Stack( textDirection: TextDirection.ltr, children: <Widget>[ DummyWidget(child: DummyWidget(key: GlobalObjectKey(0))), DummyWidget( child: DummyWidget(key: GlobalObjectKey(0), ), ), ], )); final dynamic error = tester.takeException(); expect(error, isFlutterError); expect(error.toString(), startsWith('Multiple widgets used the same GlobalKey.\n')); expect(error.toString(), contains('different widgets that both had the following description')); expect(error.toString(), contains('DummyWidget')); expect(error.toString(), contains('[GlobalObjectKey ${describeIdentity(0)}]')); expect(error.toString(), endsWith('\nA GlobalKey can only be specified on one widget at a time in the widget tree.')); }); testWidgets('GlobalKey children of two different nodes - B', (WidgetTester tester) async { await tester.pumpWidget(const Stack( textDirection: TextDirection.ltr, children: <Widget>[ DummyWidget(child: DummyWidget(key: GlobalObjectKey(0))), DummyWidget(key: Key('x'), child: DummyWidget(key: GlobalObjectKey(0))), ], )); final dynamic error = tester.takeException(); expect(error, isFlutterError); expect(error.toString(), startsWith('Multiple widgets used the same GlobalKey.\n')); expect(error.toString(), isNot(contains('different widgets that both had the following description'))); expect(error.toString(), contains('DummyWidget')); expect(error.toString(), contains("DummyWidget-[<'x'>]")); expect(error.toString(), contains('[GlobalObjectKey ${describeIdentity(0)}]')); expect(error.toString(), endsWith('\nA GlobalKey can only be specified on one widget at a time in the widget tree.')); }); testWidgets('GlobalKey children of two nodes - C', (WidgetTester tester) async { late StateSetter nestedSetState; bool flag = false; await tester.pumpWidget(Stack( textDirection: TextDirection.ltr, children: <Widget>[ const DummyWidget(child: DummyWidget(key: GlobalObjectKey(0))), DummyWidget( child: StatefulBuilder( builder: (BuildContext context, StateSetter setState) { nestedSetState = setState; if (flag) { return const DummyWidget(key: GlobalObjectKey(0)); } return const DummyWidget(); }, ), ), ], )); nestedSetState(() { flag = true; }); await tester.pump(); final dynamic error = tester.takeException(); expect(error.toString(), startsWith('Duplicate GlobalKey detected in widget tree.\n')); expect(error.toString(), contains('The following GlobalKey was specified multiple times')); // The following line is verifying the grammar is correct in this common case. // We should probably also verify the three other combinations that can be generated... expect(error.toString().split('\n').join(' '), contains('This was determined by noticing that after the widget with the above global key was moved out of its previous parent, that previous parent never updated during this frame, meaning that it either did not update at all or updated before the widget was moved, in either case implying that it still thinks that it should have a child with that global key.')); expect(error.toString(), contains('[GlobalObjectKey ${describeIdentity(0)}]')); expect(error.toString(), contains('DummyWidget')); expect(error.toString(), endsWith('\nA GlobalKey can only be specified on one widget at a time in the widget tree.')); expect(error, isFlutterError); }); } class DummyWidget extends StatelessWidget { const DummyWidget({ super.key, this.child }); final Widget? child; @override Widget build(BuildContext context) { return child ?? LimitedBox( maxWidth: 0.0, maxHeight: 0.0, child: ConstrainedBox(constraints: const BoxConstraints.expand()), ); } }
flutter/packages/flutter/test/widgets/global_keys_duplicated_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/global_keys_duplicated_test.dart", "repo_id": "flutter", "token_count": 1743 }
300
// Copyright 2014 The Flutter 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:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { test('AssetImage from package', () { const AssetImage image = AssetImage( 'assets/image.png', package: 'test_package', ); expect(image.keyName, 'packages/test_package/assets/image.png'); }); test('ExactAssetImage from package', () { const ExactAssetImage image = ExactAssetImage( 'assets/image.png', scale: 1.5, package: 'test_package', ); expect(image.keyName, 'packages/test_package/assets/image.png'); }); test('Image.asset from package', () { final Image imageWidget = Image.asset( 'assets/image.png', package: 'test_package', ); assert(imageWidget.image is AssetImage); final AssetImage assetImage = imageWidget.image as AssetImage; expect(assetImage.keyName, 'packages/test_package/assets/image.png'); }); test('Image.asset from package', () { final Image imageWidget = Image.asset( 'assets/image.png', scale: 1.5, package: 'test_package', ); assert(imageWidget.image is ExactAssetImage); final ExactAssetImage assetImage = imageWidget.image as ExactAssetImage; expect(assetImage.keyName, 'packages/test_package/assets/image.png'); }); }
flutter/packages/flutter/test/widgets/image_package_asset_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/image_package_asset_test.dart", "repo_id": "flutter", "token_count": 518 }
301
// Copyright 2014 The Flutter 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:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; class TestValueKey<T> extends ValueKey<T> { const TestValueKey(super.value); } @immutable class NotEquals { const NotEquals(); @override bool operator ==(Object other) => false; @override int get hashCode => 0; } void main() { testWidgets('Keys', (WidgetTester tester) async { expect(ValueKey<int>(nonconst(3)) == ValueKey<int>(nonconst(3)), isTrue); expect(ValueKey<num>(nonconst(3)) == ValueKey<int>(nonconst(3)), isFalse); expect(ValueKey<int>(nonconst(3)) == ValueKey<int>(nonconst(2)), isFalse); expect(const ValueKey<double>(double.nan) == const ValueKey<double>(double.nan), isFalse); expect(Key(nonconst('')) == ValueKey<String>(nonconst('')), isTrue); expect(ValueKey<String>(nonconst('')) == ValueKey<String>(nonconst('')), isTrue); expect(TestValueKey<String>(nonconst('')) == ValueKey<String>(nonconst('')), isFalse); expect(TestValueKey<String>(nonconst('')) == TestValueKey<String>(nonconst('')), isTrue); expect(ValueKey<String>(nonconst('')) == ValueKey<dynamic>(nonconst('')), isFalse); expect(TestValueKey<String>(nonconst('')) == TestValueKey<dynamic>(nonconst('')), isFalse); expect(UniqueKey() == UniqueKey(), isFalse); final UniqueKey k = UniqueKey(); expect(UniqueKey() == UniqueKey(), isFalse); expect(k == k, isTrue); expect(ValueKey<LocalKey>(k) == ValueKey<LocalKey>(k), isTrue); expect(ValueKey<LocalKey>(k) == ValueKey<UniqueKey>(k), isFalse); expect(ObjectKey(k) == ObjectKey(k), isTrue); final NotEquals constNotEquals = nonconst(const NotEquals()); expect(ValueKey<NotEquals>(constNotEquals) == ValueKey<NotEquals>(constNotEquals), isFalse); expect(ObjectKey(constNotEquals) == ObjectKey(constNotEquals), isTrue); final Object constObject = nonconst(const Object()); expect(ObjectKey(constObject) == ObjectKey(constObject), isTrue); expect(ObjectKey(nonconst(Object())) == ObjectKey(nonconst(Object())), isFalse); expect(const ValueKey<bool>(true), hasOneLineDescription); expect(UniqueKey(), hasOneLineDescription); expect(const ObjectKey(true), hasOneLineDescription); expect(GlobalKey(), hasOneLineDescription); expect(GlobalKey(debugLabel: 'hello'), hasOneLineDescription); expect(const GlobalObjectKey(true), hasOneLineDescription); }); }
flutter/packages/flutter/test/widgets/key_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/key_test.dart", "repo_id": "flutter", "token_count": 864 }
302
// Copyright 2014 The Flutter 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:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'semantics_tester.dart'; void main() { group('Available semantic scroll actions', () { // Regression tests for https://github.com/flutter/flutter/issues/52032. const int itemCount = 10; const double itemHeight = 150.0; testWidgets('forward vertical', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListView.builder( controller: controller, itemCount: itemCount, itemBuilder: (BuildContext context, int index) { return SizedBox( height: itemHeight, child: Text('Tile $index'), ); }, ), ), ); expect(semantics, includesNodeWith(actions: <SemanticsAction>[SemanticsAction.scrollUp])); // Jump to the end. controller.jumpTo(itemCount * itemHeight); await tester.pumpAndSettle(); expect(semantics, includesNodeWith(actions: <SemanticsAction>[SemanticsAction.scrollDown])); semantics.dispose(); }); testWidgets('reverse vertical', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListView.builder( reverse: true, controller: controller, itemCount: itemCount, itemBuilder: (BuildContext context, int index) { return SizedBox( height: itemHeight, child: Text('Tile $index'), ); }, ), ), ); expect(semantics, includesNodeWith(actions: <SemanticsAction>[SemanticsAction.scrollDown])); // Jump to the end. controller.jumpTo(itemCount * itemHeight); await tester.pumpAndSettle(); expect(semantics, includesNodeWith(actions: <SemanticsAction>[SemanticsAction.scrollUp])); semantics.dispose(); }); testWidgets('forward horizontal', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListView.builder( scrollDirection: Axis.horizontal, controller: controller, itemCount: itemCount, itemBuilder: (BuildContext context, int index) { return SizedBox( height: itemHeight, child: Text('Tile $index'), ); }, ), ), ); expect(semantics, includesNodeWith(actions: <SemanticsAction>[SemanticsAction.scrollLeft])); // Jump to the end. controller.jumpTo(itemCount * itemHeight); await tester.pumpAndSettle(); expect(semantics, includesNodeWith(actions: <SemanticsAction>[SemanticsAction.scrollRight])); semantics.dispose(); }); testWidgets('reverse horizontal', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListView.builder( scrollDirection: Axis.horizontal, reverse: true, controller: controller, itemCount: itemCount, itemBuilder: (BuildContext context, int index) { return SizedBox( height: itemHeight, child: Text('Tile $index'), ); }, ), ), ); expect(semantics, includesNodeWith(actions: <SemanticsAction>[SemanticsAction.scrollRight])); // Jump to the end. controller.jumpTo(itemCount * itemHeight); await tester.pumpAndSettle(); expect(semantics, includesNodeWith(actions: <SemanticsAction>[SemanticsAction.scrollLeft])); semantics.dispose(); }); }); }
flutter/packages/flutter/test/widgets/list_view_semantics_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/list_view_semantics_test.dart", "repo_id": "flutter", "token_count": 1965 }
303
// Copyright 2014 The Flutter 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:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; class HoverClient extends StatefulWidget { const HoverClient({ super.key, this.onHover, this.child, this.onEnter, this.onExit, }); final ValueChanged<bool>? onHover; final Widget? child; final VoidCallback? onEnter; final VoidCallback? onExit; @override HoverClientState createState() => HoverClientState(); } class HoverClientState extends State<HoverClient> { void _onExit(PointerExitEvent details) { widget.onExit?.call(); widget.onHover?.call(false); } void _onEnter(PointerEnterEvent details) { widget.onEnter?.call(); widget.onHover?.call(true); } @override Widget build(BuildContext context) { return MouseRegion( onEnter: _onEnter, onExit: _onExit, child: widget.child, ); } } class HoverFeedback extends StatefulWidget { const HoverFeedback({super.key, this.onEnter, this.onExit}); final VoidCallback? onEnter; final VoidCallback? onExit; @override State<HoverFeedback> createState() => _HoverFeedbackState(); } class _HoverFeedbackState extends State<HoverFeedback> { bool _hovering = false; @override Widget build(BuildContext context) { return Directionality( textDirection: TextDirection.ltr, child: HoverClient( onHover: (bool hovering) => setState(() => _hovering = hovering), onEnter: widget.onEnter, onExit: widget.onExit, child: Text(_hovering ? 'HOVERING' : 'not hovering'), ), ); } } void main() { // Regression test for https://github.com/flutter/flutter/issues/73330 testWidgets('hitTestBehavior test - HitTestBehavior.deferToChild/opaque', (WidgetTester tester) async { bool onEnter = false; await tester.pumpWidget(Center( child: MouseRegion( hitTestBehavior: HitTestBehavior.deferToChild, onEnter: (_) => onEnter = true, ), )); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: Offset.zero); await tester.pump(); // The child is null, so `onEnter` does not trigger. expect(onEnter, false); // Update to the default value `HitTestBehavior.opaque` await tester.pumpWidget(Center( child: MouseRegion( onEnter: (_) => onEnter = true, ), )); expect(onEnter, true); }); testWidgets('hitTestBehavior test - HitTestBehavior.deferToChild and non-opaque', (WidgetTester tester) async { bool onEnterRegion1 = false; bool onEnterRegion2 = false; await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ SizedBox( width: 50.0, height: 50.0, child: MouseRegion( onEnter: (_) => onEnterRegion1 = true, ), ), SizedBox( width: 50.0, height: 50.0, child: MouseRegion( opaque: false, hitTestBehavior: HitTestBehavior.deferToChild, onEnter: (_) => onEnterRegion2 = true, child: Container( color: const Color.fromARGB(0xff, 0xff, 0x10, 0x19), width: 50.0, height: 50.0, ), ), ), ], ), )); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: Offset.zero); await tester.pump(); expect(onEnterRegion2, true); expect(onEnterRegion1, true); }); testWidgets('hitTestBehavior test - HitTestBehavior.translucent', (WidgetTester tester) async { bool onEnterRegion1 = false; bool onEnterRegion2 = false; await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ SizedBox( width: 50.0, height: 50.0, child: MouseRegion( onEnter: (_) => onEnterRegion1 = true, ), ), SizedBox( width: 50.0, height: 50.0, child: MouseRegion( hitTestBehavior: HitTestBehavior.translucent, onEnter: (_) => onEnterRegion2 = true, ), ), ], ), )); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: Offset.zero); await tester.pump(); expect(onEnterRegion2, true); expect(onEnterRegion1, true); }); testWidgets('onEnter and onExit can be triggered with mouse buttons pressed', (WidgetTester tester) async { PointerEnterEvent? enter; PointerExitEvent? exit; await tester.pumpWidget(Center( child: MouseRegion( child: Container( color: const Color.fromARGB(0xff, 0xff, 0x00, 0x00), width: 100.0, height: 100.0, ), onEnter: (PointerEnterEvent details) => enter = details, onExit: (PointerExitEvent details) => exit = details, ), )); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: Offset.zero); await gesture.down(Offset.zero); // Press the mouse button. await tester.pump(); enter = null; exit = null; // Trigger the enter event. await gesture.moveTo(const Offset(400.0, 300.0)); expect(enter, isNotNull); expect(enter!.position, equals(const Offset(400.0, 300.0))); expect(enter!.localPosition, equals(const Offset(50.0, 50.0))); expect(exit, isNull); // Trigger the exit event. await gesture.moveTo(const Offset(1.0, 1.0)); expect(exit, isNotNull); expect(exit!.position, equals(const Offset(1.0, 1.0))); expect(exit!.localPosition, equals(const Offset(-349.0, -249.0))); }); testWidgets('detects pointer enter', (WidgetTester tester) async { PointerEnterEvent? enter; PointerHoverEvent? move; PointerExitEvent? exit; await tester.pumpWidget(Center( child: MouseRegion( child: Container( color: const Color.fromARGB(0xff, 0xff, 0x00, 0x00), width: 100.0, height: 100.0, ), onEnter: (PointerEnterEvent details) => enter = details, onHover: (PointerHoverEvent details) => move = details, onExit: (PointerExitEvent details) => exit = details, ), )); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: Offset.zero); await tester.pump(); move = null; enter = null; exit = null; await gesture.moveTo(const Offset(400.0, 300.0)); expect(move, isNotNull); expect(move!.position, equals(const Offset(400.0, 300.0))); expect(move!.localPosition, equals(const Offset(50.0, 50.0))); expect(enter, isNotNull); expect(enter!.position, equals(const Offset(400.0, 300.0))); expect(enter!.localPosition, equals(const Offset(50.0, 50.0))); expect(exit, isNull); }); testWidgets('detects pointer exiting', (WidgetTester tester) async { PointerEnterEvent? enter; PointerHoverEvent? move; PointerExitEvent? exit; await tester.pumpWidget(Center( child: MouseRegion( child: Container( color: const Color.fromARGB(0xff, 0xff, 0x00, 0x00), width: 100.0, height: 100.0, ), onEnter: (PointerEnterEvent details) => enter = details, onHover: (PointerHoverEvent details) => move = details, onExit: (PointerExitEvent details) => exit = details, ), )); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: Offset.zero); await gesture.moveTo(const Offset(400.0, 300.0)); await tester.pump(); move = null; enter = null; exit = null; await gesture.moveTo(const Offset(1.0, 1.0)); expect(move, isNull); expect(enter, isNull); expect(exit, isNotNull); expect(exit!.position, equals(const Offset(1.0, 1.0))); expect(exit!.localPosition, equals(const Offset(-349.0, -249.0))); }); testWidgets('triggers pointer enter when a mouse is connected', (WidgetTester tester) async { PointerEnterEvent? enter; PointerHoverEvent? move; PointerExitEvent? exit; await tester.pumpWidget(Center( child: MouseRegion( child: const SizedBox( width: 100.0, height: 100.0, ), onEnter: (PointerEnterEvent details) => enter = details, onHover: (PointerHoverEvent details) => move = details, onExit: (PointerExitEvent details) => exit = details, ), )); await tester.pump(); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: const Offset(400, 300)); expect(move, isNull); expect(enter, isNotNull); expect(enter!.position, equals(const Offset(400.0, 300.0))); expect(enter!.localPosition, equals(const Offset(50.0, 50.0))); expect(exit, isNull); }); testWidgets('triggers pointer exit when a mouse is disconnected', (WidgetTester tester) async { PointerEnterEvent? enter; PointerHoverEvent? move; PointerExitEvent? exit; await tester.pumpWidget(Center( child: MouseRegion( child: const SizedBox( width: 100.0, height: 100.0, ), onEnter: (PointerEnterEvent details) => enter = details, onHover: (PointerHoverEvent details) => move = details, onExit: (PointerExitEvent details) => exit = details, ), )); await tester.pump(); TestGesture? gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: const Offset(400, 300)); addTearDown(() => gesture?.removePointer); await tester.pump(); move = null; enter = null; exit = null; await gesture.removePointer(); gesture = null; expect(move, isNull); expect(enter, isNull); expect(exit, isNotNull); expect(exit!.position, equals(const Offset(400.0, 300.0))); expect(exit!.localPosition, equals(const Offset(50.0, 50.0))); exit = null; await tester.pump(); expect(move, isNull); expect(enter, isNull); expect(exit, isNull); }); testWidgets('triggers pointer enter when widget appears', (WidgetTester tester) async { PointerEnterEvent? enter; PointerHoverEvent? move; PointerExitEvent? exit; await tester.pumpWidget(const Center( child: SizedBox( width: 100.0, height: 100.0, ), )); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: Offset.zero); await gesture.moveTo(const Offset(400.0, 300.0)); await tester.pump(); expect(enter, isNull); expect(move, isNull); expect(exit, isNull); await tester.pumpWidget(Center( child: MouseRegion( child: const SizedBox( width: 100.0, height: 100.0, ), onEnter: (PointerEnterEvent details) => enter = details, onHover: (PointerHoverEvent details) => move = details, onExit: (PointerExitEvent details) => exit = details, ), )); await tester.pump(); expect(move, isNull); expect(enter, isNotNull); expect(enter!.position, equals(const Offset(400.0, 300.0))); expect(enter!.localPosition, equals(const Offset(50.0, 50.0))); expect(exit, isNull); }); testWidgets("doesn't trigger pointer exit when widget disappears", (WidgetTester tester) async { PointerEnterEvent? enter; PointerHoverEvent? move; PointerExitEvent? exit; await tester.pumpWidget(Center( child: MouseRegion( child: const SizedBox( width: 100.0, height: 100.0, ), onEnter: (PointerEnterEvent details) => enter = details, onHover: (PointerHoverEvent details) => move = details, onExit: (PointerExitEvent details) => exit = details, ), )); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: Offset.zero); await gesture.moveTo(const Offset(400.0, 300.0)); await tester.pump(); move = null; enter = null; exit = null; await tester.pumpWidget(const Center( child: SizedBox( width: 100.0, height: 100.0, ), )); expect(enter, isNull); expect(move, isNull); expect(exit, isNull); }); testWidgets('triggers pointer enter when widget moves in', (WidgetTester tester) async { PointerEnterEvent? enter; PointerHoverEvent? move; PointerExitEvent? exit; await tester.pumpWidget(Container( alignment: Alignment.topLeft, child: MouseRegion( child: const SizedBox( width: 100.0, height: 100.0, ), onEnter: (PointerEnterEvent details) => enter = details, onHover: (PointerHoverEvent details) => move = details, onExit: (PointerExitEvent details) => exit = details, ), )); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: const Offset(401.0, 301.0)); await tester.pump(); expect(enter, isNull); expect(move, isNull); expect(exit, isNull); await tester.pumpWidget(Container( alignment: Alignment.center, child: MouseRegion( child: const SizedBox( width: 100.0, height: 100.0, ), onEnter: (PointerEnterEvent details) => enter = details, onHover: (PointerHoverEvent details) => move = details, onExit: (PointerExitEvent details) => exit = details, ), )); await tester.pump(); expect(enter, isNotNull); expect(enter!.position, equals(const Offset(401.0, 301.0))); expect(enter!.localPosition, equals(const Offset(51.0, 51.0))); expect(move, isNull); expect(exit, isNull); }); testWidgets('triggers pointer exit when widget moves out', (WidgetTester tester) async { PointerEnterEvent? enter; PointerHoverEvent? move; PointerExitEvent? exit; await tester.pumpWidget(Container( alignment: Alignment.center, child: MouseRegion( child: const SizedBox( width: 100.0, height: 100.0, ), onEnter: (PointerEnterEvent details) => enter = details, onHover: (PointerHoverEvent details) => move = details, onExit: (PointerExitEvent details) => exit = details, ), )); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: const Offset(400, 300)); await tester.pump(); enter = null; move = null; exit = null; await tester.pumpWidget(Container( alignment: Alignment.topLeft, child: MouseRegion( child: const SizedBox( width: 100.0, height: 100.0, ), onEnter: (PointerEnterEvent details) => enter = details, onHover: (PointerHoverEvent details) => move = details, onExit: (PointerExitEvent details) => exit = details, ), )); await tester.pump(); expect(enter, isNull); expect(move, isNull); expect(exit, isNotNull); expect(exit!.position, equals(const Offset(400, 300))); expect(exit!.localPosition, equals(const Offset(50, 50))); }); testWidgets('detects hover from touch devices', (WidgetTester tester) async { PointerEnterEvent? enter; PointerHoverEvent? move; PointerExitEvent? exit; await tester.pumpWidget(Center( child: MouseRegion( child: Container( color: const Color.fromARGB(0xff, 0xff, 0x00, 0x00), width: 100.0, height: 100.0, ), onEnter: (PointerEnterEvent details) => enter = details, onHover: (PointerHoverEvent details) => move = details, onExit: (PointerExitEvent details) => exit = details, ), )); final TestGesture gesture = await tester.createGesture(); await gesture.addPointer(location: Offset.zero); await tester.pump(); move = null; enter = null; exit = null; await gesture.moveTo(const Offset(400.0, 300.0)); expect(move, isNotNull); expect(move!.position, equals(const Offset(400.0, 300.0))); expect(move!.localPosition, equals(const Offset(50.0, 50.0))); expect(enter, isNull); expect(exit, isNull); }); testWidgets('Hover works with nested listeners', (WidgetTester tester) async { final UniqueKey key1 = UniqueKey(); final UniqueKey key2 = UniqueKey(); final List<PointerEnterEvent> enter1 = <PointerEnterEvent>[]; final List<PointerHoverEvent> move1 = <PointerHoverEvent>[]; final List<PointerExitEvent> exit1 = <PointerExitEvent>[]; final List<PointerEnterEvent> enter2 = <PointerEnterEvent>[]; final List<PointerHoverEvent> move2 = <PointerHoverEvent>[]; final List<PointerExitEvent> exit2 = <PointerExitEvent>[]; void clearLists() { enter1.clear(); move1.clear(); exit1.clear(); enter2.clear(); move2.clear(); exit2.clear(); } await tester.pumpWidget(Container()); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.moveTo(const Offset(400.0, 0.0)); await tester.pump(); await tester.pumpWidget( Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ MouseRegion( onEnter: (PointerEnterEvent details) => enter1.add(details), onHover: (PointerHoverEvent details) => move1.add(details), onExit: (PointerExitEvent details) => exit1.add(details), key: key1, child: Container( width: 200, height: 200, padding: const EdgeInsets.all(50.0), child: MouseRegion( key: key2, onEnter: (PointerEnterEvent details) => enter2.add(details), onHover: (PointerHoverEvent details) => move2.add(details), onExit: (PointerExitEvent details) => exit2.add(details), child: Container(), ), ), ), ], ), ); Offset center = tester.getCenter(find.byKey(key2)); await gesture.moveTo(center); await tester.pump(); expect(move2, isNotEmpty); expect(enter2, isNotEmpty); expect(exit2, isEmpty); expect(move1, isNotEmpty); expect(move1.last.position, equals(center)); expect(enter1, isNotEmpty); expect(enter1.last.position, equals(center)); expect(exit1, isEmpty); clearLists(); // Now make sure that exiting the child only triggers the child exit, not // the parent too. center = center - const Offset(75.0, 0.0); await gesture.moveTo(center); await tester.pumpAndSettle(); expect(move2, isEmpty); expect(enter2, isEmpty); expect(exit2, isNotEmpty); expect(move1, isNotEmpty); expect(move1.last.position, equals(center)); expect(enter1, isEmpty); expect(exit1, isEmpty); clearLists(); }); testWidgets('Hover transfers between two listeners', (WidgetTester tester) async { final UniqueKey key1 = UniqueKey(); final UniqueKey key2 = UniqueKey(); final List<PointerEnterEvent> enter1 = <PointerEnterEvent>[]; final List<PointerHoverEvent> move1 = <PointerHoverEvent>[]; final List<PointerExitEvent> exit1 = <PointerExitEvent>[]; final List<PointerEnterEvent> enter2 = <PointerEnterEvent>[]; final List<PointerHoverEvent> move2 = <PointerHoverEvent>[]; final List<PointerExitEvent> exit2 = <PointerExitEvent>[]; void clearLists() { enter1.clear(); move1.clear(); exit1.clear(); enter2.clear(); move2.clear(); exit2.clear(); } await tester.pumpWidget(Container()); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.moveTo(const Offset(400.0, 0.0)); await tester.pump(); await tester.pumpWidget( Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ MouseRegion( key: key1, child: const SizedBox( width: 100.0, height: 100.0, ), onEnter: (PointerEnterEvent details) => enter1.add(details), onHover: (PointerHoverEvent details) => move1.add(details), onExit: (PointerExitEvent details) => exit1.add(details), ), MouseRegion( key: key2, child: const SizedBox( width: 100.0, height: 100.0, ), onEnter: (PointerEnterEvent details) => enter2.add(details), onHover: (PointerHoverEvent details) => move2.add(details), onExit: (PointerExitEvent details) => exit2.add(details), ), ], ), ); final Offset center1 = tester.getCenter(find.byKey(key1)); final Offset center2 = tester.getCenter(find.byKey(key2)); await gesture.moveTo(center1); await tester.pump(); expect(move1, isNotEmpty); expect(move1.last.position, equals(center1)); expect(enter1, isNotEmpty); expect(enter1.last.position, equals(center1)); expect(exit1, isEmpty); expect(move2, isEmpty); expect(enter2, isEmpty); expect(exit2, isEmpty); clearLists(); await gesture.moveTo(center2); await tester.pump(); expect(move1, isEmpty); expect(enter1, isEmpty); expect(exit1, isNotEmpty); expect(exit1.last.position, equals(center2)); expect(move2, isNotEmpty); expect(move2.last.position, equals(center2)); expect(enter2, isNotEmpty); expect(enter2.last.position, equals(center2)); expect(exit2, isEmpty); clearLists(); await gesture.moveTo(const Offset(400.0, 450.0)); await tester.pump(); expect(move1, isEmpty); expect(enter1, isEmpty); expect(exit1, isEmpty); expect(move2, isEmpty); expect(enter2, isEmpty); expect(exit2, isNotEmpty); expect(exit2.last.position, equals(const Offset(400.0, 450.0))); clearLists(); await tester.pumpWidget(Container()); expect(move1, isEmpty); expect(enter1, isEmpty); expect(exit1, isEmpty); expect(move2, isEmpty); expect(enter2, isEmpty); expect(exit2, isEmpty); }); testWidgets('applies mouse cursor', (WidgetTester tester) async { await tester.pumpWidget(const _Scaffold( topLeft: MouseRegion( cursor: SystemMouseCursors.text, child: SizedBox(width: 10, height: 10), ), )); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: const Offset(100, 100)); await tester.pump(); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic); await gesture.moveTo(const Offset(5, 5)); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text); await gesture.moveTo(const Offset(100, 100)); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic); }); testWidgets('MouseRegion uses updated callbacks', (WidgetTester tester) async { final List<String> logs = <String>[]; Widget hoverableContainer({ PointerEnterEventListener? onEnter, PointerHoverEventListener? onHover, PointerExitEventListener? onExit, }) { return Container( alignment: Alignment.topLeft, child: MouseRegion( onEnter: onEnter, onHover: onHover, onExit: onExit, child: Container( color: const Color.fromARGB(0xff, 0xff, 0x00, 0x00), width: 100.0, height: 100.0, ), ), ); } await tester.pumpWidget(hoverableContainer( onEnter: (PointerEnterEvent details) { logs.add('enter1'); }, onHover: (PointerHoverEvent details) { logs.add('hover1'); }, onExit: (PointerExitEvent details) { logs.add('exit1'); }, )); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: const Offset(150.0, 150.0)); // Start outside, move inside, then move outside await gesture.moveTo(const Offset(150.0, 150.0)); await tester.pump(); expect(logs, isEmpty); logs.clear(); await gesture.moveTo(const Offset(50.0, 50.0)); await tester.pump(); await gesture.moveTo(const Offset(150.0, 150.0)); await tester.pump(); expect(logs, <String>['enter1', 'hover1', 'exit1']); logs.clear(); // Same tests but with updated callbacks await tester.pumpWidget(hoverableContainer( onEnter: (PointerEnterEvent details) => logs.add('enter2'), onHover: (PointerHoverEvent details) => logs.add('hover2'), onExit: (PointerExitEvent details) => logs.add('exit2'), )); await gesture.moveTo(const Offset(150.0, 150.0)); await tester.pump(); await gesture.moveTo(const Offset(50.0, 50.0)); await tester.pump(); await gesture.moveTo(const Offset(150.0, 150.0)); await tester.pump(); expect(logs, <String>['enter2', 'hover2', 'exit2']); }); testWidgets('needsCompositing set when parent class needsCompositing is set', (WidgetTester tester) async { await tester.pumpWidget( MouseRegion( onEnter: (PointerEnterEvent _) {}, child: const RepaintBoundary(child: Placeholder()), ), ); RenderMouseRegion listener = tester.renderObject(find.byType(MouseRegion).first); expect(listener.needsCompositing, isTrue); await tester.pumpWidget( MouseRegion( onEnter: (PointerEnterEvent _) {}, child: const Placeholder(), ), ); listener = tester.renderObject(find.byType(MouseRegion).first); expect(listener.needsCompositing, isFalse); }); testWidgets('works with transform', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/31986. final Key key = UniqueKey(); const double scaleFactor = 2.0; const double localWidth = 150.0; const double localHeight = 100.0; final List<PointerEvent> events = <PointerEvent>[]; await tester.pumpWidget( MaterialApp( home: Center( child: Transform.scale( scale: scaleFactor, child: MouseRegion( onEnter: (PointerEnterEvent event) { events.add(event); }, onHover: (PointerHoverEvent event) { events.add(event); }, onExit: (PointerExitEvent event) { events.add(event); }, child: Container( key: key, color: Colors.blue, height: localHeight, width: localWidth, child: const Text('Hi'), ), ), ), ), ), ); final Offset topLeft = tester.getTopLeft(find.byKey(key)); final Offset topRight = tester.getTopRight(find.byKey(key)); final Offset bottomLeft = tester.getBottomLeft(find.byKey(key)); expect(topRight.dx - topLeft.dx, scaleFactor * localWidth); expect(bottomLeft.dy - topLeft.dy, scaleFactor * localHeight); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(); await gesture.moveTo(topLeft - const Offset(1, 1)); await tester.pump(); expect(events, isEmpty); await gesture.moveTo(topLeft + const Offset(1, 1)); await tester.pump(); expect(events, hasLength(2)); expect(events.first, isA<PointerEnterEvent>()); expect(events.last, isA<PointerHoverEvent>()); events.clear(); await gesture.moveTo(bottomLeft + const Offset(1, -1)); await tester.pump(); expect(events.single, isA<PointerHoverEvent>()); expect(events.single.delta, const Offset(0.0, scaleFactor * localHeight - 2)); events.clear(); await gesture.moveTo(bottomLeft + const Offset(1, 1)); await tester.pump(); expect(events.single, isA<PointerExitEvent>()); events.clear(); }); testWidgets('needsCompositing is always false', (WidgetTester tester) async { // Pretend that we have a mouse connected. final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(); await tester.pumpWidget( Transform.scale( scale: 2.0, child: const MouseRegion(opaque: false), ), ); final RenderMouseRegion mouseRegion = tester.renderObject(find.byType(MouseRegion)); expect(mouseRegion.needsCompositing, isFalse); // No TransformLayer for `Transform.scale` is added because composting is // not required and therefore the transform is executed on the canvas // directly. (One TransformLayer is always present for the root // transform.) expect(tester.layers.whereType<TransformLayer>(), hasLength(1)); // Test that needsCompositing stays false with callback change await tester.pumpWidget( Transform.scale( scale: 2.0, child: MouseRegion( opaque: false, onHover: (PointerHoverEvent _) {}, ), ), ); expect(mouseRegion.needsCompositing, isFalse); // If compositing was required, a dedicated TransformLayer for // `Transform.scale` would be added. expect(tester.layers.whereType<TransformLayer>(), hasLength(1)); }); testWidgets("Callbacks aren't called during build", (WidgetTester tester) async { final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: Offset.zero); int numEntrances = 0; int numExits = 0; await tester.pumpWidget( Center( child: HoverFeedback( onEnter: () { numEntrances += 1; }, onExit: () { numExits += 1; }, ), ), ); await gesture.moveTo(tester.getCenter(find.byType(Text))); await tester.pumpAndSettle(); expect(numEntrances, equals(1)); expect(numExits, equals(0)); expect(find.text('HOVERING'), findsOneWidget); await tester.pumpWidget( Container(), ); await tester.pump(); expect(numEntrances, equals(1)); expect(numExits, equals(0)); await tester.pumpWidget( Center( child: HoverFeedback( onEnter: () { numEntrances += 1; }, onExit: () { numExits += 1; }, ), ), ); await tester.pump(); expect(numEntrances, equals(2)); expect(numExits, equals(0)); }); testWidgets("MouseRegion activate/deactivate don't duplicate annotations", (WidgetTester tester) async { final GlobalKey feedbackKey = GlobalKey(); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(); int numEntrances = 0; int numExits = 0; await tester.pumpWidget( Center( child: HoverFeedback( key: feedbackKey, onEnter: () { numEntrances += 1; }, onExit: () { numExits += 1; }, ), ), ); await gesture.moveTo(tester.getCenter(find.byType(Text))); await tester.pumpAndSettle(); expect(numEntrances, equals(1)); expect(numExits, equals(0)); expect(find.text('HOVERING'), findsOneWidget); await tester.pumpWidget( Center( child: HoverFeedback( key: feedbackKey, onEnter: () { numEntrances += 1; }, onExit: () { numExits += 1; }, ), ), ); await tester.pump(); expect(numEntrances, equals(1)); expect(numExits, equals(0)); await tester.pumpWidget( Container(), ); await tester.pump(); expect(numEntrances, equals(1)); expect(numExits, equals(0)); }); testWidgets('Exit event when unplugging mouse should have a position', (WidgetTester tester) async { final List<PointerEnterEvent> enter = <PointerEnterEvent>[]; final List<PointerHoverEvent> hover = <PointerHoverEvent>[]; final List<PointerExitEvent> exit = <PointerExitEvent>[]; await tester.pumpWidget( Center( child: MouseRegion( onEnter: (PointerEnterEvent e) => enter.add(e), onHover: (PointerHoverEvent e) => hover.add(e), onExit: (PointerExitEvent e) => exit.add(e), child: const SizedBox( height: 100.0, width: 100.0, ), ), ), ); // Plug-in a mouse and move it to the center of the container. TestGesture? gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: Offset.zero); addTearDown(() => gesture?.removePointer()); await tester.pumpAndSettle(); await gesture.moveTo(tester.getCenter(find.byType(SizedBox))); expect(enter.length, 1); expect(enter.single.position, const Offset(400.0, 300.0)); expect(hover.length, 1); expect(hover.single.position, const Offset(400.0, 300.0)); expect(exit.length, 0); enter.clear(); hover.clear(); exit.clear(); // Unplug the mouse. await gesture.removePointer(); gesture = null; await tester.pumpAndSettle(); expect(enter.length, 0); expect(hover.length, 0); expect(exit.length, 1); expect(exit.single.position, const Offset(400.0, 300.0)); expect(exit.single.delta, Offset.zero); }); testWidgets('detects pointer enter with closure arguments', (WidgetTester tester) async { await tester.pumpWidget(const _HoverClientWithClosures()); expect(find.text('not hovering'), findsOneWidget); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(); // Move to a position out of MouseRegion await gesture.moveTo(tester.getBottomRight(find.byType(MouseRegion)) + const Offset(10, -10)); await tester.pumpAndSettle(); expect(find.text('not hovering'), findsOneWidget); // Move into MouseRegion await gesture.moveBy(const Offset(-20, 0)); await tester.pumpAndSettle(); expect(find.text('HOVERING'), findsOneWidget); }); testWidgets('MouseRegion paints child once and only once when MouseRegion is inactive', (WidgetTester tester) async { int paintCount = 0; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: MouseRegion( onEnter: (PointerEnterEvent e) {}, child: CustomPaint( painter: _DelegatedPainter(onPaint: () { paintCount += 1; }), child: const Text('123'), ), ), ), ); expect(paintCount, 1); }); testWidgets('MouseRegion paints child once and only once when MouseRegion is active', (WidgetTester tester) async { int paintCount = 0; final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: MouseRegion( onEnter: (PointerEnterEvent e) {}, child: CustomPaint( painter: _DelegatedPainter(onPaint: () { paintCount += 1; }), child: const Text('123'), ), ), ), ); expect(paintCount, 1); }); testWidgets('A MouseRegion mounted under the pointer should take effect in the next postframe', (WidgetTester tester) async { bool hovered = false; final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: const Offset(5, 5)); await tester.pumpWidget( StatefulBuilder(builder: (BuildContext context, StateSetter setState) { return _ColumnContainer( children: <Widget>[ Text(hovered ? 'hover outer' : 'unhover outer'), ], ); }), ); expect(find.text('unhover outer'), findsOneWidget); await tester.pumpWidget( StatefulBuilder(builder: (BuildContext context, StateSetter setState) { return _ColumnContainer( children: <Widget>[ HoverClient( onHover: (bool value) { setState(() { hovered = value; }); }, child: Text(hovered ? 'hover inner' : 'unhover inner'), ), Text(hovered ? 'hover outer' : 'unhover outer'), ], ); }), ); expect(find.text('unhover outer'), findsOneWidget); expect(find.text('unhover inner'), findsOneWidget); await tester.pump(); expect(find.text('hover outer'), findsOneWidget); expect(find.text('hover inner'), findsOneWidget); expect(tester.binding.hasScheduledFrame, isFalse); }); testWidgets('A MouseRegion unmounted under the pointer should not trigger state change', (WidgetTester tester) async { bool hovered = true; final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: const Offset(5, 5)); await tester.pumpWidget( StatefulBuilder(builder: (BuildContext context, StateSetter setState) { return _ColumnContainer( children: <Widget>[ HoverClient( onHover: (bool value) { setState(() { hovered = value; }); }, child: Text(hovered ? 'hover inner' : 'unhover inner'), ), Text(hovered ? 'hover outer' : 'unhover outer'), ], ); }), ); expect(find.text('hover outer'), findsOneWidget); expect(find.text('hover inner'), findsOneWidget); expect(tester.binding.hasScheduledFrame, isTrue); await tester.pump(); expect(find.text('hover outer'), findsOneWidget); expect(find.text('hover inner'), findsOneWidget); expect(tester.binding.hasScheduledFrame, isFalse); await tester.pumpWidget( StatefulBuilder(builder: (BuildContext context, StateSetter setState) { return _ColumnContainer( children: <Widget> [ Text(hovered ? 'hover outer' : 'unhover outer'), ], ); }), ); expect(find.text('hover outer'), findsOneWidget); expect(tester.binding.hasScheduledFrame, isFalse); }); testWidgets('A MouseRegion moved into the mouse should take effect in the next postframe', (WidgetTester tester) async { bool hovered = false; final List<bool> logHovered = <bool>[]; bool moved = false; late StateSetter mySetState; final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: const Offset(5, 5)); await tester.pumpWidget( StatefulBuilder(builder: (BuildContext context, StateSetter setState) { mySetState = setState; return _ColumnContainer( children: <Widget>[ Container( height: 100, width: 10, alignment: moved ? Alignment.topLeft : Alignment.bottomLeft, child: SizedBox( height: 10, width: 10, child: HoverClient( onHover: (bool value) { setState(() { hovered = value; }); logHovered.add(value); }, child: Text(hovered ? 'hover inner' : 'unhover inner'), ), ), ), Text(hovered ? 'hover outer' : 'unhover outer'), ], ); }), ); expect(find.text('unhover inner'), findsOneWidget); expect(find.text('unhover outer'), findsOneWidget); expect(logHovered, isEmpty); expect(tester.binding.hasScheduledFrame, isFalse); mySetState(() { moved = true; }); // The first frame is for the widget movement to take effect. await tester.pump(); expect(find.text('unhover inner'), findsOneWidget); expect(find.text('unhover outer'), findsOneWidget); expect(logHovered, <bool>[true]); logHovered.clear(); // The second frame is for the mouse hover to take effect. await tester.pump(); expect(find.text('hover inner'), findsOneWidget); expect(find.text('hover outer'), findsOneWidget); expect(logHovered, isEmpty); expect(tester.binding.hasScheduledFrame, isFalse); }); group('MouseRegion respects opacity:', () { // A widget that contains 3 MouseRegions: // y // —————————————————————— 0 // | ——————————— A | 20 // | | B | | // | | ——————————— | 50 // | | | C | | // | ——————| | | 100 // | | | | // | ——————————— | 130 // —————————————————————— 150 // x 0 20 50 100 130 150 Widget tripleRegions({bool? opaqueC, required void Function(String) addLog}) { // Same as MouseRegion, but when opaque is null, use the default value. Widget mouseRegionWithOptionalOpaque({ void Function(PointerEnterEvent e)? onEnter, void Function(PointerHoverEvent e)? onHover, void Function(PointerExitEvent e)? onExit, Widget? child, bool? opaque, }) { if (opaque == null) { return MouseRegion(onEnter: onEnter, onHover: onHover, onExit: onExit, child: child); } return MouseRegion(onEnter: onEnter, onHover: onHover, onExit: onExit, opaque: opaque, child: child); } return Directionality( textDirection: TextDirection.ltr, child: Align( alignment: Alignment.topLeft, child: MouseRegion( onEnter: (PointerEnterEvent e) { addLog('enterA'); }, onHover: (PointerHoverEvent e) { addLog('hoverA'); }, onExit: (PointerExitEvent e) { addLog('exitA'); }, child: SizedBox( width: 150, height: 150, child: Stack( children: <Widget>[ Positioned( left: 20, top: 20, width: 80, height: 80, child: MouseRegion( onEnter: (PointerEnterEvent e) { addLog('enterB'); }, onHover: (PointerHoverEvent e) { addLog('hoverB'); }, onExit: (PointerExitEvent e) { addLog('exitB'); }, ), ), Positioned( left: 50, top: 50, width: 80, height: 80, child: mouseRegionWithOptionalOpaque( opaque: opaqueC, onEnter: (PointerEnterEvent e) { addLog('enterC'); }, onHover: (PointerHoverEvent e) { addLog('hoverC'); }, onExit: (PointerExitEvent e) { addLog('exitC'); }, ), ), ], ), ), ), ), ); } testWidgets('a transparent one should allow MouseRegions behind it to receive pointers', (WidgetTester tester) async { final List<String> logs = <String>[]; await tester.pumpWidget(tripleRegions( opaqueC: false, addLog: (String log) => logs.add(log), )); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(); await tester.pumpAndSettle(); // Move to the overlapping area. await gesture.moveTo(const Offset(75, 75)); await tester.pumpAndSettle(); expect(logs, <String>['enterA', 'enterB', 'enterC', 'hoverC', 'hoverB', 'hoverA']); logs.clear(); // Move to the B only area. await gesture.moveTo(const Offset(25, 75)); await tester.pumpAndSettle(); expect(logs, <String>['exitC', 'hoverB', 'hoverA']); logs.clear(); // Move back to the overlapping area. await gesture.moveTo(const Offset(75, 75)); await tester.pumpAndSettle(); expect(logs, <String>['enterC', 'hoverC', 'hoverB', 'hoverA']); logs.clear(); // Move to the C only area. await gesture.moveTo(const Offset(125, 75)); await tester.pumpAndSettle(); expect(logs, <String>['exitB', 'hoverC', 'hoverA']); logs.clear(); // Move back to the overlapping area. await gesture.moveTo(const Offset(75, 75)); await tester.pumpAndSettle(); expect(logs, <String>['enterB', 'hoverC', 'hoverB', 'hoverA']); logs.clear(); // Move out. await gesture.moveTo(const Offset(160, 160)); await tester.pumpAndSettle(); expect(logs, <String>['exitC', 'exitB', 'exitA']); }); testWidgets('an opaque one should prevent MouseRegions behind it receiving pointers', (WidgetTester tester) async { final List<String> logs = <String>[]; await tester.pumpWidget(tripleRegions( opaqueC: true, addLog: (String log) => logs.add(log), )); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(); await tester.pumpAndSettle(); // Move to the overlapping area. await gesture.moveTo(const Offset(75, 75)); await tester.pumpAndSettle(); expect(logs, <String>['enterA', 'enterC', 'hoverC', 'hoverA']); logs.clear(); // Move to the B only area. await gesture.moveTo(const Offset(25, 75)); await tester.pumpAndSettle(); expect(logs, <String>['exitC', 'enterB', 'hoverB', 'hoverA']); logs.clear(); // Move back to the overlapping area. await gesture.moveTo(const Offset(75, 75)); await tester.pumpAndSettle(); expect(logs, <String>['exitB', 'enterC', 'hoverC', 'hoverA']); logs.clear(); // Move to the C only area. await gesture.moveTo(const Offset(125, 75)); await tester.pumpAndSettle(); expect(logs, <String>['hoverC', 'hoverA']); logs.clear(); // Move back to the overlapping area. await gesture.moveTo(const Offset(75, 75)); await tester.pumpAndSettle(); expect(logs, <String>['hoverC', 'hoverA']); logs.clear(); // Move out. await gesture.moveTo(const Offset(160, 160)); await tester.pumpAndSettle(); expect(logs, <String>['exitC', 'exitA']); }); testWidgets('opaque should default to true', (WidgetTester tester) async { final List<String> logs = <String>[]; await tester.pumpWidget(tripleRegions( addLog: (String log) => logs.add(log), )); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(); await tester.pumpAndSettle(); // Move to the overlapping area. await gesture.moveTo(const Offset(75, 75)); await tester.pumpAndSettle(); expect(logs, <String>['enterA', 'enterC', 'hoverC', 'hoverA']); logs.clear(); // Move out. await gesture.moveTo(const Offset(160, 160)); await tester.pumpAndSettle(); expect(logs, <String>['exitC', 'exitA']); }); }); testWidgets('an empty opaque MouseRegion is effective', (WidgetTester tester) async { bool bottomRegionIsHovered = false; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Align( alignment: Alignment.topLeft, child: MouseRegion( onEnter: (_) { bottomRegionIsHovered = true; }, onHover: (_) { bottomRegionIsHovered = true; }, onExit: (_) { bottomRegionIsHovered = true; }, child: const SizedBox( width: 10, height: 10, ), ), ), const MouseRegion(), ], ), ), ); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: const Offset(20, 20)); await gesture.moveTo(const Offset(5, 5)); await tester.pump(); await gesture.moveTo(const Offset(20, 20)); await tester.pump(); expect(bottomRegionIsHovered, isFalse); }); testWidgets("Changing MouseRegion's callbacks is effective and doesn't repaint", (WidgetTester tester) async { final List<String> logs = <String>[]; const Key key = ValueKey<int>(1); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: const Offset(20, 20)); await tester.pumpWidget(_Scaffold( topLeft: SizedBox( height: 10, width: 10, child: MouseRegion( onEnter: (_) { logs.add('enter1'); }, onHover: (_) { logs.add('hover1'); }, onExit: (_) { logs.add('exit1'); }, child: CustomPaint( painter: _DelegatedPainter(onPaint: () { logs.add('paint'); }, key: key), ), ), ), )); expect(logs, <String>['paint']); logs.clear(); await gesture.moveTo(const Offset(5, 5)); expect(logs, <String>['enter1', 'hover1']); logs.clear(); await tester.pumpWidget(_Scaffold( topLeft: SizedBox( height: 10, width: 10, child: MouseRegion( onEnter: (_) { logs.add('enter2'); }, onHover: (_) { logs.add('hover2'); }, onExit: (_) { logs.add('exit2'); }, child: CustomPaint( painter: _DelegatedPainter(onPaint: () { logs.add('paint'); }, key: key), ), ), ), )); expect(logs, isEmpty); await gesture.moveTo(const Offset(6, 6)); expect(logs, <String>['hover2']); logs.clear(); // Compare: It repaints if the MouseRegion is deactivated. await tester.pumpWidget(_Scaffold( topLeft: SizedBox( height: 10, width: 10, child: MouseRegion( opaque: false, child: CustomPaint( painter: _DelegatedPainter(onPaint: () { logs.add('paint'); }, key: key), ), ), ), )); expect(logs, <String>['paint']); }); testWidgets('Changing MouseRegion.opaque is effective and repaints', (WidgetTester tester) async { final List<String> logs = <String>[]; final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: const Offset(5, 5)); void handleHover(PointerHoverEvent _) {} void handlePaintChild() { logs.add('paint'); } await tester.pumpWidget(_Scaffold( topLeft: SizedBox( height: 10, width: 10, child: MouseRegion( onHover: handleHover, child: CustomPaint(painter: _DelegatedPainter(onPaint: handlePaintChild)), ), ), background: MouseRegion(onEnter: (_) { logs.add('hover-enter'); }), )); expect(logs, <String>['paint']); logs.clear(); expect(logs, isEmpty); logs.clear(); await tester.pumpWidget(_Scaffold( topLeft: SizedBox( height: 10, width: 10, child: MouseRegion( opaque: false, // Dummy callback so that MouseRegion stays affective after opaque // turns false. onHover: handleHover, child: CustomPaint(painter: _DelegatedPainter(onPaint: handlePaintChild)), ), ), background: MouseRegion(onEnter: (_) { logs.add('hover-enter'); }), )); expect(logs, <String>['paint', 'hover-enter']); }); testWidgets('Changing MouseRegion.cursor is effective and repaints', (WidgetTester tester) async { final List<String> logPaints = <String>[]; final List<String> logEnters = <String>[]; final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: const Offset(100, 100)); void onPaintChild() { logPaints.add('paint'); } await tester.pumpWidget(_Scaffold( topLeft: SizedBox( height: 10, width: 10, child: MouseRegion( cursor: SystemMouseCursors.forbidden, onEnter: (_) { logEnters.add('enter'); }, child: CustomPaint(painter: _DelegatedPainter(onPaint: onPaintChild)), ), ), )); await gesture.moveTo(const Offset(5, 5)); expect(logPaints, <String>['paint']); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.forbidden); expect(logEnters, <String>['enter']); logPaints.clear(); logEnters.clear(); await tester.pumpWidget(_Scaffold( topLeft: SizedBox( height: 10, width: 10, child: MouseRegion( cursor: SystemMouseCursors.text, onEnter: (_) { logEnters.add('enter'); }, child: CustomPaint(painter: _DelegatedPainter(onPaint: onPaintChild)), ), ), )); expect(logPaints, <String>['paint']); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text); expect(logEnters, isEmpty); logPaints.clear(); logEnters.clear(); }); testWidgets('Changing whether MouseRegion.cursor is null is effective and repaints', (WidgetTester tester) async { final List<String> logEnters = <String>[]; final List<String> logPaints = <String>[]; final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: const Offset(100, 100)); void onPaintChild() { logPaints.add('paint'); } await tester.pumpWidget(_Scaffold( topLeft: SizedBox( height: 10, width: 10, child: MouseRegion( cursor: SystemMouseCursors.forbidden, child: MouseRegion( cursor: SystemMouseCursors.text, onEnter: (_) { logEnters.add('enter'); }, child: CustomPaint(painter: _DelegatedPainter(onPaint: onPaintChild)), ), ), ), )); await gesture.moveTo(const Offset(5, 5)); expect(logPaints, <String>['paint']); expect(logEnters, <String>['enter']); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text); logPaints.clear(); logEnters.clear(); await tester.pumpWidget(_Scaffold( topLeft: SizedBox( height: 10, width: 10, child: MouseRegion( cursor: SystemMouseCursors.forbidden, child: MouseRegion( onEnter: (_) { logEnters.add('enter'); }, child: CustomPaint(painter: _DelegatedPainter(onPaint: onPaintChild)), ), ), ), )); expect(logPaints, <String>['paint']); expect(logEnters, isEmpty); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.forbidden); logPaints.clear(); logEnters.clear(); await tester.pumpWidget(_Scaffold( topLeft: SizedBox( height: 10, width: 10, child: MouseRegion( cursor: SystemMouseCursors.forbidden, child: MouseRegion( cursor: SystemMouseCursors.text, child: CustomPaint(painter: _DelegatedPainter(onPaint: onPaintChild)), ), ), ), )); expect(logPaints, <String>['paint']); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text); expect(logEnters, isEmpty); logPaints.clear(); logEnters.clear(); }); testWidgets('Does not trigger side effects during a reparent', (WidgetTester tester) async { final List<String> logEnters = <String>[]; final List<String> logExits = <String>[]; final List<String> logCursors = <String>[]; final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: const Offset(100, 100)); tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.mouseCursor, (_) async { logCursors.add('cursor'); return null; }); final GlobalKey key = GlobalKey(); // Pump a row of 2 SizedBox's, each taking 50px of width. await tester.pumpWidget(_Scaffold( topLeft: SizedBox( width: 100, height: 50, child: Row( children: <Widget>[ SizedBox( width: 50, height: 50, child: MouseRegion( key: key, onEnter: (_) { logEnters.add('enter'); }, onExit: (_) { logEnters.add('enter'); }, cursor: SystemMouseCursors.click, ), ), const SizedBox( width: 50, height: 50, ), ], ), ), )); // Move to the mouse region inside the first box. await gesture.moveTo(const Offset(40, 5)); expect(logEnters, <String>['enter']); expect(logExits, isEmpty); expect(logCursors, isNotEmpty); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.click); logEnters.clear(); logExits.clear(); logCursors.clear(); // Move MouseRegion to the second box while resizing them so that the // mouse is still on the MouseRegion await tester.pumpWidget(_Scaffold( topLeft: SizedBox( width: 100, height: 50, child: Row( children: <Widget>[ const SizedBox( width: 30, height: 50, ), SizedBox( width: 70, height: 50, child: MouseRegion( key: key, onEnter: (_) { logEnters.add('enter'); }, onExit: (_) { logEnters.add('enter'); }, cursor: SystemMouseCursors.click, ), ), ], ), ), )); expect(logEnters, isEmpty); expect(logExits, isEmpty); expect(logCursors, isEmpty); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.click); }); testWidgets("RenderMouseRegion's debugFillProperties when default", (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); final RenderMouseRegion renderMouseRegion = RenderMouseRegion(); addTearDown(renderMouseRegion.dispose); renderMouseRegion.debugFillProperties(builder); final List<String> description = builder.properties.where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)).map((DiagnosticsNode node) => node.toString()).toList(); expect(description, <String>[ 'parentData: MISSING', 'constraints: MISSING', 'size: MISSING', 'behavior: opaque', 'listeners: <none>', ]); }); testWidgets("RenderMouseRegion's debugFillProperties when full", (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); final RenderErrorBox renderErrorBox = RenderErrorBox(); addTearDown(renderErrorBox.dispose); final RenderMouseRegion renderMouseRegion = RenderMouseRegion( onEnter: (PointerEnterEvent event) {}, onExit: (PointerExitEvent event) {}, onHover: (PointerHoverEvent event) {}, cursor: SystemMouseCursors.click, validForMouseTracker: false, child: renderErrorBox, ); addTearDown(renderMouseRegion.dispose); renderMouseRegion.debugFillProperties(builder); final List<String> description = builder.properties.where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)).map((DiagnosticsNode node) => node.toString()).toList(); expect(description, <String>[ 'parentData: MISSING', 'constraints: MISSING', 'size: MISSING', 'behavior: opaque', 'listeners: enter, hover, exit', 'cursor: SystemMouseCursor(click)', 'invalid for MouseTracker', ]); }); testWidgets('No new frames are scheduled when mouse moves without triggering callbacks', (WidgetTester tester) async { await tester.pumpWidget(Center( child: MouseRegion( child: const SizedBox( width: 100.0, height: 100.0, ), onEnter: (PointerEnterEvent details) {}, onHover: (PointerHoverEvent details) {}, onExit: (PointerExitEvent details) {}, ), )); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: const Offset(400.0, 300.0)); await tester.pumpAndSettle(); await gesture.moveBy(const Offset(10.0, 10.0)); expect(tester.binding.hasScheduledFrame, isFalse); }); // Regression test for https://github.com/flutter/flutter/issues/67044 testWidgets('Handle mouse events should ignore the detached MouseTrackerAnnotation', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( home: Center( child: Draggable<int>( feedback: Container(width: 20, height: 20, color: Colors.blue), childWhenDragging: Container(width: 20, height: 20, color: Colors.yellow), child: ElevatedButton(child: const Text('Drag me'), onPressed: (){}), ), ), )); // Long press the button with mouse. final Offset textFieldPos = tester.getCenter(find.byType(Text)); final TestGesture gesture = await tester.startGesture( textFieldPos, kind: PointerDeviceKind.mouse, ); await tester.pump(const Duration(seconds: 2)); await tester.pumpAndSettle(); // Drag the Draggable Widget will replace the child with [childWhenDragging]. await gesture.moveBy(const Offset(10.0, 10.0)); await tester.pump(); // Trigger detach the button. // Continue drag mouse should not trigger any assert. await gesture.moveBy(const Offset(10.0, 10.0)); // Dispose gesture await gesture.cancel(); expect(tester.takeException(), isNull); }); testWidgets('stylus input works', (WidgetTester tester) async { bool onEnter = false; bool onExit = false; bool onHover = false; await tester.pumpWidget(MaterialApp( home: Scaffold( body: MouseRegion( onEnter: (_) => onEnter = true, onExit: (_) => onExit = true, onHover: (_) => onHover = true, child: const SizedBox( width: 10.0, height: 10.0, ), ), ), )); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.stylus); await gesture.addPointer(location: const Offset(20.0, 20.0)); await tester.pump(); expect(onEnter, false); expect(onHover, false); expect(onExit, false); await gesture.moveTo(const Offset(5.0, 5.0)); await tester.pump(); expect(onEnter, true); expect(onHover, true); expect(onExit, false); await gesture.moveTo(const Offset(20.0, 20.0)); await tester.pump(); expect(onEnter, true); expect(onHover, true); expect(onExit, true); }); } // Render widget `topLeft` at the top-left corner, stacking on top of the widget // `background`. class _Scaffold extends StatelessWidget { const _Scaffold({this.topLeft, this.background}); final Widget? topLeft; final Widget? background; @override Widget build(BuildContext context) { return Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ if (background != null) background!, Align( alignment: Alignment.topLeft, child: topLeft, ), ], ), ); } } class _DelegatedPainter extends CustomPainter { _DelegatedPainter({this.key, required this.onPaint}); final Key? key; final VoidCallback onPaint; @override void paint(Canvas canvas, Size size) { onPaint(); } @override bool shouldRepaint(CustomPainter oldDelegate) => !(oldDelegate is _DelegatedPainter && key == oldDelegate.key); } class _HoverClientWithClosures extends StatefulWidget { const _HoverClientWithClosures(); @override _HoverClientWithClosuresState createState() => _HoverClientWithClosuresState(); } class _HoverClientWithClosuresState extends State<_HoverClientWithClosures> { bool _hovering = false; @override Widget build(BuildContext context) { return Directionality( textDirection: TextDirection.ltr, child: MouseRegion( onEnter: (PointerEnterEvent _) { setState(() { _hovering = true; }); }, onExit: (PointerExitEvent _) { setState(() { _hovering = false; }); }, child: Text(_hovering ? 'HOVERING' : 'not hovering'), ), ); } } // A column that aligns to the top left. class _ColumnContainer extends StatelessWidget { const _ColumnContainer({ required this.children, }); final List<Widget> children; @override Widget build(BuildContext context) { return Directionality( textDirection: TextDirection.ltr, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: children, ), ); } }
flutter/packages/flutter/test/widgets/mouse_region_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/mouse_region_test.dart", "repo_id": "flutter", "token_count": 27852 }
304
// Copyright 2014 The Flutter 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:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('RenderOpacity avoids repainting and does not drop layer at fully opaque', (WidgetTester tester) async { RenderTestObject.paintCount = 0; await tester.pumpWidget( const ColoredBox( color: Colors.red, child: Opacity( opacity: 0.0, child: TestWidget(), ), ) ); expect(RenderTestObject.paintCount, 0); await tester.pumpWidget( const ColoredBox( color: Colors.red, child: Opacity( opacity: 0.1, child: TestWidget(), ), ) ); expect(RenderTestObject.paintCount, 1); await tester.pumpWidget( const ColoredBox( color: Colors.red, child: Opacity( opacity: 1, child: TestWidget(), ), ) ); expect(RenderTestObject.paintCount, 1); }); testWidgets('RenderOpacity allows opacity layer to be dropped at 0 opacity', (WidgetTester tester) async { RenderTestObject.paintCount = 0; await tester.pumpWidget( const ColoredBox( color: Colors.red, child: Opacity( opacity: 0.5, child: TestWidget(), ), ) ); expect(RenderTestObject.paintCount, 1); await tester.pumpWidget( const ColoredBox( color: Colors.red, child: Opacity( opacity: 0.0, child: TestWidget(), ), ) ); expect(RenderTestObject.paintCount, 1); expect(tester.layers, isNot(contains(isA<OpacityLayer>()))); }); } class TestWidget extends SingleChildRenderObjectWidget { const TestWidget({super.key, super.child}); @override RenderObject createRenderObject(BuildContext context) { return RenderTestObject(); } } class RenderTestObject extends RenderProxyBox { static int paintCount = 0; @override void paint(PaintingContext context, Offset offset) { paintCount += 1; super.paint(context, offset); } }
flutter/packages/flutter/test/widgets/opacity_repaint_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/opacity_repaint_test.dart", "repo_id": "flutter", "token_count": 931 }
305
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file is run as part of a reduced test set in CI on Mac and Windows // machines. @Tags(<String>['reduced-test-set']) library; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('PhysicalModel updates clipBehavior in updateRenderObject', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp(home: PhysicalModel(color: Colors.red)), ); final RenderPhysicalModel renderPhysicalModel = tester.allRenderObjects.whereType<RenderPhysicalModel>().first; expect(renderPhysicalModel.clipBehavior, equals(Clip.none)); await tester.pumpWidget( const MaterialApp(home: PhysicalModel(clipBehavior: Clip.antiAlias, color: Colors.red)), ); expect(renderPhysicalModel.clipBehavior, equals(Clip.antiAlias)); }); testWidgets('PhysicalShape updates clipBehavior in updateRenderObject', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp(home: PhysicalShape(color: Colors.red, clipper: ShapeBorderClipper(shape: CircleBorder()))), ); final RenderPhysicalShape renderPhysicalShape = tester.allRenderObjects.whereType<RenderPhysicalShape>().first; expect(renderPhysicalShape.clipBehavior, equals(Clip.none)); await tester.pumpWidget( const MaterialApp(home: PhysicalShape(clipBehavior: Clip.antiAlias, color: Colors.red, clipper: ShapeBorderClipper(shape: CircleBorder()))), ); expect(renderPhysicalShape.clipBehavior, equals(Clip.antiAlias)); }); testWidgets('PhysicalModel - clips when overflows and elevation is 0', (WidgetTester tester) async { const Key key = Key('test'); await tester.pumpWidget( Theme( data: ThemeData(useMaterial3: false), child: const MediaQuery( key: key, data: MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: Padding( padding: EdgeInsets.all(50), child: Row( children: <Widget>[ Material(child: Text('A long long long long long long long string')), Material(child: Text('A long long long long long long long string')), Material(child: Text('A long long long long long long long string')), Material(child: Text('A long long long long long long long string')), ], ), ), ), ), ), ); final dynamic exception = tester.takeException(); expect(exception, isFlutterError); // ignore: avoid_dynamic_calls expect(exception.diagnostics.first.level, DiagnosticLevel.summary); // ignore: avoid_dynamic_calls expect(exception.diagnostics.first.toString(), startsWith('A RenderFlex overflowed by ')); await expectLater( find.byKey(key), matchesGoldenFile('physical_model_overflow.png'), ); }); }
flutter/packages/flutter/test/widgets/physical_model_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/physical_model_test.dart", "repo_id": "flutter", "token_count": 1157 }
306
// Copyright 2014 The Flutter 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:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; // This is a regression test for https://github.com/flutter/flutter/issues/5840. class Bar extends StatefulWidget { const Bar({ super.key }); @override BarState createState() => BarState(); } class BarState extends State<Bar> { final GlobalKey _fooKey = GlobalKey(); bool _mode = false; void trigger() { setState(() { _mode = !_mode; }); } @override Widget build(BuildContext context) { if (_mode) { return SizedBox( child: LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { return StatefulCreationCounter(key: _fooKey); }, ), ); } else { return LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { return StatefulCreationCounter(key: _fooKey); }, ); } } } class StatefulCreationCounter extends StatefulWidget { const StatefulCreationCounter({ super.key }); @override StatefulCreationCounterState createState() => StatefulCreationCounterState(); } class StatefulCreationCounterState extends State<StatefulCreationCounter> { static int creationCount = 0; @override void initState() { super.initState(); creationCount += 1; } @override Widget build(BuildContext context) => Container(); } void main() { testWidgets('reparent state with layout builder', (WidgetTester tester) async { expect(StatefulCreationCounterState.creationCount, 0); await tester.pumpWidget(const Bar()); expect(StatefulCreationCounterState.creationCount, 1); final BarState s = tester.state<BarState>(find.byType(Bar)); s.trigger(); await tester.pump(); expect(StatefulCreationCounterState.creationCount, 1); }); testWidgets('Clean then reparent with dependencies', (WidgetTester tester) async { int layoutBuilderBuildCount = 0; late StateSetter keyedSetState; late StateSetter layoutBuilderSetState; late StateSetter childSetState; final GlobalKey key = GlobalKey(); final Widget keyedWidget = StatefulBuilder( key: key, builder: (BuildContext context, StateSetter setState) { keyedSetState = setState; MediaQuery.of(context); return Container(); }, ); Widget layoutBuilderChild = keyedWidget; Widget deepChild = Container(); await tester.pumpWidget(MediaQuery( data: MediaQueryData.fromView(tester.view), child: Column( children: <Widget>[ StatefulBuilder(builder: (BuildContext context, StateSetter setState) { layoutBuilderSetState = setState; return LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { layoutBuilderBuildCount += 1; return layoutBuilderChild; // initially keyedWidget above, but then a new Container }, ); }), ColoredBox( color: Colors.green, child: ColoredBox( color: Colors.green, child: ColoredBox( color: Colors.green, child: ColoredBox( color: Colors.green, child: ColoredBox( color: Colors.green, child: ColoredBox( color: Colors.green, child: StatefulBuilder( builder: (BuildContext context, StateSetter setState) { childSetState = setState; return deepChild; // initially a Container, but then the keyedWidget above }, ), ), ), ), ), ), ), ], ), )); expect(layoutBuilderBuildCount, 1); keyedSetState(() { /* Change nothing but add the element to the dirty list. */ }); childSetState(() { // The deep child builds in the initial build phase. It takes the child // from the LayoutBuilder before the LayoutBuilder has a chance to build. deepChild = keyedWidget; }); layoutBuilderSetState(() { // The layout builder will build in a separate build scope. This delays // the removal of the keyed child until this build scope. layoutBuilderChild = Container(); }); // The essential part of this test is that this call to pump doesn't throw. await tester.pump(); expect(layoutBuilderBuildCount, 2); }); }
flutter/packages/flutter/test/widgets/reparent_state_with_layout_builder_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/reparent_state_with_layout_builder_test.dart", "repo_id": "flutter", "token_count": 1940 }
307
// Copyright 2014 The Flutter 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:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('runApp inside onPressed does not throw', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Material( child: ElevatedButton( onPressed: () { runApp(const Center(child: Text('Done', textDirection: TextDirection.ltr))); }, child: const Text('GO'), ), ), ), ); await tester.tap(find.text('GO')); expect(find.text('Done'), findsOneWidget); }); }
flutter/packages/flutter/test/widgets/run_app_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/run_app_test.dart", "repo_id": "flutter", "token_count": 331 }
308
// Copyright 2014 The Flutter 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:flutter/gestures.dart' show DragStartBehavior; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; const TextStyle testFont = TextStyle( color: Color(0xFF00FF00), ); Future<void> pumpTest(WidgetTester tester, TargetPlatform platform) async { await tester.pumpWidget(Container()); await tester.pumpWidget(MaterialApp( theme: ThemeData( platform: platform, ), home: ColoredBox( color: const Color(0xFF111111), child: ListView.builder( dragStartBehavior: DragStartBehavior.down, itemBuilder: (BuildContext context, int index) { return Text('$index', style: testFont); }, ), ), )); } const double dragOffset = 213.82; void main() { testWidgets('Flings on different platforms', (WidgetTester tester) async { double getCurrentOffset() { return tester.state<ScrollableState>(find.byType(Scrollable)).position.pixels; } await pumpTest(tester, TargetPlatform.android); await tester.fling(find.byType(ListView), const Offset(0.0, -dragOffset), 1000.0); expect(getCurrentOffset(), dragOffset); await tester.pump(); // trigger fling expect(getCurrentOffset(), dragOffset); await tester.pump(const Duration(seconds: 5)); final double androidResult = getCurrentOffset(); // Regression test for https://github.com/flutter/flutter/issues/83632 // Before changing these values, ensure the fling results in a distance that // makes sense. See issue for more context. expect(androidResult, greaterThan(408.0)); expect(androidResult, lessThan(409.0)); await pumpTest(tester, TargetPlatform.linux); await tester.fling(find.byType(ListView), const Offset(0.0, -dragOffset), 1000.0); expect(getCurrentOffset(), dragOffset); await tester.pump(); // trigger fling expect(getCurrentOffset(), dragOffset); await tester.pump(const Duration(seconds: 5)); final double linuxResult = getCurrentOffset(); await pumpTest(tester, TargetPlatform.windows); await tester.fling(find.byType(ListView), const Offset(0.0, -dragOffset), 1000.0); expect(getCurrentOffset(), dragOffset); await tester.pump(); // trigger fling expect(getCurrentOffset(), dragOffset); await tester.pump(const Duration(seconds: 5)); final double windowsResult = getCurrentOffset(); await pumpTest(tester, TargetPlatform.iOS); await tester.fling(find.byType(ListView), const Offset(0.0, -dragOffset), 1000.0); // Scroll starts ease into the scroll on iOS. expect(getCurrentOffset(), moreOrLessEquals(210.71026666666666)); await tester.pump(); // trigger fling expect(getCurrentOffset(), moreOrLessEquals(210.71026666666666)); await tester.pump(const Duration(seconds: 5)); final double iOSResult = getCurrentOffset(); await pumpTest(tester, TargetPlatform.macOS); await tester.fling(find.byType(ListView), const Offset(0.0, -dragOffset), 1000.0); // Scroll starts ease into the scroll on iOS. expect(getCurrentOffset(), moreOrLessEquals(210.71026666666666)); await tester.pump(); // trigger fling expect(getCurrentOffset(), moreOrLessEquals(210.71026666666666)); await tester.pump(const Duration(seconds: 5)); final double macOSResult = getCurrentOffset(); expect(androidResult, lessThan(iOSResult)); // iOS is slipperier than Android expect(macOSResult, lessThan(iOSResult)); // iOS is slipperier than macOS expect(macOSResult, lessThan(androidResult)); // Android is slipperier than macOS expect(linuxResult, lessThan(iOSResult)); // iOS is slipperier than Linux expect(macOSResult, lessThan(linuxResult)); // Linux is slipperier than macOS expect(windowsResult, lessThan(iOSResult)); // iOS is slipperier than Windows expect(macOSResult, lessThan(windowsResult)); // Windows is slipperier than macOS expect(windowsResult, equals(androidResult)); expect(windowsResult, equals(androidResult)); expect(linuxResult, equals(androidResult)); expect(linuxResult, equals(androidResult)); }); testWidgets('fling and tap to stop', (WidgetTester tester) async { final List<String> log = <String>[]; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListView( dragStartBehavior: DragStartBehavior.down, children: List<Widget>.generate(250, (int i) => GestureDetector( onTap: () { log.add('tap $i'); }, child: Text('$i', style: testFont), )), ), ), ); expect(log, equals(<String>[])); await tester.tap(find.byType(Scrollable)); await tester.pump(const Duration(milliseconds: 50)); expect(log, equals(<String>['tap 21'])); await tester.fling(find.byType(Scrollable), const Offset(0.0, -200.0), 1000.0); await tester.pump(const Duration(milliseconds: 50)); expect(log, equals(<String>['tap 21'])); await tester.tap(find.byType(Scrollable)); // should stop the fling but not tap anything await tester.pump(const Duration(milliseconds: 50)); expect(log, equals(<String>['tap 21'])); await tester.tap(find.byType(Scrollable)); await tester.pump(const Duration(milliseconds: 50)); expect(log, equals(<String>['tap 21', 'tap 35'])); }); testWidgets('fling and wait and tap', (WidgetTester tester) async { final List<String> log = <String>[]; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListView( dragStartBehavior: DragStartBehavior.down, children: List<Widget>.generate(250, (int i) => GestureDetector( onTap: () { log.add('tap $i'); }, child: Text('$i', style: testFont), )), ), ), ); expect(log, equals(<String>[])); await tester.tap(find.byType(Scrollable)); await tester.pump(const Duration(milliseconds: 50)); expect(log, equals(<String>['tap 21'])); await tester.fling(find.byType(Scrollable), const Offset(0.0, -200.0), 1000.0); await tester.pump(const Duration(milliseconds: 50)); expect(log, equals(<String>['tap 21'])); await tester.pump(const Duration(seconds: 50)); // long wait, so the fling will have ended at the end of it expect(log, equals(<String>['tap 21'])); await tester.tap(find.byType(Scrollable)); await tester.pump(const Duration(milliseconds: 50)); expect(log, equals(<String>['tap 21', 'tap 49'])); }); }
flutter/packages/flutter/test/widgets/scrollable_fling_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/scrollable_fling_test.dart", "repo_id": "flutter", "token_count": 2410 }
309
// Copyright 2014 The Flutter 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:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'semantics_tester.dart'; void main() { testWidgets('can cease to be semantics boundary after markNeedsSemanticsUpdate() has already been called once', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( buildTestWidgets( excludeSemantics: false, label: 'label', isSemanticsBoundary: true, ), ); // The following should not trigger an assert. await tester.pumpWidget( buildTestWidgets( excludeSemantics: true, label: 'label CHANGED', isSemanticsBoundary: false, ), ); semantics.dispose(); }); } Widget buildTestWidgets({ required bool excludeSemantics, required String label, required bool isSemanticsBoundary, }) { return Directionality( textDirection: TextDirection.ltr, child: Semantics( label: 'container', container: true, child: ExcludeSemantics( excluding: excludeSemantics, child: TestWidget( label: label, isSemanticBoundary: isSemanticsBoundary, child: Column( children: <Widget>[ Semantics( label: 'child1', ), Semantics( label: 'child2', ), ], ), ), ), ), ); } class TestWidget extends SingleChildRenderObjectWidget { const TestWidget({ super.key, required Widget super.child, required this.label, required this.isSemanticBoundary, }); final String label; final bool isSemanticBoundary; @override RenderTest createRenderObject(BuildContext context) { return RenderTest() ..label = label ..isSemanticBoundary = isSemanticBoundary; } @override void updateRenderObject(BuildContext context, RenderTest renderObject) { renderObject ..label = label ..isSemanticBoundary = isSemanticBoundary; } } class RenderTest extends RenderProxyBox { @override void describeSemanticsConfiguration(SemanticsConfiguration config) { super.describeSemanticsConfiguration(config); if (!isSemanticBoundary) { return; } config ..isSemanticBoundary = isSemanticBoundary ..label = label ..textDirection = TextDirection.ltr; } String get label => _label; String _label = '<>'; set label(String value) { if (value == _label) { return; } _label = value; markNeedsSemanticsUpdate(); } bool get isSemanticBoundary => _isSemanticBoundary; bool _isSemanticBoundary = false; set isSemanticBoundary(bool value) { if (_isSemanticBoundary == value) { return; } _isSemanticBoundary = value; markNeedsSemanticsUpdate(); } }
flutter/packages/flutter/test/widgets/semantics_10_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/semantics_10_test.dart", "repo_id": "flutter", "token_count": 1212 }
310
// Copyright 2014 The Flutter 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:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'semantics_tester.dart'; void main() { setUp(() { debugResetSemanticsIdCounter(); }); testWidgets('MergeSemantics', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); // not merged await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Row( children: <Widget>[ Semantics( container: true, child: const Text('test1'), ), Semantics( container: true, child: const Text('test2'), ), ], ), ), ); expect(semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, label: 'test1', ), TestSemantics.rootChild( id: 2, label: 'test2', ), ], ), ignoreRect: true, ignoreTransform: true, )); // merged await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: MergeSemantics( child: Row( children: <Widget>[ Semantics( container: true, child: const Text('test1'), ), Semantics( container: true, child: const Text('test2'), ), ], ), ), ), ); expect(semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 3, label: 'test1\ntest2', ), ], ), ignoreRect: true, ignoreTransform: true, )); // not merged await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Row( children: <Widget>[ Semantics( container: true, child: const Text('test1'), ), Semantics( container: true, child: const Text('test2'), ), ], ), ), ); expect(semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild(id: 6, label: 'test1'), TestSemantics.rootChild(id: 7, label: 'test2'), ], ), ignoreRect: true, ignoreTransform: true, )); semantics.dispose(); }); testWidgets('MergeSemantics works if other nodes are implicitly merged into its node', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: MergeSemantics( child: Semantics( selected: true, // this is implicitly merged into the MergeSemantics node child: Row( children: <Widget>[ Semantics( container: true, child: const Text('test1'), ), Semantics( container: true, child: const Text('test2'), ), ], ), ), ), ), ); expect(semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, flags: <SemanticsFlag>[ SemanticsFlag.isSelected, ], label: 'test1\ntest2', ), ], ), ignoreRect: true, ignoreTransform: true, )); semantics.dispose(); }); }
flutter/packages/flutter/test/widgets/semantics_merge_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/semantics_merge_test.dart", "repo_id": "flutter", "token_count": 2103 }
311
// Copyright 2014 The Flutter 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:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; void main() { group(LogicalKeySet, () { test('LogicalKeySet passes parameters correctly.', () { final LogicalKeySet set1 = LogicalKeySet(LogicalKeyboardKey.keyA); final LogicalKeySet set2 = LogicalKeySet( LogicalKeyboardKey.keyA, LogicalKeyboardKey.keyB, ); final LogicalKeySet set3 = LogicalKeySet( LogicalKeyboardKey.keyA, LogicalKeyboardKey.keyB, LogicalKeyboardKey.keyC, ); final LogicalKeySet set4 = LogicalKeySet( LogicalKeyboardKey.keyA, LogicalKeyboardKey.keyB, LogicalKeyboardKey.keyC, LogicalKeyboardKey.keyD, ); final LogicalKeySet setFromSet = LogicalKeySet.fromSet(<LogicalKeyboardKey>{ LogicalKeyboardKey.keyA, LogicalKeyboardKey.keyB, LogicalKeyboardKey.keyC, LogicalKeyboardKey.keyD, }); expect( set1.keys, equals(<LogicalKeyboardKey>{ LogicalKeyboardKey.keyA, }), ); expect( set2.keys, equals(<LogicalKeyboardKey>{ LogicalKeyboardKey.keyA, LogicalKeyboardKey.keyB, }), ); expect( set3.keys, equals(<LogicalKeyboardKey>{ LogicalKeyboardKey.keyA, LogicalKeyboardKey.keyB, LogicalKeyboardKey.keyC, }), ); expect( set4.keys, equals(<LogicalKeyboardKey>{ LogicalKeyboardKey.keyA, LogicalKeyboardKey.keyB, LogicalKeyboardKey.keyC, LogicalKeyboardKey.keyD, }), ); expect( setFromSet.keys, equals(<LogicalKeyboardKey>{ LogicalKeyboardKey.keyA, LogicalKeyboardKey.keyB, LogicalKeyboardKey.keyC, LogicalKeyboardKey.keyD, }), ); }); test('LogicalKeySet works as a map key.', () { final LogicalKeySet set1 = LogicalKeySet(LogicalKeyboardKey.keyA); final LogicalKeySet set2 = LogicalKeySet( LogicalKeyboardKey.keyA, LogicalKeyboardKey.keyB, LogicalKeyboardKey.keyC, LogicalKeyboardKey.keyD, ); final LogicalKeySet set3 = LogicalKeySet( LogicalKeyboardKey.keyD, LogicalKeyboardKey.keyC, LogicalKeyboardKey.keyB, LogicalKeyboardKey.keyA, ); final LogicalKeySet set4 = LogicalKeySet.fromSet(<LogicalKeyboardKey>{ LogicalKeyboardKey.keyD, LogicalKeyboardKey.keyC, LogicalKeyboardKey.keyB, LogicalKeyboardKey.keyA, }); final Map<LogicalKeySet, String> map = <LogicalKeySet, String>{set1: 'one'}; expect(set2 == set3, isTrue); expect(set2 == set4, isTrue); expect(set2.hashCode, set3.hashCode); expect(set2.hashCode, set4.hashCode); expect(map.containsKey(set1), isTrue); expect(map.containsKey(LogicalKeySet(LogicalKeyboardKey.keyA)), isTrue); expect( set2, equals(LogicalKeySet.fromSet(<LogicalKeyboardKey>{ LogicalKeyboardKey.keyA, LogicalKeyboardKey.keyB, LogicalKeyboardKey.keyC, LogicalKeyboardKey.keyD, })), ); }); testWidgets('handles two keys', (WidgetTester tester) async { int invoked = 0; await tester.pumpWidget(activatorTester( LogicalKeySet( LogicalKeyboardKey.keyC, LogicalKeyboardKey.control, ), (Intent intent) { invoked += 1; }, )); await tester.pump(); // LCtrl -> KeyC: Accept await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); expect(invoked, 0); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyC); expect(invoked, 1); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyC); await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); expect(invoked, 1); invoked = 0; // KeyC -> LCtrl: Accept await tester.sendKeyDownEvent(LogicalKeyboardKey.keyC); expect(invoked, 0); await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); expect(invoked, 1); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyC); await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); expect(invoked, 1); invoked = 0; // RCtrl -> KeyC: Accept await tester.sendKeyDownEvent(LogicalKeyboardKey.controlRight); expect(invoked, 0); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyC); expect(invoked, 1); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyC); await tester.sendKeyUpEvent(LogicalKeyboardKey.controlRight); expect(invoked, 1); invoked = 0; // LCtrl -> LShift -> KeyC: Reject await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyC); expect(invoked, 0); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyC); await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft); expect(invoked, 0); invoked = 0; // LCtrl -> KeyA -> KeyC: Reject await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyA); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyC); expect(invoked, 0); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyC); await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyA); expect(invoked, 0); invoked = 0; expect(HardwareKeyboard.instance.logicalKeysPressed, isEmpty); }); test('LogicalKeySet.hashCode is stable', () { final LogicalKeySet set1 = LogicalKeySet(LogicalKeyboardKey.keyA); expect(set1.hashCode, set1.hashCode); final LogicalKeySet set2 = LogicalKeySet(LogicalKeyboardKey.keyA, LogicalKeyboardKey.keyB); expect(set2.hashCode, set2.hashCode); final LogicalKeySet set3 = LogicalKeySet(LogicalKeyboardKey.keyA, LogicalKeyboardKey.keyB, LogicalKeyboardKey.keyC); expect(set3.hashCode, set3.hashCode); final LogicalKeySet set4 = LogicalKeySet(LogicalKeyboardKey.keyA, LogicalKeyboardKey.keyB, LogicalKeyboardKey.keyC, LogicalKeyboardKey.keyD); expect(set4.hashCode, set4.hashCode); }); test('LogicalKeySet.hashCode is order-independent', () { expect( LogicalKeySet(LogicalKeyboardKey.keyA).hashCode, LogicalKeySet(LogicalKeyboardKey.keyA).hashCode, ); expect( LogicalKeySet(LogicalKeyboardKey.keyA, LogicalKeyboardKey.keyB).hashCode, LogicalKeySet(LogicalKeyboardKey.keyB, LogicalKeyboardKey.keyA).hashCode, ); expect( LogicalKeySet(LogicalKeyboardKey.keyA, LogicalKeyboardKey.keyB, LogicalKeyboardKey.keyC).hashCode, LogicalKeySet(LogicalKeyboardKey.keyC, LogicalKeyboardKey.keyB, LogicalKeyboardKey.keyA).hashCode, ); expect( LogicalKeySet(LogicalKeyboardKey.keyA, LogicalKeyboardKey.keyB, LogicalKeyboardKey.keyC, LogicalKeyboardKey.keyD).hashCode, LogicalKeySet(LogicalKeyboardKey.keyD, LogicalKeyboardKey.keyC, LogicalKeyboardKey.keyB, LogicalKeyboardKey.keyA).hashCode, ); }); testWidgets('isActivatedBy works as expected', (WidgetTester tester) async { // Collect some key events to use for testing. final List<KeyEvent> events = <KeyEvent>[]; await tester.pumpWidget( Focus( autofocus: true, onKeyEvent: (FocusNode node, KeyEvent event) { events.add(event); return KeyEventResult.ignored; }, child: const SizedBox(), ), ); final LogicalKeySet set = LogicalKeySet(LogicalKeyboardKey.keyA, LogicalKeyboardKey.control); await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyA); expect(ShortcutActivator.isActivatedBy(set, events.last), isTrue); await tester.sendKeyRepeatEvent(LogicalKeyboardKey.keyA); expect(ShortcutActivator.isActivatedBy(set, events.last), isTrue); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyA); expect(ShortcutActivator.isActivatedBy(set, events.last), isFalse); await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); expect(ShortcutActivator.isActivatedBy(set, events.last), isFalse); }); test('LogicalKeySet diagnostics work.', () { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); LogicalKeySet( LogicalKeyboardKey.keyA, LogicalKeyboardKey.keyB, ).debugFillProperties(builder); final List<String> description = builder.properties.where((DiagnosticsNode node) { return !node.isFiltered(DiagnosticLevel.info); }).map((DiagnosticsNode node) => node.toString()).toList(); expect(description.length, equals(1)); expect(description[0], equals('keys: Key A + Key B')); }); }); group(SingleActivator, () { testWidgets('handles Ctrl-C', (WidgetTester tester) async { int invoked = 0; await tester.pumpWidget(activatorTester( const SingleActivator( LogicalKeyboardKey.keyC, control: true, ), (Intent intent) { invoked += 1; }, )); await tester.pump(); // LCtrl -> KeyC: Accept await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); expect(invoked, 0); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyC); expect(invoked, 1); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyC); await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); expect(invoked, 1); invoked = 0; // KeyC -> LCtrl: Reject await tester.sendKeyDownEvent(LogicalKeyboardKey.keyC); await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); expect(invoked, 0); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyC); await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); invoked = 0; // LShift -> LCtrl -> KeyC: Reject await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft); await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyC); expect(invoked, 0); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyC); await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft); invoked = 0; // With Ctrl-C pressed, KeyA -> Release KeyA: Reject await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyC); invoked = 0; await tester.sendKeyDownEvent(LogicalKeyboardKey.keyA); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyA); expect(invoked, 0); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyC); await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); invoked = 0; // LCtrl -> KeyA -> KeyC: Accept await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyA); expect(invoked, 0); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyC); expect(invoked, 1); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyA); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyC); await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); invoked = 0; // RCtrl -> KeyC: Accept await tester.sendKeyDownEvent(LogicalKeyboardKey.controlRight); expect(invoked, 0); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyC); expect(invoked, 1); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyC); await tester.sendKeyUpEvent(LogicalKeyboardKey.controlRight); expect(invoked, 1); invoked = 0; // LCtrl -> RCtrl -> KeyC: Accept await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); await tester.sendKeyDownEvent(LogicalKeyboardKey.controlRight); expect(invoked, 0); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyC); expect(invoked, 1); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyC); await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); await tester.sendKeyUpEvent(LogicalKeyboardKey.controlRight); expect(invoked, 1); invoked = 0; // While holding Ctrl-C, press KeyA: Reject await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); expect(invoked, 0); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyC); expect(invoked, 1); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyA); expect(invoked, 1); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyC); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyA); await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); expect(invoked, 1); invoked = 0; expect(HardwareKeyboard.instance.logicalKeysPressed, isEmpty); }, variant: KeySimulatorTransitModeVariant.all()); testWidgets('handles repeated events', (WidgetTester tester) async { int invoked = 0; await tester.pumpWidget(activatorTester( const SingleActivator( LogicalKeyboardKey.keyC, control: true, ), (Intent intent) { invoked += 1; }, )); await tester.pump(); // LCtrl -> KeyC: Accept await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); expect(invoked, 0); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyC); expect(invoked, 1); await tester.sendKeyRepeatEvent(LogicalKeyboardKey.keyC); expect(invoked, 2); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyC); await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); expect(invoked, 2); invoked = 0; expect(HardwareKeyboard.instance.logicalKeysPressed, isEmpty); }, variant: KeySimulatorTransitModeVariant.all()); testWidgets('rejects repeated events if requested', (WidgetTester tester) async { int invoked = 0; await tester.pumpWidget(activatorTester( const SingleActivator( LogicalKeyboardKey.keyC, control: true, includeRepeats: false, ), (Intent intent) { invoked += 1; }, )); await tester.pump(); // LCtrl -> KeyC: Accept await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); expect(invoked, 0); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyC); expect(invoked, 1); await tester.sendKeyRepeatEvent(LogicalKeyboardKey.keyC); expect(invoked, 1); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyC); await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); expect(invoked, 1); invoked = 0; expect(HardwareKeyboard.instance.logicalKeysPressed, isEmpty); }, variant: KeySimulatorTransitModeVariant.all()); testWidgets('handles Shift-Ctrl-C', (WidgetTester tester) async { int invoked = 0; await tester.pumpWidget(activatorTester( const SingleActivator( LogicalKeyboardKey.keyC, shift: true, control: true, ), (Intent intent) { invoked += 1; }, )); await tester.pump(); // LShift -> LCtrl -> KeyC: Accept await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft); await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); expect(invoked, 0); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyC); expect(invoked, 1); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyC); await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft); expect(invoked, 1); invoked = 0; // LCtrl -> LShift -> KeyC: Accept await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft); expect(invoked, 0); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyC); expect(invoked, 1); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyC); await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft); expect(invoked, 1); invoked = 0; // LCtrl -> KeyC -> LShift: Reject await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyC); await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft); expect(invoked, 0); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyC); await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft); expect(invoked, 0); invoked = 0; expect(HardwareKeyboard.instance.logicalKeysPressed, isEmpty); }); testWidgets('isActivatedBy works as expected', (WidgetTester tester) async { // Collect some key events to use for testing. final List<KeyEvent> events = <KeyEvent>[]; await tester.pumpWidget( Focus( autofocus: true, onKeyEvent: (FocusNode node, KeyEvent event) { events.add(event); return KeyEventResult.ignored; }, child: const SizedBox(), ), ); const SingleActivator singleActivator = SingleActivator(LogicalKeyboardKey.keyA, control: true); await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyA); expect(ShortcutActivator.isActivatedBy(singleActivator, events.last), isTrue); await tester.sendKeyRepeatEvent(LogicalKeyboardKey.keyA); expect(ShortcutActivator.isActivatedBy(singleActivator, events.last), isTrue); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyA); expect(ShortcutActivator.isActivatedBy(singleActivator, events.last), isFalse); await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); expect(ShortcutActivator.isActivatedBy(singleActivator, events.last), isFalse); const SingleActivator noRepeatSingleActivator = SingleActivator(LogicalKeyboardKey.keyA, control: true, includeRepeats: false); await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyA); expect(ShortcutActivator.isActivatedBy(noRepeatSingleActivator, events.last), isTrue); await tester.sendKeyRepeatEvent(LogicalKeyboardKey.keyA); expect(ShortcutActivator.isActivatedBy(noRepeatSingleActivator, events.last), isFalse); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyA); expect(ShortcutActivator.isActivatedBy(noRepeatSingleActivator, events.last), isFalse); await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); expect(ShortcutActivator.isActivatedBy(noRepeatSingleActivator, events.last), isFalse); }); testWidgets('numLock works as expected when set to LockState.locked', (WidgetTester tester) async { // Collect some key events to use for testing. final List<KeyEvent> events = <KeyEvent>[]; await tester.pumpWidget( Focus( autofocus: true, onKeyEvent: (FocusNode node, KeyEvent event) { events.add(event); return KeyEventResult.ignored; }, child: const SizedBox(), ), ); const SingleActivator singleActivator = SingleActivator(LogicalKeyboardKey.numpad4, numLock: LockState.locked); // Lock NumLock. await tester.sendKeyEvent(LogicalKeyboardKey.numLock); expect(HardwareKeyboard.instance.lockModesEnabled.contains(KeyboardLockMode.numLock), isTrue); await tester.sendKeyDownEvent(LogicalKeyboardKey.numpad4); expect(ShortcutActivator.isActivatedBy(singleActivator, events.last), isTrue); await tester.sendKeyUpEvent(LogicalKeyboardKey.numpad4); // Unlock NumLock. await tester.sendKeyEvent(LogicalKeyboardKey.numLock); expect(HardwareKeyboard.instance.lockModesEnabled.contains(KeyboardLockMode.numLock), isFalse); await tester.sendKeyDownEvent(LogicalKeyboardKey.numpad4); expect(ShortcutActivator.isActivatedBy(singleActivator, events.last), isFalse); await tester.sendKeyUpEvent(LogicalKeyboardKey.numpad4); }); testWidgets('numLock works as expected when set to LockState.unlocked', (WidgetTester tester) async { // Collect some key events to use for testing. final List<KeyEvent> events = <KeyEvent>[]; await tester.pumpWidget( Focus( autofocus: true, onKeyEvent: (FocusNode node, KeyEvent event) { events.add(event); return KeyEventResult.ignored; }, child: const SizedBox(), ), ); const SingleActivator singleActivator = SingleActivator(LogicalKeyboardKey.numpad4, numLock: LockState.unlocked); // Lock NumLock. await tester.sendKeyEvent(LogicalKeyboardKey.numLock); expect(HardwareKeyboard.instance.lockModesEnabled.contains(KeyboardLockMode.numLock), isTrue); await tester.sendKeyDownEvent(LogicalKeyboardKey.numpad4); expect(ShortcutActivator.isActivatedBy(singleActivator, events.last), isFalse); await tester.sendKeyUpEvent(LogicalKeyboardKey.numpad4); // Unlock NumLock. await tester.sendKeyEvent(LogicalKeyboardKey.numLock); expect(HardwareKeyboard.instance.lockModesEnabled.contains(KeyboardLockMode.numLock), isFalse); await tester.sendKeyDownEvent(LogicalKeyboardKey.numpad4); expect(ShortcutActivator.isActivatedBy(singleActivator, events.last), isTrue); await tester.sendKeyUpEvent(LogicalKeyboardKey.numpad4); }); testWidgets('numLock works as expected when set to LockState.ignored', (WidgetTester tester) async { // Collect some key events to use for testing. final List<KeyEvent> events = <KeyEvent>[]; await tester.pumpWidget( Focus( autofocus: true, onKeyEvent: (FocusNode node, KeyEvent event) { events.add(event); return KeyEventResult.ignored; }, child: const SizedBox(), ), ); const SingleActivator singleActivator = SingleActivator(LogicalKeyboardKey.numpad4); // Lock NumLock. await tester.sendKeyEvent(LogicalKeyboardKey.numLock); expect(HardwareKeyboard.instance.lockModesEnabled.contains(KeyboardLockMode.numLock), isTrue); await tester.sendKeyDownEvent(LogicalKeyboardKey.numpad4); expect(ShortcutActivator.isActivatedBy(singleActivator, events.last), isTrue); await tester.sendKeyUpEvent(LogicalKeyboardKey.numpad4); // Unlock NumLock. await tester.sendKeyEvent(LogicalKeyboardKey.numLock); expect(HardwareKeyboard.instance.lockModesEnabled.contains(KeyboardLockMode.numLock), isFalse); await tester.sendKeyDownEvent(LogicalKeyboardKey.numpad4); expect(ShortcutActivator.isActivatedBy(singleActivator, events.last), isTrue); await tester.sendKeyUpEvent(LogicalKeyboardKey.numpad4); }); group('diagnostics.', () { test('single key', () { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); const SingleActivator( LogicalKeyboardKey.keyA, ).debugFillProperties(builder); final List<String> description = builder.properties.where((DiagnosticsNode node) { return !node.isFiltered(DiagnosticLevel.info); }).map((DiagnosticsNode node) => node.toString()).toList(); expect(description.length, equals(1)); expect(description[0], equals('keys: Key A')); }); test('no repeats', () { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); const SingleActivator( LogicalKeyboardKey.keyA, includeRepeats: false, ).debugFillProperties(builder); final List<String> description = builder.properties.where((DiagnosticsNode node) { return !node.isFiltered(DiagnosticLevel.info); }).map((DiagnosticsNode node) => node.toString()).toList(); expect(description.length, equals(2)); expect(description[0], equals('keys: Key A')); expect(description[1], equals('excluding repeats')); }); test('combination', () { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); const SingleActivator( LogicalKeyboardKey.keyA, control: true, shift: true, alt: true, meta: true, ).debugFillProperties(builder); final List<String> description = builder.properties.where((DiagnosticsNode node) { return !node.isFiltered(DiagnosticLevel.info); }).map((DiagnosticsNode node) => node.toString()).toList(); expect(description.length, equals(1)); expect(description[0], equals('keys: Control + Alt + Meta + Shift + Key A')); }); }); }); group(Shortcuts, () { testWidgets('Default constructed Shortcuts has empty shortcuts', (WidgetTester tester) async { const Shortcuts shortcuts = Shortcuts(shortcuts: <LogicalKeySet, Intent>{}, child: SizedBox()); await tester.pumpWidget(shortcuts); expect(shortcuts.shortcuts, isNotNull); expect(shortcuts.shortcuts, isEmpty); }); testWidgets('Default constructed Shortcuts.manager has empty shortcuts', (WidgetTester tester) async { final ShortcutManager manager = ShortcutManager(); addTearDown(manager.dispose); expect(manager.shortcuts, isNotNull); expect(manager.shortcuts, isEmpty); final Shortcuts shortcuts = Shortcuts.manager(manager: manager, child: const SizedBox()); await tester.pumpWidget(shortcuts); expect(shortcuts.shortcuts, isNotNull); expect(shortcuts.shortcuts, isEmpty); }); testWidgets('Shortcuts.manager passes on shortcuts', (WidgetTester tester) async { final Map<LogicalKeySet, Intent> testShortcuts = <LogicalKeySet, Intent>{ LogicalKeySet(LogicalKeyboardKey.shift): const TestIntent(), }; final ShortcutManager manager = ShortcutManager(shortcuts: testShortcuts); addTearDown(manager.dispose); expect(manager.shortcuts, isNotNull); expect(manager.shortcuts, equals(testShortcuts)); final Shortcuts shortcuts = Shortcuts.manager(manager: manager, child: const SizedBox()); await tester.pumpWidget(shortcuts); expect(shortcuts.shortcuts, isNotNull); expect(shortcuts.shortcuts, equals(testShortcuts)); }); testWidgets('ShortcutManager handles shortcuts', (WidgetTester tester) async { final GlobalKey containerKey = GlobalKey(); final List<LogicalKeyboardKey> pressedKeys = <LogicalKeyboardKey>[]; final TestShortcutManager testManager = TestShortcutManager( pressedKeys, shortcuts: <LogicalKeySet, Intent>{ LogicalKeySet(LogicalKeyboardKey.shift): const TestIntent(), }, ); addTearDown(testManager.dispose); bool invoked = false; await tester.pumpWidget( Actions( actions: <Type, Action<Intent>>{ TestIntent: TestAction( onInvoke: (Intent intent) { invoked = true; return true; }, ), }, child: Shortcuts.manager( manager: testManager, child: Focus( autofocus: true, child: SizedBox(key: containerKey, width: 100, height: 100), ), ), ), ); await tester.pump(); await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft); expect(invoked, isTrue); expect(pressedKeys, equals(<LogicalKeyboardKey>[LogicalKeyboardKey.shiftLeft])); }); testWidgets('Shortcuts.manager lets manager handle shortcuts', (WidgetTester tester) async { final GlobalKey containerKey = GlobalKey(); final List<LogicalKeyboardKey> pressedKeys = <LogicalKeyboardKey>[]; final TestShortcutManager testManager = TestShortcutManager( pressedKeys, shortcuts: <LogicalKeySet, Intent>{ LogicalKeySet(LogicalKeyboardKey.shift): const TestIntent(), }, ); addTearDown(testManager.dispose); bool invoked = false; await tester.pumpWidget( Actions( actions: <Type, Action<Intent>>{ TestIntent: TestAction( onInvoke: (Intent intent) { invoked = true; return true; }, ), }, child: Shortcuts.manager( manager: testManager, child: Focus( autofocus: true, child: SizedBox(key: containerKey, width: 100, height: 100), ), ), ), ); await tester.pump(); await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft); expect(invoked, isTrue); expect(pressedKeys, equals(<LogicalKeyboardKey>[LogicalKeyboardKey.shiftLeft])); }); testWidgets('ShortcutManager ignores key presses with no primary focus', (WidgetTester tester) async { final GlobalKey containerKey = GlobalKey(); final List<LogicalKeyboardKey> pressedKeys = <LogicalKeyboardKey>[]; final TestShortcutManager testManager = TestShortcutManager( pressedKeys, shortcuts: <LogicalKeySet, Intent>{ LogicalKeySet(LogicalKeyboardKey.shift): const TestIntent(), }, ); addTearDown(testManager.dispose); bool invoked = false; await tester.pumpWidget( Actions( actions: <Type, Action<Intent>>{ TestIntent: TestAction( onInvoke: (Intent intent) { invoked = true; return true; }, ), }, child: Shortcuts.manager( manager: testManager, child: SizedBox(key: containerKey, width: 100, height: 100), ), ), ); await tester.pump(); expect(primaryFocus, isNull); await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft); expect(invoked, isFalse); expect(pressedKeys, isEmpty); }); test('$ShortcutManager dispatches object creation in constructor', () async { await expectLater( await memoryEvents(() => ShortcutManager().dispose(), ShortcutManager), areCreateAndDispose, ); }); testWidgets("Shortcuts passes to the next Shortcuts widget if it doesn't map the key", (WidgetTester tester) async { final GlobalKey containerKey = GlobalKey(); final List<LogicalKeyboardKey> pressedKeys = <LogicalKeyboardKey>[]; final TestShortcutManager testManager = TestShortcutManager( pressedKeys, shortcuts: <LogicalKeySet, Intent>{ LogicalKeySet(LogicalKeyboardKey.shift): const TestIntent(), }, ); addTearDown(testManager.dispose); bool invoked = false; await tester.pumpWidget( Shortcuts.manager( manager: testManager, child: Actions( actions: <Type, Action<Intent>>{ TestIntent: TestAction( onInvoke: (Intent intent) { invoked = true; return invoked; }, ), }, child: Shortcuts( shortcuts: <LogicalKeySet, Intent>{ LogicalKeySet(LogicalKeyboardKey.keyA): Intent.doNothing, }, child: Focus( autofocus: true, child: SizedBox(key: containerKey, width: 100, height: 100), ), ), ), ), ); await tester.pump(); await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft); expect(invoked, isTrue); expect(pressedKeys, equals(<LogicalKeyboardKey>[LogicalKeyboardKey.shiftLeft])); }); testWidgets('Shortcuts can disable a shortcut with Intent.doNothing', (WidgetTester tester) async { final GlobalKey containerKey = GlobalKey(); final List<LogicalKeyboardKey> pressedKeys = <LogicalKeyboardKey>[]; final TestShortcutManager testManager = TestShortcutManager( pressedKeys, shortcuts: <LogicalKeySet, Intent>{ LogicalKeySet(LogicalKeyboardKey.shift): const TestIntent(), }, ); addTearDown(testManager.dispose); bool invoked = false; await tester.pumpWidget( MaterialApp( home: Shortcuts.manager( manager: testManager, child: Actions( actions: <Type, Action<Intent>>{ TestIntent: TestAction( onInvoke: (Intent intent) { invoked = true; return invoked; }, ), }, child: Shortcuts( shortcuts: <LogicalKeySet, Intent>{ LogicalKeySet(LogicalKeyboardKey.shift): Intent.doNothing, }, child: Focus( autofocus: true, child: SizedBox(key: containerKey, width: 100, height: 100), ), ), ), ), ), ); await tester.pump(); await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft); expect(invoked, isFalse); expect(pressedKeys, isEmpty); }); testWidgets("Shortcuts that aren't bound to an action don't absorb keys meant for text fields", (WidgetTester tester) async { final GlobalKey textFieldKey = GlobalKey(); final List<LogicalKeyboardKey> pressedKeys = <LogicalKeyboardKey>[]; final TestShortcutManager testManager = TestShortcutManager( pressedKeys, shortcuts: <LogicalKeySet, Intent>{ LogicalKeySet(LogicalKeyboardKey.keyA): const TestIntent(), }, ); addTearDown(testManager.dispose); await tester.pumpWidget( MaterialApp( home: Material( child: Shortcuts.manager( manager: testManager, child: TextField(key: textFieldKey, autofocus: true), ), ), ), ); await tester.pump(); final bool handled = await tester.sendKeyEvent(LogicalKeyboardKey.keyA); expect(handled, isFalse); expect(pressedKeys, equals(<LogicalKeyboardKey>[LogicalKeyboardKey.keyA])); }); testWidgets('Shortcuts that are bound to an action do override text fields', (WidgetTester tester) async { final GlobalKey textFieldKey = GlobalKey(); final List<LogicalKeyboardKey> pressedKeys = <LogicalKeyboardKey>[]; final TestShortcutManager testManager = TestShortcutManager( pressedKeys, shortcuts: <LogicalKeySet, Intent>{ LogicalKeySet(LogicalKeyboardKey.keyA): const TestIntent(), }, ); addTearDown(testManager.dispose); bool invoked = false; await tester.pumpWidget( MaterialApp( home: Material( child: Shortcuts.manager( manager: testManager, child: Actions( actions: <Type, Action<Intent>>{ TestIntent: TestAction( onInvoke: (Intent intent) { invoked = true; return invoked; }, ), }, child: TextField(key: textFieldKey, autofocus: true), ), ), ), ), ); await tester.pump(); final bool result = await tester.sendKeyEvent(LogicalKeyboardKey.keyA); expect(result, isTrue); expect(pressedKeys, equals(<LogicalKeyboardKey>[LogicalKeyboardKey.keyA])); expect(invoked, isTrue); }); testWidgets('Shortcuts can override intents that apply to text fields', (WidgetTester tester) async { final GlobalKey textFieldKey = GlobalKey(); final List<LogicalKeyboardKey> pressedKeys = <LogicalKeyboardKey>[]; final TestShortcutManager testManager = TestShortcutManager( pressedKeys, shortcuts: <LogicalKeySet, Intent>{ LogicalKeySet(LogicalKeyboardKey.keyA): const TestIntent(), }, ); addTearDown(testManager.dispose); bool invoked = false; await tester.pumpWidget( MaterialApp( home: Material( child: Shortcuts.manager( manager: testManager, child: Actions( actions: <Type, Action<Intent>>{ TestIntent: TestAction( onInvoke: (Intent intent) { invoked = true; return invoked; }, ), }, child: Actions( actions: <Type, Action<Intent>>{ TestIntent: DoNothingAction(consumesKey: false), }, child: TextField(key: textFieldKey, autofocus: true), ), ), ), ), ), ); await tester.pump(); final bool result = await tester.sendKeyEvent(LogicalKeyboardKey.keyA); expect(result, isFalse); expect(invoked, isFalse); }); testWidgets('Shortcuts can override intents that apply to text fields with DoNothingAndStopPropagationIntent', (WidgetTester tester) async { final GlobalKey textFieldKey = GlobalKey(); final List<LogicalKeyboardKey> pressedKeys = <LogicalKeyboardKey>[]; final TestShortcutManager testManager = TestShortcutManager( pressedKeys, shortcuts: <LogicalKeySet, Intent>{ LogicalKeySet(LogicalKeyboardKey.keyA): const TestIntent(), }, ); addTearDown(testManager.dispose); bool invoked = false; await tester.pumpWidget( MaterialApp( home: Material( child: Shortcuts.manager( manager: testManager, child: Actions( actions: <Type, Action<Intent>>{ TestIntent: TestAction( onInvoke: (Intent intent) { invoked = true; return invoked; }, ), }, child: Shortcuts( shortcuts: <LogicalKeySet, Intent>{ LogicalKeySet(LogicalKeyboardKey.keyA): const DoNothingAndStopPropagationIntent(), }, child: TextField(key: textFieldKey, autofocus: true), ), ), ), ), ), ); await tester.pump(); final bool result = await tester.sendKeyEvent(LogicalKeyboardKey.keyA); expect(result, isFalse); expect(invoked, isFalse); }); test('Shortcuts diagnostics work.', () { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); Shortcuts( shortcuts: <LogicalKeySet, Intent>{ LogicalKeySet( LogicalKeyboardKey.shift, LogicalKeyboardKey.keyA, ): const ActivateIntent(), LogicalKeySet( LogicalKeyboardKey.shift, LogicalKeyboardKey.arrowRight, ): const DirectionalFocusIntent(TraversalDirection.right), }, child: const SizedBox(), ).debugFillProperties(builder); final List<String> description = builder.properties.where((DiagnosticsNode node) { return !node.isFiltered(DiagnosticLevel.info); }).map((DiagnosticsNode node) => node.toString()).toList(); expect(description.length, equals(1)); expect( description[0], equalsIgnoringHashCodes( 'shortcuts: {{Shift + Key A}: ActivateIntent#00000, {Shift + Arrow Right}: DirectionalFocusIntent#00000(direction: right)}', ), ); }); test('Shortcuts diagnostics work when debugLabel specified.', () { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); Shortcuts( debugLabel: '<Debug Label>', shortcuts: <LogicalKeySet, Intent>{ LogicalKeySet( LogicalKeyboardKey.keyA, LogicalKeyboardKey.keyB, ): const ActivateIntent(), }, child: const SizedBox(), ).debugFillProperties(builder); final List<String> description = builder.properties.where((DiagnosticsNode node) { return !node.isFiltered(DiagnosticLevel.info); }).map((DiagnosticsNode node) => node.toString()).toList(); expect(description.length, equals(1)); expect(description[0], equals('shortcuts: <Debug Label>')); }); test('Shortcuts diagnostics work when manager not specified.', () { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); Shortcuts( shortcuts: <LogicalKeySet, Intent>{ LogicalKeySet( LogicalKeyboardKey.keyA, LogicalKeyboardKey.keyB, ): const ActivateIntent(), }, child: const SizedBox(), ).debugFillProperties(builder); final List<String> description = builder.properties.where((DiagnosticsNode node) { return !node.isFiltered(DiagnosticLevel.info); }).map((DiagnosticsNode node) => node.toString()).toList(); expect(description.length, equals(1)); expect(description[0], equalsIgnoringHashCodes('shortcuts: {{Key A + Key B}: ActivateIntent#00000}')); }); test('Shortcuts diagnostics work when manager specified.', () { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); final List<LogicalKeyboardKey> pressedKeys = <LogicalKeyboardKey>[]; final TestShortcutManager testManager = TestShortcutManager( pressedKeys, shortcuts: <LogicalKeySet, Intent>{ LogicalKeySet( LogicalKeyboardKey.keyA, LogicalKeyboardKey.keyB, ): const ActivateIntent(), }, ); addTearDown(testManager.dispose); Shortcuts.manager( manager: testManager, child: const SizedBox(), ).debugFillProperties(builder); final List<String> description = builder.properties.where((DiagnosticsNode node) { return !node.isFiltered(DiagnosticLevel.info); }).map((DiagnosticsNode node) => node.toString()).toList(); expect(description.length, equals(2)); expect(description[0], equalsIgnoringHashCodes('manager: TestShortcutManager#00000(shortcuts: {LogicalKeySet#00000(keys: Key A + Key B): ActivateIntent#00000})')); expect(description[1], equalsIgnoringHashCodes('shortcuts: {{Key A + Key B}: ActivateIntent#00000}')); }); testWidgets('Shortcuts support multiple intents', (WidgetTester tester) async { tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; bool? value = true; Widget buildApp() { return MaterialApp( shortcuts: <LogicalKeySet, Intent>{ LogicalKeySet(LogicalKeyboardKey.space): const PrioritizedIntents( orderedIntents: <Intent>[ ActivateIntent(), ScrollIntent(direction: AxisDirection.down, type: ScrollIncrementType.page), ], ), LogicalKeySet(LogicalKeyboardKey.tab): const NextFocusIntent(), LogicalKeySet(LogicalKeyboardKey.pageUp): const ScrollIntent(direction: AxisDirection.up, type: ScrollIncrementType.page), }, home: Material( child: Center( child: ListView( primary: true, children: <Widget> [ StatefulBuilder( builder: (BuildContext context, StateSetter setState) { return Checkbox( value: value, onChanged: (bool? newValue) => setState(() { value = newValue; }), focusColor: Colors.orange[500], ); }, ), Container( color: Colors.blue, height: 1000, ), ], ), ), ), ); } await tester.pumpWidget(buildApp()); await tester.pumpAndSettle(); expect( tester.binding.focusManager.primaryFocus!.toStringShort(), equalsIgnoringHashCodes('FocusScopeNode#00000(_ModalScopeState<dynamic> Focus Scope [PRIMARY FOCUS])'), ); final ScrollController controller = PrimaryScrollController.of( tester.element(find.byType(ListView)), ); expect(controller.position.pixels, 0.0); expect(value, isTrue); await tester.sendKeyEvent(LogicalKeyboardKey.space); await tester.pumpAndSettle(); // ScrollView scrolls expect(controller.position.pixels, 448.0); expect(value, isTrue); await tester.sendKeyEvent(LogicalKeyboardKey.pageUp); await tester.pumpAndSettle(); await tester.sendKeyEvent(LogicalKeyboardKey.tab); await tester.pumpAndSettle(); // Focus is now on the checkbox. expect( tester.binding.focusManager.primaryFocus!.toStringShort(), equalsIgnoringHashCodes('FocusNode#00000([PRIMARY FOCUS])'), ); expect(value, isTrue); expect(controller.position.pixels, 0.0); await tester.sendKeyEvent(LogicalKeyboardKey.space); await tester.pumpAndSettle(); // Checkbox is toggled, scroll view does not scroll. expect(value, isFalse); expect(controller.position.pixels, 0.0); await tester.sendKeyEvent(LogicalKeyboardKey.space); await tester.pumpAndSettle(); expect(value, isTrue); expect(controller.position.pixels, 0.0); }); testWidgets('Shortcuts support activators that returns null in triggers', (WidgetTester tester) async { int invoked = 0; await tester.pumpWidget(activatorTester( const DumbLogicalActivator(LogicalKeyboardKey.keyC), (Intent intent) { invoked += 1; }, const SingleActivator(LogicalKeyboardKey.keyC, control: true), (Intent intent) { invoked += 10; }, )); await tester.pump(); // Press KeyC: Accepted by DumbLogicalActivator await tester.sendKeyDownEvent(LogicalKeyboardKey.keyC); expect(invoked, 1); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyC); expect(invoked, 1); invoked = 0; // Press ControlLeft + KeyC: Accepted by SingleActivator await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); expect(invoked, 0); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyC); expect(invoked, 10); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyC); await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); expect(invoked, 10); invoked = 0; // Press ControlLeft + ShiftLeft + KeyC: Accepted by DumbLogicalActivator await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft); await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); expect(invoked, 0); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyC); expect(invoked, 1); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyC); await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft); expect(invoked, 1); invoked = 0; }); }); group('CharacterActivator', () { testWidgets('is triggered on events with correct character', (WidgetTester tester) async { int invoked = 0; await tester.pumpWidget(activatorTester( const CharacterActivator('?'), (Intent intent) { invoked += 1; }, )); await tester.pump(); // Press Shift + / await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft); await tester.sendKeyDownEvent(LogicalKeyboardKey.slash, character: '?'); expect(invoked, 1); await tester.sendKeyUpEvent(LogicalKeyboardKey.slash); await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft); expect(invoked, 1); invoked = 0; }, variant: KeySimulatorTransitModeVariant.all()); testWidgets('handles repeated events', (WidgetTester tester) async { int invoked = 0; await tester.pumpWidget(activatorTester( const CharacterActivator('?'), (Intent intent) { invoked += 1; }, )); await tester.pump(); // Press KeyC: Accepted by DumbLogicalActivator await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft); await tester.sendKeyDownEvent(LogicalKeyboardKey.slash, character: '?'); expect(invoked, 1); await tester.sendKeyRepeatEvent(LogicalKeyboardKey.slash, character: '?'); expect(invoked, 2); await tester.sendKeyUpEvent(LogicalKeyboardKey.slash); await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft); expect(invoked, 2); invoked = 0; }, variant: KeySimulatorTransitModeVariant.all()); testWidgets('rejects repeated events if requested', (WidgetTester tester) async { int invoked = 0; await tester.pumpWidget(activatorTester( const CharacterActivator('?', includeRepeats: false), (Intent intent) { invoked += 1; }, )); await tester.pump(); // Press Shift + / await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft); await tester.sendKeyDownEvent(LogicalKeyboardKey.slash, character: '?'); expect(invoked, 1); await tester.sendKeyRepeatEvent(LogicalKeyboardKey.slash, character: '?'); expect(invoked, 1); await tester.sendKeyUpEvent(LogicalKeyboardKey.slash); await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft); expect(invoked, 1); invoked = 0; }, variant: KeySimulatorTransitModeVariant.all()); testWidgets('handles Alt, Ctrl and Meta', (WidgetTester tester) async { int invoked = 0; await tester.pumpWidget(activatorTester( const CharacterActivator('?', alt: true, meta: true, control: true), (Intent intent) { invoked += 1; }, )); await tester.pump(); // Press Shift + / await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft); await tester.sendKeyDownEvent(LogicalKeyboardKey.slash, character: '?'); await tester.sendKeyUpEvent(LogicalKeyboardKey.slash); expect(invoked, 0); // Press Left Alt + Ctrl + Meta + Shift + / await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft); await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft); await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); expect(invoked, 0); await tester.sendKeyDownEvent(LogicalKeyboardKey.slash, character: '?'); expect(invoked, 1); await tester.sendKeyUpEvent(LogicalKeyboardKey.slash); await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft); await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft); await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft); await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); expect(invoked, 1); invoked = 0; // Press Right Alt + Ctrl + Meta + Shift + / await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftRight); await tester.sendKeyDownEvent(LogicalKeyboardKey.altRight); await tester.sendKeyDownEvent(LogicalKeyboardKey.metaRight); await tester.sendKeyDownEvent(LogicalKeyboardKey.controlRight); expect(invoked, 0); await tester.sendKeyDownEvent(LogicalKeyboardKey.slash, character: '?'); expect(invoked, 1); await tester.sendKeyUpEvent(LogicalKeyboardKey.slash); await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftRight); await tester.sendKeyUpEvent(LogicalKeyboardKey.metaRight); await tester.sendKeyUpEvent(LogicalKeyboardKey.altRight); await tester.sendKeyUpEvent(LogicalKeyboardKey.controlRight); expect(invoked, 1); invoked = 0; }, variant: KeySimulatorTransitModeVariant.all()); testWidgets('isActivatedBy works as expected', (WidgetTester tester) async { // Collect some key events to use for testing. final List<KeyEvent> events = <KeyEvent>[]; await tester.pumpWidget( Focus( autofocus: true, onKeyEvent: (FocusNode node, KeyEvent event) { events.add(event); return KeyEventResult.ignored; }, child: const SizedBox(), ), ); const CharacterActivator characterActivator = CharacterActivator('a'); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyA); expect(ShortcutActivator.isActivatedBy(characterActivator, events.last), isTrue); await tester.sendKeyRepeatEvent(LogicalKeyboardKey.keyA); expect(ShortcutActivator.isActivatedBy(characterActivator, events.last), isTrue); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyA); expect(ShortcutActivator.isActivatedBy(characterActivator, events.last), isFalse); const CharacterActivator noRepeatCharacterActivator = CharacterActivator('a', includeRepeats: false); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyA); expect(ShortcutActivator.isActivatedBy(noRepeatCharacterActivator, events.last), isTrue); await tester.sendKeyRepeatEvent(LogicalKeyboardKey.keyA); expect(ShortcutActivator.isActivatedBy(noRepeatCharacterActivator, events.last), isFalse); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyA); expect(ShortcutActivator.isActivatedBy(noRepeatCharacterActivator, events.last), isFalse); }); group('diagnostics.', () { test('single key', () { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); const CharacterActivator('A').debugFillProperties(builder); final List<String> description = builder.properties.where((DiagnosticsNode node) { return !node.isFiltered(DiagnosticLevel.info); }).map((DiagnosticsNode node) => node.toString()).toList(); expect(description.length, equals(1)); expect(description[0], equals("character: 'A'")); }); test('no repeats', () { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); const CharacterActivator('A', includeRepeats: false) .debugFillProperties(builder); final List<String> description = builder.properties.where((DiagnosticsNode node) { return !node.isFiltered(DiagnosticLevel.info); }).map((DiagnosticsNode node) => node.toString()).toList(); expect(description.length, equals(2)); expect(description[0], equals("character: 'A'")); expect(description[1], equals('excluding repeats')); }); test('combination', () { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); const CharacterActivator('A', control: true, meta: true, ).debugFillProperties(builder); final List<String> description = builder.properties.where((DiagnosticsNode node) { return !node.isFiltered(DiagnosticLevel.info); }).map((DiagnosticsNode node) => node.toString()).toList(); expect(description.length, equals(1)); expect(description[0], equals("character: Control + Meta + 'A'")); }); }); }); group('CallbackShortcuts', () { testWidgets('trigger on key events', (WidgetTester tester) async { int invokedA = 0; int invokedB = 0; await tester.pumpWidget( CallbackShortcuts( bindings: <ShortcutActivator, VoidCallback>{ const SingleActivator(LogicalKeyboardKey.keyA): () { invokedA += 1; }, const SingleActivator(LogicalKeyboardKey.keyB): () { invokedB += 1; }, }, child: const Focus( autofocus: true, child: Placeholder(), ), ), ); await tester.pump(); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyA); await tester.pump(); expect(invokedA, equals(1)); expect(invokedB, equals(0)); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyA); expect(invokedA, equals(1)); expect(invokedB, equals(0)); invokedA = 0; invokedB = 0; await tester.sendKeyDownEvent(LogicalKeyboardKey.keyB); expect(invokedA, equals(0)); expect(invokedB, equals(1)); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyB); expect(invokedA, equals(0)); expect(invokedB, equals(1)); }); testWidgets('nested CallbackShortcuts stop propagation', (WidgetTester tester) async { int invokedOuter = 0; int invokedInner = 0; await tester.pumpWidget( CallbackShortcuts( bindings: <ShortcutActivator, VoidCallback>{ const SingleActivator(LogicalKeyboardKey.keyA): () { invokedOuter += 1; }, }, child: CallbackShortcuts( bindings: <ShortcutActivator, VoidCallback>{ const SingleActivator(LogicalKeyboardKey.keyA): () { invokedInner += 1; }, }, child: const Focus( autofocus: true, child: Placeholder(), ), ), ), ); await tester.pump(); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyA); expect(invokedOuter, equals(0)); expect(invokedInner, equals(1)); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyA); expect(invokedOuter, equals(0)); expect(invokedInner, equals(1)); }); testWidgets('non-overlapping nested CallbackShortcuts fire appropriately', (WidgetTester tester) async { int invokedOuter = 0; int invokedInner = 0; await tester.pumpWidget( CallbackShortcuts( bindings: <ShortcutActivator, VoidCallback>{ const CharacterActivator('b'): () { invokedOuter += 1; }, }, child: CallbackShortcuts( bindings: <ShortcutActivator, VoidCallback>{ const CharacterActivator('a'): () { invokedInner += 1; }, }, child: const Focus( autofocus: true, child: Placeholder(), ), ), ), ); await tester.pump(); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyA); expect(invokedOuter, equals(0)); expect(invokedInner, equals(1)); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyB); expect(invokedOuter, equals(1)); expect(invokedInner, equals(1)); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyA); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyB); expect(invokedOuter, equals(1)); expect(invokedInner, equals(1)); }); testWidgets('Works correctly with Shortcuts too', (WidgetTester tester) async { int invokedCallbackA = 0; int invokedCallbackB = 0; int invokedActionA = 0; int invokedActionB = 0; void clear() { invokedCallbackA = 0; invokedCallbackB = 0; invokedActionA = 0; invokedActionB = 0; } await tester.pumpWidget( Actions( actions: <Type, Action<Intent>>{ TestIntent: TestAction( onInvoke: (Intent intent) { invokedActionA += 1; return true; }, ), TestIntent2: TestAction( onInvoke: (Intent intent) { invokedActionB += 1; return true; }, ), }, child: CallbackShortcuts( bindings: <ShortcutActivator, VoidCallback>{ const CharacterActivator('b'): () { invokedCallbackB += 1; }, }, child: Shortcuts( shortcuts: <LogicalKeySet, Intent>{ LogicalKeySet(LogicalKeyboardKey.keyA): const TestIntent(), LogicalKeySet(LogicalKeyboardKey.keyB): const TestIntent2(), }, child: CallbackShortcuts( bindings: <ShortcutActivator, VoidCallback>{ const CharacterActivator('a'): () { invokedCallbackA += 1; }, }, child: const Focus( autofocus: true, child: Placeholder(), ), ), ), ), ), ); await tester.pump(); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyA); expect(invokedCallbackA, equals(1)); expect(invokedCallbackB, equals(0)); expect(invokedActionA, equals(0)); expect(invokedActionB, equals(0)); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyA); clear(); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyB); expect(invokedCallbackA, equals(0)); expect(invokedCallbackB, equals(0)); expect(invokedActionA, equals(0)); expect(invokedActionB, equals(1)); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyB); }); }); group('ShortcutRegistrar', () { testWidgets('trigger ShortcutRegistrar on key events', (WidgetTester tester) async { int invokedA = 0; int invokedB = 0; await tester.pumpWidget( ShortcutRegistrar( child: TestCallbackRegistration( shortcuts: <ShortcutActivator, Intent>{ const SingleActivator(LogicalKeyboardKey.keyA): VoidCallbackIntent(() { invokedA += 1; }), const SingleActivator(LogicalKeyboardKey.keyB): VoidCallbackIntent(() { invokedB += 1; }), }, child: Actions( actions: <Type, Action<Intent>>{ VoidCallbackIntent: VoidCallbackAction(), }, child: const Focus( autofocus: true, child: Placeholder(), ), ), ), ), ); await tester.pump(); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyA); await tester.pump(); expect(invokedA, equals(1)); expect(invokedB, equals(0)); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyA); expect(invokedA, equals(1)); expect(invokedB, equals(0)); invokedA = 0; invokedB = 0; await tester.sendKeyDownEvent(LogicalKeyboardKey.keyB); expect(invokedA, equals(0)); expect(invokedB, equals(1)); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyB); expect(invokedA, equals(0)); expect(invokedB, equals(1)); }); testWidgets('MaterialApp has a ShortcutRegistrar listening', (WidgetTester tester) async { int invokedA = 0; int invokedB = 0; await tester.pumpWidget( MaterialApp( home: TestCallbackRegistration( shortcuts: <ShortcutActivator, Intent>{ const SingleActivator(LogicalKeyboardKey.keyA): VoidCallbackIntent(() { invokedA += 1; }), const SingleActivator(LogicalKeyboardKey.keyB): VoidCallbackIntent(() { invokedB += 1; }), }, child: Actions( actions: <Type, Action<Intent>>{ VoidCallbackIntent: VoidCallbackAction(), }, child: const Focus( autofocus: true, child: Placeholder(), ), ), ), ), ); await tester.pump(); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyA); await tester.pump(); expect(invokedA, equals(1)); expect(invokedB, equals(0)); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyA); expect(invokedA, equals(1)); expect(invokedB, equals(0)); invokedA = 0; invokedB = 0; await tester.sendKeyDownEvent(LogicalKeyboardKey.keyB); expect(invokedA, equals(0)); expect(invokedB, equals(1)); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyB); expect(invokedA, equals(0)); expect(invokedB, equals(1)); }); testWidgets("doesn't override text field shortcuts", (WidgetTester tester) async { final TextEditingController controller = TextEditingController(); addTearDown(controller.dispose); await tester.pumpWidget( MaterialApp( home: Scaffold( body: ShortcutRegistrar( child: TestCallbackRegistration( shortcuts: const <ShortcutActivator, Intent>{ SingleActivator(LogicalKeyboardKey.keyA, control: true): SelectAllTextIntent(SelectionChangedCause.keyboard), }, child: TextField( autofocus: true, controller: controller, ), ), ), ), ), ); controller.text = 'Testing'; await tester.pump(); // Send a "Ctrl-A", which should be bound to select all by default. await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); await tester.sendKeyEvent(LogicalKeyboardKey.keyA); await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); await tester.pump(); expect(controller.selection.baseOffset, equals(0)); expect(controller.selection.extentOffset, equals(7)); }); testWidgets('nested ShortcutRegistrars stop propagation', (WidgetTester tester) async { int invokedOuter = 0; int invokedInner = 0; await tester.pumpWidget( ShortcutRegistrar( child: TestCallbackRegistration( shortcuts: <ShortcutActivator, Intent>{ const SingleActivator(LogicalKeyboardKey.keyA): VoidCallbackIntent(() { invokedOuter += 1; }), }, child: ShortcutRegistrar( child: TestCallbackRegistration( shortcuts: <ShortcutActivator, Intent>{ const SingleActivator(LogicalKeyboardKey.keyA): VoidCallbackIntent(() { invokedInner += 1; }), }, child: Actions( actions: <Type, Action<Intent>>{ VoidCallbackIntent: VoidCallbackAction(), }, child: const Focus( autofocus: true, child: Placeholder(), ), ),), ), ), ), ); await tester.pump(); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyA); expect(invokedOuter, equals(0)); expect(invokedInner, equals(1)); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyA); expect(invokedOuter, equals(0)); expect(invokedInner, equals(1)); }); testWidgets('non-overlapping nested ShortcutRegistrars fire appropriately', (WidgetTester tester) async { int invokedOuter = 0; int invokedInner = 0; await tester.pumpWidget( ShortcutRegistrar( child: TestCallbackRegistration( shortcuts: <ShortcutActivator, Intent>{ const CharacterActivator('b'): VoidCallbackIntent(() { invokedOuter += 1; }), }, child: ShortcutRegistrar( child: TestCallbackRegistration( shortcuts: <ShortcutActivator, Intent>{ const CharacterActivator('a'): VoidCallbackIntent(() { invokedInner += 1; }), }, child: Actions( actions: <Type, Action<Intent>>{ VoidCallbackIntent: VoidCallbackAction(), }, child: const Focus( autofocus: true, child: Placeholder(), ), ), ), ), ), ), ); await tester.pump(); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyA); expect(invokedOuter, equals(0)); expect(invokedInner, equals(1)); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyB); expect(invokedOuter, equals(1)); expect(invokedInner, equals(1)); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyA); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyB); expect(invokedOuter, equals(1)); expect(invokedInner, equals(1)); }); testWidgets('Works correctly with Shortcuts too', (WidgetTester tester) async { int invokedCallbackA = 0; int invokedCallbackB = 0; int invokedActionA = 0; int invokedActionB = 0; void clear() { invokedCallbackA = 0; invokedCallbackB = 0; invokedActionA = 0; invokedActionB = 0; } await tester.pumpWidget( Actions( actions: <Type, Action<Intent>>{ TestIntent: TestAction( onInvoke: (Intent intent) { invokedActionA += 1; return true; }, ), TestIntent2: TestAction( onInvoke: (Intent intent) { invokedActionB += 1; return true; }, ), VoidCallbackIntent: VoidCallbackAction(), }, child: ShortcutRegistrar( child: TestCallbackRegistration( shortcuts: <ShortcutActivator, Intent>{ const CharacterActivator('b'): VoidCallbackIntent(() { invokedCallbackB += 1; }), }, child: Shortcuts( shortcuts: const <ShortcutActivator, Intent>{ SingleActivator(LogicalKeyboardKey.keyA): TestIntent(), SingleActivator(LogicalKeyboardKey.keyB): TestIntent2(), }, child: ShortcutRegistrar( child: TestCallbackRegistration( shortcuts: <ShortcutActivator, Intent>{ const CharacterActivator('a'): VoidCallbackIntent(() { invokedCallbackA += 1; }), }, child: const Focus( autofocus: true, child: Placeholder(), ), ), ), ), ), ), ), ); await tester.pump(); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyA); expect(invokedCallbackA, equals(1)); expect(invokedCallbackB, equals(0)); expect(invokedActionA, equals(0)); expect(invokedActionB, equals(0)); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyA); clear(); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyB); expect(invokedCallbackA, equals(0)); expect(invokedCallbackB, equals(0)); expect(invokedActionA, equals(0)); expect(invokedActionB, equals(1)); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyB); }); testWidgets('Updating shortcuts triggers dependency rebuild', (WidgetTester tester) async { final List<Map<ShortcutActivator, Intent>> shortcutsChanged = <Map<ShortcutActivator, Intent>>[]; void dependenciesUpdated(Map<ShortcutActivator, Intent> shortcuts) { shortcutsChanged.add(shortcuts); } await tester.pumpWidget( ShortcutRegistrar( child: TestCallbackRegistration( onDependencyUpdate: dependenciesUpdated, shortcuts: const <ShortcutActivator, Intent>{ SingleActivator(LogicalKeyboardKey.keyA): SelectAllTextIntent(SelectionChangedCause.keyboard), SingleActivator(LogicalKeyboardKey.keyB): ActivateIntent(), }, child: Actions( actions: <Type, Action<Intent>>{ VoidCallbackIntent: VoidCallbackAction(), }, child: const Focus( autofocus: true, child: Placeholder(), ), ), ), ), ); await tester.pumpWidget( ShortcutRegistrar( child: TestCallbackRegistration( onDependencyUpdate: dependenciesUpdated, shortcuts: const <ShortcutActivator, Intent>{ SingleActivator(LogicalKeyboardKey.keyA): SelectAllTextIntent(SelectionChangedCause.keyboard), }, child: Actions( actions: <Type, Action<Intent>>{ VoidCallbackIntent: VoidCallbackAction(), }, child: const Focus( autofocus: true, child: Placeholder(), ), ), ), ), ); await tester.pumpWidget( ShortcutRegistrar( child: TestCallbackRegistration( onDependencyUpdate: dependenciesUpdated, shortcuts: const <ShortcutActivator, Intent>{ SingleActivator(LogicalKeyboardKey.keyA): SelectAllTextIntent(SelectionChangedCause.keyboard), SingleActivator(LogicalKeyboardKey.keyB): ActivateIntent(), }, child: Actions( actions: <Type, Action<Intent>>{ VoidCallbackIntent: VoidCallbackAction(), }, child: const Focus( autofocus: true, child: Placeholder(), ), ), ), ), ); expect(shortcutsChanged.length, equals(2)); expect(shortcutsChanged.last, equals(const <ShortcutActivator, Intent>{ SingleActivator(LogicalKeyboardKey.keyA): SelectAllTextIntent(SelectionChangedCause.keyboard), SingleActivator(LogicalKeyboardKey.keyB): ActivateIntent(), })); }); testWidgets('using a disposed token asserts', (WidgetTester tester) async { final ShortcutRegistry registry = ShortcutRegistry(); addTearDown(registry.dispose); final ShortcutRegistryEntry token = registry.addAll(const <ShortcutActivator, Intent>{ SingleActivator(LogicalKeyboardKey.keyA): DoNothingIntent(), }); token.dispose(); expect(() {token.replaceAll(<ShortcutActivator, Intent>{}); }, throwsFlutterError); }); testWidgets('setting duplicate bindings asserts', (WidgetTester tester) async { final ShortcutRegistry registry = ShortcutRegistry(); addTearDown(registry.dispose); final ShortcutRegistryEntry token = registry.addAll(const <ShortcutActivator, Intent>{ SingleActivator(LogicalKeyboardKey.keyA): DoNothingIntent(), }); expect(() { final ShortcutRegistryEntry token2 = registry.addAll(const <ShortcutActivator, Intent>{ SingleActivator(LogicalKeyboardKey.keyA): ActivateIntent(), }); token2.dispose(); }, throwsAssertionError); token.dispose(); }); test('dispatches object creation in constructor', () async { await expectLater( await memoryEvents(() => ShortcutRegistry().dispose(), ShortcutRegistry), areCreateAndDispose, ); }); }); } class TestCallbackRegistration extends StatefulWidget { const TestCallbackRegistration({super.key, required this.shortcuts, this.onDependencyUpdate, required this.child}); final Map<ShortcutActivator, Intent> shortcuts; final void Function(Map<ShortcutActivator, Intent> shortcuts)? onDependencyUpdate; final Widget child; @override State<TestCallbackRegistration> createState() => _TestCallbackRegistrationState(); } class _TestCallbackRegistrationState extends State<TestCallbackRegistration> { ShortcutRegistryEntry? _registryToken; @override void didChangeDependencies() { super.didChangeDependencies(); _registryToken?.dispose(); _registryToken = ShortcutRegistry.of(context).addAll(widget.shortcuts); } @override void didUpdateWidget(TestCallbackRegistration oldWidget) { super.didUpdateWidget(oldWidget); if (widget.shortcuts != oldWidget.shortcuts || _registryToken == null) { _registryToken?.dispose(); _registryToken = ShortcutRegistry.of(context).addAll(widget.shortcuts); } widget.onDependencyUpdate?.call(ShortcutRegistry.of(context).shortcuts); } @override void dispose() { _registryToken?.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return widget.child; } } class TestAction extends CallbackAction<Intent> { TestAction({ required super.onInvoke, }); } /// An activator that accepts down events that has [key] as the logical key. /// /// This class is used only to tests. It is intentionally designed poorly by /// returning null in [triggers], and checks [key] in [acceptsEvent]. class DumbLogicalActivator extends ShortcutActivator { const DumbLogicalActivator(this.key); final LogicalKeyboardKey key; @override Iterable<LogicalKeyboardKey>? get triggers => null; @override bool accepts(KeyEvent event, HardwareKeyboard state) { return (event is KeyDownEvent || event is KeyRepeatEvent) && event.logicalKey == key; } /// Returns a short and readable description of the key combination. /// /// Intended to be used in debug mode for logging purposes. In release mode, /// [debugDescribeKeys] returns an empty string. @override String debugDescribeKeys() { String result = ''; assert(() { result = key.keyLabel; return true; }()); return result; } } class TestIntent extends Intent { const TestIntent(); } class TestIntent2 extends Intent { const TestIntent2(); } class TestShortcutManager extends ShortcutManager { TestShortcutManager(this.keys, { super.shortcuts }); List<LogicalKeyboardKey> keys; @override KeyEventResult handleKeypress(BuildContext context, KeyEvent event) { if (event is KeyDownEvent || event is KeyRepeatEvent) { keys.add(event.logicalKey); } return super.handleKeypress(context, event); } } Widget activatorTester( ShortcutActivator activator, ValueSetter<Intent> onInvoke, [ ShortcutActivator? activator2, ValueSetter<Intent>? onInvoke2, ]) { final bool hasSecond = activator2 != null && onInvoke2 != null; return Actions( key: GlobalKey(), actions: <Type, Action<Intent>>{ TestIntent: TestAction(onInvoke: (Intent intent) { onInvoke(intent); return true; }), if (hasSecond) TestIntent2: TestAction(onInvoke: (Intent intent) { onInvoke2(intent); return null; }), }, child: Shortcuts( shortcuts: <ShortcutActivator, Intent>{ activator: const TestIntent(), if (hasSecond) activator2: const TestIntent2(), }, child: const Focus( autofocus: true, child: SizedBox(width: 100, height: 100), ), ), ); }
flutter/packages/flutter/test/widgets/shortcuts_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/shortcuts_test.dart", "repo_id": "flutter", "token_count": 34750 }
312
// Copyright 2014 The Flutter 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:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('SliverResizingHeader basics', (WidgetTester tester) async { Widget buildFrame({ required Axis axis, required bool reverse }) { final (Widget minPrototype, Widget maxPrototype) = switch (axis) { Axis.vertical => (const SizedBox(height: 100), const SizedBox(height: 300)), Axis.horizontal => (const SizedBox(width: 100), const SizedBox(width: 300)), }; return MaterialApp( home: Scaffold( body: CustomScrollView( scrollDirection: axis, reverse: reverse, slivers: <Widget>[ SliverResizingHeader( minExtentPrototype: minPrototype, maxExtentPrototype: maxPrototype, child: const SizedBox.expand(child: Text('header')), ), SliverList( delegate: SliverChildBuilderDelegate( (BuildContext context, int index) => Text('item $index'), childCount: 100, ), ), ], ), ), ); } Rect getHeaderRect() => tester.getRect(find.text('header')); Rect getItemRect(int index) => tester.getRect(find.text('item $index')); // axis: Axis.vertical, reverse: false { await tester.pumpWidget(buildFrame(axis: Axis.vertical, reverse: false)); await tester.pumpAndSettle(); final ScrollPosition position = tester.state<ScrollableState>(find.byType(Scrollable)).position; // The test viewport is width=800 x height=600 // The height=300 header is at the top of the scroll view and all items are the same height. expect(getHeaderRect().topLeft, Offset.zero); expect(getHeaderRect().width, 800); expect(getHeaderRect().height, 300); // First and last visible items final double itemHeight = getItemRect(0).height; final int visibleItemCount = 300 ~/ itemHeight; // 300 = viewport height - header height expect(find.text('item 0'), findsOneWidget); expect(find.text('item ${visibleItemCount - 1}'), findsOneWidget); // Scrolling up and down leaves the header at the top but changes its height // between the heights of the min and max extent prototypes. position.moveTo(200); await tester.pumpAndSettle(); expect(getHeaderRect().topLeft, Offset.zero); expect(getHeaderRect().width, 800); expect(getHeaderRect().height, 100); position.moveTo(0); await tester.pumpAndSettle(); expect(getHeaderRect().topLeft, Offset.zero); expect(getHeaderRect().width, 800); expect(getHeaderRect().height, 300); } // axis: Axis.horizontal, reverse: false { await tester.pumpWidget(buildFrame(axis: Axis.horizontal, reverse: false)); await tester.pumpAndSettle(); final ScrollPosition position = tester.state<ScrollableState>(find.byType(Scrollable)).position; // The width=300 header is at the left of the scroll view and all items are the same width. expect(getHeaderRect().topLeft, Offset.zero); expect(getHeaderRect().width, 300); expect(getHeaderRect().height, 600); // First and last visible items (assuming < 10 items visible) final double itemWidth = getItemRect(0).width; final int visibleItemCount = 500 ~/ itemWidth; // 500 = viewport width - header width expect(find.text('item 0'), findsOneWidget); expect(find.text('item ${visibleItemCount - 1}'), findsOneWidget); // Scrolling up and down leaves the header on the left but changes its width // between the heights of the min and max extent prototypes. position.moveTo(200); await tester.pumpAndSettle(); expect(getHeaderRect().topLeft, Offset.zero); expect(getHeaderRect().height, 600); expect(getHeaderRect().width, 100); position.moveTo(0); await tester.pumpAndSettle(); expect(getHeaderRect().topLeft, Offset.zero); expect(getHeaderRect().height, 600); expect(getHeaderRect().width, 300); } // axis: Axis.vertical, reverse: true { await tester.pumpWidget(buildFrame(axis: Axis.vertical, reverse: true)); await tester.pumpAndSettle(); final ScrollPosition position = tester.state<ScrollableState>(find.byType(Scrollable)).position; // The height=300 header is at the bottom of the scroll view and all items are the same height. expect(getHeaderRect().bottomLeft, const Offset(0, 600)); expect(getHeaderRect().width, 800); expect(getHeaderRect().height, 300); // First and last visible items (assuming < 10 items visible) final double itemHeight = getItemRect(0).height; final int visibleItemCount = 300 ~/ itemHeight; // 300 = viewport height - header height expect(find.text('item 0'), findsOneWidget); expect(find.text('item ${visibleItemCount - 1}'), findsOneWidget); // Scrolling up and down leaves the header at the bottom but changes its height // between the heights of the min and max extent prototypes. position.moveTo(200); await tester.pumpAndSettle(); expect(getHeaderRect().bottomLeft, const Offset(0, 600)); expect(getHeaderRect().width, 800); expect(getHeaderRect().height, 100); position.moveTo(0); await tester.pumpAndSettle(); expect(getHeaderRect().bottomLeft, const Offset(0, 600)); expect(getHeaderRect().width, 800); expect(getHeaderRect().height, 300); } // axis: Axis.horizontal, reverse: true { await tester.pumpWidget(buildFrame(axis: Axis.horizontal, reverse: true)); await tester.pumpAndSettle(); final ScrollPosition position = tester.state<ScrollableState>(find.byType(Scrollable)).position; // The width=300 header is on the right of the scroll view and all items are the same width. expect(getHeaderRect().topRight, const Offset(800, 0)); expect(getHeaderRect().width, 300); expect(getHeaderRect().height, 600); final double itemWidth = getItemRect(0).width; final int visibleItemCount = 500 ~/ itemWidth; // 500 = viewport width - header width expect(find.text('item 0'), findsOneWidget); expect(find.text('item ${visibleItemCount - 1}'), findsOneWidget); // Scrolling up and down leaves the header on the left but changes its width // between the heights of the min and max extent prototypes. position.moveTo(200); await tester.pumpAndSettle(); expect(getHeaderRect().topRight, const Offset(800, 0)); expect(getHeaderRect().height, 600); expect(getHeaderRect().width, 100); position.moveTo(0); await tester.pumpAndSettle(); expect(getHeaderRect().topRight, const Offset(800, 0)); expect(getHeaderRect().height, 600); expect(getHeaderRect().width, 300); } }); testWidgets('SliverResizingHeader default minExtent is 0', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: CustomScrollView( slivers: <Widget>[ const SliverResizingHeader( maxExtentPrototype: SizedBox(height: 300), child: SizedBox.expand(child: Text('header')), ), SliverList( delegate: SliverChildBuilderDelegate( (BuildContext context, int index) => Text('item $index'), childCount: 100, ), ), ], ), ), ), ); expect(tester.getSize(find.text('header')).height, 300); final ScrollPosition position = tester.state<ScrollableState>(find.byType(Scrollable)).position; position.moveTo(299); await tester.pumpAndSettle(); expect(tester.getSize(find.text('header')).height, 1); position.moveTo(300); await tester.pumpAndSettle(); expect(find.text('header'), findsNothing); }); testWidgets('SliverResizingHeader with identcial min/max prototypes is effectively a pinned header', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: CustomScrollView( slivers: <Widget>[ const SliverResizingHeader( minExtentPrototype: SizedBox(height: 100), maxExtentPrototype: SizedBox(height: 100), child: SizedBox.expand(child: Text('header')), ), SliverList( delegate: SliverChildBuilderDelegate( (BuildContext context, int index) => Text('item $index'), childCount: 100, ), ), ], ), ), ), ); expect(tester.getTopLeft(find.text('header')), Offset.zero); expect(tester.getSize(find.text('header')), const Size(800, 100)); final ScrollPosition position = tester.state<ScrollableState>(find.byType(Scrollable)).position; position.moveTo(100); await tester.pumpAndSettle(); expect(tester.getTopLeft(find.text('header')), Offset.zero); expect(tester.getSize(find.text('header')), const Size(800, 100)); position.moveTo(0); await tester.pumpAndSettle(); expect(tester.getTopLeft(find.text('header')), Offset.zero); expect(tester.getSize(find.text('header')), const Size(800, 100)); }); testWidgets('SliverResizingHeader default maxExtent matches the child', (WidgetTester tester) async { final Key headerKey = UniqueKey(); await tester.pumpWidget( MaterialApp( home: Scaffold( body: CustomScrollView( slivers: <Widget>[ SliverResizingHeader( child: SizedBox(key: headerKey, height: 300), ), SliverList( delegate: SliverChildBuilderDelegate( (BuildContext context, int index) => Text('item $index'), childCount: 100, ), ), ], ), ), ), ); expect(tester.getSize(find.byKey(headerKey)).height, 300); final ScrollPosition position = tester.state<ScrollableState>(find.byType(Scrollable)).position; position.moveTo(299); await tester.pumpAndSettle(); expect(tester.getSize(find.byKey(headerKey)).height, 1); position.moveTo(300); await tester.pumpAndSettle(); expect(find.byKey(headerKey), findsNothing); }); testWidgets('SliverResizingHeader overrides initial out of bounds child size', (WidgetTester tester) async { Widget buildFrame(double childHeight) { return MaterialApp( home: Scaffold( body: CustomScrollView( slivers: <Widget>[ SliverResizingHeader( minExtentPrototype: const SizedBox(height: 100), maxExtentPrototype: const SizedBox(height: 300), child: SizedBox(height: childHeight, child: const Text('header')), ), ], ), ), ); } await tester.pumpWidget(buildFrame(50)); expect(tester.getSize(find.text('header')).height, 100); await tester.pumpWidget(buildFrame(350)); expect(tester.getSize(find.text('header')).height, 300); }); testWidgets('SliverResizingHeader update prototypes', (WidgetTester tester) async { Widget buildFrame(double minHeight, double maxHeight) { return MaterialApp( home: Scaffold( body: CustomScrollView( slivers: <Widget>[ SliverResizingHeader( minExtentPrototype: SizedBox(height: minHeight), maxExtentPrototype: SizedBox(height: maxHeight), child: const SizedBox(height: 300, child: Text('header')), ), SliverList( delegate: SliverChildBuilderDelegate( (BuildContext context, int index) => SizedBox(height: 50, child: Text('$index')), childCount: 100, ), ), ], ), ), ); } double getHeaderHeight() => tester.getSize(find.text('header')).height; await tester.pumpWidget(buildFrame(100, 300)); expect(getHeaderHeight(), 300); // Scroll more than needed to reach the min and max header heights. await tester.drag(find.byType(CustomScrollView), const Offset(0, -300)); await tester.pumpAndSettle(); expect(getHeaderHeight(), 100); await tester.drag(find.byType(CustomScrollView), const Offset(0, 300)); await tester.pumpAndSettle(); expect(getHeaderHeight(), 300); // Change min,maxExtentPrototype widget heights from 150,200 to await tester.pumpWidget(buildFrame(150, 200)); expect(getHeaderHeight(), 200); await tester.drag(find.byType(CustomScrollView), const Offset(0, -100)); await tester.pumpAndSettle(); expect(getHeaderHeight(), 150); await tester.drag(find.byType(CustomScrollView), const Offset(0, 100)); await tester.pumpAndSettle(); expect(getHeaderHeight(), 200); }); }
flutter/packages/flutter/test/widgets/sliver_resizing_header_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/sliver_resizing_header_test.dart", "repo_id": "flutter", "token_count": 5410 }
313
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file is run as part of a reduced test set in CI on Mac and Windows // machines. @Tags(<String>['reduced-test-set']) library; import 'dart:ui' as ui; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; import '../impeller_test_helpers.dart'; void main() { testWidgets('SnapshotWidget can rasterize child', (WidgetTester tester) async { final SnapshotController controller = SnapshotController(allowSnapshotting: true); addTearDown(controller.dispose); final Key key = UniqueKey(); await tester.pumpWidget(RepaintBoundary( key: key, child: TestDependencies( child: SnapshotWidget( controller: controller, child: Container( width: 100, height: 100, color: const Color(0xFFAABB11), ), ), ), )); await expectLater(find.byKey(key), matchesGoldenFile('raster_widget.yellow.png')); // Now change the color and assert the old snapshot still matches. await tester.pumpWidget(RepaintBoundary( key: key, child: TestDependencies( child: SnapshotWidget( controller: controller, child: Container( width: 100, height: 100, color: const Color(0xFFAA0000), ), ), ), )); await expectLater(find.byKey(key), matchesGoldenFile('raster_widget.yellow.png')); // Now invoke clear and the raster is re-generated. controller.clear(); await tester.pump(); await expectLater(find.byKey(key), matchesGoldenFile('raster_widget.red.png')); }, skip: kIsWeb); // TODO(jonahwilliams): https://github.com/flutter/flutter/issues/106689 testWidgets('Changing devicePixelRatio does not repaint if snapshotting is not enabled', (WidgetTester tester) async { final SnapshotController controller = SnapshotController(); addTearDown(controller.dispose); final TestPainter painter = TestPainter(); addTearDown(painter.dispose); double devicePixelRatio = 1.0; late StateSetter localSetState; await tester.pumpWidget( StatefulBuilder(builder: (BuildContext context, StateSetter setState) { localSetState = setState; return Center( child: TestDependencies( devicePixelRatio: devicePixelRatio, child: SnapshotWidget( controller: controller, painter: painter, child: const SizedBox(width: 100, height: 100), ), ), ); }), ); expect(painter.count, 1); localSetState(() { devicePixelRatio = 2.0; }); await tester.pump(); // Not repainted as dpr was not used. expect(painter.count, 1); }, skip: kIsWeb); // TODO(jonahwilliams): https://github.com/flutter/flutter/issues/106689 testWidgets('Changing devicePixelRatio forces raster regeneration', (WidgetTester tester) async { final SnapshotController controller = SnapshotController(allowSnapshotting: true); addTearDown(controller.dispose); final TestPainter painter = TestPainter(); addTearDown(painter.dispose); double devicePixelRatio = 1.0; late StateSetter localSetState; await tester.pumpWidget( StatefulBuilder(builder: (BuildContext context, StateSetter setState) { localSetState = setState; return Center( child: TestDependencies( devicePixelRatio: devicePixelRatio, child: SnapshotWidget( controller: controller, painter: painter, child: const SizedBox(width: 100, height: 100), ), ), ); }), ); final ui.Image? raster = painter.lastImage; expect(raster, isNotNull); expect(painter.count, 1); localSetState(() { devicePixelRatio = 2.0; }); await tester.pump(); final ui.Image? newRaster = painter.lastImage; expect(painter.count, 2); expect(raster, isNot(newRaster)); }, skip: kIsWeb); // TODO(jonahwilliams): https://github.com/flutter/flutter/issues/106689 testWidgets('SnapshotWidget paints its child as a single picture layer', (WidgetTester tester) async { final SnapshotController controller = SnapshotController(allowSnapshotting: true); addTearDown(controller.dispose); await tester.pumpWidget(RepaintBoundary( child: Center( child: TestDependencies( child: SnapshotWidget( controller: controller, child: Container( width: 100, height: 100, color: const Color(0xFFAABB11), ), ), ), ), )); expect(tester.layers, hasLength(3)); expect(tester.layers.last, isA<PictureLayer>()); controller.allowSnapshotting = false; await tester.pump(); expect(tester.layers, hasLength(3)); expect(tester.layers.last, isA<PictureLayer>()); }, skip: kIsWeb); // TODO(jonahwilliams): https://github.com/flutter/flutter/issues/106689 testWidgets('SnapshotWidget can update the painter type', (WidgetTester tester) async { final SnapshotController controller = SnapshotController(allowSnapshotting: true); addTearDown(controller.dispose); final TestPainter painter1 = TestPainter(); addTearDown(painter1.dispose); final TestPainter2 painter2 = TestPainter2(); addTearDown(painter2.dispose); await tester.pumpWidget( Center( child: TestDependencies( child: SnapshotWidget( controller: controller, painter: painter1, child: const SizedBox(), ), ), ), ); await tester.pumpWidget( Center( child: TestDependencies( child: SnapshotWidget( controller: controller, painter: painter2, child: const SizedBox(), ), ), ), ); expect(tester.takeException(), isNull); }, skip: kIsWeb); // TODO(jonahwilliams): https://github.com/flutter/flutter/issues/106689 testWidgets('RenderSnapshotWidget does not error on rasterization of child with empty size', (WidgetTester tester) async { final SnapshotController controller = SnapshotController(allowSnapshotting: true); addTearDown(controller.dispose); await tester.pumpWidget( Center( child: TestDependencies( child: SnapshotWidget( controller: controller, child: const SizedBox(), ), ), ), ); expect(tester.takeException(), isNull); }, skip: kIsWeb); // TODO(jonahwilliams): https://github.com/flutter/flutter/issues/106689 testWidgets('RenderSnapshotWidget throws assertion if platform view is encountered', (WidgetTester tester) async { final SnapshotController controller = SnapshotController(allowSnapshotting: true); addTearDown(controller.dispose); await tester.pumpWidget( Center( child: TestDependencies( child: SnapshotWidget( controller: controller, child: const SizedBox( width: 100, height: 100, child: TestPlatformView(), ), ), ), ), ); expect(tester.takeException(), isA<FlutterError>() .having((FlutterError error) => error.message, 'message', contains('SnapshotWidget used with a child that contains a PlatformView'))); }, skip: kIsWeb); // TODO(jonahwilliams): https://github.com/flutter/flutter/issues/106689 testWidgets('RenderSnapshotWidget does not assert if SnapshotMode.forced', (WidgetTester tester) async { final SnapshotController controller = SnapshotController(allowSnapshotting: true); addTearDown(controller.dispose); await tester.pumpWidget( Center( child: TestDependencies( child: SnapshotWidget( controller: controller, mode: SnapshotMode.forced, child: const SizedBox( width: 100, height: 100, child: TestPlatformView(), ), ), ), ), ); expect(tester.takeException(), isNull); }, skip: kIsWeb); // TODO(jonahwilliams): https://github.com/flutter/flutter/issues/106689 testWidgets('RenderSnapshotWidget does not take a snapshot if a platform view is encountered with SnapshotMode.permissive', (WidgetTester tester) async { final SnapshotController controller = SnapshotController(allowSnapshotting: true); addTearDown(controller.dispose); await tester.pumpWidget( Center( child: TestDependencies( child: SnapshotWidget( controller: controller, mode: SnapshotMode.permissive, child: const SizedBox( width: 100, height: 100, child: TestPlatformView(), ), ), ), ), ); expect(tester.takeException(), isNull); expect(tester.layers.last, isA<PlatformViewLayer>()); }, skip: kIsWeb); // TODO(jonahwilliams): https://github.com/flutter/flutter/issues/106689 testWidgets('SnapshotWidget should have same result when enabled', (WidgetTester tester) async { addTearDown(tester.view.reset); tester.view ..physicalSize = const Size(10, 10) ..devicePixelRatio = 1; const ValueKey<String> repaintBoundaryKey = ValueKey<String>('boundary'); final SnapshotController controller = SnapshotController(); addTearDown(controller.dispose); await tester.pumpWidget(RepaintBoundary( key: repaintBoundaryKey, child: MaterialApp( debugShowCheckedModeBanner: false, home: Container( color: Colors.black, padding: const EdgeInsets.only(right: 0.6, bottom: 0.6), child: SnapshotWidget( controller: controller, child: Container( margin: const EdgeInsets.only(right: 0.4, bottom: 0.4), color: Colors.blue, ), ), ), ), )); final ui.Image imageWhenDisabled = (tester.renderObject(find.byKey(repaintBoundaryKey)) as RenderRepaintBoundary).toImageSync(); addTearDown(imageWhenDisabled.dispose); controller.allowSnapshotting = true; await tester.pump(); await expectLater(find.byKey(repaintBoundaryKey), matchesReferenceImage(imageWhenDisabled)); }, skip: kIsWeb || impellerEnabled); // TODO(jonahwilliams): https://github.com/flutter/flutter/issues/106689 test('SnapshotPainter dispatches memory events', () async { await expectLater( await memoryEvents( () => TestPainter().dispose(), TestPainter, ), areCreateAndDispose, ); }); } class TestPlatformView extends SingleChildRenderObjectWidget { const TestPlatformView({super.key}); @override RenderObject createRenderObject(BuildContext context) { return RenderTestPlatformView(); } } class RenderTestPlatformView extends RenderProxyBox { @override void paint(PaintingContext context, ui.Offset offset) { context.addLayer(PlatformViewLayer(rect: offset & size, viewId: 1)); } } class TestPainter extends SnapshotPainter { int count = 0; bool shouldRepaintValue = false; ui.Image? lastImage; int addedListenerCount = 0; int removedListenerCount = 0; @override void addListener(ui.VoidCallback listener) { addedListenerCount += 1; super.addListener(listener); } @override void removeListener(ui.VoidCallback listener) { removedListenerCount += 1; super.removeListener(listener); } @override void paintSnapshot(PaintingContext context, Offset offset, Size size, ui.Image image, Size sourceSize, double pixelRatio) { count += 1; lastImage = image; } @override void paint(PaintingContext context, ui.Offset offset, ui.Size size, PaintingContextCallback painter) { count += 1; } @override bool shouldRepaint(covariant TestPainter oldDelegate) => shouldRepaintValue; } class TestPainter2 extends TestPainter { @override bool shouldRepaint(covariant TestPainter2 oldDelegate) => shouldRepaintValue; } class TestDependencies extends StatelessWidget { const TestDependencies({required this.child, super.key, this.devicePixelRatio}); final Widget child; final double? devicePixelRatio; @override Widget build(BuildContext context) { return Directionality( textDirection: TextDirection.ltr, child: MediaQuery( data: const MediaQueryData().copyWith(devicePixelRatio: devicePixelRatio), child: child, ), ); } }
flutter/packages/flutter/test/widgets/snapshot_widget_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/snapshot_widget_test.dart", "repo_id": "flutter", "token_count": 5131 }
314
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // TODO(LongCatIsLooong): Remove this file once textScaleFactor is removed. import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { group('TextStyle', () { test('getTextStyle is backward compatible', () { expect( const TextStyle(fontSize: 14).getTextStyle(textScaleFactor: 2.0).toString(), contains('fontSize: 28'), ); }, skip: kIsWeb); // [intended] CkTextStyle doesn't have a custom toString implementation. }); group('TextPainter', () { test('textScaleFactor translates to textScaler', () { final TextPainter textPainter = TextPainter( text: const TextSpan(text: 'text'), textDirection: TextDirection.ltr, textScaleFactor: 42, ); expect(textPainter.textScaler, const TextScaler.linear(42.0)); // Linear TextScaler translates to textScaleFactor. textPainter.textScaler = const TextScaler.linear(12.0); expect(textPainter.textScaleFactor, 12.0); textPainter.textScaleFactor = 10; expect(textPainter.textScaler, const TextScaler.linear(10)); }); }); group('MediaQuery', () { test('specifying both textScaler and textScalingFactor asserts', () { expect( () => MediaQueryData(textScaleFactor: 2, textScaler: const TextScaler.linear(2.0)), throwsAssertionError, ); }); test('copyWith is backward compatible', () { const MediaQueryData data = MediaQueryData(textScaler: TextScaler.linear(2.0)); final MediaQueryData data1 = data.copyWith(textScaleFactor: 42); expect(data1.textScaler, const TextScaler.linear(42)); expect(data1.textScaleFactor, 42); final MediaQueryData data2 = data.copyWith(textScaler: TextScaler.noScaling); expect(data2.textScaler, TextScaler.noScaling); expect(data2.textScaleFactor, 1.0); }); test('copyWith specifying both textScaler and textScalingFactor asserts', () { const MediaQueryData data = MediaQueryData(); expect( () => data.copyWith(textScaleFactor: 2, textScaler: const TextScaler.linear(2.0)), throwsAssertionError, ); }); testWidgets('MediaQuery.textScaleFactorOf overriding compatibility', (WidgetTester tester) async { late final double outsideTextScaleFactor; late final TextScaler outsideTextScaler; late final double insideTextScaleFactor; late final TextScaler insideTextScaler; await tester.pumpWidget( Builder( builder: (BuildContext context) { outsideTextScaleFactor = MediaQuery.textScaleFactorOf(context); outsideTextScaler = MediaQuery.textScalerOf(context); return MediaQuery( data: const MediaQueryData( textScaleFactor: 4.0, ), child: Builder( builder: (BuildContext context) { insideTextScaleFactor = MediaQuery.textScaleFactorOf(context); insideTextScaler = MediaQuery.textScalerOf(context); return Container(); }, ), ); }, ), ); // Overriding textScaleFactor should work for unmigrated widgets that are // still using MediaQuery.textScaleFactorOf. Also if a unmigrated widget // overrides MediaQuery.textScaleFactor, migrated widgets in the subtree // should get the correct TextScaler. expect(outsideTextScaleFactor, 1.0); expect(outsideTextScaler.textScaleFactor, 1.0); expect(outsideTextScaler, TextScaler.noScaling); expect(insideTextScaleFactor, 4.0); expect(insideTextScaler.textScaleFactor, 4.0); expect(insideTextScaler, const TextScaler.linear(4.0)); }); testWidgets('textScaleFactor overriding backward compatibility', (WidgetTester tester) async { late final double outsideTextScaleFactor; late final TextScaler outsideTextScaler; late final double insideTextScaleFactor; late final TextScaler insideTextScaler; await tester.pumpWidget( Builder( builder: (BuildContext context) { outsideTextScaleFactor = MediaQuery.textScaleFactorOf(context); outsideTextScaler = MediaQuery.textScalerOf(context); return MediaQuery( data: const MediaQueryData(textScaler: TextScaler.linear(4.0)), child: Builder( builder: (BuildContext context) { insideTextScaleFactor = MediaQuery.textScaleFactorOf(context); insideTextScaler = MediaQuery.textScalerOf(context); return Container(); }, ), ); }, ), ); expect(outsideTextScaleFactor, 1.0); expect(outsideTextScaler.textScaleFactor, 1.0); expect(outsideTextScaler, TextScaler.noScaling); expect(insideTextScaleFactor, 4.0); expect(insideTextScaler.textScaleFactor, 4.0); expect(insideTextScaler, const TextScaler.linear(4.0)); }); }); group('RenderObjects backward compatibility', () { test('RenderEditable', () { final RenderEditable renderObject = RenderEditable( backgroundCursorColor: const Color.fromARGB(0xFF, 0xFF, 0x00, 0x00), textDirection: TextDirection.ltr, cursorColor: const Color.fromARGB(0xFF, 0xFF, 0x00, 0x00), offset: ViewportOffset.zero(), textSelectionDelegate: _FakeEditableTextState(), text: const TextSpan( text: 'test', style: TextStyle(height: 1.0, fontSize: 10.0), ), startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), selection: const TextSelection.collapsed(offset: 0), ); expect(renderObject.textScaleFactor, 1.0); renderObject.textScaleFactor = 3.0; expect(renderObject.textScaleFactor, 3.0); expect(renderObject.textScaler, const TextScaler.linear(3.0)); renderObject.textScaler = const TextScaler.linear(4.0); expect(renderObject.textScaleFactor, 4.0); }); test('RenderParagraph', () { final RenderParagraph renderObject = RenderParagraph( const TextSpan( text: 'test', style: TextStyle(height: 1.0, fontSize: 10.0), ), textDirection: TextDirection.ltr, ); expect(renderObject.textScaleFactor, 1.0); renderObject.textScaleFactor = 3.0; expect(renderObject.textScaleFactor, 3.0); expect(renderObject.textScaler, const TextScaler.linear(3.0)); renderObject.textScaler = const TextScaler.linear(4.0); expect(renderObject.textScaleFactor, 4.0); }); }); group('Widgets backward compatibility', () { testWidgets('RichText', (WidgetTester tester) async { await tester.pumpWidget( RichText( textDirection: TextDirection.ltr, text: const TextSpan(), textScaleFactor: 2.0, ), ); expect( tester.renderObject<RenderParagraph>(find.byType(RichText)).textScaler, const TextScaler.linear(2.0), ); expect(tester.renderObject<RenderParagraph>(find.byType(RichText)).textScaleFactor, 2.0); }); testWidgets('Text', (WidgetTester tester) async { await tester.pumpWidget( const Text( 'text', textDirection: TextDirection.ltr, textScaleFactor: 2.0, ), ); expect( tester.renderObject<RenderParagraph>(find.text('text')).textScaler, const TextScaler.linear(2.0), ); }); testWidgets('EditableText', (WidgetTester tester) async { final TextEditingController controller = TextEditingController(); addTearDown(controller.dispose); final FocusNode focusNode = FocusNode(debugLabel: 'EditableText Node'); addTearDown(focusNode.dispose); const TextStyle textStyle = TextStyle(); const Color cursorColor = Color.fromARGB(0xFF, 0xFF, 0x00, 0x00); await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.rtl, child: EditableText( backgroundCursorColor: cursorColor, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, textScaleFactor: 2.0, ), ), ), ); final RenderEditable renderEditable = tester.allRenderObjects.whereType<RenderEditable>().first; expect( renderEditable.textScaler, const TextScaler.linear(2.0), ); }); }); } class _FakeEditableTextState with TextSelectionDelegate { @override TextEditingValue textEditingValue = TextEditingValue.empty; TextSelection? selection; @override void hideToolbar([bool hideHandles = true]) { } @override void userUpdateTextEditingValue(TextEditingValue value, SelectionChangedCause cause) { selection = value.selection; } @override void bringIntoView(TextPosition position) { } @override void cutSelection(SelectionChangedCause cause) { } @override Future<void> pasteText(SelectionChangedCause cause) { return Future<void>.value(); } @override void selectAll(SelectionChangedCause cause) { } @override void copySelection(SelectionChangedCause cause) { } }
flutter/packages/flutter/test/widgets/text_scaler_backward_compatibility_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/text_scaler_backward_compatibility_test.dart", "repo_id": "flutter", "token_count": 3923 }
315
// Copyright 2014 The Flutter 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:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Animates forward when built', (WidgetTester tester) async { final List<int> values = <int>[]; int endCount = 0; await tester.pumpWidget( TweenAnimationBuilder<int>( duration: const Duration(seconds: 1), tween: IntTween(begin: 10, end: 110), builder: (BuildContext context, int i, Widget? child) { values.add(i); return const Placeholder(); }, onEnd: () { endCount++; }, ), ); expect(endCount, 0); expect(values, <int>[10]); await tester.pump(const Duration(milliseconds: 500)); expect(values, <int>[10, 60]); await tester.pump(const Duration(milliseconds: 501)); expect(endCount, 1); expect(values, <int>[10, 60, 110]); await tester.pump(const Duration(milliseconds: 500)); expect(endCount, 1); expect(values, <int>[10, 60, 110]); }); testWidgets('No initial animation when begin=null', (WidgetTester tester) async { final List<int> values = <int>[]; int endCount = 0; await tester.pumpWidget( TweenAnimationBuilder<int>( duration: const Duration(seconds: 1), tween: IntTween(end: 100), builder: (BuildContext context, int i, Widget? child) { values.add(i); return const Placeholder(); }, onEnd: () { endCount++; }, ), ); expect(endCount, 0); expect(values, <int>[100]); await tester.pump(const Duration(seconds: 2)); expect(endCount, 0); expect(values, <int>[100]); }); testWidgets('No initial animation when begin=end', (WidgetTester tester) async { final List<int> values = <int>[]; int endCount = 0; await tester.pumpWidget( TweenAnimationBuilder<int>( duration: const Duration(seconds: 1), tween: IntTween(begin: 100, end: 100), builder: (BuildContext context, int i, Widget? child) { values.add(i); return const Placeholder(); }, onEnd: () { endCount++; }, ), ); expect(endCount, 0); expect(values, <int>[100]); await tester.pump(const Duration(seconds: 2)); expect(endCount, 0); expect(values, <int>[100]); }); testWidgets('Replace tween animates new tween', (WidgetTester tester) async { final List<int> values = <int>[]; Widget buildWidget({required IntTween tween}) { return TweenAnimationBuilder<int>( duration: const Duration(seconds: 1), tween: tween, builder: (BuildContext context, int i, Widget? child) { values.add(i); return const Placeholder(); }, ); } await tester.pumpWidget(buildWidget(tween: IntTween(begin: 0, end: 100))); expect(values, <int>[0]); await tester.pump(const Duration(seconds: 2)); // finish first animation. expect(values, <int>[0, 100]); await tester.pumpWidget(buildWidget(tween: IntTween(begin: 100, end: 200))); expect(values, <int>[0, 100, 100]); await tester.pump(const Duration(milliseconds: 500)); expect(values, <int>[0, 100, 100, 150]); await tester.pump(const Duration(milliseconds: 500)); expect(values, <int>[0, 100, 100, 150, 200]); }); testWidgets('Curve is respected', (WidgetTester tester) async { final List<int> values = <int>[]; Widget buildWidget({required IntTween tween, required Curve curve}) { return TweenAnimationBuilder<int>( duration: const Duration(seconds: 1), tween: tween, curve: curve, builder: (BuildContext context, int i, Widget? child) { values.add(i); return const Placeholder(); }, ); } await tester.pumpWidget(buildWidget(tween: IntTween(begin: 0, end: 100), curve: Curves.easeInExpo)); expect(values, <int>[0]); await tester.pump(const Duration(milliseconds: 500)); expect(values.last, lessThan(50)); expect(values.last, greaterThan(0)); await tester.pump(const Duration(seconds: 2)); // finish animation. values.clear(); // Update curve (and tween to re-trigger animation). await tester.pumpWidget(buildWidget(tween: IntTween(begin: 100, end: 200), curve: Curves.linear)); expect(values, <int>[100]); await tester.pump(const Duration(milliseconds: 500)); expect(values, <int>[100, 150]); }); testWidgets('Duration is respected', (WidgetTester tester) async { final List<int> values = <int>[]; Widget buildWidget({required IntTween tween, required Duration duration}) { return TweenAnimationBuilder<int>( tween: tween, duration: duration, builder: (BuildContext context, int i, Widget? child) { values.add(i); return const Placeholder(); }, ); } await tester.pumpWidget(buildWidget(tween: IntTween(begin: 0, end: 100), duration: const Duration(seconds: 1))); expect(values, <int>[0]); await tester.pump(const Duration(milliseconds: 500)); expect(values, <int>[0, 50]); await tester.pump(const Duration(seconds: 2)); // finish animation. values.clear(); // Update duration (and tween to re-trigger animation). await tester.pumpWidget(buildWidget(tween: IntTween(begin: 100, end: 200), duration: const Duration(seconds: 2))); expect(values, <int>[100]); await tester.pump(const Duration(milliseconds: 500)); expect(values, <int>[100, 125]); }); testWidgets('Child is integrated into tree', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: TweenAnimationBuilder<int>( tween: IntTween(begin: 0, end: 100), duration: const Duration(seconds: 1), builder: (BuildContext context, int i, Widget? child) { return child!; }, child: const Text('Hello World'), ), ), ); expect(find.text('Hello World'), findsOneWidget); }); group('Change tween gapless while', () { testWidgets('running forward', (WidgetTester tester) async { final List<int> values = <int>[]; Widget buildWidget({required IntTween tween}) { return TweenAnimationBuilder<int>( tween: tween, duration: const Duration(seconds: 1), builder: (BuildContext context, int i, Widget? child) { values.add(i); return const Placeholder(); }, ); } await tester.pumpWidget(buildWidget( tween: IntTween(begin: 0, end: 100), )); expect(values, <int>[0]); await tester.pump(const Duration(milliseconds: 500)); expect(values, <int>[0, 50]); // Change tween await tester.pumpWidget(buildWidget( tween: IntTween(begin: 200, end: 300), )); expect(values, <int>[0, 50, 50]); // gapless: animation continues where it left off. await tester.pump(const Duration(milliseconds: 500)); expect(values, <int>[0, 50, 50, 175]); // 175 = halfway between 50 and new target 300. // Run animation to end await tester.pump(const Duration(seconds: 2)); expect(values, <int>[0, 50, 50, 175, 300]); values.clear(); }); testWidgets('running forward and then reverse with same tween instance', (WidgetTester tester) async { final List<int> values = <int>[]; Widget buildWidget({required IntTween tween}) { return TweenAnimationBuilder<int>( tween: tween, duration: const Duration(seconds: 1), builder: (BuildContext context, int i, Widget? child) { values.add(i); return const Placeholder(); }, ); } final IntTween tween1 = IntTween(begin: 0, end: 100); final IntTween tween2 = IntTween(begin: 200, end: 300); await tester.pumpWidget(buildWidget( tween: tween1, )); await tester.pump(const Duration(milliseconds: 500)); await tester.pumpWidget(buildWidget( tween: tween2, )); await tester.pump(const Duration(milliseconds: 500)); await tester.pump(const Duration(seconds: 2)); expect(values, <int>[0, 50, 50, 175, 300]); values.clear(); }); }); testWidgets('Changing tween while gapless tween change is in progress', (WidgetTester tester) async { final List<int> values = <int>[]; Widget buildWidget({required IntTween tween}) { return TweenAnimationBuilder<int>( tween: tween, duration: const Duration(seconds: 1), builder: (BuildContext context, int i, Widget? child) { values.add(i); return const Placeholder(); }, ); } final IntTween tween1 = IntTween(begin: 0, end: 100); final IntTween tween2 = IntTween(begin: 200, end: 300); final IntTween tween3 = IntTween(begin: 400, end: 501); await tester.pumpWidget(buildWidget( tween: tween1, )); await tester.pump(const Duration(milliseconds: 500)); expect(values, <int>[0, 50]); values.clear(); // Change tween await tester.pumpWidget(buildWidget( tween: tween2, )); await tester.pump(const Duration(milliseconds: 500)); expect(values, <int>[50, 175]); values.clear(); await tester.pumpWidget(buildWidget( tween: tween3, )); await tester.pump(const Duration(milliseconds: 500)); await tester.pump(const Duration(milliseconds: 500)); expect(values, <int>[175, 338, 501]); }); testWidgets('Changing curve while no animation is running does not trigger animation', (WidgetTester tester) async { final List<int> values = <int>[]; Widget buildWidget({required Curve curve}) { return TweenAnimationBuilder<int>( tween: IntTween(begin: 0, end: 100), curve: curve, duration: const Duration(seconds: 1), builder: (BuildContext context, int i, Widget? child) { values.add(i); return const Placeholder(); }, ); } await tester.pumpWidget(buildWidget( curve: Curves.linear, )); await tester.pump(const Duration(seconds: 2)); expect(values, <int>[0, 100]); values.clear(); await tester.pumpWidget(buildWidget( curve: Curves.easeInExpo, )); expect(values, <int>[100]); await tester.pump(const Duration(seconds: 2)); expect(values, <int>[100]); }); testWidgets('Setting same tween and direction does not trigger animation', (WidgetTester tester) async { final List<int> values = <int>[]; Widget buildWidget({required IntTween tween}) { return TweenAnimationBuilder<int>( tween: tween, duration: const Duration(seconds: 1), builder: (BuildContext context, int i, Widget? child) { values.add(i); return const Placeholder(); }, ); } await tester.pumpWidget(buildWidget( tween: IntTween(begin: 0, end: 100), )); await tester.pump(const Duration(milliseconds: 500)); await tester.pump(const Duration(milliseconds: 500)); expect(values, <int>[0, 50, 100]); values.clear(); await tester.pumpWidget(buildWidget( tween: IntTween(begin: 0, end: 100), )); await tester.pump(const Duration(milliseconds: 500)); await tester.pump(const Duration(milliseconds: 500)); expect(values, everyElement(100)); }); testWidgets('Setting same tween and direction while gapless animation is in progress works', (WidgetTester tester) async { final List<int> values = <int>[]; Widget buildWidget({required IntTween tween}) { return TweenAnimationBuilder<int>( tween: tween, duration: const Duration(seconds: 1), builder: (BuildContext context, int i, Widget? child) { values.add(i); return const Placeholder(); }, ); } await tester.pumpWidget(buildWidget( tween: IntTween(begin: 0, end: 100), )); await tester.pump(const Duration(milliseconds: 500)); expect(values, <int>[0, 50]); await tester.pumpWidget(buildWidget( tween: IntTween(begin: 200, end: 300), )); await tester.pump(const Duration(milliseconds: 500)); expect(values, <int>[0, 50, 50, 175]); await tester.pumpWidget(buildWidget( tween: IntTween(begin: 200, end: 300), )); expect(values, <int>[0, 50, 50, 175, 175]); await tester.pump(const Duration(milliseconds: 500)); expect(values, <int>[0, 50, 50, 175, 175, 300]); values.clear(); await tester.pump(const Duration(seconds: 2)); expect(values, everyElement(300)); }); testWidgets('Works with nullable tweens', (WidgetTester tester) async { final List<Size?> values = <Size?>[]; await tester.pumpWidget( TweenAnimationBuilder<Size?>( duration: const Duration(seconds: 1), tween: SizeTween(end: const Size(10,10)), builder: (BuildContext context, Size? s, Widget? child) { values.add(s); return const Placeholder(); }, ), ); expect(values, <Size>[const Size(10,10)]); await tester.pump(const Duration(seconds: 2)); expect(values, <Size>[const Size(10,10)]); }); }
flutter/packages/flutter/test/widgets/tween_animation_builder_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/tween_animation_builder_test.dart", "repo_id": "flutter", "token_count": 5440 }
316
// Copyright 2014 The Flutter 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:flutter/material.dart'; void main() { // Changes made in https://github.com/flutter/flutter/pull/93427 ColorScheme colorScheme = ColorScheme(); colorScheme = ColorScheme(); colorScheme = ColorScheme.light(); colorScheme = ColorScheme.dark(); colorScheme = ColorScheme.highContrastLight(); colorScheme = ColorScheme.highContrastDark(); colorScheme = colorScheme.copyWith(); colorScheme.primaryContainer; // Removing field reference not supported. colorScheme.secondaryContainer; // Changes made in https://github.com/flutter/flutter/pull/138521 ColorScheme colorScheme = ColorScheme(); colorScheme = ColorScheme(surface: Colors.black, onSurface: Colors.white, surfaceContainerHighest: Colors.red); colorScheme = ColorScheme(surface: Colors.orange, onSurface: Colors.yellow, surfaceContainerHighest: Colors.blue); colorScheme = ColorScheme.light(surface: Colors.black, onSurface: Colors.white, surfaceContainerHighest: Colors.red); colorScheme = ColorScheme.light(surface: Colors.orange, onSurface: Colors.yellow, surfaceContainerHighest: Colors.blue); colorScheme = ColorScheme.dark(surface: Colors.black, onSurface: Colors.white, surfaceContainerHighest: Colors.red); colorScheme = ColorScheme.dark(surface: Colors.orange, onSurface: Colors.yellow, surfaceContainerHighest: Colors.blue); colorScheme = ColorScheme.highContrastLight(surface: Colors.black, onSurface: Colors.white, surfaceContainerHighest: Colors.red); colorScheme = ColorScheme.highContrastLight(surface: Colors.orange, onSurface: Colors.yellow, surfaceContainerHighest: Colors.blue); colorScheme = ColorScheme.highContrastDark(surface: Colors.black, onSurface: Colors.white, surfaceContainerHighest: Colors.red); colorScheme = ColorScheme.highContrastDark(surface: Colors.orange, onSurface: Colors.yellow, surfaceContainerHighest: Colors.blue); colorScheme = colorScheme.copyWith(surface: Colors.black, onSurface: Colors.white, surfaceContainerHighest: Colors.red); colorScheme = colorScheme.copyWith(surface: Colors.orange, onSurface: Colors.yellow, surfaceContainerHighest: Colors.blue); colorScheme.surface; colorScheme.onSurface; colorScheme.surfaceContainerHighest; }
flutter/packages/flutter/test_fixes/material/color_scheme.dart.expect/0
{ "file_path": "flutter/packages/flutter/test_fixes/material/color_scheme.dart.expect", "repo_id": "flutter", "token_count": 697 }
317
// Copyright 2014 The Flutter 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:flutter/rendering.dart'; void main() { // Changes made in https://github.com/flutter/flutter/pull/66305 RenderStack renderStack = RenderStack(); renderStack = RenderStack(clipBehavior: Clip.none); renderStack = RenderStack(clipBehavior: Clip.hardEdge); renderStack = RenderStack(error: ''); renderStack.clipBehavior; // Changes made in https://flutter.dev/docs/release/breaking-changes/clip-behavior RenderListWheelViewport renderListWheelViewport = RenderListWheelViewport(); renderListWheelViewport = RenderListWheelViewport(clipBehavior: Clip.hardEdge); renderListWheelViewport = RenderListWheelViewport(clipBehavior: Clip.none); renderListWheelViewport = RenderListWheelViewport(error: ''); renderListWheelViewport.clipBehavior; // Change made in https://github.com/flutter/flutter/pull/128522 RenderParagraph(textScaler: TextScaler.linear(math.min(123, 456))); RenderParagraph(); RenderEditable(textScaler: TextScaler.linear(math.min(123, 456))); RenderEditable(); }
flutter/packages/flutter/test_fixes/rendering/rendering.dart.expect/0
{ "file_path": "flutter/packages/flutter/test_fixes/rendering/rendering.dart.expect", "repo_id": "flutter", "token_count": 355 }
318
// Copyright 2014 The Flutter 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:ui'; import 'package:flutter/foundation.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { final FlutterMemoryAllocations ma = FlutterMemoryAllocations.instance; setUp(() { assert(!ma.hasListeners); _checkSdkHandlersNotSet(); }); test('kFlutterMemoryAllocationsEnabled is false in release mode.', () { expect(kFlutterMemoryAllocationsEnabled, isFalse); }); testWidgets( '$FlutterMemoryAllocations is noop when kFlutterMemoryAllocationsEnabled is false.', (WidgetTester tester) async { ObjectEvent? receivedEvent; ObjectEvent listener(ObjectEvent event) => receivedEvent = event; ma.addListener(listener); _checkSdkHandlersNotSet(); expect(ma.hasListeners, isFalse); await _activateFlutterObjects(tester); _checkSdkHandlersNotSet(); expect(receivedEvent, isNull); expect(ma.hasListeners, isFalse); ma.removeListener(listener); _checkSdkHandlersNotSet(); }, ); } void _checkSdkHandlersNotSet() { expect(Image.onCreate, isNull); expect(Picture.onCreate, isNull); expect(Image.onDispose, isNull); expect(Picture.onDispose, isNull); } /// Create and dispose Flutter objects to fire memory allocation events. Future<void> _activateFlutterObjects(WidgetTester tester) async { final ValueNotifier<bool> valueNotifier = ValueNotifier<bool>(true); final ChangeNotifier changeNotifier = ChangeNotifier()..addListener(() {}); final Picture picture = _createPicture(); valueNotifier.dispose(); changeNotifier.dispose(); picture.dispose(); final Image image = await _createImage(); image.dispose(); } Future<Image> _createImage() async { final Picture picture = _createPicture(); final Image result = await picture.toImage(10, 10); picture.dispose(); return result; } Picture _createPicture() { final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); const Rect rect = Rect.fromLTWH(0.0, 0.0, 100.0, 100.0); canvas.clipRect(rect); return recorder.endRecording(); }
flutter/packages/flutter/test_release/foundation/memory_allocations_test.dart/0
{ "file_path": "flutter/packages/flutter/test_release/foundation/memory_allocations_test.dart", "repo_id": "flutter", "token_count": 738 }
319
// Copyright 2014 The Flutter 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 'message.dart'; /// A Flutter Driver command that enables or disables the FrameSync mechanism. class SetFrameSync extends Command { /// Creates a command to toggle the FrameSync mechanism. const SetFrameSync(this.enabled, { super.timeout }); /// Deserializes this command from the value generated by [serialize]. SetFrameSync.deserialize(super.json) : enabled = json['enabled']!.toLowerCase() == 'true', super.deserialize(); /// Whether frameSync should be enabled or disabled. final bool enabled; @override String get kind => 'set_frame_sync'; @override Map<String, String> serialize() => super.serialize()..addAll(<String, String>{ 'enabled': '$enabled', }); }
flutter/packages/flutter_driver/lib/src/common/frame_sync.dart/0
{ "file_path": "flutter/packages/flutter_driver/lib/src/common/frame_sync.dart", "repo_id": "flutter", "token_count": 253 }
320
// Copyright 2014 The Flutter 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 'percentile_utils.dart'; import 'timeline.dart'; /// Event name for frame request pending timeline events. const String kFrameRequestPendingEvent = 'Frame Request Pending'; /// Summarizes [TimelineEvents]s corresponding to [kFrameRequestPendingEvent] events. /// /// `FrameRequestPendingLatency` is the time between `Animator::RequestFrame` /// and `Animator::BeginFrame` for each frame built by the Flutter engine. class FrameRequestPendingLatencySummarizer { /// Creates a FrameRequestPendingLatencySummarizer given the timeline events. FrameRequestPendingLatencySummarizer(this.frameRequestPendingEvents); /// Timeline events with names in [kFrameRequestPendingTimelineEventNames]. final List<TimelineEvent> frameRequestPendingEvents; /// Computes the average `FrameRequestPendingLatency` over the period of the timeline. double computeAverageFrameRequestPendingLatency() { final List<double> frameRequestPendingLatencies = _computeFrameRequestPendingLatencies(); if (frameRequestPendingLatencies.isEmpty) { return 0; } final double total = frameRequestPendingLatencies.reduce((double a, double b) => a + b); return total / frameRequestPendingLatencies.length; } /// Computes the [percentile]-th percentile `FrameRequestPendingLatency` over the /// period of the timeline. double computePercentileFrameRequestPendingLatency(double percentile) { final List<double> frameRequestPendingLatencies = _computeFrameRequestPendingLatencies(); if (frameRequestPendingLatencies.isEmpty) { return 0; } return findPercentile(frameRequestPendingLatencies, percentile); } List<double> _computeFrameRequestPendingLatencies() { final List<double> result = <double>[]; final Map<String, int> starts = <String, int>{}; for (int i = 0; i < frameRequestPendingEvents.length; i++) { final TimelineEvent event = frameRequestPendingEvents[i]; if (event.phase == 'b') { final String? id = event.json['id'] as String?; if (id != null) { starts[id] = event.timestampMicros!; } } else if (event.phase == 'e') { final int? start = starts[event.json['id']]; if (start != null) { result.add((event.timestampMicros! - start).toDouble()); } } } return result; } }
flutter/packages/flutter_driver/lib/src/driver/frame_request_pending_latency_summarizer.dart/0
{ "file_path": "flutter/packages/flutter_driver/lib/src/driver/frame_request_pending_latency_summarizer.dart", "repo_id": "flutter", "token_count": 820 }
321
// Copyright 2014 The Flutter 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:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart' show RendererBinding; import 'package:flutter/scheduler.dart'; import 'package:flutter/semantics.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import '../common/deserialization_factory.dart'; import '../common/error.dart'; import '../common/find.dart'; import '../common/handler_factory.dart'; import '../common/message.dart'; import '_extension_io.dart' if (dart.library.js_interop) '_extension_web.dart'; const String _extensionMethodName = 'driver'; /// Signature for the handler passed to [enableFlutterDriverExtension]. /// /// Messages are described in string form and should return a [Future] which /// eventually completes to a string response. typedef DataHandler = Future<String> Function(String? message); class _DriverBinding extends BindingBase with SchedulerBinding, ServicesBinding, GestureBinding, PaintingBinding, SemanticsBinding, RendererBinding, WidgetsBinding, TestDefaultBinaryMessengerBinding { _DriverBinding(this._handler, this._silenceErrors, this._enableTextEntryEmulation, this.finders, this.commands); final DataHandler? _handler; final bool _silenceErrors; final bool _enableTextEntryEmulation; final List<FinderExtension>? finders; final List<CommandExtension>? commands; // Because you can't really control which zone a driver test uses, // we override the test for zones here. @override bool debugCheckZone(String entryPoint) { return true; } @override void initServiceExtensions() { super.initServiceExtensions(); final FlutterDriverExtension extension = FlutterDriverExtension(_handler, _silenceErrors, _enableTextEntryEmulation, finders: finders ?? const <FinderExtension>[], commands: commands ?? const <CommandExtension>[]); registerServiceExtension( name: _extensionMethodName, callback: extension.call, ); if (kIsWeb) { registerWebServiceExtension(extension.call); } } } // Examples can assume: // import 'package:flutter_driver/flutter_driver.dart'; // import 'package:flutter/widgets.dart'; // import 'package:flutter_driver/driver_extension.dart'; // import 'package:flutter_test/flutter_test.dart' hide find; // import 'package:flutter_test/flutter_test.dart' as flutter_test; // typedef MyHomeWidget = Placeholder; // abstract class SomeWidget extends StatelessWidget { const SomeWidget({super.key, required this.title}); final String title; } // late FlutterDriver driver; // abstract class StubNestedCommand { int get times; SerializableFinder get finder; } // class StubCommandResult extends Result { const StubCommandResult(this.arg); final String arg; @override Map<String, dynamic> toJson() => <String, dynamic>{}; } // abstract class StubProberCommand { int get times; SerializableFinder get finder; } /// Enables Flutter Driver VM service extension. /// /// This extension is required for tests that use `package:flutter_driver` to /// drive applications from a separate process. In order to allow the driver /// to interact with the application, this method changes the behavior of the /// framework in several ways - including keyboard interaction and text /// editing. Applications intended for release should never include this /// method. /// /// Call this function prior to running your application, e.g. before you call /// `runApp`. /// /// Optionally you can pass a [DataHandler] callback. It will be called if the /// test calls [FlutterDriver.requestData]. /// /// `silenceErrors` will prevent exceptions from being logged. This is useful /// for tests where exceptions are expected. Defaults to false. Any errors /// will still be returned in the `response` field of the result JSON along /// with an `isError` boolean. /// /// The `enableTextEntryEmulation` parameter controls whether the application interacts /// with the system's text entry methods or a mocked out version used by Flutter Driver. /// If it is set to false, [FlutterDriver.enterText] will fail, /// but testing the application with real keyboard input is possible. /// This value may be updated during a test by calling [FlutterDriver.setTextEntryEmulation]. /// /// The `finders` and `commands` parameters are optional and used to add custom /// finders or commands, as in the following example. /// /// ```dart /// void main() { /// enableFlutterDriverExtension( /// finders: <FinderExtension>[ SomeFinderExtension() ], /// commands: <CommandExtension>[ SomeCommandExtension() ], /// ); /// /// runApp(const MyHomeWidget()); /// } /// /// class SomeFinderExtension extends FinderExtension { /// @override /// String get finderType => 'SomeFinder'; /// /// @override /// SerializableFinder deserialize(Map<String, String> params, DeserializeFinderFactory finderFactory) { /// return SomeFinder(params['title']!); /// } /// /// @override /// Finder createFinder(SerializableFinder finder, CreateFinderFactory finderFactory) { /// final SomeFinder someFinder = finder as SomeFinder; /// /// return flutter_test.find.byElementPredicate((Element element) { /// final Widget widget = element.widget; /// if (widget is SomeWidget) { /// return widget.title == someFinder.title; /// } /// return false; /// }); /// } /// } /// /// // Use this class in a test anywhere where a SerializableFinder is expected. /// class SomeFinder extends SerializableFinder { /// const SomeFinder(this.title); /// /// final String title; /// /// @override /// String get finderType => 'SomeFinder'; /// /// @override /// Map<String, String> serialize() => super.serialize()..addAll(<String, String>{ /// 'title': title, /// }); /// } /// /// class SomeCommandExtension extends CommandExtension { /// @override /// String get commandKind => 'SomeCommand'; /// /// @override /// Future<Result> call(Command command, WidgetController prober, CreateFinderFactory finderFactory, CommandHandlerFactory handlerFactory) async { /// final SomeCommand someCommand = command as SomeCommand; /// /// // Deserialize [Finder]: /// final Finder finder = finderFactory.createFinder(someCommand.finder); /// /// // Wait for [Element]: /// handlerFactory.waitForElement(finder); /// /// // Alternatively, wait for [Element] absence: /// handlerFactory.waitForAbsentElement(finder); /// /// // Submit known [Command]s: /// for (int i = 0; i < someCommand.times; i++) { /// await handlerFactory.handleCommand(Tap(someCommand.finder), prober, finderFactory); /// } /// /// // Alternatively, use [WidgetController]: /// for (int i = 0; i < someCommand.times; i++) { /// await prober.tap(finder); /// } /// /// return const SomeCommandResult('foo bar'); /// } /// /// @override /// Command deserialize(Map<String, String> params, DeserializeFinderFactory finderFactory, DeserializeCommandFactory commandFactory) { /// return SomeCommand.deserialize(params, finderFactory); /// } /// } /// /// // Pass an instance of this class to `FlutterDriver.sendCommand` to invoke /// // the custom command during a test. /// class SomeCommand extends CommandWithTarget { /// SomeCommand(super.finder, this.times, {super.timeout}); /// /// SomeCommand.deserialize(super.json, super.finderFactory) /// : times = int.parse(json['times']!), /// super.deserialize(); /// /// @override /// Map<String, String> serialize() { /// return super.serialize()..addAll(<String, String>{'times': '$times'}); /// } /// /// @override /// String get kind => 'SomeCommand'; /// /// final int times; /// } /// /// class SomeCommandResult extends Result { /// const SomeCommandResult(this.resultParam); /// /// final String resultParam; /// /// @override /// Map<String, dynamic> toJson() { /// return <String, dynamic>{ /// 'resultParam': resultParam, /// }; /// } /// } /// ``` void enableFlutterDriverExtension({ DataHandler? handler, bool silenceErrors = false, bool enableTextEntryEmulation = true, List<FinderExtension>? finders, List<CommandExtension>? commands}) { _DriverBinding(handler, silenceErrors, enableTextEntryEmulation, finders ?? <FinderExtension>[], commands ?? <CommandExtension>[]); assert(WidgetsBinding.instance is _DriverBinding); } /// Signature for functions that handle a command and return a result. typedef CommandHandlerCallback = Future<Result?> Function(Command c); /// Signature for functions that deserialize a JSON map to a command object. typedef CommandDeserializerCallback = Command Function(Map<String, String> params); /// Used to expand the new [Finder]. abstract class FinderExtension { /// Identifies the type of finder to be used by the driver extension. String get finderType; /// Deserializes the finder from JSON generated by [SerializableFinder.serialize]. /// /// Use [finderFactory] to deserialize nested [Finder]s. /// /// See also: /// * [Ancestor], a finder that uses other [Finder]s as parameters. SerializableFinder deserialize(Map<String, String> params, DeserializeFinderFactory finderFactory); /// Signature for functions that run the given finder and return the [Element] /// found, if any, or null otherwise. /// /// Call [finderFactory] to create known, nested [Finder]s from [SerializableFinder]s. Finder createFinder(SerializableFinder finder, CreateFinderFactory finderFactory); } /// Used to expand the new [Command]. /// /// See also: /// * [CommandWithTarget], a base class for [Command]s with [Finder]s. abstract class CommandExtension { /// Identifies the type of command to be used by the driver extension. String get commandKind; /// Deserializes the command from JSON generated by [Command.serialize]. /// /// Use [finderFactory] to deserialize nested [Finder]s. /// Usually used for [CommandWithTarget]s. /// /// Call [commandFactory] to deserialize commands specified as parameters. /// /// See also: /// * [CommandWithTarget], a base class for commands with target finders. /// * [Tap], a command that uses [Finder]s as parameter. Command deserialize(Map<String, String> params, DeserializeFinderFactory finderFactory, DeserializeCommandFactory commandFactory); /// Calls action for given [command]. /// Returns action [Result]. /// Invoke [prober] functions to perform widget actions. /// Use [finderFactory] to create [Finder]s from [SerializableFinder]. /// Call [handlerFactory] to invoke other [Command]s or [CommandWithTarget]s. /// /// The following example shows invoking nested command with [handlerFactory]. /// /// ```dart /// @override /// Future<Result> call(Command command, WidgetController prober, CreateFinderFactory finderFactory, CommandHandlerFactory handlerFactory) async { /// final StubNestedCommand stubCommand = command as StubNestedCommand; /// for (int i = 0; i < stubCommand.times; i++) { /// await handlerFactory.handleCommand(Tap(stubCommand.finder), prober, finderFactory); /// } /// return const StubCommandResult('stub response'); /// } /// ``` /// /// Check the example below for direct [WidgetController] usage with [prober]: /// /// ```dart /// @override /// Future<Result> call(Command command, WidgetController prober, CreateFinderFactory finderFactory, CommandHandlerFactory handlerFactory) async { /// final StubProberCommand stubCommand = command as StubProberCommand; /// for (int i = 0; i < stubCommand.times; i++) { /// await prober.tap(finderFactory.createFinder(stubCommand.finder)); /// } /// return const StubCommandResult('stub response'); /// } /// ``` Future<Result> call(Command command, WidgetController prober, CreateFinderFactory finderFactory, CommandHandlerFactory handlerFactory); } /// The class that manages communication between a Flutter Driver test and the /// application being remote-controlled, on the application side. /// /// This is not normally used directly. It is instantiated automatically when /// calling [enableFlutterDriverExtension]. @visibleForTesting class FlutterDriverExtension with DeserializeFinderFactory, CreateFinderFactory, DeserializeCommandFactory, CommandHandlerFactory { /// Creates an object to manage a Flutter Driver connection. FlutterDriverExtension( this._requestDataHandler, this._silenceErrors, this._enableTextEntryEmulation, { List<FinderExtension> finders = const <FinderExtension>[], List<CommandExtension> commands = const <CommandExtension>[], }) { if (_enableTextEntryEmulation) { registerTextInput(); } for (final FinderExtension finder in finders) { _finderExtensions[finder.finderType] = finder; } for (final CommandExtension command in commands) { _commandExtensions[command.commandKind] = command; } } final WidgetController _prober = LiveWidgetController(WidgetsBinding.instance); final DataHandler? _requestDataHandler; final bool _silenceErrors; final bool _enableTextEntryEmulation; void _log(String message) { driverLog('FlutterDriverExtension', message); } final Map<String, FinderExtension> _finderExtensions = <String, FinderExtension>{}; final Map<String, CommandExtension> _commandExtensions = <String, CommandExtension>{}; /// Processes a driver command configured by [params] and returns a result /// as an arbitrary JSON object. /// /// [params] must contain key "command" whose value is a string that /// identifies the kind of the command and its corresponding /// [CommandDeserializerCallback]. Other keys and values are specific to the /// concrete implementation of [Command] and [CommandDeserializerCallback]. /// /// The returned JSON is command specific. Generally the caller deserializes /// the result into a subclass of [Result], but that's not strictly required. @visibleForTesting Future<Map<String, dynamic>> call(Map<String, String> params) async { final String commandKind = params['command']!; try { final Command command = deserializeCommand(params, this); assert(WidgetsBinding.instance.isRootWidgetAttached || !command.requiresRootWidgetAttached, 'No root widget is attached; have you remembered to call runApp()?'); Future<Result> responseFuture = handleCommand(command, _prober, this); if (command.timeout != null) { responseFuture = responseFuture.timeout(command.timeout!); } final Result response = await responseFuture; return _makeResponse(response.toJson()); } on TimeoutException catch (error, stackTrace) { final String message = 'Timeout while executing $commandKind: $error\n$stackTrace'; _log(message); return _makeResponse(message, isError: true); } catch (error, stackTrace) { final String message = 'Uncaught extension error while executing $commandKind: $error\n$stackTrace'; if (!_silenceErrors) { _log(message); } return _makeResponse(message, isError: true); } } Map<String, dynamic> _makeResponse(dynamic response, { bool isError = false }) { return <String, dynamic>{ 'isError': isError, 'response': response, }; } @override SerializableFinder deserializeFinder(Map<String, String> json) { final String? finderType = json['finderType']; if (_finderExtensions.containsKey(finderType)) { return _finderExtensions[finderType]!.deserialize(json, this); } return super.deserializeFinder(json); } @override Finder createFinder(SerializableFinder finder) { final String finderType = finder.finderType; if (_finderExtensions.containsKey(finderType)) { return _finderExtensions[finderType]!.createFinder(finder, this); } return super.createFinder(finder); } @override Command deserializeCommand(Map<String, String> params, DeserializeFinderFactory finderFactory) { final String? kind = params['command']; if (_commandExtensions.containsKey(kind)) { return _commandExtensions[kind]!.deserialize(params, finderFactory, this); } return super.deserializeCommand(params, finderFactory); } @override @protected DataHandler? getDataHandler() { return _requestDataHandler; } @override Future<Result> handleCommand(Command command, WidgetController prober, CreateFinderFactory finderFactory) { final String kind = command.kind; if (_commandExtensions.containsKey(kind)) { return _commandExtensions[kind]!.call(command, prober, finderFactory, this); } return super.handleCommand(command, prober, finderFactory); } }
flutter/packages/flutter_driver/lib/src/extension/extension.dart/0
{ "file_path": "flutter/packages/flutter_driver/lib/src/extension/extension.dart", "repo_id": "flutter", "token_count": 5171 }
322
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert' show json; import 'dart:math'; import 'package:file/file.dart'; import 'package:flutter_driver/flutter_driver.dart'; import 'package:flutter_driver/src/driver/profiling_summarizer.dart'; import 'package:flutter_driver/src/driver/refresh_rate_summarizer.dart'; import 'package:flutter_driver/src/driver/scene_display_lag_summarizer.dart'; import 'package:flutter_driver/src/driver/vsync_frame_lag_summarizer.dart'; import 'package:path/path.dart' as path; import '../../common.dart'; void main() { group('TimelineSummary', () { TimelineSummary summarize(List<Map<String, dynamic>> testEvents) { return TimelineSummary.summarize(Timeline.fromJson(<String, dynamic>{ 'traceEvents': testEvents, })); } Map<String, dynamic> frameBegin(int timeStamp) => <String, dynamic>{ 'name': 'Frame', 'ph': 'B', 'ts': timeStamp, }; Map<String, dynamic> frameEnd(int timeStamp) => <String, dynamic>{ 'name': 'Frame', 'ph': 'E', 'ts': timeStamp, }; Map<String, dynamic> begin(int timeStamp) => <String, dynamic>{ 'name': 'GPURasterizer::Draw', 'ph': 'B', 'ts': timeStamp, }; Map<String, dynamic> end(int timeStamp) => <String, dynamic>{ 'name': 'GPURasterizer::Draw', 'ph': 'E', 'ts': timeStamp, }; Map<String, dynamic> lagBegin(int timeStamp, int vsyncsMissed) => <String, dynamic>{ 'name': 'SceneDisplayLag', 'ph': 'b', 'ts': timeStamp, 'args': <String, String>{ 'vsync_transitions_missed': vsyncsMissed.toString(), }, }; Map<String, dynamic> lagEnd(int timeStamp, int vsyncsMissed) => <String, dynamic>{ 'name': 'SceneDisplayLag', 'ph': 'e', 'ts': timeStamp, 'args': <String, String>{ 'vsync_transitions_missed': vsyncsMissed.toString(), }, }; Map<String, dynamic> cpuUsage(int timeStamp, double cpuUsage) => <String, dynamic>{ 'cat': 'embedder', 'name': 'CpuUsage', 'ts': timeStamp, 'args': <String, String>{ 'total_cpu_usage': cpuUsage.toString(), }, }; Map<String, dynamic> memoryUsage(int timeStamp, double dirty, double shared) => <String, dynamic>{ 'cat': 'embedder', 'name': 'MemoryUsage', 'ts': timeStamp, 'args': <String, String>{ 'owned_shared_memory_usage': shared.toString(), 'dirty_memory_usage': dirty.toString(), }, }; Map<String, dynamic> platformVsync(int timeStamp) => <String, dynamic>{ 'name': 'VSYNC', 'ph': 'B', 'ts': timeStamp, }; Map<String, dynamic> vsyncCallback(int timeStamp, {String phase = 'B', String startTime = '2750850055428', String endTime = '2750866722095'}) => <String, dynamic>{ 'name': 'VsyncProcessCallback', 'ph': phase, 'ts': timeStamp, 'args': <String, dynamic>{ 'StartTime': startTime, 'TargetTime': endTime, }, }; List<Map<String, dynamic>> genGC(String name, int count, int startTime, int timeDiff) { int ts = startTime; bool begin = true; final List<Map<String, dynamic>> ret = <Map<String, dynamic>>[]; for (int i = 0; i < count; i++) { ret.add(<String, dynamic>{ 'name': name, 'cat': 'GC', 'tid': 19695, 'pid': 19650, 'ts': ts, 'tts': ts, 'ph': begin ? 'B' : 'E', 'args': <String, dynamic>{ 'isolateGroupId': 'isolateGroups/10824099774666259225', }, }); ts = ts + timeDiff; begin = !begin; } return ret; } List<Map<String, dynamic>> newGenGC(int count, int startTime, int timeDiff) { return genGC('CollectNewGeneration', count, startTime, timeDiff); } List<Map<String, dynamic>> oldGenGC(int count, int startTime, int timeDiff) { return genGC('CollectOldGeneration', count, startTime, timeDiff); } List<Map<String, dynamic>> rasterizeTimeSequenceInMillis(List<int> sequence) { final List<Map<String, dynamic>> result = <Map<String, dynamic>>[]; int t = 0; for (final int duration in sequence) { result.add(begin(t)); t += duration * 1000; result.add(end(t)); } return result; } Map<String, dynamic> frameRequestPendingStart(String id, int timeStamp) => <String, dynamic>{ 'name': 'Frame Request Pending', 'ph': 'b', 'id': id, 'ts': timeStamp, }; Map<String, dynamic> frameRequestPendingEnd(String id, int timeStamp) => <String, dynamic>{ 'name': 'Frame Request Pending', 'ph': 'e', 'id': id, 'ts': timeStamp, }; group('frame_count', () { test('counts frames', () { expect( summarize(<Map<String, dynamic>>[ frameBegin(1000), frameEnd(2000), frameBegin(3000), frameEnd(5000), ]).countFrames(), 2, ); }); }); group('average_frame_build_time_millis', () { test('throws when there is no data', () { expect( () => summarize(<Map<String, dynamic>>[]).computeAverageFrameBuildTimeMillis(), throwsA( isA<StateError>() .having((StateError e) => e.message, 'message', contains('The TimelineSummary had no events to summarize.'), )), ); }); test('computes average frame build time in milliseconds', () { expect( summarize(<Map<String, dynamic>>[ frameBegin(1000), frameEnd(2000), frameBegin(3000), frameEnd(5000), ]).computeAverageFrameBuildTimeMillis(), 1.5, ); }); test('skips leading "end" events', () { expect( summarize(<Map<String, dynamic>>[ frameEnd(1000), frameBegin(2000), frameEnd(4000), ]).computeAverageFrameBuildTimeMillis(), 2.0, ); }); test('skips trailing "begin" events', () { expect( summarize(<Map<String, dynamic>>[ frameBegin(2000), frameEnd(4000), frameBegin(5000), ]).computeAverageFrameBuildTimeMillis(), 2.0, ); }); // see https://github.com/flutter/flutter/issues/54095. test('ignore multiple "end" events', () { expect( summarize(<Map<String, dynamic>>[ frameBegin(2000), frameEnd(4000), frameEnd(4300), // rogue frame end. frameBegin(5000), frameEnd(6000), ]).computeAverageFrameBuildTimeMillis(), 1.5, ); }); test('pick latest when there are multiple "begin" events', () { expect( summarize(<Map<String, dynamic>>[ frameBegin(1000), // rogue frame begin. frameBegin(2000), frameEnd(4000), frameEnd(4300), // rogue frame end. frameBegin(4400), // rogue frame begin. frameBegin(5000), frameEnd(6000), ]).computeAverageFrameBuildTimeMillis(), 1.5, ); }); }); group('worst_frame_build_time_millis', () { test('throws when there is no data', () { expect( () => summarize(<Map<String, dynamic>>[]).computeWorstFrameBuildTimeMillis(), throwsA( isA<StateError>() .having((StateError e) => e.message, 'message', contains('The TimelineSummary had no events to summarize.'), )), ); }); test('computes worst frame build time in milliseconds', () { expect( summarize(<Map<String, dynamic>>[ frameBegin(1000), frameEnd(2000), frameBegin(3000), frameEnd(5000), ]).computeWorstFrameBuildTimeMillis(), 2.0, ); expect( summarize(<Map<String, dynamic>>[ frameBegin(3000), frameEnd(5000), frameBegin(1000), frameEnd(2000), ]).computeWorstFrameBuildTimeMillis(), 2.0, ); }); test('skips leading "end" events', () { expect( summarize(<Map<String, dynamic>>[ frameEnd(1000), frameBegin(2000), frameEnd(4000), ]).computeWorstFrameBuildTimeMillis(), 2.0, ); }); test('skips trailing "begin" events', () { expect( summarize(<Map<String, dynamic>>[ frameBegin(2000), frameEnd(4000), frameBegin(5000), ]).computeWorstFrameBuildTimeMillis(), 2.0, ); }); }); group('computeMissedFrameBuildBudgetCount', () { test('computes the number of missed build budgets', () { final TimelineSummary summary = summarize(<Map<String, dynamic>>[ frameBegin(1000), frameEnd(18000), frameBegin(19000), frameEnd(28000), frameBegin(29000), frameEnd(47000), ]); expect(summary.countFrames(), 3); expect(summary.computeMissedFrameBuildBudgetCount(), 2); }); }); group('average_frame_rasterizer_time_millis', () { test('throws when there is no data', () { expect( () => summarize(<Map<String, dynamic>>[]).computeAverageFrameRasterizerTimeMillis(), throwsA( isA<StateError>() .having((StateError e) => e.message, 'message', contains('The TimelineSummary had no events to summarize.'), )), ); }); test('computes average frame rasterizer time in milliseconds', () { expect( summarize(<Map<String, dynamic>>[ begin(1000), end(2000), begin(3000), end(5000), ]).computeAverageFrameRasterizerTimeMillis(), 1.5, ); }); test('skips leading "end" events', () { expect( summarize(<Map<String, dynamic>>[ end(1000), begin(2000), end(4000), ]).computeAverageFrameRasterizerTimeMillis(), 2.0, ); }); test('skips trailing "begin" events', () { expect( summarize(<Map<String, dynamic>>[ begin(2000), end(4000), begin(5000), ]).computeAverageFrameRasterizerTimeMillis(), 2.0, ); }); }); group('worst_frame_rasterizer_time_millis', () { test('throws when there is no data', () { expect( () => summarize(<Map<String, dynamic>>[]).computeWorstFrameRasterizerTimeMillis(), throwsA( isA<StateError>() .having((StateError e) => e.message, 'message', contains('The TimelineSummary had no events to summarize.'), )), ); }); test('computes worst frame rasterizer time in milliseconds', () { expect( summarize(<Map<String, dynamic>>[ begin(1000), end(2000), begin(3000), end(5000), ]).computeWorstFrameRasterizerTimeMillis(), 2.0, ); expect( summarize(<Map<String, dynamic>>[ begin(3000), end(5000), begin(1000), end(2000), ]).computeWorstFrameRasterizerTimeMillis(), 2.0, ); }); test('skips leading "end" events', () { expect( summarize(<Map<String, dynamic>>[ end(1000), begin(2000), end(4000), ]).computeWorstFrameRasterizerTimeMillis(), 2.0, ); }); test('skips trailing "begin" events', () { expect( summarize(<Map<String, dynamic>>[ begin(2000), end(4000), begin(5000), ]).computeWorstFrameRasterizerTimeMillis(), 2.0, ); }); }); group('percentile_frame_rasterizer_time_millis', () { test('throws when there is no data', () { expect( () => summarize(<Map<String, dynamic>>[]).computePercentileFrameRasterizerTimeMillis(90.0), throwsA( isA<StateError>() .having((StateError e) => e.message, 'message', contains('The TimelineSummary had no events to summarize.'), )), ); }); const List<List<int>> sequences = <List<int>>[ <int>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], <int>[1, 2, 3, 4, 5], <int>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], ]; const List<int> p90s = <int>[ 9, 5, 18, ]; test('computes 90th frame rasterizer time in milliseconds', () { for (int i = 0; i < sequences.length; ++i) { expect( summarize(rasterizeTimeSequenceInMillis(sequences[i])).computePercentileFrameRasterizerTimeMillis(90.0), p90s[i], ); } }); test('compute 99th frame rasterizer time in milliseconds', () { final List<int> sequence = <int>[]; for (int i = 1; i <= 100; ++i) { sequence.add(i); } expect( summarize(rasterizeTimeSequenceInMillis(sequence)).computePercentileFrameRasterizerTimeMillis(99.0), 99, ); }); }); group('computeMissedFrameRasterizerBudgetCount', () { test('computes the number of missed rasterizer budgets', () { final TimelineSummary summary = summarize(<Map<String, dynamic>>[ begin(1000), end(18000), begin(19000), end(28000), begin(29000), end(47000), ]); expect(summary.computeMissedFrameRasterizerBudgetCount(), 2); }); }); group('summaryJson', () { test('computes and returns summary as JSON', () { expect( summarize(<Map<String, dynamic>>[ begin(1000), end(19000), begin(19001), end(29001), begin(29002), end(49002), ...newGenGC(4, 10, 100), ...oldGenGC(5, 10000, 100), frameBegin(1000), frameEnd(18000), frameBegin(19000), frameEnd(28000), frameBegin(29000), frameEnd(48000), frameRequestPendingStart('1', 1000), frameRequestPendingEnd('1', 2000), frameRequestPendingStart('2', 3000), frameRequestPendingEnd('2', 5000), frameRequestPendingStart('3', 6000), frameRequestPendingEnd('3', 9000), ]).summaryJson, <String, dynamic>{ 'average_frame_build_time_millis': 15.0, '90th_percentile_frame_build_time_millis': 19.0, '99th_percentile_frame_build_time_millis': 19.0, 'worst_frame_build_time_millis': 19.0, 'missed_frame_build_budget_count': 2, 'average_frame_rasterizer_time_millis': 16.0, 'stddev_frame_rasterizer_time_millis': 4.0, '90th_percentile_frame_rasterizer_time_millis': 20.0, '99th_percentile_frame_rasterizer_time_millis': 20.0, 'worst_frame_rasterizer_time_millis': 20.0, 'missed_frame_rasterizer_budget_count': 2, 'frame_count': 3, 'frame_rasterizer_count': 3, 'new_gen_gc_count': 4, 'old_gen_gc_count': 5, 'frame_build_times': <int>[17000, 9000, 19000], 'frame_rasterizer_times': <int>[18000, 10000, 20000], 'frame_begin_times': <int>[0, 18000, 28000], 'frame_rasterizer_begin_times': <int>[0, 18001, 28002], 'average_vsync_transitions_missed': 0.0, '90th_percentile_vsync_transitions_missed': 0.0, '99th_percentile_vsync_transitions_missed': 0.0, 'average_vsync_frame_lag': 0.0, '90th_percentile_vsync_frame_lag': 0.0, '99th_percentile_vsync_frame_lag': 0.0, 'average_layer_cache_count': 0.0, '90th_percentile_layer_cache_count': 0.0, '99th_percentile_layer_cache_count': 0.0, 'worst_layer_cache_count': 0.0, 'average_layer_cache_memory': 0.0, '90th_percentile_layer_cache_memory': 0.0, '99th_percentile_layer_cache_memory': 0.0, 'worst_layer_cache_memory': 0.0, 'average_picture_cache_count': 0.0, '90th_percentile_picture_cache_count': 0.0, '99th_percentile_picture_cache_count': 0.0, 'worst_picture_cache_count': 0.0, 'average_picture_cache_memory': 0.0, '90th_percentile_picture_cache_memory': 0.0, '99th_percentile_picture_cache_memory': 0.0, 'worst_picture_cache_memory': 0.0, 'total_ui_gc_time': 0.4, '30hz_frame_percentage': 0, '60hz_frame_percentage': 0, '80hz_frame_percentage': 0, '90hz_frame_percentage': 0, '120hz_frame_percentage': 0, 'illegal_refresh_rate_frame_count': 0, 'average_frame_request_pending_latency': 2000.0, '90th_percentile_frame_request_pending_latency': 3000.0, '99th_percentile_frame_request_pending_latency': 3000.0, 'average_gpu_frame_time': 0, '90th_percentile_gpu_frame_time': 0, '99th_percentile_gpu_frame_time': 0, 'worst_gpu_frame_time': 0, 'average_gpu_memory_mb': 0, '90th_percentile_gpu_memory_mb': 0, '99th_percentile_gpu_memory_mb': 0, 'worst_gpu_memory_mb': 0, }, ); }); }); group('writeTimelineToFile', () { late Directory tempDir; setUp(() { useMemoryFileSystemForTesting(); tempDir = fs.systemTempDirectory.createTempSync('flutter_driver_test.'); }); tearDown(() { tryToDelete(tempDir); restoreFileSystem(); }); test('writes timeline to JSON file without summary', () async { await summarize(<Map<String, String>>[<String, String>{'foo': 'bar'}]) .writeTimelineToFile('test', destinationDirectory: tempDir.path, includeSummary: false); final String written = await fs.file(path.join(tempDir.path, 'test.timeline.json')).readAsString(); expect(written, '{"traceEvents":[{"foo":"bar"}]}'); }); test('writes timeline to JSON file with summary', () async { await summarize(<Map<String, dynamic>>[ <String, String>{'foo': 'bar'}, begin(1000), end(19000), frameBegin(1000), frameEnd(18000), ]).writeTimelineToFile( 'test', destinationDirectory: tempDir.path, ); final String written = await fs.file(path.join(tempDir.path, 'test.timeline.json')).readAsString(); expect( written, '{"traceEvents":[{"foo":"bar"},' '{"name":"GPURasterizer::Draw","ph":"B","ts":1000},' '{"name":"GPURasterizer::Draw","ph":"E","ts":19000},' '{"name":"Frame","ph":"B","ts":1000},' '{"name":"Frame","ph":"E","ts":18000}]}', ); }); test('writes summary to JSON file', () async { await summarize(<Map<String, dynamic>>[ begin(1000), end(19000), begin(19001), end(29001), begin(29002), end(49002), frameBegin(1000), frameEnd(18000), frameBegin(19000), frameEnd(28000), frameBegin(29000), frameEnd(48000), lagBegin(1000, 4), lagEnd(2000, 4), lagBegin(1200, 12), lagEnd(2400, 12), lagBegin(4200, 8), lagEnd(9400, 8), ...newGenGC(4, 10, 100), ...oldGenGC(5, 10000, 100), cpuUsage(5000, 20), cpuUsage(5010, 60), memoryUsage(6000, 20, 40), memoryUsage(6100, 30, 45), platformVsync(7000), vsyncCallback(7500), frameRequestPendingStart('1', 1000), frameRequestPendingEnd('1', 2000), frameRequestPendingStart('2', 3000), frameRequestPendingEnd('2', 5000), frameRequestPendingStart('3', 6000), frameRequestPendingEnd('3', 9000), ]).writeTimelineToFile('test', destinationDirectory: tempDir.path); final String written = await fs.file(path.join(tempDir.path, 'test.timeline_summary.json')).readAsString(); expect(json.decode(written), <String, dynamic>{ 'average_frame_build_time_millis': 15.0, 'worst_frame_build_time_millis': 19.0, '90th_percentile_frame_build_time_millis': 19.0, '99th_percentile_frame_build_time_millis': 19.0, 'missed_frame_build_budget_count': 2, 'average_frame_rasterizer_time_millis': 16.0, 'stddev_frame_rasterizer_time_millis': 4.0, '90th_percentile_frame_rasterizer_time_millis': 20.0, '99th_percentile_frame_rasterizer_time_millis': 20.0, 'worst_frame_rasterizer_time_millis': 20.0, 'missed_frame_rasterizer_budget_count': 2, 'frame_count': 3, 'frame_rasterizer_count': 3, 'new_gen_gc_count': 4, 'old_gen_gc_count': 5, 'frame_build_times': <int>[17000, 9000, 19000], 'frame_rasterizer_times': <int>[18000, 10000, 20000], 'frame_begin_times': <int>[0, 18000, 28000], 'frame_rasterizer_begin_times': <int>[0, 18001, 28002], 'average_vsync_transitions_missed': 8.0, '90th_percentile_vsync_transitions_missed': 12.0, '99th_percentile_vsync_transitions_missed': 12.0, 'average_vsync_frame_lag': 500.0, '90th_percentile_vsync_frame_lag': 500.0, '99th_percentile_vsync_frame_lag': 500.0, 'average_cpu_usage': 40.0, '90th_percentile_cpu_usage': 60.0, '99th_percentile_cpu_usage': 60.0, 'average_memory_usage': 67.5, '90th_percentile_memory_usage': 75.0, '99th_percentile_memory_usage': 75.0, 'average_layer_cache_count': 0.0, '90th_percentile_layer_cache_count': 0.0, '99th_percentile_layer_cache_count': 0.0, 'worst_layer_cache_count': 0.0, 'average_layer_cache_memory': 0.0, '90th_percentile_layer_cache_memory': 0.0, '99th_percentile_layer_cache_memory': 0.0, 'worst_layer_cache_memory': 0.0, 'average_picture_cache_count': 0.0, '90th_percentile_picture_cache_count': 0.0, '99th_percentile_picture_cache_count': 0.0, 'worst_picture_cache_count': 0.0, 'average_picture_cache_memory': 0.0, '90th_percentile_picture_cache_memory': 0.0, '99th_percentile_picture_cache_memory': 0.0, 'worst_picture_cache_memory': 0.0, 'total_ui_gc_time': 0.4, '30hz_frame_percentage': 0, '60hz_frame_percentage': 100, '80hz_frame_percentage': 0, '90hz_frame_percentage': 0, '120hz_frame_percentage': 0, 'illegal_refresh_rate_frame_count': 0, 'average_frame_request_pending_latency': 2000.0, '90th_percentile_frame_request_pending_latency': 3000.0, '99th_percentile_frame_request_pending_latency': 3000.0, 'average_gpu_frame_time': 0, '90th_percentile_gpu_frame_time': 0, '99th_percentile_gpu_frame_time': 0, 'worst_gpu_frame_time': 0, 'average_gpu_memory_mb': 0, '90th_percentile_gpu_memory_mb': 0, '99th_percentile_gpu_memory_mb': 0, 'worst_gpu_memory_mb': 0, }); }); }); group('SceneDisplayLagSummarizer tests', () { SceneDisplayLagSummarizer summarize(List<Map<String, dynamic>> traceEvents) { final Timeline timeline = Timeline.fromJson(<String, dynamic>{ 'traceEvents': traceEvents, }); return SceneDisplayLagSummarizer(timeline.events!); } test('average_vsyncs_missed', () async { final SceneDisplayLagSummarizer summarizer = summarize(<Map<String, dynamic>>[ lagBegin(1000, 4), lagEnd(2000, 4), lagBegin(1200, 12), lagEnd(2400, 12), lagBegin(4200, 8), lagEnd(9400, 8), ]); expect(summarizer.computeAverageVsyncTransitionsMissed(), 8.0); }); test('all stats are 0 for 0 missed transitions', () async { final SceneDisplayLagSummarizer summarizer = summarize(<Map<String, dynamic>>[]); expect(summarizer.computeAverageVsyncTransitionsMissed(), 0.0); expect(summarizer.computePercentileVsyncTransitionsMissed(90.0), 0.0); expect(summarizer.computePercentileVsyncTransitionsMissed(99.0), 0.0); }); test('90th_percentile_vsyncs_missed', () async { final SceneDisplayLagSummarizer summarizer = summarize(<Map<String, dynamic>>[ lagBegin(1000, 4), lagEnd(2000, 4), lagBegin(1200, 12), lagEnd(2400, 12), lagBegin(4200, 8), lagEnd(9400, 8), lagBegin(6100, 14), lagEnd(11000, 14), lagBegin(7100, 16), lagEnd(11500, 16), lagBegin(7400, 11), lagEnd(13000, 11), lagBegin(8200, 27), lagEnd(14100, 27), lagBegin(8700, 7), lagEnd(14300, 7), lagBegin(24200, 4187), lagEnd(39400, 4187), ]); expect(summarizer.computePercentileVsyncTransitionsMissed(90), 27.0); }); test('99th_percentile_vsyncs_missed', () async { final SceneDisplayLagSummarizer summarizer = summarize(<Map<String, dynamic>>[ lagBegin(1000, 4), lagEnd(2000, 4), lagBegin(1200, 12), lagEnd(2400, 12), lagBegin(4200, 8), lagEnd(9400, 8), lagBegin(6100, 14), lagEnd(11000, 14), lagBegin(24200, 4187), lagEnd(39400, 4187), ]); expect(summarizer.computePercentileVsyncTransitionsMissed(99), 4187.0); }); }); group('ProfilingSummarizer tests', () { ProfilingSummarizer summarize(List<Map<String, dynamic>> traceEvents) { final Timeline timeline = Timeline.fromJson(<String, dynamic>{ 'traceEvents': traceEvents, }); return ProfilingSummarizer.fromEvents(timeline.events!); } test('has_both_cpu_and_memory_usage', () async { final ProfilingSummarizer summarizer = summarize(<Map<String, dynamic>>[ cpuUsage(0, 10), memoryUsage(0, 6, 10), cpuUsage(0, 12), memoryUsage(0, 8, 40), ]); expect(summarizer.computeAverage(ProfileType.CPU), 11.0); expect(summarizer.computeAverage(ProfileType.Memory), 32.0); }); test('has_only_memory_usage', () async { final ProfilingSummarizer summarizer = summarize(<Map<String, dynamic>>[ memoryUsage(0, 6, 10), memoryUsage(0, 8, 40), ]); expect(summarizer.computeAverage(ProfileType.Memory), 32.0); expect(summarizer.summarize().containsKey('average_cpu_usage'), false); }); test('90th_percentile_cpu_usage', () async { final ProfilingSummarizer summarizer = summarize(<Map<String, dynamic>>[ cpuUsage(0, 10), cpuUsage(1, 20), cpuUsage(2, 20), cpuUsage(3, 80), cpuUsage(4, 70), cpuUsage(4, 72), cpuUsage(4, 85), cpuUsage(4, 100), ]); expect(summarizer.computePercentile(ProfileType.CPU, 90), 85.0); }); }); group('VsyncFrameLagSummarizer tests', () { VsyncFrameLagSummarizer summarize(List<Map<String, dynamic>> traceEvents) { final Timeline timeline = Timeline.fromJson(<String, dynamic>{ 'traceEvents': traceEvents, }); return VsyncFrameLagSummarizer(timeline.events!); } test('average_vsync_frame_lag', () async { final VsyncFrameLagSummarizer summarizer = summarize(<Map<String, dynamic>>[ platformVsync(10), vsyncCallback(12), platformVsync(16), vsyncCallback(29), ]); expect(summarizer.computeAverageVsyncFrameLag(), 7.5); }); test('malformed_event_ordering', () async { final VsyncFrameLagSummarizer summarizer = summarize(<Map<String, dynamic>>[ vsyncCallback(10), platformVsync(10), ]); expect(summarizer.computeAverageVsyncFrameLag(), 0); expect(summarizer.computePercentileVsyncFrameLag(80), 0); }); test('penalize_consecutive_vsyncs', () async { final VsyncFrameLagSummarizer summarizer = summarize(<Map<String, dynamic>>[ platformVsync(10), platformVsync(12), ]); expect(summarizer.computeAverageVsyncFrameLag(), 2); }); test('pick_nearest_platform_vsync', () async { final VsyncFrameLagSummarizer summarizer = summarize(<Map<String, dynamic>>[ platformVsync(10), platformVsync(12), vsyncCallback(18), ]); expect(summarizer.computeAverageVsyncFrameLag(), 4); }); test('percentile_vsync_frame_lag', () async { final List<Map<String, dynamic>> events = <Map<String, dynamic>>[]; int ts = 100; for (int i = 0; i < 100; i++) { events.add(platformVsync(ts)); ts = ts + 10 * (i + 1); events.add(vsyncCallback(ts)); } final VsyncFrameLagSummarizer summarizer = summarize(events); expect(summarizer.computePercentileVsyncFrameLag(90), 890); expect(summarizer.computePercentileVsyncFrameLag(99), 990); }); }); group('RefreshRateSummarizer tests', () { const double kCompareDelta = 0.01; RefreshRateSummary summarizeRefresh(List<Map<String, dynamic>> traceEvents) { final Timeline timeline = Timeline.fromJson(<String, dynamic>{ 'traceEvents': traceEvents, }); return RefreshRateSummary(vsyncEvents: timeline.events!); } List<Map<String, dynamic>> populateEvents({required int numberOfEvents, required int startTime, required int interval, required int margin}) { final List<Map<String, dynamic>> events = <Map<String, dynamic>>[]; int startTimeInNanoseconds = startTime; for (int i = 0; i < numberOfEvents; i ++) { final int randomMargin = margin >= 1 ? (-margin + Random().nextInt(margin*2)) : 0; final int endTime = startTimeInNanoseconds + interval + randomMargin; events.add(vsyncCallback(0, startTime: startTimeInNanoseconds.toString(), endTime: endTime.toString())); startTimeInNanoseconds = endTime; } return events; } test('Recognize 30 hz frames.', () async { const int startTimeInNanoseconds = 2750850055430; const int intervalInNanoseconds = 33333333; // allow some margins const int margin = 3000000; final List<Map<String, dynamic>> events = populateEvents(numberOfEvents: 100, startTime: startTimeInNanoseconds, interval: intervalInNanoseconds, margin: margin, ); final RefreshRateSummary summary = summarizeRefresh(events); expect(summary.percentageOf30HzFrames, closeTo(100, kCompareDelta)); expect(summary.percentageOf60HzFrames, 0); expect(summary.percentageOf90HzFrames, 0); expect(summary.percentageOf120HzFrames, 0); expect(summary.framesWithIllegalRefreshRate, isEmpty); }); test('Recognize 60 hz frames.', () async { const int startTimeInNanoseconds = 2750850055430; const int intervalInNanoseconds = 16666666; // allow some margins const int margin = 1200000; final List<Map<String, dynamic>> events = populateEvents(numberOfEvents: 100, startTime: startTimeInNanoseconds, interval: intervalInNanoseconds, margin: margin, ); final RefreshRateSummary summary = summarizeRefresh(events); expect(summary.percentageOf30HzFrames, 0); expect(summary.percentageOf60HzFrames, closeTo(100, kCompareDelta)); expect(summary.percentageOf90HzFrames, 0); expect(summary.percentageOf120HzFrames, 0); expect(summary.framesWithIllegalRefreshRate, isEmpty); }); test('Recognize 90 hz frames.', () async { const int startTimeInNanoseconds = 2750850055430; const int intervalInNanoseconds = 11111111; // allow some margins const int margin = 500000; final List<Map<String, dynamic>> events = populateEvents(numberOfEvents: 100, startTime: startTimeInNanoseconds, interval: intervalInNanoseconds, margin: margin, ); final RefreshRateSummary summary = summarizeRefresh(events); expect(summary.percentageOf30HzFrames, 0); expect(summary.percentageOf60HzFrames, 0); expect(summary.percentageOf90HzFrames, closeTo(100, kCompareDelta)); expect(summary.percentageOf120HzFrames, 0); expect(summary.framesWithIllegalRefreshRate, isEmpty); }); test('Recognize 120 hz frames.', () async { const int startTimeInNanoseconds = 2750850055430; const int intervalInNanoseconds = 8333333; // allow some margins const int margin = 300000; final List<Map<String, dynamic>> events = populateEvents(numberOfEvents: 100, startTime: startTimeInNanoseconds, interval: intervalInNanoseconds, margin: margin, ); final RefreshRateSummary summary = summarizeRefresh(events); expect(summary.percentageOf30HzFrames, 0); expect(summary.percentageOf60HzFrames, 0); expect(summary.percentageOf90HzFrames, 0); expect(summary.percentageOf120HzFrames, closeTo(100, kCompareDelta)); expect(summary.framesWithIllegalRefreshRate, isEmpty); }); test('Identify illegal refresh rates.', () async { const int startTimeInNanoseconds = 2750850055430; const int intervalInNanoseconds = 10000000; final List<Map<String, dynamic>> events = populateEvents(numberOfEvents: 1, startTime: startTimeInNanoseconds, interval: intervalInNanoseconds, margin: 0, ); final RefreshRateSummary summary = summarizeRefresh(events); expect(summary.percentageOf30HzFrames, 0); expect(summary.percentageOf60HzFrames, 0); expect(summary.percentageOf90HzFrames, 0); expect(summary.percentageOf120HzFrames, 0); expect(summary.framesWithIllegalRefreshRate, isNotEmpty); expect(summary.framesWithIllegalRefreshRate.first, closeTo(100, kCompareDelta)); }); test('Mixed refresh rates.', () async { final List<Map<String, dynamic>> events = <Map<String, dynamic>>[]; const int num30Hz = 10; const int num60Hz = 20; const int num80Hz = 20; const int num90Hz = 20; const int num120Hz = 40; const int numIllegal = 10; const int totalFrames = num30Hz + num60Hz + num80Hz + num90Hz + num120Hz + numIllegal; // Add 30hz frames events.addAll(populateEvents(numberOfEvents: num30Hz, startTime: 0, interval: 32000000, margin: 0, )); // Add 60hz frames events.addAll(populateEvents(numberOfEvents: num60Hz, startTime: 0, interval: 16000000, margin: 0, )); // Add 80hz frames events.addAll(populateEvents(numberOfEvents: num80Hz, startTime: 0, interval: 12000000, margin: 0, )); // Add 90hz frames events.addAll(populateEvents(numberOfEvents: num90Hz, startTime: 0, interval: 11000000, margin: 0, )); // Add 120hz frames events.addAll(populateEvents(numberOfEvents: num120Hz, startTime: 0, interval: 8000000, margin: 0, )); // Add illegal refresh rate frames events.addAll(populateEvents(numberOfEvents: numIllegal, startTime: 0, interval: 60000, margin: 0, )); final RefreshRateSummary summary = summarizeRefresh(events); expect(summary.percentageOf30HzFrames, closeTo(num30Hz/totalFrames*100, kCompareDelta)); expect(summary.percentageOf60HzFrames, closeTo(num60Hz/totalFrames*100, kCompareDelta)); expect(summary.percentageOf80HzFrames, closeTo(num80Hz/totalFrames*100, kCompareDelta)); expect(summary.percentageOf90HzFrames, closeTo(num90Hz/totalFrames*100, kCompareDelta)); expect(summary.percentageOf120HzFrames, closeTo(num120Hz/totalFrames*100, kCompareDelta)); expect(summary.framesWithIllegalRefreshRate, isNotEmpty); expect(summary.framesWithIllegalRefreshRate.length, 10); }); }); }); }
flutter/packages/flutter_driver/test/src/real_tests/timeline_summary_test.dart/0
{ "file_path": "flutter/packages/flutter_driver/test/src/real_tests/timeline_summary_test.dart", "repo_id": "flutter", "token_count": 19072 }
323
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'dart:io' as io; import 'package:crypto/crypto.dart'; import 'package:file/file.dart'; import 'package:path/path.dart' as path; import 'package:platform/platform.dart'; import 'package:process/process.dart'; // If you are here trying to figure out how to use golden files in the Flutter // repo itself, consider reading this wiki page: // https://github.com/flutter/flutter/wiki/Writing-a-golden-file-test-for-package%3Aflutter const String _kFlutterRootKey = 'FLUTTER_ROOT'; const String _kGoldctlKey = 'GOLDCTL'; const String _kTestBrowserKey = 'FLUTTER_TEST_BROWSER'; const String _kWebRendererKey = 'FLUTTER_WEB_RENDERER'; const String _kImpellerKey = 'FLUTTER_TEST_IMPELLER'; /// Signature of callbacks used to inject [print] replacements. typedef LogCallback = void Function(String); /// Exception thrown when an error is returned from the [SkiaClient]. class SkiaException implements Exception { /// Creates a new `SkiaException` with a required error [message]. const SkiaException(this.message); /// A message describing the error. final String message; /// Returns a description of the Skia exception. /// /// The description always contains the [message]. @override String toString() => 'SkiaException: $message'; } /// A client for uploading image tests and making baseline requests to the /// Flutter Gold Dashboard. class SkiaGoldClient { /// Creates a [SkiaGoldClient] with the given [workDirectory] and [Platform]. /// /// All other parameters are optional. They may be provided in tests to /// override the defaults for [fs], [process], and [httpClient]. SkiaGoldClient( this.workDirectory, { required this.fs, required this.process, required this.platform, required this.httpClient, required this.log, }); /// The file system to use for storing the local clone of the repository. /// /// This is useful in tests, where a local file system (the default) can be /// replaced by a memory file system. final FileSystem fs; /// The environment (current working directory, identity of the OS, /// environment variables, etc). final Platform platform; /// A controller for launching sub-processes. /// /// This is useful in tests, where the real process manager (the default) can /// be replaced by a mock process manager that doesn't really create /// sub-processes. final ProcessManager process; /// A client for making Http requests to the Flutter Gold dashboard. final io.HttpClient httpClient; /// The local [Directory] within the [comparisonRoot] for the current test /// context. In this directory, the client will create image and JSON files /// for the goldctl tool to use. /// /// This is informed by the [FlutterGoldenFileComparator] [basedir]. It cannot /// be null. final Directory workDirectory; /// The logging function to use when reporting messages to the console. final LogCallback log; /// The local [Directory] where the Flutter repository is hosted. /// /// Uses the [fs] file system. Directory get _flutterRoot => fs.directory(platform.environment[_kFlutterRootKey]); /// The path to the local [Directory] where the goldctl tool is hosted. /// /// Uses the [platform] environment in this implementation. String get _goldctl => platform.environment[_kGoldctlKey]!; /// Prepares the local work space for golden file testing and calls the /// goldctl `auth` command. /// /// This ensures that the goldctl tool is authorized and ready for testing. /// Used by the [FlutterPostSubmitFileComparator] and the /// [FlutterPreSubmitFileComparator]. Future<void> auth() async { if (await clientIsAuthorized()) { return; } final List<String> authCommand = <String>[ _goldctl, 'auth', '--work-dir', workDirectory .childDirectory('temp') .path, '--luci', ]; final io.ProcessResult result = await process.run(authCommand); if (result.exitCode != 0) { final StringBuffer buf = StringBuffer() ..writeln('Skia Gold authorization failed.') ..writeln('Luci environments authenticate using the file provided ' 'by LUCI_CONTEXT. There may be an error with this file or Gold ' 'authentication.') ..writeln('Debug information for Gold --------------------------------') ..writeln('stdout: ${result.stdout}') ..writeln('stderr: ${result.stderr}'); throw SkiaException(buf.toString()); } } /// Signals if this client is initialized for uploading images to the Gold /// service. /// /// Since Flutter framework tests are executed in parallel, and in random /// order, this will signal is this instance of the Gold client has been /// initialized. bool _initialized = false; /// Executes the `imgtest init` command in the goldctl tool. /// /// The `imgtest` command collects and uploads test results to the Skia Gold /// backend, the `init` argument initializes the current test. Used by the /// [FlutterPostSubmitFileComparator]. Future<void> imgtestInit() async { // This client has already been initialized if (_initialized) { return; } final File keys = workDirectory.childFile('keys.json'); final File failures = workDirectory.childFile('failures.json'); await keys.writeAsString(_getKeysJSON()); await failures.create(); final String commitHash = await _getCurrentCommit(); final List<String> imgtestInitCommand = <String>[ _goldctl, 'imgtest', 'init', '--instance', 'flutter', '--work-dir', workDirectory .childDirectory('temp') .path, '--commit', commitHash, '--keys-file', keys.path, '--failure-file', failures.path, '--passfail', ]; if (imgtestInitCommand.contains(null)) { final StringBuffer buf = StringBuffer() ..writeln('A null argument was provided for Skia Gold imgtest init.') ..writeln('Please confirm the settings of your golden file test.') ..writeln('Arguments provided:'); imgtestInitCommand.forEach(buf.writeln); throw SkiaException(buf.toString()); } final io.ProcessResult result = await process.run(imgtestInitCommand); if (result.exitCode != 0) { _initialized = false; final StringBuffer buf = StringBuffer() ..writeln('Skia Gold imgtest init failed.') ..writeln('An error occurred when initializing golden file test with ') ..writeln('goldctl.') ..writeln() ..writeln('Debug information for Gold --------------------------------') ..writeln('stdout: ${result.stdout}') ..writeln('stderr: ${result.stderr}'); throw SkiaException(buf.toString()); } _initialized = true; } /// Executes the `imgtest add` command in the goldctl tool. /// /// The `imgtest` command collects and uploads test results to the Skia Gold /// backend, the `add` argument uploads the current image test. A response is /// returned from the invocation of this command that indicates a pass or fail /// result. /// /// The [testName] and [goldenFile] parameters reference the current /// comparison being evaluated by the [FlutterPostSubmitFileComparator]. Future<bool> imgtestAdd(String testName, File goldenFile) async { final List<String> imgtestCommand = <String>[ _goldctl, 'imgtest', 'add', '--work-dir', workDirectory .childDirectory('temp') .path, '--test-name', cleanTestName(testName), '--png-file', goldenFile.path, '--passfail', ..._getPixelMatchingArguments(), ]; final io.ProcessResult result = await process.run(imgtestCommand); if (result.exitCode != 0) { // If an unapproved image has made it to post-submit, throw to close the // tree. String? resultContents; final File resultFile = workDirectory.childFile(fs.path.join( 'result-state.json', )); if (await resultFile.exists()) { resultContents = await resultFile.readAsString(); } final StringBuffer buf = StringBuffer() ..writeln('Skia Gold received an unapproved image in post-submit ') ..writeln('testing. Golden file images in flutter/flutter are triaged ') ..writeln('in pre-submit during code review for the given PR.') ..writeln() ..writeln('Visit https://flutter-gold.skia.org/ to view and approve ') ..writeln('the image(s), or revert the associated change. For more ') ..writeln('information, visit the wiki: ') ..writeln('https://github.com/flutter/flutter/wiki/Writing-a-golden-file-test-for-package:flutter') ..writeln() ..writeln('Debug information for Gold --------------------------------') ..writeln('stdout: ${result.stdout}') ..writeln('stderr: ${result.stderr}') ..writeln() ..writeln('result-state.json: ${resultContents ?? 'No result file found.'}'); throw SkiaException(buf.toString()); } return true; } /// Signals if this client is initialized for uploading tryjobs to the Gold /// service. /// /// Since Flutter framework tests are executed in parallel, and in random /// order, this will signal is this instance of the Gold client has been /// initialized for tryjobs. bool _tryjobInitialized = false; /// Executes the `imgtest init` command in the goldctl tool for tryjobs. /// /// The `imgtest` command collects and uploads test results to the Skia Gold /// backend, the `init` argument initializes the current tryjob. Used by the /// [FlutterPreSubmitFileComparator]. Future<void> tryjobInit() async { // This client has already been initialized if (_tryjobInitialized) { return; } final File keys = workDirectory.childFile('keys.json'); final File failures = workDirectory.childFile('failures.json'); await keys.writeAsString(_getKeysJSON()); await failures.create(); final String commitHash = await _getCurrentCommit(); final List<String> imgtestInitCommand = <String>[ _goldctl, 'imgtest', 'init', '--instance', 'flutter', '--work-dir', workDirectory .childDirectory('temp') .path, '--commit', commitHash, '--keys-file', keys.path, '--failure-file', failures.path, '--passfail', '--crs', 'github', '--patchset_id', commitHash, ...getCIArguments(), ]; if (imgtestInitCommand.contains(null)) { final StringBuffer buf = StringBuffer() ..writeln('A null argument was provided for Skia Gold tryjob init.') ..writeln('Please confirm the settings of your golden file test.') ..writeln('Arguments provided:'); imgtestInitCommand.forEach(buf.writeln); throw SkiaException(buf.toString()); } final io.ProcessResult result = await process.run(imgtestInitCommand); if (result.exitCode != 0) { _tryjobInitialized = false; final StringBuffer buf = StringBuffer() ..writeln('Skia Gold tryjobInit failure.') ..writeln('An error occurred when initializing golden file tryjob with ') ..writeln('goldctl.') ..writeln() ..writeln('Debug information for Gold --------------------------------') ..writeln('stdout: ${result.stdout}') ..writeln('stderr: ${result.stderr}'); throw SkiaException(buf.toString()); } _tryjobInitialized = true; } /// Executes the `imgtest add` command in the goldctl tool for tryjobs. /// /// The `imgtest` command collects and uploads test results to the Skia Gold /// backend, the `add` argument uploads the current image test. A response is /// returned from the invocation of this command that indicates a pass or fail /// result for the tryjob. /// /// The [testName] and [goldenFile] parameters reference the current /// comparison being evaluated by the [FlutterPreSubmitFileComparator]. Future<void> tryjobAdd(String testName, File goldenFile) async { final List<String> imgtestCommand = <String>[ _goldctl, 'imgtest', 'add', '--work-dir', workDirectory .childDirectory('temp') .path, '--test-name', cleanTestName(testName), '--png-file', goldenFile.path, ..._getPixelMatchingArguments(), ]; final io.ProcessResult result = await process.run(imgtestCommand); final String resultStdout = result.stdout.toString(); if (result.exitCode != 0 && !(resultStdout.contains('Untriaged') || resultStdout.contains('negative image'))) { String? resultContents; final File resultFile = workDirectory.childFile(fs.path.join( 'result-state.json', )); if (await resultFile.exists()) { resultContents = await resultFile.readAsString(); } final StringBuffer buf = StringBuffer() ..writeln('Unexpected Gold tryjobAdd failure.') ..writeln('Tryjob execution for golden file test $testName failed for') ..writeln('a reason unrelated to pixel comparison.') ..writeln() ..writeln('Debug information for Gold --------------------------------') ..writeln('stdout: ${result.stdout}') ..writeln('stderr: ${result.stderr}') ..writeln() ..writeln() ..writeln('result-state.json: ${resultContents ?? 'No result file found.'}'); throw SkiaException(buf.toString()); } } // Constructs arguments for `goldctl` for controlling how pixels are compared. // // For AOT and CanvasKit exact pixel matching is used. For the HTML renderer // on the web a fuzzy matching algorithm is used that allows very small deltas // because Chromium cannot exactly reproduce the same golden on all computers. // It seems to depend on the hardware/OS/driver combination. However, those // differences are very small (typically not noticeable to human eye). List<String> _getPixelMatchingArguments() { // Only use fuzzy pixel matching in the HTML renderer. if (!_isBrowserTest || _isBrowserSkiaTest) { return const <String>[]; } // The algorithm to be used when matching images. The available options are: // - "fuzzy": Allows for customizing the thresholds of pixel differences. // - "sobel": Same as "fuzzy" but performs edge detection before performing // a fuzzy match. const String algorithm = 'fuzzy'; // The number of pixels in this image that are allowed to differ from the // baseline. // // The chosen number - 20 - is arbitrary. Even for a small golden file, say // 50 x 50, it would be less than 1% of the total number of pixels. This // number should not grow too much. If it's growing, it is probably due to a // larger issue that needs to be addressed at the infra level. const int maxDifferentPixels = 20; // The maximum acceptable difference per pixel. // // Uses the Manhattan distance using the RGBA color components as // coordinates. The chosen number - 4 - is arbitrary. It's small enough to // both not be noticeable and not trigger test flakes due to sub-pixel // golden deltas. This number should not grow too much. If it's growing, it // is probably due to a larger issue that needs to be addressed at the infra // level. const int pixelDeltaThreshold = 4; return <String>[ '--add-test-optional-key', 'image_matching_algorithm:$algorithm', '--add-test-optional-key', 'fuzzy_max_different_pixels:$maxDifferentPixels', '--add-test-optional-key', 'fuzzy_pixel_delta_threshold:$pixelDeltaThreshold', ]; } /// Returns the latest positive digest for the given test known to Flutter /// Gold at head. Future<String?> getExpectationForTest(String testName) async { late String? expectation; final String traceID = getTraceID(testName); await io.HttpOverrides.runWithHttpOverrides<Future<void>>(() async { final Uri requestForExpectations = Uri.parse( 'https://flutter-gold.skia.org/json/v2/latestpositivedigest/$traceID' ); late String rawResponse; try { final io.HttpClientRequest request = await httpClient.getUrl(requestForExpectations); final io.HttpClientResponse response = await request.close(); rawResponse = await utf8.decodeStream(response); final dynamic jsonResponse = json.decode(rawResponse); if (jsonResponse is! Map<String, dynamic>) { throw const FormatException('Skia gold expectations do not match expected format.'); } expectation = jsonResponse['digest'] as String?; } on FormatException catch (error) { log( 'Formatting error detected requesting expectations from Flutter Gold.\n' 'error: $error\n' 'url: $requestForExpectations\n' 'response: $rawResponse' ); rethrow; } }, SkiaGoldHttpOverrides(), ); return expectation; } /// Returns a list of bytes representing the golden image retrieved from the /// Flutter Gold dashboard. /// /// The provided image hash represents an expectation from Flutter Gold. Future<List<int>>getImageBytes(String imageHash) async { final List<int> imageBytes = <int>[]; await io.HttpOverrides.runWithHttpOverrides<Future<void>>(() async { final Uri requestForImage = Uri.parse( 'https://flutter-gold.skia.org/img/images/$imageHash.png', ); final io.HttpClientRequest request = await httpClient.getUrl(requestForImage); final io.HttpClientResponse response = await request.close(); await response.forEach((List<int> bytes) => imageBytes.addAll(bytes)); }, SkiaGoldHttpOverrides(), ); return imageBytes; } /// Returns the current commit hash of the Flutter repository. Future<String> _getCurrentCommit() async { if (!_flutterRoot.existsSync()) { throw SkiaException('Flutter root could not be found: $_flutterRoot\n'); } else { final io.ProcessResult revParse = await process.run( <String>['git', 'rev-parse', 'HEAD'], workingDirectory: _flutterRoot.path, ); if (revParse.exitCode != 0) { throw const SkiaException('Current commit of Flutter can not be found.'); } return (revParse.stdout as String).trim(); } } /// Returns a JSON String with keys value pairs used to uniquely identify the /// configuration that generated the given golden file. /// /// Currently, the only key value pairs being tracked is the platform the /// image was rendered on, and for web tests, the browser the image was /// rendered on. String _getKeysJSON() { final String? webRenderer = _webRendererValue; final Map<String, dynamic> keys = <String, dynamic>{ 'Platform' : platform.operatingSystem, 'CI' : 'luci', if (_isImpeller) 'impeller': 'swiftshader', }; if (_isBrowserTest) { keys['Browser'] = _browserKey; keys['Platform'] = '${keys['Platform']}-browser'; if (webRenderer != null) { keys['WebRenderer'] = webRenderer; } } return json.encode(keys); } /// Removes the file extension from the [fileName] to represent the test name /// properly. String cleanTestName(String fileName) { return fileName.split(path.extension(fileName))[0]; } /// Returns a boolean value to prevent the client from re-authorizing itself /// for multiple tests. Future<bool> clientIsAuthorized() async { final File authFile = workDirectory.childFile(fs.path.join( 'temp', 'auth_opt.json', )); if (await authFile.exists()) { final String contents = await authFile.readAsString(); final Map<String, dynamic> decoded = json.decode(contents) as Map<String, dynamic>; return !(decoded['GSUtil'] as bool); } return false; } /// Returns a list of arguments for initializing a tryjob based on the testing /// environment. List<String> getCIArguments() { final String jobId = platform.environment['LOGDOG_STREAM_PREFIX']!.split('/').last; final List<String> refs = platform.environment['GOLD_TRYJOB']!.split('/'); final String pullRequest = refs[refs.length - 2]; return <String>[ '--changelist', pullRequest, '--cis', 'buildbucket', '--jobid', jobId, ]; } bool get _isBrowserTest { return platform.environment[_kTestBrowserKey] != null; } bool get _isBrowserSkiaTest { return _isBrowserTest && switch (platform.environment[_kWebRendererKey]) { 'canvaskit' || 'skwasm' => true, _ => false, }; } String? get _webRendererValue { return _isBrowserSkiaTest ? platform.environment[_kWebRendererKey] : null; } bool get _isImpeller { return (platform.environment[_kImpellerKey] != null); } String get _browserKey { assert(_isBrowserTest); return platform.environment[_kTestBrowserKey]!; } /// Returns a trace id based on the current testing environment to lookup /// the latest positive digest on Flutter Gold with a hex-encoded md5 hash of /// the image keys. String getTraceID(String testName) { final String? webRenderer = _webRendererValue; final Map<String, Object?> parameters = <String, Object?>{ if (_isBrowserTest) 'Browser' : _browserKey, 'CI' : 'luci', 'Platform' : platform.operatingSystem, if (webRenderer != null) 'WebRenderer' : webRenderer, if (_isImpeller) 'impeller': 'swiftshader', 'name' : testName, 'source_type' : 'flutter', }; final Map<String, Object?> sorted = <String, Object?>{}; for (final String key in parameters.keys.toList()..sort()) { sorted[key] = parameters[key]; } final String jsonTrace = json.encode(sorted); final String md5Sum = md5.convert(utf8.encode(jsonTrace)).toString(); return md5Sum; } } /// Used to make HttpRequests during testing. class SkiaGoldHttpOverrides extends io.HttpOverrides { }
flutter/packages/flutter_goldens/lib/skia_client.dart/0
{ "file_path": "flutter/packages/flutter_goldens/lib/skia_client.dart", "repo_id": "flutter", "token_count": 7559 }
324
{ "datePickerHourSemanticsLabelOne": "$hourটা বাজে", "datePickerHourSemanticsLabelOther": "$hourটা বাজে", "datePickerMinuteSemanticsLabelOne": "১ মিনিট", "datePickerMinuteSemanticsLabelOther": "$minute মিনিট", "datePickerDateOrder": "mdy", "datePickerDateTimeOrder": "date_time_dayPeriod", "anteMeridiemAbbreviation": "AM", "postMeridiemAbbreviation": "PM", "todayLabel": "আজ", "alertDialogLabel": "সতর্কতা", "timerPickerHourLabelOne": "ঘণ্টা", "timerPickerHourLabelOther": "ঘণ্টা", "timerPickerMinuteLabelOne": "মিনিট।", "timerPickerMinuteLabelOther": "মিনিট।", "timerPickerSecondLabelOne": "সেকেন্ড।", "timerPickerSecondLabelOther": "সেকেন্ড।", "cutButtonLabel": "কাট করুন", "copyButtonLabel": "কপি করুন", "pasteButtonLabel": "পেস্ট করুন", "clearButtonLabel": "Clear", "selectAllButtonLabel": "সব বেছে নিন", "tabSemanticsLabel": "$tabCount-এর মধ্যে $tabIndex নম্বর ট্যাব", "modalBarrierDismissLabel": "খারিজ করুন", "searchTextFieldPlaceholderLabel": "সার্চ করুন", "noSpellCheckReplacementsLabel": "কোনও বিকল্প বানান দেখানো হয়নি", "menuDismissLabel": "বাতিল করার মেনু", "lookUpButtonLabel": "লুক-আপ", "searchWebButtonLabel": "ওয়েবে সার্চ করুন", "shareButtonLabel": "শেয়ার করুন..." }
flutter/packages/flutter_localizations/lib/src/l10n/cupertino_bn.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_bn.arb", "repo_id": "flutter", "token_count": 829 }
325
{ "datePickerHourSemanticsLabelOne": "$hour વાગ્યો છે", "datePickerHourSemanticsLabelOther": "$hour વાગ્યા છે", "datePickerMinuteSemanticsLabelOne": "1 મિનિટ", "datePickerMinuteSemanticsLabelOther": "$minute મિનિટ", "datePickerDateOrder": "dmy", "datePickerDateTimeOrder": "date_time_dayPeriod", "anteMeridiemAbbreviation": "AM", "postMeridiemAbbreviation": "PM", "todayLabel": "આજે", "alertDialogLabel": "અલર્ટ", "timerPickerHourLabelOne": "કલાક", "timerPickerHourLabelOther": "કલાક", "timerPickerMinuteLabelOne": "મિનિટ", "timerPickerMinuteLabelOther": "મિનિટ", "timerPickerSecondLabelOne": "સેકન્ડ", "timerPickerSecondLabelOther": "સેકન્ડ", "cutButtonLabel": "કાપો", "copyButtonLabel": "કૉપિ કરો", "pasteButtonLabel": "પેસ્ટ કરો", "selectAllButtonLabel": "બધા પસંદ કરો", "tabSemanticsLabel": "$tabCountમાંથી $tabIndex ટૅબ", "modalBarrierDismissLabel": "છોડી દો", "searchTextFieldPlaceholderLabel": "શોધો", "noSpellCheckReplacementsLabel": "બદલવા માટે કોઈ શબ્દ મળ્યો નથી", "menuDismissLabel": "મેનૂ છોડી દો", "lookUpButtonLabel": "શોધો", "searchWebButtonLabel": "વેબ પર શોધો", "shareButtonLabel": "શેર કરો…", "clearButtonLabel": "Clear" }
flutter/packages/flutter_localizations/lib/src/l10n/cupertino_gu.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_gu.arb", "repo_id": "flutter", "token_count": 872 }
326
{ "datePickerHourSemanticsLabelOne": "$hour ໂມງກົງ", "datePickerHourSemanticsLabelOther": "$hour ໂມງກົງ", "datePickerMinuteSemanticsLabelOne": "1 ນາທີ", "datePickerMinuteSemanticsLabelOther": "$minute ນາທີ", "datePickerDateOrder": "mdy", "datePickerDateTimeOrder": "date_time_dayPeriod", "anteMeridiemAbbreviation": "ກ່ອນທ່ຽງ", "postMeridiemAbbreviation": "ຫຼັງທ່ຽງ", "todayLabel": "ມື້ນີ້", "alertDialogLabel": "ການເຕືອນ", "timerPickerHourLabelOne": "ຊົ່ວໂມງ", "timerPickerHourLabelOther": "ຊົ່ວໂມງ", "timerPickerMinuteLabelOne": "ນທ.", "timerPickerMinuteLabelOther": "ນທ.", "timerPickerSecondLabelOne": "ວິ.", "timerPickerSecondLabelOther": "ວິ.", "cutButtonLabel": "ຕັດ", "copyButtonLabel": "ສຳເນົາ", "pasteButtonLabel": "ວາງ", "selectAllButtonLabel": "ເລືອກທັງໝົດ", "tabSemanticsLabel": "ແຖບທີ $tabIndex ຈາກທັງໝົດ $tabCount", "modalBarrierDismissLabel": "ປິດໄວ້", "searchTextFieldPlaceholderLabel": "ຊອກຫາ", "noSpellCheckReplacementsLabel": "ບໍ່ພົບການແທນທີ່", "menuDismissLabel": "ປິດເມນູ", "lookUpButtonLabel": "ຊອກຫາຂໍ້ມູນ", "searchWebButtonLabel": "ຊອກຫາຢູ່ອິນເຕີເນັດ", "shareButtonLabel": "ແບ່ງປັນ...", "clearButtonLabel": "Clear" }
flutter/packages/flutter_localizations/lib/src/l10n/cupertino_lo.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_lo.arb", "repo_id": "flutter", "token_count": 896 }
327
{ "datePickerHourSemanticsLabelOne": "$hour hora", "datePickerHourSemanticsLabelOther": "$hour horas", "datePickerMinuteSemanticsLabelOne": "1 minuto", "datePickerMinuteSemanticsLabelOther": "$minute minutos", "datePickerDateOrder": "dmy", "datePickerDateTimeOrder": "date_time_dayPeriod", "anteMeridiemAbbreviation": "AM", "postMeridiemAbbreviation": "PM", "todayLabel": "Hoje", "alertDialogLabel": "Alerta", "timerPickerHourLabelOne": "hora", "timerPickerHourLabelOther": "horas", "timerPickerMinuteLabelOne": "min", "timerPickerMinuteLabelOther": "min", "timerPickerSecondLabelOne": "s", "timerPickerSecondLabelOther": "s", "cutButtonLabel": "Cortar", "copyButtonLabel": "Copiar", "pasteButtonLabel": "Colar", "selectAllButtonLabel": "Selecionar tudo", "tabSemanticsLabel": "Guia $tabIndex de $tabCount", "modalBarrierDismissLabel": "Dispensar", "searchTextFieldPlaceholderLabel": "Pesquisar", "noSpellCheckReplacementsLabel": "Nenhuma alternativa encontrada", "menuDismissLabel": "Dispensar menu", "lookUpButtonLabel": "Pesquisar", "searchWebButtonLabel": "Pesquisar na Web", "shareButtonLabel": "Compartilhar…", "clearButtonLabel": "Clear" }
flutter/packages/flutter_localizations/lib/src/l10n/cupertino_pt.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_pt.arb", "repo_id": "flutter", "token_count": 438 }
328
{ "datePickerHourSemanticsLabelOne": "Saat $hour", "datePickerHourSemanticsLabelOther": "Saat $hour", "datePickerMinuteSemanticsLabelOne": "1 dakika", "datePickerMinuteSemanticsLabelOther": "$minute dakika", "datePickerDateOrder": "dmy", "datePickerDateTimeOrder": "date_time_dayPeriod", "anteMeridiemAbbreviation": "ÖÖ", "postMeridiemAbbreviation": "ÖS", "todayLabel": "Bugün", "alertDialogLabel": "Uyarı", "timerPickerHourLabelOne": "saat", "timerPickerHourLabelOther": "saat", "timerPickerMinuteLabelOne": "dk.", "timerPickerMinuteLabelOther": "dk.", "timerPickerSecondLabelOne": "sn.", "timerPickerSecondLabelOther": "sn.", "cutButtonLabel": "Kes", "copyButtonLabel": "Kopyala", "pasteButtonLabel": "Yapıştır", "selectAllButtonLabel": "Tümünü Seç", "tabSemanticsLabel": "Sekme $tabIndex/$tabCount", "modalBarrierDismissLabel": "Kapat", "searchTextFieldPlaceholderLabel": "Ara", "noSpellCheckReplacementsLabel": "Yerine Kelime Bulunamadı", "menuDismissLabel": "Menüyü kapat", "lookUpButtonLabel": "Ara", "searchWebButtonLabel": "Web'de Ara", "shareButtonLabel": "Paylaş...", "clearButtonLabel": "Clear" }
flutter/packages/flutter_localizations/lib/src/l10n/cupertino_tr.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_tr.arb", "repo_id": "flutter", "token_count": 445 }
329
{ "scriptCategory": "English-like", "timeOfDayFormat": "H:mm", "openAppDrawerTooltip": "নেভিগেশ্বন মেনু খোলক", "backButtonTooltip": "উভতি যাওক", "closeButtonTooltip": "বন্ধ কৰক", "deleteButtonTooltip": "মচক", "nextMonthTooltip": "পৰৱৰ্তী মাহ", "previousMonthTooltip": "পূৰ্বৱৰ্তী মাহ", "nextPageTooltip": "পৰৱৰ্তী পৃষ্ঠা", "firstPageTooltip": "প্রথম পৃষ্ঠা", "lastPageTooltip": "অন্তিম পৃষ্ঠা", "previousPageTooltip": "পূৰ্বৱৰ্তী পৃষ্ঠা", "showMenuTooltip": "মেনুখন দেখুৱাওক", "aboutListTileTitle": "$applicationNameৰ বিষয়ে", "licensesPageTitle": "অনুজ্ঞাপত্ৰসমূহ", "pageRowsInfoTitle": "$rowCountৰ $firstRow–$lastRow", "pageRowsInfoTitleApproximate": "$rowCountৰ $firstRow–$lastRow", "rowsPerPageTitle": "প্ৰতিটো পৃষ্ঠাত থকা শাৰী:", "tabLabel": "$tabCountৰ $tabIndexটা টেব", "selectedRowCountTitleOne": "১টা বস্তু বাছনি কৰা হ'ল", "selectedRowCountTitleOther": "$selectedRowCountটা বস্তু বাছনি কৰা হ’ল", "cancelButtonLabel": "বাতিল কৰক", "closeButtonLabel": "বন্ধ কৰক", "continueButtonLabel": "অব্যাহত ৰাখক", "copyButtonLabel": "প্ৰতিলিপি কৰক", "cutButtonLabel": "কাট কৰক", "scanTextButtonLabel": "পাঠ স্কেন কৰক", "okButtonLabel": "ঠিক আছে", "pasteButtonLabel": "পে'ষ্ট কৰক", "selectAllButtonLabel": "সকলো বাছনি কৰক", "viewLicensesButtonLabel": "অনুজ্ঞাপত্ৰসমূহ চাওক", "anteMeridiemAbbreviation": "পূৰ্বাহ্ন", "postMeridiemAbbreviation": "অপৰাহ্ন", "timePickerHourModeAnnouncement": "সময় বাছনি কৰক", "timePickerMinuteModeAnnouncement": "মিনিট বাছনি কৰক", "modalBarrierDismissLabel": "অগ্ৰাহ্য কৰক", "signedInLabel": "ছাইন ইন কৰা হ’ল", "hideAccountsLabel": "একাউণ্টসমূহ লুকুৱাওক", "showAccountsLabel": "একাউণ্টসমূহ দেখুৱাওক", "drawerLabel": "নেভিগেশ্বন মেনু", "popupMenuLabel": "প'পআপ মেনু", "dialogLabel": "ডায়ল'গ", "alertDialogLabel": "সতৰ্কবাৰ্তা", "searchFieldLabel": "সন্ধান কৰক", "reorderItemToStart": "আৰম্ভণিলৈ স্থানান্তৰ কৰক", "reorderItemToEnd": "শেষলৈ স্থানান্তৰ কৰক", "reorderItemUp": "ওপৰলৈ নিয়ক", "reorderItemDown": "তললৈ স্থানান্তৰ কৰক", "reorderItemLeft": "বাওঁফাললৈ স্থানান্তৰ কৰক", "reorderItemRight": "সোঁফাললৈ স্থানান্তৰ কৰক", "expandedIconTapHint": "সংকোচন কৰক", "collapsedIconTapHint": "বিস্তাৰ কৰক", "remainingTextFieldCharacterCountOne": "১টা বর্ণ বাকী আছে", "remainingTextFieldCharacterCountOther": "$remainingCountটা বর্ণ বাকী আছে", "refreshIndicatorSemanticLabel": "ৰিফ্ৰেশ্ব কৰক", "moreButtonTooltip": "অধিক", "dateSeparator": "/", "dateHelpText": "mm/dd/yyyy", "selectYearSemanticsLabel": "বছৰ বাছনি কৰক", "unspecifiedDate": "তাৰিখ", "unspecifiedDateRange": "তাৰিখৰ পৰিসৰ", "dateInputLabel": "তাৰিখটো দিয়ক", "dateRangeStartLabel": "আৰম্ভণিৰ তাৰিখ", "dateRangeEndLabel": "সমাপ্তিৰ তাৰিখ", "dateRangeStartDateSemanticLabel": "আৰম্ভণিৰ তাৰিখ $fullDate", "dateRangeEndDateSemanticLabel": "সমাপ্তিৰ তাৰিখ $fullDate", "invalidDateFormatLabel": "অমান্য ফৰ্মেট।", "invalidDateRangeLabel": "অমান্য পৰিসৰ।", "dateOutOfRangeLabel": "সীমাৰ বাহিৰত।", "saveButtonLabel": "ছেভ কৰক", "datePickerHelpText": "তাৰিখ বাছনি কৰক", "dateRangePickerHelpText": "পৰিসৰ বাছনি কৰক", "calendarModeButtonLabel": "কেলেণ্ডাৰলৈ সলনি কৰক", "inputDateModeButtonLabel": "ইনপুটলৈ সলনি কৰক", "timePickerDialHelpText": "সময় বাছনি কৰক", "timePickerInputHelpText": "সময় দিয়ক", "timePickerHourLabel": "ঘণ্টা", "timePickerMinuteLabel": "মিনিট", "invalidTimeLabel": "এটা মান্য সময় দিয়ক", "dialModeButtonLabel": "ডায়েল বাছনিকৰ্তাৰ ম’ডলৈ সলনি কৰক", "inputTimeModeButtonLabel": "পাঠ ইনপুটৰ ম’ডলৈ সলনি কৰক", "licensesPackageDetailTextZero": "No licenses", "licensesPackageDetailTextOne": "১ খন অনুজ্ঞাপত্ৰ", "licensesPackageDetailTextOther": "$licenseCount খন অনুজ্ঞাপত্ৰ", "keyboardKeyAlt": "Alt", "keyboardKeyAltGraph": "AltGr", "keyboardKeyBackspace": "বেকস্পেচ", "keyboardKeyCapsLock": "কেপ্‌ছ লক", "keyboardKeyChannelDown": "চেনেল ডাউন", "keyboardKeyChannelUp": "চেনেল আপ", "keyboardKeyControl": "Ctrl", "keyboardKeyDelete": "Del", "keyboardKeyEject": "ইজেক্ট", "keyboardKeyEnd": "End", "keyboardKeyEscape": "Esc", "keyboardKeyFn": "Fn", "keyboardKeyHome": "Home", "keyboardKeyInsert": "Insert", "keyboardKeyMeta": "মেটা", "keyboardKeyNumLock": "Num Lock", "keyboardKeyNumpad1": "নং ১", "keyboardKeyNumpad2": "নং ২", "keyboardKeyNumpad3": "নং ৩", "keyboardKeyNumpad4": "নং ৪", "keyboardKeyNumpad5": "নং ৫", "keyboardKeyNumpad6": "নং ৬", "keyboardKeyNumpad7": "নং ৭", "keyboardKeyNumpad8": "নং ৮", "keyboardKeyNumpad9": "নং ৯", "keyboardKeyNumpad0": "নং ০", "keyboardKeyNumpadAdd": "নং +", "keyboardKeyNumpadComma": "নং ,", "keyboardKeyNumpadDecimal": "নং .", "keyboardKeyNumpadDivide": "নং /", "keyboardKeyNumpadEnter": "Num Enter", "keyboardKeyNumpadEqual": "নং =", "keyboardKeyNumpadMultiply": "নং *", "keyboardKeyNumpadParenLeft": "নং (", "keyboardKeyNumpadParenRight": "নং )", "keyboardKeyNumpadSubtract": "নং -", "keyboardKeyPageDown": "PgDown", "keyboardKeyPageUp": "PgUp", "keyboardKeyPower": "পাৱাৰ", "keyboardKeyPowerOff": "পাৱাৰ অফ", "keyboardKeyPrintScreen": "প্ৰিণ্ট স্ক্ৰীন", "keyboardKeyScrollLock": "স্ক্ৰ’ল লক", "keyboardKeySelect": "ছিলেক্ট", "keyboardKeySpace": "স্পেচ", "keyboardKeyMetaMacOs": "Command", "keyboardKeyMetaWindows": "Win", "menuBarMenuLabel": "মেনু বাৰ মেনু", "currentDateLabel": "আজি", "scrimLabel": "স্ক্ৰিম", "bottomSheetLabel": "তলৰ শ্বীট", "scrimOnTapHint": "$modalRouteContentName বন্ধ কৰক", "keyboardKeyShift": "শ্বিফ্ট", "expansionTileExpandedHint": "সংকোচন কৰিবলৈ দুবাৰ টিপক", "expansionTileCollapsedHint": "বিস্তাৰ কৰিবলৈ দুবাৰ টিপক", "expansionTileExpandedTapHint": "সংকোচন কৰক", "expansionTileCollapsedTapHint": "অধিক সবিশেষ জানিবলৈ বিস্তাৰ কৰক", "expandedHint": "সংকোচন কৰা আছে", "collapsedHint": "বিস্তাৰ কৰা আছে", "menuDismissLabel": "অগ্ৰাহ্য কৰাৰ মেনু", "lookUpButtonLabel": "ওপৰলৈ চাওক", "searchWebButtonLabel": "ৱেবত সন্ধান কৰক", "shareButtonLabel": "শ্বেয়াৰ কৰক…", "clearButtonTooltip": "Clear text", "selectedDateLabel": "Selected" }
flutter/packages/flutter_localizations/lib/src/l10n/material_as.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_as.arb", "repo_id": "flutter", "token_count": 4797 }
330
{ "searchWebButtonLabel": "Search Web", "shareButtonLabel": "Share...", "scanTextButtonLabel": "Scan text", "lookUpButtonLabel": "Look up", "menuDismissLabel": "Dismiss menu", "expansionTileExpandedHint": "double-tap to collapse", "expansionTileCollapsedHint": "double-tap to expand", "expansionTileExpandedTapHint": "Collapse", "expansionTileCollapsedTapHint": "Expand for more details", "expandedHint": "Collapsed", "collapsedHint": "Expanded", "scrimLabel": "Scrim", "bottomSheetLabel": "Bottom sheet", "scrimOnTapHint": "Close $modalRouteContentName", "currentDateLabel": "Today", "keyboardKeyShift": "Shift", "menuBarMenuLabel": "Menu bar menu", "keyboardKeyNumpad8": "Num 8", "keyboardKeyCapsLock": "Caps lock", "keyboardKeyAltGraph": "AltGr", "keyboardKeyNumpad4": "Num 4", "keyboardKeyNumpad5": "Num 5", "keyboardKeyNumpad6": "Num 6", "keyboardKeyNumpad7": "Num 7", "keyboardKeyNumpad2": "Num 2", "keyboardKeyNumpad0": "Num 0", "keyboardKeyNumpadAdd": "Num +", "keyboardKeyNumpadComma": "Num ,", "keyboardKeyNumpadDecimal": "Num .", "keyboardKeyNumpadDivide": "Num /", "keyboardKeyNumpadEqual": "Num =", "keyboardKeyNumpadMultiply": "Num *", "keyboardKeyNumpadParenLeft": "Num (", "keyboardKeyInsert": "Insert", "keyboardKeyHome": "Home", "keyboardKeyEject": "Eject", "keyboardKeyNumpadParenRight": "Num )", "keyboardKeyFn": "Fn", "keyboardKeyEscape": "Esc", "keyboardKeyEnd": "End", "keyboardKeyDelete": "Del", "keyboardKeyControl": "Ctrl", "keyboardKeyChannelUp": "Channel up", "keyboardKeyNumpadSubtract": "Num -", "keyboardKeyChannelDown": "Channel down", "keyboardKeyBackspace": "Backspace", "keyboardKeySelect": "Select", "keyboardKeyAlt": "Alt", "keyboardKeyMeta": "Meta", "keyboardKeyMetaMacOs": "Command", "keyboardKeyMetaWindows": "Win", "keyboardKeyNumLock": "Num lock", "keyboardKeyNumpad1": "Num 1", "keyboardKeyPageDown": "PgDown", "keyboardKeySpace": "Space", "keyboardKeyNumpad3": "Num 3", "keyboardKeyScrollLock": "Scroll lock", "keyboardKeyNumpad9": "Num 9", "keyboardKeyPrintScreen": "Print screen", "keyboardKeyPowerOff": "Power off", "keyboardKeyPower": "Power", "keyboardKeyPageUp": "PgUp", "keyboardKeyNumpadEnter": "Num enter", "inputTimeModeButtonLabel": "Switch to text input mode", "timePickerDialHelpText": "Select time", "timePickerHourLabel": "Hour", "timePickerMinuteLabel": "Minute", "invalidTimeLabel": "Enter a valid time", "dialModeButtonLabel": "Switch to dial picker mode", "timePickerInputHelpText": "Enter time", "dateSeparator": "/", "dateInputLabel": "Enter date", "calendarModeButtonLabel": "Switch to calendar", "dateRangePickerHelpText": "Select range", "datePickerHelpText": "Select date", "saveButtonLabel": "Save", "dateOutOfRangeLabel": "Out of range.", "invalidDateRangeLabel": "Invalid range.", "invalidDateFormatLabel": "Invalid format.", "dateRangeEndDateSemanticLabel": "End date $fullDate", "dateRangeStartDateSemanticLabel": "Start date $fullDate", "dateRangeEndLabel": "End date", "dateRangeStartLabel": "Start date", "inputDateModeButtonLabel": "Switch to input", "unspecifiedDateRange": "Date range", "unspecifiedDate": "Date", "selectYearSemanticsLabel": "Select year", "dateHelpText": "dd/mm/yyyy", "moreButtonTooltip": "More", "tabLabel": "Tab $tabIndex of $tabCount", "showAccountsLabel": "Show accounts", "hideAccountsLabel": "Hide accounts", "signedInLabel": "Signed in", "timePickerMinuteModeAnnouncement": "Select minutes", "timePickerHourModeAnnouncement": "Select hours", "scriptCategory": "English-like", "timeOfDayFormat": "HH:mm", "nextMonthTooltip": "Next month", "pageRowsInfoTitleApproximate": "$firstRow–$lastRow of about $rowCount", "copyButtonLabel": "Copy", "closeButtonTooltip": "Close", "deleteButtonTooltip": "Delete", "selectAllButtonLabel": "Select all", "viewLicensesButtonLabel": "View licences", "rowsPerPageTitle": "Rows per page:", "aboutListTileTitle": "About $applicationName", "backButtonTooltip": "Back", "licensesPageTitle": "Licences", "licensesPackageDetailTextZero": "No licences", "licensesPackageDetailTextOne": "1 licence", "licensesPackageDetailTextOther": "$licenseCount licences", "okButtonLabel": "OK", "pasteButtonLabel": "Paste", "previousMonthTooltip": "Previous month", "closeButtonLabel": "Close", "cutButtonLabel": "Cut", "continueButtonLabel": "Continue", "nextPageTooltip": "Next page", "openAppDrawerTooltip": "Open navigation menu", "previousPageTooltip": "Previous page", "firstPageTooltip": "First page", "lastPageTooltip": "Last page", "cancelButtonLabel": "Cancel", "pageRowsInfoTitle": "$firstRow–$lastRow of $rowCount", "selectedRowCountTitleOne": "1 item selected", "selectedRowCountTitleOther": "$selectedRowCount items selected", "showMenuTooltip": "Show menu", "anteMeridiemAbbreviation": "AM", "postMeridiemAbbreviation": "PM", "modalBarrierDismissLabel": "Dismiss", "drawerLabel": "Navigation menu", "popupMenuLabel": "Pop-up menu", "dialogLabel": "Dialogue", "alertDialogLabel": "Alert", "searchFieldLabel": "Search", "reorderItemToStart": "Move to the start", "reorderItemToEnd": "Move to the end", "reorderItemUp": "Move up", "reorderItemDown": "Move down", "reorderItemLeft": "Move to the left", "reorderItemRight": "Move to the right", "expandedIconTapHint": "Collapse", "collapsedIconTapHint": "Expand", "remainingTextFieldCharacterCountZero": "No characters remaining", "remainingTextFieldCharacterCountOne": "1 character remaining", "remainingTextFieldCharacterCountOther": "$remainingCount characters remaining", "refreshIndicatorSemanticLabel": "Refresh" }
flutter/packages/flutter_localizations/lib/src/l10n/material_en_GB.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_en_GB.arb", "repo_id": "flutter", "token_count": 1994 }
331
{ "scriptCategory": "English-like", "timeOfDayFormat": "HH:mm", "openAppDrawerTooltip": "Ouvrir le menu de navigation", "backButtonTooltip": "Retour", "closeButtonTooltip": "Fermer", "deleteButtonTooltip": "Supprimer", "nextMonthTooltip": "Mois suivant", "previousMonthTooltip": "Mois précédent", "nextPageTooltip": "Page suivante", "previousPageTooltip": "Page précédente", "firstPageTooltip": "Première page", "lastPageTooltip": "Dernière page", "showMenuTooltip": "Afficher le menu", "aboutListTileTitle": "À propos de $applicationName", "licensesPageTitle": "Licences", "pageRowsInfoTitle": "$firstRow – $lastRow sur $rowCount", "pageRowsInfoTitleApproximate": "$firstRow – $lastRow sur environ $rowCount", "rowsPerPageTitle": "Lignes par page :", "tabLabel": "Onglet $tabIndex sur $tabCount", "selectedRowCountTitleZero": "Aucun élément sélectionné", "selectedRowCountTitleOne": "1 élément sélectionné", "selectedRowCountTitleOther": "$selectedRowCount éléments sélectionnés", "cancelButtonLabel": "Annuler", "closeButtonLabel": "Fermer", "continueButtonLabel": "Continuer", "copyButtonLabel": "Copier", "cutButtonLabel": "Couper", "scanTextButtonLabel": "Scanner du texte", "okButtonLabel": "OK", "pasteButtonLabel": "Coller", "selectAllButtonLabel": "Tout sélectionner", "viewLicensesButtonLabel": "Afficher les licences", "anteMeridiemAbbreviation": "AM", "postMeridiemAbbreviation": "PM", "timePickerHourModeAnnouncement": "Sélectionner une heure", "timePickerMinuteModeAnnouncement": "Sélectionner des minutes", "signedInLabel": "Connecté", "hideAccountsLabel": "Masquer les comptes", "showAccountsLabel": "Afficher les comptes", "modalBarrierDismissLabel": "Ignorer", "drawerLabel": "Menu de navigation", "popupMenuLabel": "Menu contextuel", "dialogLabel": "Boîte de dialogue", "alertDialogLabel": "Alerte", "searchFieldLabel": "Rechercher", "reorderItemToStart": "Déplacer vers le début", "reorderItemToEnd": "Déplacer vers la fin", "reorderItemUp": "Déplacer vers le haut", "reorderItemDown": "Déplacer vers le bas", "reorderItemLeft": "Déplacer vers la gauche", "reorderItemRight": "Déplacer vers la droite", "expandedIconTapHint": "Réduire", "collapsedIconTapHint": "Développer", "remainingTextFieldCharacterCountOne": "1 caractère restant", "remainingTextFieldCharacterCountOther": "$remainingCount caractères restants", "refreshIndicatorSemanticLabel": "Actualiser", "moreButtonTooltip": "Plus", "dateSeparator": "/", "dateHelpText": "jj/mm/aaaa", "selectYearSemanticsLabel": "Sélectionner une année", "unspecifiedDate": "Date", "unspecifiedDateRange": "Plage de dates", "dateInputLabel": "Saisir une date", "dateRangeStartLabel": "Date de début", "dateRangeEndLabel": "Date de fin", "dateRangeStartDateSemanticLabel": "Date de début : $fullDate", "dateRangeEndDateSemanticLabel": "Date de fin : $fullDate", "invalidDateFormatLabel": "Format non valide.", "invalidDateRangeLabel": "Plage non valide.", "dateOutOfRangeLabel": "Hors de portée.", "saveButtonLabel": "Enregistrer", "datePickerHelpText": "Sélectionner une date", "dateRangePickerHelpText": "Sélectionner une plage", "calendarModeButtonLabel": "Passer à l'agenda", "inputDateModeButtonLabel": "Passer à la saisie", "timePickerDialHelpText": "Sélectionner une heure", "timePickerInputHelpText": "Saisir une heure", "timePickerHourLabel": "Heure", "timePickerMinuteLabel": "Minute", "invalidTimeLabel": "Veuillez indiquer une heure valide", "dialModeButtonLabel": "Passer au mode de sélection via le cadran", "inputTimeModeButtonLabel": "Passer au mode de saisie au format texte", "licensesPackageDetailTextZero": "No licenses", "licensesPackageDetailTextOne": "1 licence", "licensesPackageDetailTextOther": "$licenseCount licences", "keyboardKeyAlt": "Alt", "keyboardKeyAltGraph": "Alt Gr", "keyboardKeyBackspace": "Retour arrière", "keyboardKeyCapsLock": "Verr Maj", "keyboardKeyChannelDown": "Chaîne suivante", "keyboardKeyChannelUp": "Chaîne précédente", "keyboardKeyControl": "Ctrl", "keyboardKeyDelete": "Suppr", "keyboardKeyEject": "Éjecter", "keyboardKeyEnd": "Fin", "keyboardKeyEscape": "Échap", "keyboardKeyFn": "Fn", "keyboardKeyHome": "Accueil", "keyboardKeyInsert": "Insérer", "keyboardKeyMeta": "Méta", "keyboardKeyNumLock": "Verr Num", "keyboardKeyNumpad1": "Num 1", "keyboardKeyNumpad2": "Num 2", "keyboardKeyNumpad3": "Num 3", "keyboardKeyNumpad4": "Num 4", "keyboardKeyNumpad5": "Num 5", "keyboardKeyNumpad6": "Num 6", "keyboardKeyNumpad7": "Num 7", "keyboardKeyNumpad8": "Num 8", "keyboardKeyNumpad9": "Num 9", "keyboardKeyNumpad0": "Num 0", "keyboardKeyNumpadAdd": "Num +", "keyboardKeyNumpadComma": "Num ,", "keyboardKeyNumpadDecimal": "Num .", "keyboardKeyNumpadDivide": "Num /", "keyboardKeyNumpadEnter": "Num Entrée", "keyboardKeyNumpadEqual": "Num =", "keyboardKeyNumpadMultiply": "Num *", "keyboardKeyNumpadParenLeft": "Num (", "keyboardKeyNumpadParenRight": "Num )", "keyboardKeyNumpadSubtract": "Num -", "keyboardKeyPageDown": "PgSuiv", "keyboardKeyPageUp": "PgPréc", "keyboardKeyPower": "Puissance", "keyboardKeyPowerOff": "Éteindre", "keyboardKeyPrintScreen": "Impr. écran", "keyboardKeyScrollLock": "Arrêt défil", "keyboardKeySelect": "Sélectionner", "keyboardKeySpace": "Espace", "keyboardKeyMetaMacOs": "Commande", "keyboardKeyMetaWindows": "Win", "menuBarMenuLabel": "Menu de la barre de menu", "currentDateLabel": "Aujourd'hui", "scrimLabel": "Fond", "bottomSheetLabel": "Bottom sheet", "scrimOnTapHint": "Fermer $modalRouteContentName", "keyboardKeyShift": "Maj", "expansionTileExpandedHint": "appuyez deux fois pour réduire", "expansionTileCollapsedHint": "appuyez deux fois pour développer", "expansionTileExpandedTapHint": "Réduire", "expansionTileCollapsedTapHint": "Développer pour en savoir plus", "expandedHint": "Réduit", "collapsedHint": "Développé", "menuDismissLabel": "Fermer le menu", "lookUpButtonLabel": "Recherche visuelle", "searchWebButtonLabel": "Rechercher sur le Web", "shareButtonLabel": "Partager…", "clearButtonTooltip": "Clear text", "selectedDateLabel": "Selected" }
flutter/packages/flutter_localizations/lib/src/l10n/material_fr.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_fr.arb", "repo_id": "flutter", "token_count": 2347 }
332
{ "scriptCategory": "dense", "timeOfDayFormat": "h:mm a", "openAppDrawerTooltip": "បើក​ម៉ឺនុយរុករក", "backButtonTooltip": "ថយក្រោយ", "closeButtonTooltip": "បិទ", "deleteButtonTooltip": "លុប", "nextMonthTooltip": "ខែ​​ក្រោយ", "previousMonthTooltip": "ខែមុន", "nextPageTooltip": "ទំព័របន្ទាប់", "previousPageTooltip": "ទំព័រមុន", "firstPageTooltip": "ទំព័រ​ដំបូង", "lastPageTooltip": "ទំព័រ​ចុង​ក្រោយ", "showMenuTooltip": "បង្ហាញ​ម៉ឺនុយ", "aboutListTileTitle": "អំពី $applicationName", "licensesPageTitle": "អាជ្ញាបណ្ណ", "pageRowsInfoTitle": "$firstRow–$lastRow ក្នុង​ចំណោម​ $rowCount", "pageRowsInfoTitleApproximate": "$firstRow–$lastRow ក្នុង​ចំណោម​ប្រហែល $rowCount", "rowsPerPageTitle": "ជួរ​ដេក​ក្នុង​មួយ​ទំព័រ៖", "tabLabel": "ផ្ទាំង $tabIndex ក្នុង​ចំណោម​ $tabCount", "selectedRowCountTitleOne": "បាន​ជ្រើស​រើស​ធាតុ 1", "selectedRowCountTitleOther": "បាន​ជ្រើស​រើស​ធាតុ $selectedRowCount", "cancelButtonLabel": "បោះបង់", "closeButtonLabel": "បិទ", "continueButtonLabel": "បន្ត", "copyButtonLabel": "ចម្លង", "cutButtonLabel": "កាត់", "scanTextButtonLabel": "ស្កេន​អក្សរ", "okButtonLabel": "យល់ព្រម", "pasteButtonLabel": "ដាក់​ចូល", "selectAllButtonLabel": "ជ្រើសរើស​ទាំងអស់", "viewLicensesButtonLabel": "មើលអាជ្ញាបណ្ណ", "anteMeridiemAbbreviation": "AM", "postMeridiemAbbreviation": "PM", "timePickerHourModeAnnouncement": "ជ្រើសរើស​ម៉ោង", "timePickerMinuteModeAnnouncement": "ជ្រើសរើស​នាទី", "signedInLabel": "បានចូល​គណនី", "hideAccountsLabel": "លាក់គណនី", "showAccountsLabel": "បង្ហាញគណនី", "modalBarrierDismissLabel": "ច្រាន​ចោល", "drawerLabel": "ម៉ឺនុយរុករក", "popupMenuLabel": "​ម៉ឺនុយ​លោត​ឡើង", "dialogLabel": "ប្រអប់", "alertDialogLabel": "ជូនដំណឹង", "searchFieldLabel": "ស្វែងរក", "reorderItemToStart": "ផ្លាស់ទីទៅ​ចំណុច​ចាប់ផ្ដើម", "reorderItemToEnd": "ផ្លាស់ទីទៅ​ចំណុចបញ្ចប់", "reorderItemUp": "ផ្លាស់ទី​ឡើង​លើ", "reorderItemDown": "ផ្លាស់ទី​ចុះ​ក្រោម", "reorderItemLeft": "ផ្លាស់ទី​ទៅ​ឆ្វេង", "reorderItemRight": "ផ្លាស់ទីទៅ​ស្តាំ", "expandedIconTapHint": "បង្រួម", "collapsedIconTapHint": "ពង្រីក", "remainingTextFieldCharacterCountOne": "នៅសល់​ 1 តួ​ទៀត", "remainingTextFieldCharacterCountOther": "នៅសល់ $remainingCount តួ​ទៀត", "refreshIndicatorSemanticLabel": "ផ្ទុកឡើងវិញ", "moreButtonTooltip": "ច្រើន​ទៀត", "dateSeparator": "/", "dateHelpText": "ថ្ងៃ/ខែ/ឆ្នាំ", "selectYearSemanticsLabel": "ជ្រើសរើសឆ្នាំ", "unspecifiedDate": "កាលបរិច្ឆេទ", "unspecifiedDateRange": "ចន្លោះ​កាលបរិច្ឆេទ", "dateInputLabel": "បញ្ចូល​កាលបរិច្ឆេទ", "dateRangeStartLabel": "កាលបរិច្ឆេទ​ចាប់ផ្ដើម", "dateRangeEndLabel": "កាលបរិច្ឆេទ​បញ្ចប់", "dateRangeStartDateSemanticLabel": "កាលបរិច្ឆេទ​ចាប់ផ្ដើម $fullDate", "dateRangeEndDateSemanticLabel": "កាលបរិច្ឆេទ​បញ្ចប់ $fullDate", "invalidDateFormatLabel": "ទម្រង់មិន​ត្រឹមត្រូវទេ។", "invalidDateRangeLabel": "ចន្លោះ​មិនត្រឹមត្រូវទេ។", "dateOutOfRangeLabel": "ក្រៅចន្លោះ។", "saveButtonLabel": "រក្សាទុក", "datePickerHelpText": "ជ្រើសរើស​កាល​បរិច្ឆេទ", "dateRangePickerHelpText": "ជ្រើសរើសចន្លោះ", "calendarModeButtonLabel": "ប្ដូរទៅ​ប្រតិទិន", "inputDateModeButtonLabel": "ប្ដូរទៅ​ការបញ្ចូល", "timePickerDialHelpText": "ជ្រើសរើសម៉ោង", "timePickerInputHelpText": "បញ្ចូលម៉ោង", "timePickerHourLabel": "ម៉ោង", "timePickerMinuteLabel": "នាទី​", "invalidTimeLabel": "បញ្ចូលពេលវេលា​ដែល​ត្រឹមត្រូវ", "dialModeButtonLabel": "ប្ដូរទៅមុខងារផ្ទាំង​ជ្រើសរើសលេខ", "inputTimeModeButtonLabel": "ប្ដូរទៅ​មុខងារ​បញ្ចូល​អក្សរ", "licensesPackageDetailTextZero": "No licenses", "licensesPackageDetailTextOne": "អាជ្ញាបណ្ណ 1", "licensesPackageDetailTextOther": "អាជ្ញាបណ្ណ $licenseCount", "keyboardKeyAlt": "Alt", "keyboardKeyAltGraph": "AltGr", "keyboardKeyBackspace": "Backspace", "keyboardKeyCapsLock": "Caps Lock", "keyboardKeyChannelDown": "Channel Down", "keyboardKeyChannelUp": "Channel Up", "keyboardKeyControl": "Ctrl", "keyboardKeyDelete": "Del", "keyboardKeyEject": "Eject", "keyboardKeyEnd": "End", "keyboardKeyEscape": "Esc", "keyboardKeyFn": "Fn", "keyboardKeyHome": "Home", "keyboardKeyInsert": "Insert", "keyboardKeyMeta": "Meta", "keyboardKeyNumLock": "Num Lock", "keyboardKeyNumpad1": "Num 1", "keyboardKeyNumpad2": "Num 2", "keyboardKeyNumpad3": "Num 3", "keyboardKeyNumpad4": "Num 4", "keyboardKeyNumpad5": "Num 5", "keyboardKeyNumpad6": "Num 6", "keyboardKeyNumpad7": "Num 7", "keyboardKeyNumpad8": "Num 8", "keyboardKeyNumpad9": "Num 9", "keyboardKeyNumpad0": "Num 0", "keyboardKeyNumpadAdd": "Num +", "keyboardKeyNumpadComma": "Num ,", "keyboardKeyNumpadDecimal": "Num .", "keyboardKeyNumpadDivide": "Num /", "keyboardKeyNumpadEnter": "Num Enter", "keyboardKeyNumpadEqual": "Num =", "keyboardKeyNumpadMultiply": "Num *", "keyboardKeyNumpadParenLeft": "Num (", "keyboardKeyNumpadParenRight": "Num )", "keyboardKeyNumpadSubtract": "Num -", "keyboardKeyPageDown": "PgDown", "keyboardKeyPageUp": "PgUp", "keyboardKeyPower": "Power", "keyboardKeyPowerOff": "Power Off", "keyboardKeyPrintScreen": "Print Screen", "keyboardKeyScrollLock": "Scroll Lock", "keyboardKeySelect": "Select", "keyboardKeySpace": "Space", "keyboardKeyMetaMacOs": "Command", "keyboardKeyMetaWindows": "Win", "menuBarMenuLabel": "ម៉ឺនុយរបារម៉ឺនុយ", "currentDateLabel": "ថ្ងៃនេះ", "scrimLabel": "ផ្ទាំងស្រអាប់", "bottomSheetLabel": "សន្លឹក​ខាងក្រោម", "scrimOnTapHint": "បិទ $modalRouteContentName", "keyboardKeyShift": "Shift", "expansionTileExpandedHint": "ចុចពីរដង ដើម្បីបង្រួម", "expansionTileCollapsedHint": "ចុចពីរដង ដើម្បីពង្រីក", "expansionTileExpandedTapHint": "បង្រួម", "expansionTileCollapsedTapHint": "ពង្រីក​ដើម្បីទទួលបាន​ព័ត៌មានលម្អិត​បន្ថែម", "expandedHint": "បាន​បង្រួម", "collapsedHint": "បាន​ពង្រីក", "menuDismissLabel": "ច្រានចោល​ម៉ឺនុយ", "lookUpButtonLabel": "រកមើល", "searchWebButtonLabel": "ស្វែងរក​លើបណ្ដាញ", "shareButtonLabel": "ចែករំលែក...", "clearButtonTooltip": "Clear text", "selectedDateLabel": "Selected" }
flutter/packages/flutter_localizations/lib/src/l10n/material_km.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_km.arb", "repo_id": "flutter", "token_count": 5260 }
333
{ "scriptCategory": "English-like", "timeOfDayFormat": "HH:mm", "openAppDrawerTooltip": "Åpne navigasjonsmenyen", "backButtonTooltip": "Tilbake", "closeButtonTooltip": "Lukk", "deleteButtonTooltip": "Slett", "moreButtonTooltip": "Mer", "nextMonthTooltip": "Neste måned", "previousMonthTooltip": "Forrige måned", "nextPageTooltip": "Neste side", "previousPageTooltip": "Forrige side", "firstPageTooltip": "Første side", "lastPageTooltip": "Siste side", "showMenuTooltip": "Vis meny", "aboutListTileTitle": "Om $applicationName", "licensesPageTitle": "Lisenser", "licensesPackageDetailTextOne": "1 lisens", "licensesPackageDetailTextOther": "$licenseCount lisenser", "pageRowsInfoTitle": "$firstRow–$lastRow av $rowCount", "pageRowsInfoTitleApproximate": "$firstRow–$lastRow av omtrent $rowCount", "rowsPerPageTitle": "Rader per side:", "tabLabel": "Fane $tabIndex av $tabCount", "selectedRowCountTitleOne": "1 element er valgt", "selectedRowCountTitleOther": "$selectedRowCount elementer er valgt", "cancelButtonLabel": "Avbryt", "closeButtonLabel": "Lukk", "continueButtonLabel": "Fortsett", "copyButtonLabel": "Kopiér", "cutButtonLabel": "Klipp ut", "scanTextButtonLabel": "Skann tekst", "okButtonLabel": "OK", "pasteButtonLabel": "Lim inn", "selectAllButtonLabel": "Velg alle", "viewLicensesButtonLabel": "Se lisenser", "anteMeridiemAbbreviation": "AM", "postMeridiemAbbreviation": "PM", "timePickerHourModeAnnouncement": "Angi timer", "timePickerMinuteModeAnnouncement": "Angi minutter", "modalBarrierDismissLabel": "Avvis", "dateSeparator": ".", "dateHelpText": "dd.mm.åååå", "selectYearSemanticsLabel": "Velg året", "unspecifiedDate": "Dato", "unspecifiedDateRange": "Datoperiode", "dateInputLabel": "Skriv inn datoen", "dateRangeStartLabel": "Startdato", "dateRangeEndLabel": "Sluttdato", "dateRangeStartDateSemanticLabel": "Startdato $fullDate", "dateRangeEndDateSemanticLabel": "Sluttdato $fullDate", "invalidDateFormatLabel": "Ugyldig format.", "invalidDateRangeLabel": "Ugyldig periode.", "dateOutOfRangeLabel": "Utenfor perioden.", "saveButtonLabel": "Lagre", "datePickerHelpText": "Velg dato", "dateRangePickerHelpText": "Velg datoperiode", "calendarModeButtonLabel": "Bytt til kalender", "inputDateModeButtonLabel": "Bytt til innskriving", "timePickerDialHelpText": "Velg tidspunkt", "timePickerInputHelpText": "Angi et tidspunkt", "timePickerHourLabel": "Time", "timePickerMinuteLabel": "Minutt", "invalidTimeLabel": "Angi et gyldig klokkeslett", "dialModeButtonLabel": "Bytt til modus for valg fra urskive", "inputTimeModeButtonLabel": "Bytt til tekstinndatamodus", "signedInLabel": "Pålogget", "hideAccountsLabel": "Skjul kontoer", "showAccountsLabel": "Vis kontoer", "drawerLabel": "Navigasjonsmeny", "popupMenuLabel": "Forgrunnsmeny", "dialogLabel": "Dialogboks", "alertDialogLabel": "Varsel", "searchFieldLabel": "Søk", "reorderItemToStart": "Flytt til starten", "reorderItemToEnd": "Flytt til slutten", "reorderItemUp": "Flytt opp", "reorderItemDown": "Flytt ned", "reorderItemLeft": "Flytt til venstre", "reorderItemRight": "Flytt til høyre", "expandedIconTapHint": "Skjul", "collapsedIconTapHint": "Vis", "remainingTextFieldCharacterCountOne": "1 tegn gjenstår", "remainingTextFieldCharacterCountOther": "$remainingCount tegn gjenstår", "refreshIndicatorSemanticLabel": "Laster inn på nytt", "keyboardKeyAlt": "Alt", "keyboardKeyAltGraph": "Alt Gr", "keyboardKeyBackspace": "Tilbaketast", "keyboardKeyCapsLock": "Caps Lock", "keyboardKeyChannelDown": "Forrige kanal", "keyboardKeyChannelUp": "Neste kanal", "keyboardKeyControl": "Ctrl", "keyboardKeyDelete": "Del", "keyboardKeyEject": "Løs ut", "keyboardKeyEnd": "End", "keyboardKeyEscape": "Esc", "keyboardKeyFn": "Fn", "keyboardKeyHome": "Home", "keyboardKeyInsert": "Insert", "keyboardKeyMeta": "Meta", "keyboardKeyNumLock": "Num Lock", "keyboardKeyNumpad1": "Num 1", "keyboardKeyNumpad2": "Num 2", "keyboardKeyNumpad3": "Num 3", "keyboardKeyNumpad4": "Num 4", "keyboardKeyNumpad5": "Num 5", "keyboardKeyNumpad6": "Num 6", "keyboardKeyNumpad7": "Num 7", "keyboardKeyNumpad8": "Num 8", "keyboardKeyNumpad9": "Num 9", "keyboardKeyNumpad0": "Num 0", "keyboardKeyNumpadAdd": "Num +", "keyboardKeyNumpadComma": "Num ,", "keyboardKeyNumpadDecimal": "Num .", "keyboardKeyNumpadDivide": "Num /", "keyboardKeyNumpadEnter": "Num Enter", "keyboardKeyNumpadEqual": "Num =", "keyboardKeyNumpadMultiply": "Num *", "keyboardKeyNumpadParenLeft": "Num (", "keyboardKeyNumpadParenRight": "Num )", "keyboardKeyNumpadSubtract": "Num -", "keyboardKeyPageDown": "PgDown", "keyboardKeyPageUp": "PgUp", "keyboardKeyPower": "Av/på", "keyboardKeyPowerOff": "Slå av", "keyboardKeyPrintScreen": "PrtScn", "keyboardKeyScrollLock": "ScrLk", "keyboardKeySelect": "Velg", "keyboardKeySpace": "Mellomrom", "keyboardKeyMetaMacOs": "Kommando", "keyboardKeyMetaWindows": "Win", "menuBarMenuLabel": "Meny med menylinje", "currentDateLabel": "I dag", "scrimLabel": "Vev", "bottomSheetLabel": "Felt nederst", "scrimOnTapHint": "Lukk $modalRouteContentName", "keyboardKeyShift": "Shift", "expansionTileExpandedHint": "dobbelttrykk for å skjule", "expansionTileCollapsedHint": "dobbelttrykk for å vise", "expansionTileExpandedTapHint": "Skjul", "expansionTileCollapsedTapHint": "Vis for å se mer informasjon", "expandedHint": "Skjules", "collapsedHint": "Vises", "menuDismissLabel": "Lukk menyen", "lookUpButtonLabel": "Slå opp", "searchWebButtonLabel": "Søk på nettet", "shareButtonLabel": "Del…", "clearButtonTooltip": "Clear text", "selectedDateLabel": "Selected" }
flutter/packages/flutter_localizations/lib/src/l10n/material_no.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_no.arb", "repo_id": "flutter", "token_count": 2225 }
334
{ "scriptCategory": "English-like", "timeOfDayFormat": "h:mm a", "openAppDrawerTooltip": "Fungua menyu ya kusogeza", "backButtonTooltip": "Rudi Nyuma", "closeButtonTooltip": "Funga", "deleteButtonTooltip": "Futa", "nextMonthTooltip": "Mwezi ujao", "previousMonthTooltip": "Mwezi uliopita", "nextPageTooltip": "Ukurasa unaofuata", "previousPageTooltip": "Ukurasa uliotangulia", "firstPageTooltip": "Ukurasa wa kwanza", "lastPageTooltip": "Ukurasa wa mwisho", "showMenuTooltip": "Onyesha menyu", "aboutListTileTitle": "Kuhusu $applicationName", "licensesPageTitle": "Leseni", "pageRowsInfoTitle": "$firstRow hadi $lastRow kati ya $rowCount", "pageRowsInfoTitleApproximate": "$firstRow hadi $lastRow kati ya takriban $rowCount", "rowsPerPageTitle": "Safu mlalo kwa kila ukurasa:", "tabLabel": "Kichupo cha $tabIndex kati ya $tabCount", "selectedRowCountTitleZero": "Hamna kilicho chaguliwa", "selectedRowCountTitleOne": "Umechagua kipengee 1", "selectedRowCountTitleOther": "Umechagua vipengee $selectedRowCount", "cancelButtonLabel": "Ghairi", "closeButtonLabel": "Funga", "continueButtonLabel": "Endelea", "copyButtonLabel": "Nakili", "cutButtonLabel": "Kata", "scanTextButtonLabel": "Changanua maandishi", "okButtonLabel": "Sawa", "pasteButtonLabel": "Bandika", "selectAllButtonLabel": "Chagua vyote", "viewLicensesButtonLabel": "Angalia leseni", "anteMeridiemAbbreviation": "AM", "postMeridiemAbbreviation": "PM", "timePickerHourModeAnnouncement": "Chagua saa", "timePickerMinuteModeAnnouncement": "Chagua dakika", "modalBarrierDismissLabel": "Ondoa", "signedInLabel": "Umeingia katika akaunti", "hideAccountsLabel": "Ficha akaunti", "showAccountsLabel": "Onyesha akaunti", "drawerLabel": "Menyu ya kusogeza", "popupMenuLabel": "Menyu ibukizi", "dialogLabel": "Kidirisha", "alertDialogLabel": "Arifa", "searchFieldLabel": "Tafuta", "reorderItemToStart": "Sogeza hadi mwanzo", "reorderItemToEnd": "Sogeza hadi mwisho", "reorderItemUp": "Sogeza juu", "reorderItemDown": "Sogeza chini", "reorderItemLeft": "Sogeza kushoto", "reorderItemRight": "Sogeza kulia", "expandedIconTapHint": "Kunja", "collapsedIconTapHint": "Panua", "remainingTextFieldCharacterCountZero": "Hapana herufi zilizo baki", "remainingTextFieldCharacterCountOne": "Imesalia herufi 1", "remainingTextFieldCharacterCountOther": "Zimesalia herufi $remainingCount", "refreshIndicatorSemanticLabel": "Onyesha upya", "moreButtonTooltip": "Zaidi", "dateSeparator": "/", "dateHelpText": "dd/mm/yyyy", "selectYearSemanticsLabel": "Chagua mwaka", "unspecifiedDate": "Tarehe", "unspecifiedDateRange": "Kipindi", "dateInputLabel": "Weka Tarehe", "dateRangeStartLabel": "Tarehe ya Kuanza", "dateRangeEndLabel": "Tarehe ya Kumalizika", "dateRangeStartDateSemanticLabel": "Tarehe ya kuanza $fullDate", "dateRangeEndDateSemanticLabel": "Tarehe ya kumalizika $fullDate", "invalidDateFormatLabel": "Muundo si sahihi.", "invalidDateRangeLabel": "Kipindi si sahihi.", "dateOutOfRangeLabel": "Umechagua tarehe iliyo nje ya kipindi.", "saveButtonLabel": "Hifadhi", "datePickerHelpText": "Chagua tarehe", "dateRangePickerHelpText": "Chagua kipindi", "calendarModeButtonLabel": "Badili utumie hali ya kalenda", "inputDateModeButtonLabel": "Badili utumie hali ya kuweka maandishi", "timePickerDialHelpText": "Chagua muda", "timePickerInputHelpText": "Weka muda", "timePickerHourLabel": "Saa", "timePickerMinuteLabel": "Dakika", "invalidTimeLabel": "Weka saa sahihi", "dialModeButtonLabel": "Badilisha ili utumie hali ya kiteuzi cha kupiga simu", "inputTimeModeButtonLabel": "Tumia programu ya kuingiza data ya maandishi", "licensesPackageDetailTextZero": "No licenses", "licensesPackageDetailTextOne": "Leseni moja", "licensesPackageDetailTextOther": "Leseni $licenseCount", "keyboardKeyAlt": "Alt", "keyboardKeyAltGraph": "AltGr", "keyboardKeyBackspace": "Backspace", "keyboardKeyCapsLock": "Caps Lock", "keyboardKeyChannelDown": "Channel Down", "keyboardKeyChannelUp": "Channel Up", "keyboardKeyControl": "Ctrl", "keyboardKeyDelete": "Del", "keyboardKeyEject": "Eject", "keyboardKeyEnd": "End", "keyboardKeyEscape": "Esc", "keyboardKeyFn": "Fn", "keyboardKeyHome": "Home", "keyboardKeyInsert": "Insert", "keyboardKeyMeta": "Meta", "keyboardKeyNumLock": "Num Lock", "keyboardKeyNumpad1": "Num 1", "keyboardKeyNumpad2": "Num 2", "keyboardKeyNumpad3": "Num 3", "keyboardKeyNumpad4": "Num 4", "keyboardKeyNumpad5": "Num 5", "keyboardKeyNumpad6": "Num 6", "keyboardKeyNumpad7": "Num 7", "keyboardKeyNumpad8": "Num 8", "keyboardKeyNumpad9": "Num 9", "keyboardKeyNumpad0": "Num 0", "keyboardKeyNumpadAdd": "Num +", "keyboardKeyNumpadComma": "Num ,", "keyboardKeyNumpadDecimal": "Num .", "keyboardKeyNumpadDivide": "Num /", "keyboardKeyNumpadEnter": "Num Enter", "keyboardKeyNumpadEqual": "Num =", "keyboardKeyNumpadMultiply": "Num *", "keyboardKeyNumpadParenLeft": "Num (", "keyboardKeyNumpadParenRight": "Num )", "keyboardKeyNumpadSubtract": "Num -", "keyboardKeyPageDown": "Pg-down", "keyboardKeyPageUp": "PgUp", "keyboardKeyPower": "Power", "keyboardKeyPowerOff": "Power Off", "keyboardKeyPrintScreen": "Print Screen", "keyboardKeyScrollLock": "Scroll Lock", "keyboardKeySelect": "Select", "keyboardKeySpace": "Space", "keyboardKeyMetaMacOs": "Command", "keyboardKeyMetaWindows": "Win", "menuBarMenuLabel": "Menyu ya upau wa menyu", "currentDateLabel": "Leo", "scrimLabel": "Scrim", "bottomSheetLabel": "Safu ya Chini", "scrimOnTapHint": "Funga $modalRouteContentName", "keyboardKeyShift": "Shift", "expansionTileExpandedHint": "gusa mara mbili ili ukunje", "expansionTileCollapsedHint": "gusa mara mbili ili upanue", "expansionTileExpandedTapHint": "Kunja", "expansionTileCollapsedTapHint": "Panua ili upate maelezo zaidi", "expandedHint": "Imekunjwa", "collapsedHint": "Imepanuliwa", "menuDismissLabel": "Ondoa menyu", "lookUpButtonLabel": "Tafuta", "searchWebButtonLabel": "Tafuta kwenye Wavuti", "shareButtonLabel": "Shiriki...", "clearButtonTooltip": "Clear text", "selectedDateLabel": "Selected" }
flutter/packages/flutter_localizations/lib/src/l10n/material_sw.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_sw.arb", "repo_id": "flutter", "token_count": 2407 }
335
{ "reorderItemToStart": "نقل إلى بداية القائمة", "reorderItemToEnd": "نقل إلى نهاية القائمة", "reorderItemUp": "نقل لأعلى", "reorderItemDown": "نقل لأسفل", "reorderItemLeft": "نقل لليمين", "reorderItemRight": "نقل لليسار" }
flutter/packages/flutter_localizations/lib/src/l10n/widgets_ar.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_ar.arb", "repo_id": "flutter", "token_count": 156 }
336
{ "reorderItemToStart": "Ilipat sa simula", "reorderItemToEnd": "Ilipat sa dulo", "reorderItemUp": "Ilipat pataas", "reorderItemDown": "Ilipat pababa", "reorderItemLeft": "Ilipat pakaliwa", "reorderItemRight": "Ilipat pakanan" }
flutter/packages/flutter_localizations/lib/src/l10n/widgets_fil.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_fil.arb", "repo_id": "flutter", "token_count": 103 }
337
{ "reorderItemToStart": "Басына өту", "reorderItemToEnd": "Соңына өту", "reorderItemUp": "Жоғарыға жылжыту", "reorderItemDown": "Төменге жылжыту", "reorderItemLeft": "Солға жылжыту", "reorderItemRight": "Оңға жылжыту" }
flutter/packages/flutter_localizations/lib/src/l10n/widgets_kk.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_kk.arb", "repo_id": "flutter", "token_count": 162 }
338
{ "reorderItemToStart": "Naar het begin verplaatsen", "reorderItemToEnd": "Naar het einde verplaatsen", "reorderItemUp": "Omhoog verplaatsen", "reorderItemDown": "Omlaag verplaatsen", "reorderItemLeft": "Naar links verplaatsen", "reorderItemRight": "Naar rechts verplaatsen" }
flutter/packages/flutter_localizations/lib/src/l10n/widgets_nl.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_nl.arb", "repo_id": "flutter", "token_count": 124 }
339
{ "reorderItemToStart": "Flytta till början", "reorderItemToEnd": "Flytta till slutet", "reorderItemUp": "Flytta uppåt", "reorderItemDown": "Flytta nedåt", "reorderItemLeft": "Flytta åt vänster", "reorderItemRight": "Flytta åt höger" }
flutter/packages/flutter_localizations/lib/src/l10n/widgets_sv.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_sv.arb", "repo_id": "flutter", "token_count": 106 }
340
// Copyright 2014 The Flutter 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:intl/date_symbol_data_custom.dart' as date_symbol_data_custom; import 'package:intl/date_symbols.dart' as intl; import '../l10n/generated_date_localizations.dart' as date_localizations; /// Tracks if date i18n data has been loaded. bool _dateIntlDataInitialized = false; /// Loads i18n data for dates if it hasn't been loaded yet. /// /// Only the first invocation of this function loads the data. Subsequent /// invocations have no effect. void loadDateIntlDataIfNotLoaded() { if (!_dateIntlDataInitialized) { date_localizations.dateSymbols .forEach((String locale, intl.DateSymbols symbols) { // Perform initialization. assert(date_localizations.datePatterns.containsKey(locale)); date_symbol_data_custom.initializeDateFormattingCustom( locale: locale, symbols: symbols, patterns: date_localizations.datePatterns[locale], ); }); _dateIntlDataInitialized = true; } }
flutter/packages/flutter_localizations/lib/src/utils/date_localizations.dart/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/utils/date_localizations.dart", "repo_id": "flutter", "token_count": 396 }
341
// Copyright 2014 The Flutter 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:ui' as ui; import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'package:matcher/expect.dart'; import 'package:matcher/src/expect/async_matcher.dart'; // ignore: implementation_imports import 'package:test_api/hooks.dart' show TestFailure; import 'binding.dart'; import 'finders.dart'; import 'goldens.dart'; /// An unsupported method that exists for API compatibility. Future<ui.Image> captureImage(Element element) { throw UnsupportedError('captureImage is not supported on the web.'); } /// Whether or not [captureImage] is supported. /// /// This can be used to skip tests on platforms that don't support /// capturing images. /// /// Currently this is true except when tests are running in the context of a web /// browser (`flutter test --platform chrome`). const bool canCaptureImage = false; /// The matcher created by [matchesGoldenFile]. This class is enabled when the /// test is running in a web browser using conditional import. class MatchesGoldenFile extends AsyncMatcher { /// Creates an instance of [MatchesGoldenFile]. Called by [matchesGoldenFile]. const MatchesGoldenFile(this.key, this.version); /// Creates an instance of [MatchesGoldenFile]. Called by [matchesGoldenFile]. MatchesGoldenFile.forStringPath(String path, this.version) : key = Uri.parse(path); /// The [key] to the golden image. final Uri key; /// The [version] of the golden image. final int? version; @override Future<String?> matchAsync(dynamic item) async { if (item is! Finder) { return 'web goldens only supports matching finders.'; } final Iterable<Element> elements = item.evaluate(); if (elements.isEmpty) { return 'could not be rendered because no widget was found'; } else if (elements.length > 1) { return 'matched too many widgets'; } final Element element = elements.single; final RenderObject renderObject = _findRepaintBoundary(element); final Size size = renderObject.paintBounds.size; final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.instance; final ui.FlutterView view = binding.platformDispatcher.implicitView!; final RenderView renderView = binding.renderViews.firstWhere((RenderView r) => r.flutterView == view); if (isSkiaWeb) { // In CanvasKit and Skwasm, use Layer.toImage to generate the screenshot. final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.instance; return binding.runAsync<String?>(() async { assert(element.renderObject != null); RenderObject renderObject = element.renderObject!; while (!renderObject.isRepaintBoundary) { renderObject = renderObject.parent!; } assert(!renderObject.debugNeedsPaint); final OffsetLayer layer = renderObject.debugLayer! as OffsetLayer; final ui.Image image = await layer.toImage(renderObject.paintBounds); try { final ByteData? bytes = await image.toByteData(format: ui.ImageByteFormat.png); if (bytes == null) { return 'could not encode screenshot.'; } if (autoUpdateGoldenFiles) { await webGoldenComparator.updateBytes(bytes.buffer.asUint8List(), key); return null; } try { final bool success = await webGoldenComparator.compareBytes(bytes.buffer.asUint8List(), key); return success ? null : 'does not match'; } on TestFailure catch (ex) { return ex.message; } } finally { image.dispose(); } }); } else { // In the HTML renderer, we don't have the ability to render an element // to an image directly. Instead, we will use `window.render()` to render // only the element being requested, and send a request to the test server // requesting it to take a screenshot through the browser's debug interface. _renderElement(view, renderObject); final String? result = await binding.runAsync<String?>(() async { if (autoUpdateGoldenFiles) { await webGoldenComparator.update(size.width, size.height, key); return null; } try { final bool success = await webGoldenComparator.compare(size.width, size.height, key); return success ? null : 'does not match'; } on TestFailure catch (ex) { return ex.message; } }); _renderElement(view, renderView); return result; } } @override Description describe(Description description) { final Uri testNameUri = webGoldenComparator.getTestUri(key, version); return description.add('one widget whose rasterized image matches golden image "$testNameUri"'); } } RenderObject _findRepaintBoundary(Element element) { assert(element.renderObject != null); RenderObject renderObject = element.renderObject!; while (!renderObject.isRepaintBoundary) { renderObject = renderObject.parent!; } return renderObject; } void _renderElement(ui.FlutterView window, RenderObject renderObject) { assert(renderObject.debugLayer != null); final Layer layer = renderObject.debugLayer!; final ui.SceneBuilder sceneBuilder = ui.SceneBuilder(); if (layer is OffsetLayer) { sceneBuilder.pushOffset(-layer.offset.dx, -layer.offset.dy); } // ignore: invalid_use_of_visible_for_testing_member, invalid_use_of_protected_member layer.updateSubtreeNeedsAddToScene(); // ignore: invalid_use_of_protected_member layer.addToScene(sceneBuilder); sceneBuilder.pop(); window.render(sceneBuilder.build()); }
flutter/packages/flutter_test/lib/src/_matchers_web.dart/0
{ "file_path": "flutter/packages/flutter_test/lib/src/_matchers_web.dart", "repo_id": "flutter", "token_count": 1993 }
342
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /// This function can be used to call a const constructor in such a way as to /// create a new instance rather than creating the common const instance. /// /// ```dart /// class A { /// const A(this.i); /// final int? i; /// } /// /// void main () { /// // prevent prefer_const_constructors lint /// A(nonconst(null)); /// /// // prevent prefer_const_declarations lint /// final int? $null = nonconst(null); /// final A a = nonconst(const A(null)); /// } /// ``` T nonconst<T>(T t) => t;
flutter/packages/flutter_test/lib/src/nonconst.dart/0
{ "file_path": "flutter/packages/flutter_test/lib/src/nonconst.dart", "repo_id": "flutter", "token_count": 210 }
343
// Copyright 2014 The Flutter 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:ui' hide window; import 'package:flutter/foundation.dart'; /// Test version of [AccessibilityFeatures] in which specific features may /// be set to arbitrary values. /// /// By default, all features are disabled. For an instance where all the /// features are enabled, consider the [FakeAccessibilityFeatures.allOn] /// constant. @immutable class FakeAccessibilityFeatures implements AccessibilityFeatures { /// Creates a test instance of [AccessibilityFeatures]. /// /// By default, all features are disabled. const FakeAccessibilityFeatures({ this.accessibleNavigation = false, this.invertColors = false, this.disableAnimations = false, this.boldText = false, this.reduceMotion = false, this.highContrast = false, this.onOffSwitchLabels = false, }); /// An instance of [AccessibilityFeatures] where all the features are enabled. static const FakeAccessibilityFeatures allOn = FakeAccessibilityFeatures( accessibleNavigation: true, invertColors: true, disableAnimations: true, boldText: true, reduceMotion: true, highContrast: true, onOffSwitchLabels: true, ); @override final bool accessibleNavigation; @override final bool invertColors; @override final bool disableAnimations; @override final bool boldText; @override final bool reduceMotion; @override final bool highContrast; @override final bool onOffSwitchLabels; @override bool operator ==(Object other) { if (other.runtimeType != runtimeType) { return false; } return other is FakeAccessibilityFeatures && other.accessibleNavigation == accessibleNavigation && other.invertColors == invertColors && other.disableAnimations == disableAnimations && other.boldText == boldText && other.reduceMotion == reduceMotion && other.highContrast == highContrast && other.onOffSwitchLabels == onOffSwitchLabels; } @override int get hashCode { return Object.hash( accessibleNavigation, invertColors, disableAnimations, boldText, reduceMotion, highContrast, onOffSwitchLabels, ); } /// This gives us some grace time when the dart:ui side adds something to /// [AccessibilityFeatures], and makes things easier when we do rolls to /// give us time to catch up. /// /// If you would like to add to this class, changes must first be made in the /// engine, followed by the framework. @override dynamic noSuchMethod(Invocation invocation) { return null; } } /// Used to fake insets and padding for [TestFlutterView]s. /// /// See also: /// /// * [TestFlutterView.padding], [TestFlutterView.systemGestureInsets], /// [TestFlutterView.viewInsets], and [TestFlutterView.viewPadding] for test /// properties that make use of [FakeViewPadding]. @immutable class FakeViewPadding implements ViewPadding { /// Instantiates a new [FakeViewPadding] object for faking insets and padding /// during tests. const FakeViewPadding({ this.left = 0.0, this.top = 0.0, this.right = 0.0, this.bottom = 0.0, }); FakeViewPadding._wrap(ViewPadding base) : left = base.left, top = base.top, right = base.right, bottom = base.bottom; /// A view padding that has zeros for each edge. static const FakeViewPadding zero = FakeViewPadding(); @override final double left; @override final double top; @override final double right; @override final double bottom; } /// [PlatformDispatcher] that wraps another [PlatformDispatcher] and /// allows faking of some properties for testing purposes. /// /// See also: /// /// * [TestFlutterView], which wraps a [FlutterView] for testing and /// mocking purposes. class TestPlatformDispatcher implements PlatformDispatcher { /// Constructs a [TestPlatformDispatcher] that defers all behavior to the given /// [PlatformDispatcher] unless explicitly overridden for test purposes. TestPlatformDispatcher({ required PlatformDispatcher platformDispatcher, }) : _platformDispatcher = platformDispatcher { _updateViewsAndDisplays(); _platformDispatcher.onMetricsChanged = _handleMetricsChanged; _platformDispatcher.onViewFocusChange = _handleViewFocusChanged; } /// The [PlatformDispatcher] that is wrapped by this [TestPlatformDispatcher]. final PlatformDispatcher _platformDispatcher; @override TestFlutterView? get implicitView { return _platformDispatcher.implicitView != null ? _testViews[_platformDispatcher.implicitView!.viewId]! : null; } final Map<int, TestFlutterView> _testViews = <int, TestFlutterView>{}; final Map<int, TestDisplay> _testDisplays = <int, TestDisplay>{}; @override VoidCallback? get onMetricsChanged => _platformDispatcher.onMetricsChanged; VoidCallback? _onMetricsChanged; @override set onMetricsChanged(VoidCallback? callback) { _onMetricsChanged = callback; } void _handleMetricsChanged() { _updateViewsAndDisplays(); _onMetricsChanged?.call(); } @override ViewFocusChangeCallback? get onViewFocusChange => _platformDispatcher.onViewFocusChange; ViewFocusChangeCallback? _onViewFocusChange; @override set onViewFocusChange(ViewFocusChangeCallback? callback) { _onViewFocusChange = callback; } void _handleViewFocusChanged(ViewFocusEvent event) { _updateViewsAndDisplays(); _onViewFocusChange?.call(event); } @override Locale get locale => _localeTestValue ?? _platformDispatcher.locale; Locale? _localeTestValue; /// Hides the real locale and reports the given [localeTestValue] instead. set localeTestValue(Locale localeTestValue) { // ignore: avoid_setters_without_getters _localeTestValue = localeTestValue; onLocaleChanged?.call(); } /// Deletes any existing test locale and returns to using the real locale. void clearLocaleTestValue() { _localeTestValue = null; onLocaleChanged?.call(); } @override List<Locale> get locales => _localesTestValue ?? _platformDispatcher.locales; List<Locale>? _localesTestValue; /// Hides the real locales and reports the given [localesTestValue] instead. set localesTestValue(List<Locale> localesTestValue) { // ignore: avoid_setters_without_getters _localesTestValue = localesTestValue; onLocaleChanged?.call(); } /// Deletes any existing test locales and returns to using the real locales. void clearLocalesTestValue() { _localesTestValue = null; onLocaleChanged?.call(); } @override VoidCallback? get onLocaleChanged => _platformDispatcher.onLocaleChanged; @override set onLocaleChanged(VoidCallback? callback) { _platformDispatcher.onLocaleChanged = callback; } @override String get initialLifecycleState => _initialLifecycleStateTestValue; String _initialLifecycleStateTestValue = ''; /// Sets a faked initialLifecycleState for testing. set initialLifecycleStateTestValue(String state) { // ignore: avoid_setters_without_getters _initialLifecycleStateTestValue = state; } /// Resets [initialLifecycleState] to the default value for the platform. void resetInitialLifecycleState() { _initialLifecycleStateTestValue = ''; } @override double get textScaleFactor => _textScaleFactorTestValue ?? _platformDispatcher.textScaleFactor; double? _textScaleFactorTestValue; /// Hides the real text scale factor and reports the given /// [textScaleFactorTestValue] instead. set textScaleFactorTestValue(double textScaleFactorTestValue) { // ignore: avoid_setters_without_getters _textScaleFactorTestValue = textScaleFactorTestValue; onTextScaleFactorChanged?.call(); } /// Deletes any existing test text scale factor and returns to using the real /// text scale factor. void clearTextScaleFactorTestValue() { _textScaleFactorTestValue = null; onTextScaleFactorChanged?.call(); } @override Brightness get platformBrightness => _platformBrightnessTestValue ?? _platformDispatcher.platformBrightness; Brightness? _platformBrightnessTestValue; @override VoidCallback? get onPlatformBrightnessChanged => _platformDispatcher.onPlatformBrightnessChanged; @override set onPlatformBrightnessChanged(VoidCallback? callback) { _platformDispatcher.onPlatformBrightnessChanged = callback; } /// Hides the real platform brightness and reports the given /// [platformBrightnessTestValue] instead. set platformBrightnessTestValue(Brightness platformBrightnessTestValue) { // ignore: avoid_setters_without_getters _platformBrightnessTestValue = platformBrightnessTestValue; onPlatformBrightnessChanged?.call(); } /// Deletes any existing test platform brightness and returns to using the /// real platform brightness. void clearPlatformBrightnessTestValue() { _platformBrightnessTestValue = null; onPlatformBrightnessChanged?.call(); } @override bool get alwaysUse24HourFormat => _alwaysUse24HourFormatTestValue ?? _platformDispatcher.alwaysUse24HourFormat; bool? _alwaysUse24HourFormatTestValue; /// Hides the real clock format and reports the given /// [alwaysUse24HourFormatTestValue] instead. set alwaysUse24HourFormatTestValue(bool alwaysUse24HourFormatTestValue) { // ignore: avoid_setters_without_getters _alwaysUse24HourFormatTestValue = alwaysUse24HourFormatTestValue; } /// Deletes any existing test clock format and returns to using the real clock /// format. void clearAlwaysUse24HourTestValue() { _alwaysUse24HourFormatTestValue = null; } @override VoidCallback? get onTextScaleFactorChanged => _platformDispatcher.onTextScaleFactorChanged; @override set onTextScaleFactorChanged(VoidCallback? callback) { _platformDispatcher.onTextScaleFactorChanged = callback; } @override bool get nativeSpellCheckServiceDefined => _nativeSpellCheckServiceDefinedTestValue ?? _platformDispatcher.nativeSpellCheckServiceDefined; bool? _nativeSpellCheckServiceDefinedTestValue; set nativeSpellCheckServiceDefinedTestValue(bool nativeSpellCheckServiceDefinedTestValue) { // ignore: avoid_setters_without_getters _nativeSpellCheckServiceDefinedTestValue = nativeSpellCheckServiceDefinedTestValue; } /// Deletes existing value that determines whether or not a native spell check /// service is defined and returns to the real value. void clearNativeSpellCheckServiceDefined() { _nativeSpellCheckServiceDefinedTestValue = null; } @override bool get supportsShowingSystemContextMenu => _supportsShowingSystemContextMenu ?? _platformDispatcher.supportsShowingSystemContextMenu; bool? _supportsShowingSystemContextMenu; set supportsShowingSystemContextMenu(bool value) { // ignore: avoid_setters_without_getters _supportsShowingSystemContextMenu = value; } /// Resets [supportsShowingSystemContextMenu] to the default value. void resetSupportsShowingSystemContextMenu() { _supportsShowingSystemContextMenu = null; } @override bool get brieflyShowPassword => _brieflyShowPasswordTestValue ?? _platformDispatcher.brieflyShowPassword; bool? _brieflyShowPasswordTestValue; /// Hides the real [brieflyShowPassword] and reports the given /// `brieflyShowPasswordTestValue` instead. set brieflyShowPasswordTestValue(bool brieflyShowPasswordTestValue) { // ignore: avoid_setters_without_getters _brieflyShowPasswordTestValue = brieflyShowPasswordTestValue; } /// Resets [brieflyShowPassword] to the default value for the platform. void resetBrieflyShowPassword() { _brieflyShowPasswordTestValue = null; } @override FrameCallback? get onBeginFrame => _platformDispatcher.onBeginFrame; @override set onBeginFrame(FrameCallback? callback) { _platformDispatcher.onBeginFrame = callback; } @override VoidCallback? get onDrawFrame => _platformDispatcher.onDrawFrame; @override set onDrawFrame(VoidCallback? callback) { _platformDispatcher.onDrawFrame = callback; } @override TimingsCallback? get onReportTimings => _platformDispatcher.onReportTimings; @override set onReportTimings(TimingsCallback? callback) { _platformDispatcher.onReportTimings = callback; } @override PointerDataPacketCallback? get onPointerDataPacket => _platformDispatcher.onPointerDataPacket; @override set onPointerDataPacket(PointerDataPacketCallback? callback) { _platformDispatcher.onPointerDataPacket = callback; } @override String get defaultRouteName => _defaultRouteNameTestValue ?? _platformDispatcher.defaultRouteName; String? _defaultRouteNameTestValue; /// Hides the real default route name and reports the given /// [defaultRouteNameTestValue] instead. set defaultRouteNameTestValue(String defaultRouteNameTestValue) { // ignore: avoid_setters_without_getters _defaultRouteNameTestValue = defaultRouteNameTestValue; } /// Deletes any existing test default route name and returns to using the real /// default route name. void clearDefaultRouteNameTestValue() { _defaultRouteNameTestValue = null; } @override void scheduleFrame() { _platformDispatcher.scheduleFrame(); } @override bool get semanticsEnabled => _semanticsEnabledTestValue ?? _platformDispatcher.semanticsEnabled; bool? _semanticsEnabledTestValue; /// Hides the real semantics enabled and reports the given /// [semanticsEnabledTestValue] instead. set semanticsEnabledTestValue(bool semanticsEnabledTestValue) { // ignore: avoid_setters_without_getters _semanticsEnabledTestValue = semanticsEnabledTestValue; onSemanticsEnabledChanged?.call(); } /// Deletes any existing test semantics enabled and returns to using the real /// semantics enabled. void clearSemanticsEnabledTestValue() { _semanticsEnabledTestValue = null; onSemanticsEnabledChanged?.call(); } @override VoidCallback? get onSemanticsEnabledChanged => _platformDispatcher.onSemanticsEnabledChanged; @override set onSemanticsEnabledChanged(VoidCallback? callback) { _platformDispatcher.onSemanticsEnabledChanged = callback; } @override SemanticsActionEventCallback? get onSemanticsActionEvent => _platformDispatcher.onSemanticsActionEvent; @override set onSemanticsActionEvent(SemanticsActionEventCallback? callback) { _platformDispatcher.onSemanticsActionEvent = callback; } @override AccessibilityFeatures get accessibilityFeatures => _accessibilityFeaturesTestValue ?? _platformDispatcher.accessibilityFeatures; AccessibilityFeatures? _accessibilityFeaturesTestValue; /// Hides the real accessibility features and reports the given /// [accessibilityFeaturesTestValue] instead. /// /// Consider using [FakeAccessibilityFeatures] to provide specific /// values for the various accessibility features under test. set accessibilityFeaturesTestValue(AccessibilityFeatures accessibilityFeaturesTestValue) { // ignore: avoid_setters_without_getters _accessibilityFeaturesTestValue = accessibilityFeaturesTestValue; onAccessibilityFeaturesChanged?.call(); } /// Deletes any existing test accessibility features and returns to using the /// real accessibility features. void clearAccessibilityFeaturesTestValue() { _accessibilityFeaturesTestValue = null; onAccessibilityFeaturesChanged?.call(); } @override VoidCallback? get onAccessibilityFeaturesChanged => _platformDispatcher.onAccessibilityFeaturesChanged; @override set onAccessibilityFeaturesChanged(VoidCallback? callback) { _platformDispatcher.onAccessibilityFeaturesChanged = callback; } @override void setIsolateDebugName(String name) { _platformDispatcher.setIsolateDebugName(name); } @override void sendPlatformMessage( String name, ByteData? data, PlatformMessageResponseCallback? callback, ) { _platformDispatcher.sendPlatformMessage(name, data, callback); } /// Delete any test value properties that have been set on this [TestPlatformDispatcher] /// and return to reporting the real [PlatformDispatcher] values for all /// [PlatformDispatcher] properties. /// /// If desired, clearing of properties can be done on an individual basis, /// e.g., [clearLocaleTestValue]. void clearAllTestValues() { clearAccessibilityFeaturesTestValue(); clearAlwaysUse24HourTestValue(); clearDefaultRouteNameTestValue(); clearPlatformBrightnessTestValue(); clearLocaleTestValue(); clearLocalesTestValue(); clearSemanticsEnabledTestValue(); clearTextScaleFactorTestValue(); clearNativeSpellCheckServiceDefined(); resetBrieflyShowPassword(); resetSupportsShowingSystemContextMenu(); resetInitialLifecycleState(); resetSystemFontFamily(); } @override VoidCallback? get onFrameDataChanged => _platformDispatcher.onFrameDataChanged; @override set onFrameDataChanged(VoidCallback? value) { _platformDispatcher.onFrameDataChanged = value; } @override KeyDataCallback? get onKeyData => _platformDispatcher.onKeyData; @override set onKeyData(KeyDataCallback? onKeyData) { _platformDispatcher.onKeyData = onKeyData; } @override VoidCallback? get onPlatformConfigurationChanged => _platformDispatcher.onPlatformConfigurationChanged; @override set onPlatformConfigurationChanged(VoidCallback? onPlatformConfigurationChanged) { _platformDispatcher.onPlatformConfigurationChanged = onPlatformConfigurationChanged; } @override Locale? computePlatformResolvedLocale(List<Locale> supportedLocales) => _platformDispatcher.computePlatformResolvedLocale(supportedLocales); @override ByteData? getPersistentIsolateData() => _platformDispatcher.getPersistentIsolateData(); @override Iterable<TestFlutterView> get views => _testViews.values; @override FlutterView? view({required int id}) => _testViews[id]; @override Iterable<TestDisplay> get displays => _testDisplays.values; void _updateViewsAndDisplays() { final List<Object> extraDisplayKeys = <Object>[..._testDisplays.keys]; for (final Display display in _platformDispatcher.displays) { extraDisplayKeys.remove(display.id); if (!_testDisplays.containsKey(display.id)) { _testDisplays[display.id] = TestDisplay(this, display); } } extraDisplayKeys.forEach(_testDisplays.remove); final List<Object> extraViewKeys = <Object>[..._testViews.keys]; for (final FlutterView view in _platformDispatcher.views) { // TODO(pdblasi-google): Remove this try-catch once the Display API is stable and supported on all platforms late final TestDisplay display; try { final Display realDisplay = view.display; if (_testDisplays.containsKey(realDisplay.id)) { display = _testDisplays[view.display.id]!; } else { display = _UnsupportedDisplay( this, view, 'PlatformDispatcher did not contain a Display with id ${realDisplay.id}, ' 'which was expected by FlutterView ($view)', ); } } catch (error){ display = _UnsupportedDisplay(this, view, error); } extraViewKeys.remove(view.viewId); if (!_testViews.containsKey(view.viewId)) { _testViews[view.viewId] = TestFlutterView( view: view, platformDispatcher: this, display: display, ); } } extraViewKeys.forEach(_testViews.remove); } @override ErrorCallback? get onError => _platformDispatcher.onError; @override set onError(ErrorCallback? value) { _platformDispatcher.onError; } @override VoidCallback? get onSystemFontFamilyChanged => _platformDispatcher.onSystemFontFamilyChanged; @override set onSystemFontFamilyChanged(VoidCallback? value) { _platformDispatcher.onSystemFontFamilyChanged = value; } @override FrameData get frameData => _platformDispatcher.frameData; @override void registerBackgroundIsolate(RootIsolateToken token) { _platformDispatcher.registerBackgroundIsolate(token); } @override void requestDartPerformanceMode(DartPerformanceMode mode) { _platformDispatcher.requestDartPerformanceMode(mode); } /// The system font family to use for this test. /// /// Defaults to the value provided by [PlatformDispatcher.systemFontFamily]. /// This can only be set in a test environment to emulate different platform /// configurations. A standard [PlatformDispatcher] is not mutable from the /// framework. /// /// Setting this value to `null` will force [systemFontFamily] to return /// `null`. If you want to have the value default to the platform /// [systemFontFamily], use [resetSystemFontFamily]. /// /// See also: /// /// * [PlatformDispatcher.systemFontFamily] for the standard implementation /// * [resetSystemFontFamily] to reset this value specifically /// * [clearAllTestValues] to reset all test values for this view @override String? get systemFontFamily { return _forceSystemFontFamilyToBeNull ? null : _systemFontFamily ?? _platformDispatcher.systemFontFamily; } String? _systemFontFamily; bool _forceSystemFontFamilyToBeNull = false; set systemFontFamily(String? value) { _systemFontFamily = value; if (value == null) { _forceSystemFontFamilyToBeNull = true; } onSystemFontFamilyChanged?.call(); } /// Resets [systemFontFamily] to the default for the platform. void resetSystemFontFamily() { _systemFontFamily = null; _forceSystemFontFamilyToBeNull = false; onSystemFontFamilyChanged?.call(); } @override void updateSemantics(SemanticsUpdate update) { _platformDispatcher.updateSemantics(update); } /// This gives us some grace time when the dart:ui side adds something to /// [PlatformDispatcher], and makes things easier when we do rolls to give /// us time to catch up. @override dynamic noSuchMethod(Invocation invocation) { return null; } } /// A [FlutterView] that wraps another [FlutterView] and allows faking of /// some properties for testing purposes. /// /// This class should not be instantiated manually, as /// it requires a backing [FlutterView] that must be produced from /// a [PlatformDispatcher]. /// /// See also: /// /// * [WidgetTester.view] which allows for accessing the [TestFlutterView] /// for single view applications or widget testing. /// * [WidgetTester.viewOf] which allows for accessing the appropriate /// [TestFlutterView] in a given situation for multi-view applications. /// * [TestPlatformDispatcher], which allows for faking of platform specific /// functionality. class TestFlutterView implements FlutterView { /// Constructs a [TestFlutterView] that defers all behavior to the given /// [FlutterView] unless explicitly overridden for testing. TestFlutterView({ required FlutterView view, required TestPlatformDispatcher platformDispatcher, required TestDisplay display, }) : _view = view, _platformDispatcher = platformDispatcher, _display = display; /// The [FlutterView] backing this [TestFlutterView]. final FlutterView _view; @override TestPlatformDispatcher get platformDispatcher => _platformDispatcher; final TestPlatformDispatcher _platformDispatcher; @override TestDisplay get display => _display; final TestDisplay _display; @override int get viewId => _view.viewId; /// The device pixel ratio to use for this test. /// /// Defaults to the value provided by [FlutterView.devicePixelRatio]. This /// can only be set in a test environment to emulate different view /// configurations. A standard [FlutterView] is not mutable from the framework. /// /// See also: /// /// * [FlutterView.devicePixelRatio] for the standard implementation /// * [TestDisplay.devicePixelRatio] which will stay in sync with this value /// * [resetDevicePixelRatio] to reset this value specifically /// * [reset] to reset all test values for this view @override double get devicePixelRatio => _display._devicePixelRatio ?? _view.devicePixelRatio; set devicePixelRatio(double value) { _display.devicePixelRatio = value; } /// Resets [devicePixelRatio] for this test view to the default value for this view. /// /// This will also reset the [devicePixelRatio] for the [TestDisplay] /// that is related to this view. void resetDevicePixelRatio() { _display.resetDevicePixelRatio(); } /// The display features to use for this test. /// /// Defaults to the value provided by [FlutterView.displayFeatures]. This /// can only be set in a test environment to emulate different view /// configurations. A standard [FlutterView] is not mutable from the framework. /// /// See also: /// /// * [FlutterView.displayFeatures] for the standard implementation /// * [resetDisplayFeatures] to reset this value specifically /// * [reset] to reset all test values for this view @override List<DisplayFeature> get displayFeatures => _displayFeatures ?? _view.displayFeatures; List<DisplayFeature>? _displayFeatures; set displayFeatures(List<DisplayFeature> value) { _displayFeatures = value; platformDispatcher.onMetricsChanged?.call(); } /// Resets [displayFeatures] to the default values for this view. void resetDisplayFeatures() { _displayFeatures = null; platformDispatcher.onMetricsChanged?.call(); } /// The padding to use for this test. /// /// Defaults to the value provided by [FlutterView.padding]. This /// can only be set in a test environment to emulate different view /// configurations. A standard [FlutterView] is not mutable from the framework. /// /// See also: /// /// * [FakeViewPadding] which is used to set this value for testing /// * [FlutterView.padding] for the standard implementation. /// * [resetPadding] to reset this value specifically. /// * [reset] to reset all test values for this view. @override FakeViewPadding get padding => _padding ?? FakeViewPadding._wrap(_view.padding); FakeViewPadding? _padding; set padding(FakeViewPadding value) { _padding = value; platformDispatcher.onMetricsChanged?.call(); } /// Resets [padding] to the default value for this view. void resetPadding() { _padding = null; platformDispatcher.onMetricsChanged?.call(); } /// The physical size to use for this test. /// /// Defaults to the value provided by [FlutterView.physicalSize]. This /// can only be set in a test environment to emulate different view /// configurations. A standard [FlutterView] is not mutable from the framework. /// /// Setting this value also sets [physicalConstraints] to tight constraints /// based on the given size. /// /// See also: /// /// * [FlutterView.physicalSize] for the standard implementation /// * [resetPhysicalSize] to reset this value specifically /// * [reset] to reset all test values for this view @override Size get physicalSize => _physicalSize ?? _view.physicalSize; Size? _physicalSize; set physicalSize(Size value) { _physicalSize = value; // For backwards compatibility the constraints are set based on the provided size. physicalConstraints = ViewConstraints.tight(value); } /// Resets [physicalSize] (and implicitly also the [physicalConstraints]) to /// the default value for this view. void resetPhysicalSize() { _physicalSize = null; resetPhysicalConstraints(); } /// The physical constraints to use for this test. /// /// Defaults to the value provided by [FlutterView.physicalConstraints]. This /// can only be set in a test environment to emulate different view /// configurations. A standard [FlutterView] is not mutable from the framework. /// /// See also: /// /// * [FlutterView.physicalConstraints] for the standard implementation /// * [physicalConstraints] to reset this value specifically /// * [reset] to reset all test values for this view @override ViewConstraints get physicalConstraints => _physicalConstraints ?? _view.physicalConstraints; ViewConstraints? _physicalConstraints; set physicalConstraints(ViewConstraints value) { _physicalConstraints = value; platformDispatcher.onMetricsChanged?.call(); } /// Resets [physicalConstraints] to the default value for this view. void resetPhysicalConstraints() { _physicalConstraints = null; platformDispatcher.onMetricsChanged?.call(); } /// The system gesture insets to use for this test. /// /// Defaults to the value provided by [FlutterView.systemGestureInsets]. /// This can only be set in a test environment to emulate different view /// configurations. A standard [FlutterView] is not mutable from the framework. /// /// See also: /// /// * [FakeViewPadding] which is used to set this value for testing /// * [FlutterView.systemGestureInsets] for the standard implementation /// * [resetSystemGestureInsets] to reset this value specifically /// * [reset] to reset all test values for this view @override FakeViewPadding get systemGestureInsets => _systemGestureInsets ?? FakeViewPadding._wrap(_view.systemGestureInsets); FakeViewPadding? _systemGestureInsets; set systemGestureInsets(FakeViewPadding value) { _systemGestureInsets = value; platformDispatcher.onMetricsChanged?.call(); } /// Resets [systemGestureInsets] to the default value for this view. void resetSystemGestureInsets() { _systemGestureInsets = null; platformDispatcher.onMetricsChanged?.call(); } /// The view insets to use for this test. /// /// Defaults to the value provided by [FlutterView.viewInsets]. This /// can only be set in a test environment to emulate different view /// configurations. A standard [FlutterView] is not mutable from the framework. /// /// See also: /// /// * [FakeViewPadding] which is used to set this value for testing /// * [FlutterView.viewInsets] for the standard implementation /// * [resetViewInsets] to reset this value specifically /// * [reset] to reset all test values for this view @override FakeViewPadding get viewInsets => _viewInsets ?? FakeViewPadding._wrap(_view.viewInsets); FakeViewPadding? _viewInsets; set viewInsets(FakeViewPadding value) { _viewInsets = value; platformDispatcher.onMetricsChanged?.call(); } /// Resets [viewInsets] to the default value for this view. void resetViewInsets() { _viewInsets = null; platformDispatcher.onMetricsChanged?.call(); } /// The view padding to use for this test. /// /// Defaults to the value provided by [FlutterView.viewPadding]. This /// can only be set in a test environment to emulate different view /// configurations. A standard [FlutterView] is not mutable from the framework. /// /// See also: /// /// * [FakeViewPadding] which is used to set this value for testing /// * [FlutterView.viewPadding] for the standard implementation /// * [resetViewPadding] to reset this value specifically /// * [reset] to reset all test values for this view @override FakeViewPadding get viewPadding => _viewPadding ?? FakeViewPadding._wrap(_view.viewPadding); FakeViewPadding? _viewPadding; set viewPadding(FakeViewPadding value) { _viewPadding = value; platformDispatcher.onMetricsChanged?.call(); } /// Resets [viewPadding] to the default value for this view. void resetViewPadding() { _viewPadding = null; platformDispatcher.onMetricsChanged?.call(); } /// The gesture settings to use for this test. /// /// Defaults to the value provided by [FlutterView.gestureSettings]. This /// can only be set in a test environment to emulate different view /// configurations. A standard [FlutterView] is not mutable from the framework. /// /// See also: /// /// * [FlutterView.gestureSettings] for the standard implementation /// * [resetGestureSettings] to reset this value specifically /// * [reset] to reset all test values for this view @override GestureSettings get gestureSettings => _gestureSettings ?? _view.gestureSettings; GestureSettings? _gestureSettings; set gestureSettings(GestureSettings value) { _gestureSettings = value; platformDispatcher.onMetricsChanged?.call(); } /// Resets [gestureSettings] to the default value for this view. void resetGestureSettings() { _gestureSettings = null; platformDispatcher.onMetricsChanged?.call(); } @override void render(Scene scene, {Size? size}) { _view.render(scene, size: size); } @override void updateSemantics(SemanticsUpdate update) { _view.updateSemantics(update); } /// Resets all test values to the defaults for this view. /// /// See also: /// /// * [resetDevicePixelRatio] to reset [devicePixelRatio] specifically /// * [resetDisplayFeatures] to reset [displayFeatures] specifically /// * [resetPadding] to reset [padding] specifically /// * [resetPhysicalSize] to reset [physicalSize] specifically /// * [resetSystemGestureInsets] to reset [systemGestureInsets] specifically /// * [resetViewInsets] to reset [viewInsets] specifically /// * [resetViewPadding] to reset [viewPadding] specifically /// * [resetGestureSettings] to reset [gestureSettings] specifically void reset() { resetDevicePixelRatio(); resetDisplayFeatures(); resetPadding(); resetPhysicalSize(); // resetPhysicalConstraints is implicitly called by resetPhysicalSize. resetSystemGestureInsets(); resetViewInsets(); resetViewPadding(); resetGestureSettings(); } /// This gives us some grace time when the dart:ui side adds something to /// [FlutterView], and makes things easier when we do rolls to give /// us time to catch up. @override dynamic noSuchMethod(Invocation invocation) { return null; } } /// A version of [Display] that can be modified to allow for testing various /// use cases. /// /// Updates to the [TestDisplay] will be surfaced through /// [PlatformDispatcher.onMetricsChanged]. class TestDisplay implements Display { /// Creates a new [TestDisplay] backed by the given [Display]. TestDisplay(TestPlatformDispatcher platformDispatcher, Display display) : _platformDispatcher = platformDispatcher, _display = display; final Display _display; final TestPlatformDispatcher _platformDispatcher; @override int get id => _display.id; /// The device pixel ratio to use for this test. /// /// Defaults to the value provided by [Display.devicePixelRatio]. This /// can only be set in a test environment to emulate different display /// configurations. A standard [Display] is not mutable from the framework. /// /// See also: /// /// * [Display.devicePixelRatio] for the standard implementation /// * [TestFlutterView.devicePixelRatio] which will stay in sync with this value /// * [resetDevicePixelRatio] to reset this value specifically /// * [reset] to reset all test values for this display @override double get devicePixelRatio => _devicePixelRatio ?? _display.devicePixelRatio; double? _devicePixelRatio; set devicePixelRatio(double value) { _devicePixelRatio = value; _platformDispatcher.onMetricsChanged?.call(); } /// Resets [devicePixelRatio] to the default value for this display. /// /// This will also reset the [devicePixelRatio] for any [TestFlutterView]s /// that are related to this display. void resetDevicePixelRatio() { _devicePixelRatio = null; _platformDispatcher.onMetricsChanged?.call(); } /// The refresh rate to use for this test. /// /// Defaults to the value provided by [Display.refreshRate]. This /// can only be set in a test environment to emulate different display /// configurations. A standard [Display] is not mutable from the framework. /// /// See also: /// /// * [Display.refreshRate] for the standard implementation /// * [resetRefreshRate] to reset this value specifically /// * [reset] to reset all test values for this display @override double get refreshRate => _refreshRate ?? _display.refreshRate; double? _refreshRate; set refreshRate(double value) { _refreshRate = value; _platformDispatcher.onMetricsChanged?.call(); } /// Resets [refreshRate] to the default value for this display. void resetRefreshRate() { _refreshRate = null; _platformDispatcher.onMetricsChanged?.call(); } /// The size of the [Display] to use for this test. /// /// Defaults to the value provided by [Display.refreshRate]. This /// can only be set in a test environment to emulate different display /// configurations. A standard [Display] is not mutable from the framework. /// /// See also: /// /// * [Display.refreshRate] for the standard implementation /// * [resetRefreshRate] to reset this value specifically /// * [reset] to reset all test values for this display @override Size get size => _size ?? _display.size; Size? _size; set size(Size value) { _size = value; _platformDispatcher.onMetricsChanged?.call(); } /// Resets [size] to the default value for this display. void resetSize() { _size = null; _platformDispatcher.onMetricsChanged?.call(); } /// Resets all values on this [TestDisplay]. /// /// See also: /// * [resetDevicePixelRatio] to reset [devicePixelRatio] specifically /// * [resetRefreshRate] to reset [refreshRate] specifically /// * [resetSize] to reset [size] specifically void reset() { resetDevicePixelRatio(); resetRefreshRate(); resetSize(); } /// This gives us some grace time when the dart:ui side adds something to /// [Display], and makes things easier when we do rolls to give /// us time to catch up. @override dynamic noSuchMethod(Invocation invocation) { return null; } } // TODO(pdblasi-google): Remove this once the Display API is stable and supported on all platforms class _UnsupportedDisplay implements TestDisplay { _UnsupportedDisplay(this._platformDispatcher, this._view, this.error); final FlutterView _view; final Object? error; @override final TestPlatformDispatcher _platformDispatcher; @override double get devicePixelRatio => _devicePixelRatio ?? _view.devicePixelRatio; @override double? _devicePixelRatio; @override set devicePixelRatio(double value) { _devicePixelRatio = value; _platformDispatcher.onMetricsChanged?.call(); } @override void resetDevicePixelRatio() { _devicePixelRatio = null; _platformDispatcher.onMetricsChanged?.call(); } @override dynamic noSuchMethod(Invocation invocation) { throw UnsupportedError( 'The Display API is unsupported in this context. ' 'As of the last metrics change on PlatformDispatcher, this was the error ' 'given when trying to prepare the display for testing: $error', ); } } /// Deprecated. Will be removed in a future version of Flutter. /// /// This class has been deprecated to prepare for Flutter's upcoming support /// for multiple views and multiple windows. /// /// [SingletonFlutterWindow] that wraps another [SingletonFlutterWindow] and /// allows faking of some properties for testing purposes. /// /// Tests for certain widgets, e.g., [MaterialApp], might require faking certain /// properties of a [SingletonFlutterWindow]. [TestWindow] facilitates the /// faking of these properties by overriding the properties of a real /// [SingletonFlutterWindow] with desired fake values. The binding used within /// tests, [TestWidgetsFlutterBinding], contains a [TestWindow] that is used by /// all tests. /// /// ## Sample Code /// /// A test can utilize a [TestWindow] in the following way: /// /// ```dart /// testWidgets('your test name here', (WidgetTester tester) async { /// // Retrieve the TestWidgetsFlutterBinding. /// final TestWidgetsFlutterBinding testBinding = tester.binding; /// /// // Fake the desired properties of the TestWindow. All code running /// // within this test will perceive the following fake text scale /// // factor as the real text scale factor of the window. /// testBinding.platformDispatcher.textScaleFactorTestValue = 2.5; /// /// // Test code that depends on text scale factor here. /// }); /// ``` /// /// The [TestWidgetsFlutterBinding] is recreated for each test and /// therefore any fake values defined in one test will not persist /// to the next. /// /// If a test needs to override a real [SingletonFlutterWindow] property and /// then later return to using the real [SingletonFlutterWindow] property, /// [TestWindow] provides methods to clear each individual test value, e.g., /// [clearDevicePixelRatioTestValue]. /// /// To clear all fake test values in a [TestWindow], consider using /// [clearAllTestValues]. /// /// See also: /// /// * [TestPlatformDispatcher], which wraps a [PlatformDispatcher] for /// testing purposes and is used by the [platformDispatcher] property of /// this class. @Deprecated( 'Use TestPlatformDispatcher (via WidgetTester.platformDispatcher) or TestFlutterView (via WidgetTester.view) instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) class TestWindow implements SingletonFlutterWindow { /// Constructs a [TestWindow] that defers all behavior to the given /// [SingletonFlutterWindow] unless explicitly overridden for test purposes. @Deprecated( 'Use TestPlatformDispatcher (via WidgetTester.platformDispatcher) or TestFlutterView (via WidgetTester.view) instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) TestWindow({ required SingletonFlutterWindow window, }) : platformDispatcher = TestPlatformDispatcher(platformDispatcher: window.platformDispatcher); /// Constructs a [TestWindow] that defers all behavior to the given /// [TestPlatformDispatcher] and its [TestPlatformDispatcher.implicitView]. /// /// This class will not work when multiple views are present. If multiple view /// support is needed use [WidgetTester.platformDispatcher] and /// [WidgetTester.viewOf]. /// /// See also: /// /// * [TestPlatformDispatcher] which allows faking of platform-wide values for /// testing purposes. /// * [TestFlutterView] which allows faking of view-specific values for /// testing purposes. @Deprecated( 'Use TestPlatformDispatcher (via WidgetTester.platformDispatcher) or TestFlutterView (via WidgetTester.view) instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) TestWindow.fromPlatformDispatcher({ @Deprecated( 'Use WidgetTester.platformDispatcher instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) required this.platformDispatcher, }); @Deprecated( 'Use WidgetTester.platformDispatcher instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override final TestPlatformDispatcher platformDispatcher; TestFlutterView get _view => platformDispatcher.implicitView!; @Deprecated( 'Use WidgetTester.view.devicePixelRatio instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override double get devicePixelRatio => _view.devicePixelRatio; /// Hides the real device pixel ratio and reports the given [devicePixelRatio] /// instead. @Deprecated( 'Use WidgetTester.view.devicePixelRatio instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) set devicePixelRatioTestValue(double devicePixelRatio) { // ignore: avoid_setters_without_getters _view.devicePixelRatio = devicePixelRatio; } /// Deletes any existing test device pixel ratio and returns to using the real /// device pixel ratio. @Deprecated( 'Use WidgetTester.view.resetDevicePixelRatio() instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) void clearDevicePixelRatioTestValue() { _view.resetDevicePixelRatio(); } @Deprecated( 'Use WidgetTester.view.physicalSize instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override Size get physicalSize => _view.physicalSize; /// Hides the real physical size and reports the given [physicalSizeTestValue] /// instead. @Deprecated( 'Use WidgetTester.view.physicalSize instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) set physicalSizeTestValue (Size physicalSizeTestValue) { // ignore: avoid_setters_without_getters _view.physicalSize = physicalSizeTestValue; } /// Deletes any existing test physical size and returns to using the real /// physical size. @Deprecated( 'Use WidgetTester.view.resetPhysicalSize() instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) void clearPhysicalSizeTestValue() { _view.resetPhysicalSize(); } @Deprecated( 'Use WidgetTester.view.viewInsets instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override ViewPadding get viewInsets => _view.viewInsets; /// Hides the real view insets and reports the given [viewInsetsTestValue] /// instead. /// /// Use [FakeViewPadding] to set this value for testing. @Deprecated( 'Use WidgetTester.view.viewInsets instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) set viewInsetsTestValue(ViewPadding value) { // ignore: avoid_setters_without_getters _view.viewInsets = value is FakeViewPadding ? value : FakeViewPadding._wrap(value); } /// Deletes any existing test view insets and returns to using the real view /// insets. @Deprecated( 'Use WidgetTester.view.resetViewInsets() instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) void clearViewInsetsTestValue() { _view.resetViewInsets(); } @Deprecated( 'Use WidgetTester.view.viewPadding instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override ViewPadding get viewPadding => _view.viewPadding; /// Hides the real view padding and reports the given [paddingTestValue] /// instead. /// /// Use [FakeViewPadding] to set this value for testing. @Deprecated( 'Use WidgetTester.view.viewPadding instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) set viewPaddingTestValue(ViewPadding value) { // ignore: avoid_setters_without_getters _view.viewPadding = value is FakeViewPadding ? value : FakeViewPadding._wrap(value); } /// Deletes any existing test view padding and returns to using the real /// viewPadding. @Deprecated( 'Use WidgetTester.view.resetViewPadding() instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) void clearViewPaddingTestValue() { _view.resetViewPadding(); } @Deprecated( 'Use WidgetTester.view.padding instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override ViewPadding get padding => _view.padding; /// Hides the real padding and reports the given [paddingTestValue] instead. /// /// Use [FakeViewPadding] to set this value for testing. @Deprecated( 'Use WidgetTester.view.padding instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) set paddingTestValue(ViewPadding value) { // ignore: avoid_setters_without_getters _view.padding = value is FakeViewPadding ? value : FakeViewPadding._wrap(value); } /// Deletes any existing test padding and returns to using the real padding. @Deprecated( 'Use WidgetTester.view.resetPadding() instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) void clearPaddingTestValue() { _view.resetPadding(); } @Deprecated( 'Use WidgetTester.view.gestureSettings instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override GestureSettings get gestureSettings => _view.gestureSettings; /// Hides the real gesture settings and reports the given [gestureSettingsTestValue] instead. @Deprecated( 'Use WidgetTester.view.gestureSettings instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) set gestureSettingsTestValue(GestureSettings gestureSettingsTestValue) { // ignore: avoid_setters_without_getters _view.gestureSettings = gestureSettingsTestValue; } /// Deletes any existing test gesture settings and returns to using the real gesture settings. @Deprecated( 'Use WidgetTester.view.resetGestureSettings() instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) void clearGestureSettingsTestValue() { _view.resetGestureSettings(); } @Deprecated( 'Use WidgetTester.view.displayFeatures instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override List<DisplayFeature> get displayFeatures => _view.displayFeatures; /// Hides the real displayFeatures and reports the given [displayFeaturesTestValue] instead. @Deprecated( 'Use WidgetTester.view.displayFeatures instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) set displayFeaturesTestValue(List<DisplayFeature> displayFeaturesTestValue) { // ignore: avoid_setters_without_getters _view.displayFeatures = displayFeaturesTestValue; } /// Deletes any existing test padding and returns to using the real padding. @Deprecated( 'Use WidgetTester.view.resetDisplayFeatures() instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) void clearDisplayFeaturesTestValue() { _view.resetDisplayFeatures(); } @Deprecated( 'Use WidgetTester.view.systemGestureInsets instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override ViewPadding get systemGestureInsets => _view.systemGestureInsets; /// Hides the real system gesture insets and reports the given /// [systemGestureInsetsTestValue] instead. /// /// Use [FakeViewPadding] to set this value for testing. @Deprecated( 'Use WidgetTester.view.systemGestureInsets instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) set systemGestureInsetsTestValue(ViewPadding value) { // ignore: avoid_setters_without_getters _view.systemGestureInsets = value is FakeViewPadding ? value : FakeViewPadding._wrap(value); } /// Deletes any existing test system gesture insets and returns to using the real system gesture insets. @Deprecated( 'Use WidgetTester.view.resetSystemGestureInsets() instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) void clearSystemGestureInsetsTestValue() { _view.resetSystemGestureInsets(); } @Deprecated( 'Use WidgetTester.platformDispatcher.onMetricsChanged instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override VoidCallback? get onMetricsChanged => platformDispatcher.onMetricsChanged; @Deprecated( 'Use WidgetTester.platformDispatcher.onMetricsChanged instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override set onMetricsChanged(VoidCallback? callback) { platformDispatcher.onMetricsChanged = callback; } @Deprecated( 'Use WidgetTester.platformDispatcher.locale instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override Locale get locale => platformDispatcher.locale; @Deprecated( 'Use WidgetTester.platformDispatcher.locales instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override List<Locale> get locales => platformDispatcher.locales; @Deprecated( 'Use WidgetTester.platformDispatcher.onLocaleChanged instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override VoidCallback? get onLocaleChanged => platformDispatcher.onLocaleChanged; @Deprecated( 'Use WidgetTester.platformDispatcher.onLocaleChanged instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override set onLocaleChanged(VoidCallback? callback) { platformDispatcher.onLocaleChanged = callback; } @Deprecated( 'Use WidgetTester.platformDispatcher.initialLifecycleState instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override String get initialLifecycleState => platformDispatcher.initialLifecycleState; @Deprecated( 'Use WidgetTester.platformDispatcher.textScaleFactor instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override double get textScaleFactor => platformDispatcher.textScaleFactor; @Deprecated( 'Use WidgetTester.platformDispatcher.platformBrightness instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override Brightness get platformBrightness => platformDispatcher.platformBrightness; @Deprecated( 'Use WidgetTester.platformDispatcher.onPlatformBrightnessChanged instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override VoidCallback? get onPlatformBrightnessChanged => platformDispatcher.onPlatformBrightnessChanged; @Deprecated( 'Use WidgetTester.platformDispatcher.onPlatformBrightnessChanged instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override set onPlatformBrightnessChanged(VoidCallback? callback) { platformDispatcher.onPlatformBrightnessChanged = callback; } @Deprecated( 'Use WidgetTester.platformDispatcher.alwaysUse24HourFormat instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override bool get alwaysUse24HourFormat => platformDispatcher.alwaysUse24HourFormat; @Deprecated( 'Use WidgetTester.platformDispatcher.onTextScaleFactorChanged instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override VoidCallback? get onTextScaleFactorChanged => platformDispatcher.onTextScaleFactorChanged; @Deprecated( 'Use WidgetTester.platformDispatcher.onTextScaleFactorChanged instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override set onTextScaleFactorChanged(VoidCallback? callback) { platformDispatcher.onTextScaleFactorChanged = callback; } @Deprecated( 'Use WidgetTester.platformDispatcher.nativeSpellCheckServiceDefined instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override bool get nativeSpellCheckServiceDefined => platformDispatcher.nativeSpellCheckServiceDefined; @Deprecated( 'Use WidgetTester.platformDispatcher.nativeSpellCheckServiceDefinedTestValue instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) set nativeSpellCheckServiceDefinedTestValue(bool nativeSpellCheckServiceDefinedTestValue) { // ignore: avoid_setters_without_getters platformDispatcher.nativeSpellCheckServiceDefinedTestValue = nativeSpellCheckServiceDefinedTestValue; } @Deprecated( 'Use WidgetTester.platformDispatcher.brieflyShowPassword instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override bool get brieflyShowPassword => platformDispatcher.brieflyShowPassword; @Deprecated( 'Use WidgetTester.platformDispatcher.onBeginFrame instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override FrameCallback? get onBeginFrame => platformDispatcher.onBeginFrame; @Deprecated( 'Use WidgetTester.platformDispatcher.onBeginFrame instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override set onBeginFrame(FrameCallback? callback) { platformDispatcher.onBeginFrame = callback; } @Deprecated( 'Use WidgetTester.platformDispatcher.onDrawFrame instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override VoidCallback? get onDrawFrame => platformDispatcher.onDrawFrame; @Deprecated( 'Use WidgetTester.platformDispatcher.onDrawFrame instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override set onDrawFrame(VoidCallback? callback) { platformDispatcher.onDrawFrame = callback; } @Deprecated( 'Use WidgetTester.platformDispatcher.onReportTimings instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override TimingsCallback? get onReportTimings => platformDispatcher.onReportTimings; @Deprecated( 'Use WidgetTester.platformDispatcher.onReportTimings instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override set onReportTimings(TimingsCallback? callback) { platformDispatcher.onReportTimings = callback; } @Deprecated( 'Use WidgetTester.platformDispatcher.onPointerDataPacket instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override PointerDataPacketCallback? get onPointerDataPacket => platformDispatcher.onPointerDataPacket; @Deprecated( 'Use WidgetTester.platformDispatcher.onPointerDataPacket instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override set onPointerDataPacket(PointerDataPacketCallback? callback) { platformDispatcher.onPointerDataPacket = callback; } @Deprecated( 'Use WidgetTester.platformDispatcher.defaultRouteName instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override String get defaultRouteName => platformDispatcher.defaultRouteName; @Deprecated( 'Use WidgetTester.platformDispatcher.scheduleFrame() instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override void scheduleFrame() { platformDispatcher.scheduleFrame(); } @Deprecated( 'Use WidgetTester.view.render(scene) instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override void render(Scene scene, {Size? size}) { _view.render(scene, size: size); } @Deprecated( 'Use WidgetTester.platformDispatcher.semanticsEnabled instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override bool get semanticsEnabled => platformDispatcher.semanticsEnabled; @Deprecated( 'Use WidgetTester.platformDispatcher.onSemanticsEnabledChanged instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override VoidCallback? get onSemanticsEnabledChanged => platformDispatcher.onSemanticsEnabledChanged; @Deprecated( 'Use WidgetTester.platformDispatcher.onSemanticsEnabledChanged instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override set onSemanticsEnabledChanged(VoidCallback? callback) { platformDispatcher.onSemanticsEnabledChanged = callback; } @Deprecated( 'Use WidgetTester.platformDispatcher.accessibilityFeatures instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override AccessibilityFeatures get accessibilityFeatures => platformDispatcher.accessibilityFeatures; @Deprecated( 'Use WidgetTester.platformDispatcher.onAccessibilityFeaturesChanged instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override VoidCallback? get onAccessibilityFeaturesChanged => platformDispatcher.onAccessibilityFeaturesChanged; @Deprecated( 'Use WidgetTester.platformDispatcher.onAccessibilityFeaturesChanged instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override set onAccessibilityFeaturesChanged(VoidCallback? callback) { platformDispatcher.onAccessibilityFeaturesChanged = callback; } @Deprecated( 'Use WidgetTester.view.updateSemantics(update) instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override void updateSemantics(SemanticsUpdate update) { _view.updateSemantics(update); } @Deprecated( 'Use WidgetTester.platformDispatcher.setIsolateDebugName(name) instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override void setIsolateDebugName(String name) { platformDispatcher.setIsolateDebugName(name); } @Deprecated( 'Use WidgetTester.platformDispatcher.sendPlatformMessage(name, data, callback) instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override void sendPlatformMessage( String name, ByteData? data, PlatformMessageResponseCallback? callback, ) { platformDispatcher.sendPlatformMessage(name, data, callback); } /// Delete any test value properties that have been set on this [TestWindow] /// as well as its [platformDispatcher]. /// /// After calling this, the real [SingletonFlutterWindow] and /// [PlatformDispatcher] values are reported again. /// /// If desired, clearing of properties can be done on an individual basis, /// e.g., [clearDevicePixelRatioTestValue]. @Deprecated( 'Use WidgetTester.platformDispatcher.clearAllTestValues() and WidgetTester.view.reset() instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) void clearAllTestValues() { clearDevicePixelRatioTestValue(); clearPaddingTestValue(); clearGestureSettingsTestValue(); clearDisplayFeaturesTestValue(); clearPhysicalSizeTestValue(); clearViewInsetsTestValue(); platformDispatcher.clearAllTestValues(); } @override @Deprecated( 'Use WidgetTester.platformDispatcher.onFrameDataChanged instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) VoidCallback? get onFrameDataChanged => platformDispatcher.onFrameDataChanged; @Deprecated( 'Use WidgetTester.platformDispatcher.onFrameDataChanged instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override set onFrameDataChanged(VoidCallback? value) { platformDispatcher.onFrameDataChanged = value; } @Deprecated( 'Use WidgetTester.platformDispatcher.onKeyData instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override KeyDataCallback? get onKeyData => platformDispatcher.onKeyData; @Deprecated( 'Use WidgetTester.platformDispatcher.onKeyData instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override set onKeyData(KeyDataCallback? value) { platformDispatcher.onKeyData = value; } @Deprecated( 'Use WidgetTester.platformDispatcher.onSystemFontFamilyChanged instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override VoidCallback? get onSystemFontFamilyChanged => platformDispatcher.onSystemFontFamilyChanged; @Deprecated( 'Use WidgetTester.platformDispatcher.onSystemFontFamilyChanged instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override set onSystemFontFamilyChanged(VoidCallback? value) { platformDispatcher.onSystemFontFamilyChanged = value; } @Deprecated( 'Use WidgetTester.platformDispatcher.computePlatformResolvedLocale(supportedLocales) instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override Locale? computePlatformResolvedLocale(List<Locale> supportedLocales) { return platformDispatcher.computePlatformResolvedLocale(supportedLocales); } @Deprecated( 'Use WidgetTester.platformDispatcher.frameData instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override FrameData get frameData => platformDispatcher.frameData; @Deprecated( 'Use WidgetTester.platformDispatcher.systemFontFamily instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override String? get systemFontFamily => platformDispatcher.systemFontFamily; @Deprecated( 'Use WidgetTester.view.viewId instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override int get viewId => _view.viewId; /// This gives us some grace time when the dart:ui side adds something to /// [SingletonFlutterWindow], and makes things easier when we do rolls to give /// us time to catch up. @override dynamic noSuchMethod(Invocation invocation) { return null; } }
flutter/packages/flutter_test/lib/src/window.dart/0
{ "file_path": "flutter/packages/flutter_test/lib/src/window.dart", "repo_id": "flutter", "token_count": 21365 }
344
// Copyright 2014 The Flutter 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:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { final LiveTestWidgetsFlutterBinding binding = LiveTestWidgetsFlutterBinding.ensureInitialized(); testWidgets('localToGlobal and globalToLocal calculate correct results', (WidgetTester tester) async { tester.view.physicalSize = const Size(2400, 1800); tester.view.devicePixelRatio = 3.0; final RenderView renderView = RenderView( view: tester.view, configuration: TestViewConfiguration.fromView( view: tester.view, size: const Size(400, 200), ) ); // The configuration above defines a view with a resolution of 2400x1800 // physical pixels. With a device pixel ratio of 3x, this yields a // resolution of 800x600 logical pixels. In this view, a RenderView sized // 400x200 (in logical pixels) is fitted using the BoxFit.contain // algorithm (as documented on TestViewConfiguration. To fit 400x200 into // 800x600 the RenderView is scaled up by 2 to fill the full width and then // vertically positioned in the middle. The origin of the RenderView is // located at (0, 100) in the logical coordinate space of the view: // // View: 800 logical pixels wide (or 2400 physical pixels) // +---------------------------------------+ // | | // | 100px | // | | // +---------------------------------------+ // | | // | RenderView (400x200px) | // | 400px scaled to 800x400px | View: 600 logical pixels high (or 1800 physical pixels) // | | // | | // +---------------------------------------+ // | | // | 200px | // | | // +---------------------------------------+ // // All values in logical pixels until otherwise noted. // // A point can be translated from the local coordinate space of the // RenderView (in logical pixels) to the global coordinate space of the View // (in logical pixels) by multiplying each coordinate by 2 and adding 100 to // the y coordinate. This is what the localToGlobal/globalToLocal methods // do: expect(binding.localToGlobal(const Offset(0, -50), renderView), Offset.zero); expect(binding.localToGlobal(Offset.zero, renderView), const Offset(0, 100)); expect(binding.localToGlobal(const Offset(200, 100), renderView), const Offset(400, 300)); expect(binding.localToGlobal(const Offset(150, 75), renderView), const Offset(300, 250)); expect(binding.localToGlobal(const Offset(400, 200), renderView), const Offset(800, 500)); expect(binding.localToGlobal(const Offset(400, 400), renderView), const Offset(800, 900)); expect(binding.globalToLocal(Offset.zero, renderView), const Offset(0, -50)); expect(binding.globalToLocal(const Offset(0, 100), renderView), Offset.zero); expect(binding.globalToLocal(const Offset(400, 300), renderView), const Offset(200, 100)); expect(binding.globalToLocal(const Offset(300, 250), renderView), const Offset(150, 75)); expect(binding.globalToLocal(const Offset(800, 500), renderView), const Offset(400, 200)); expect(binding.globalToLocal(const Offset(800, 900), renderView), const Offset(400, 400)); }); }
flutter/packages/flutter_test/test/coordinate_translation_test.dart/0
{ "file_path": "flutter/packages/flutter_test/test/coordinate_translation_test.dart", "repo_id": "flutter", "token_count": 1430 }
345
// Copyright 2014 The Flutter 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:ui'; import 'package:flutter_test/flutter_test.dart'; class FakeView extends TestFlutterView { FakeView(FlutterView view, { this.viewId = 100 }) : super( view: view, platformDispatcher: view.platformDispatcher as TestPlatformDispatcher, display: view.display as TestDisplay, ); @override final int viewId; @override void render(Scene scene, {Size? size}) { // Do not render the scene in the engine. The engine only observes one // instance of FlutterView (the _view), and it is generally expected that // the framework will render no more than one `Scene` per frame. } @override void updateSemantics(SemanticsUpdate update) { // Do not send the update to the engine. The engine only observes one // instance of FlutterView (the _view). Sending semantic updates meant for // different views to the same engine view does not work as the updates do // not produce consistent semantics trees. } }
flutter/packages/flutter_test/test/multi_view_testing.dart/0
{ "file_path": "flutter/packages/flutter_test/test/multi_view_testing.dart", "repo_id": "flutter", "token_count": 332 }
346
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert' show json; import 'dart:math' as math; import 'package:args/args.dart'; import 'package:flutter_tools/src/artifacts.dart'; import 'package:flutter_tools/src/base/common.dart'; import 'package:flutter_tools/src/base/context.dart'; import 'package:flutter_tools/src/base/file_system.dart'; import 'package:flutter_tools/src/base/io.dart'; import 'package:flutter_tools/src/build_info.dart'; import 'package:flutter_tools/src/cache.dart'; import 'package:flutter_tools/src/context_runner.dart'; import 'package:flutter_tools/src/device.dart'; import 'package:flutter_tools/src/globals.dart' as globals; import 'package:flutter_tools/src/isolated/native_assets/test/native_assets.dart'; import 'package:flutter_tools/src/project.dart'; import 'package:flutter_tools/src/reporting/reporting.dart'; import 'package:flutter_tools/src/test/coverage_collector.dart'; import 'package:flutter_tools/src/test/runner.dart'; import 'package:flutter_tools/src/test/test_wrapper.dart'; const String _kOptionPackages = 'packages'; const String _kOptionShell = 'shell'; const String _kOptionTestDirectory = 'test-directory'; const String _kOptionSdkRoot = 'sdk-root'; const String _kOptionIcudtl = 'icudtl'; const String _kOptionTests = 'tests'; const String _kOptionCoverageDirectory = 'coverage-directory'; const List<String> _kRequiredOptions = <String>[ _kOptionPackages, _kOptionShell, _kOptionSdkRoot, _kOptionIcudtl, _kOptionTests, ]; const String _kOptionCoverage = 'coverage'; const String _kOptionCoveragePath = 'coverage-path'; void main(List<String> args) { runInContext<void>(() => run(args), overrides: <Type, Generator>{ Usage: () => DisabledUsage(), }); } Future<void> run(List<String> args) async { final ArgParser parser = ArgParser() ..addOption(_kOptionPackages, help: 'The .packages file') ..addOption(_kOptionShell, help: 'The Flutter shell binary') ..addOption(_kOptionTestDirectory, help: 'Directory containing the tests') ..addOption(_kOptionSdkRoot, help: 'Path to the SDK platform files') ..addOption(_kOptionIcudtl, help: 'Path to the ICU data file') ..addOption(_kOptionTests, help: 'Path to json file that maps Dart test files to precompiled dill files') ..addOption(_kOptionCoverageDirectory, help: 'The path to the directory that will have coverage collected') ..addFlag(_kOptionCoverage, negatable: false, help: 'Whether to collect coverage information.', ) ..addOption(_kOptionCoveragePath, defaultsTo: 'coverage/lcov.info', help: 'Where to store coverage information (if coverage is enabled).', ); final ArgResults argResults = parser.parse(args); if (_kRequiredOptions .any((String option) => !argResults.options.contains(option))) { throwToolExit('Missing option! All options must be specified.'); } final Directory tempDir = globals.fs.systemTempDirectory.createTempSync('flutter_fuchsia_tester.'); try { Cache.flutterRoot = tempDir.path; final String shellPath = globals.fs.file(argResults[_kOptionShell]).resolveSymbolicLinksSync(); if (!globals.fs.isFileSync(shellPath)) { throwToolExit('Cannot find Flutter shell at $shellPath'); } final Directory sdkRootSrc = globals.fs.directory(argResults[_kOptionSdkRoot]); if (!globals.fs.isDirectorySync(sdkRootSrc.path)) { throwToolExit('Cannot find SDK files at ${sdkRootSrc.path}'); } Directory? coverageDirectory; final String? coverageDirectoryPath = argResults[_kOptionCoverageDirectory] as String?; if (coverageDirectoryPath != null) { if (!globals.fs.isDirectorySync(coverageDirectoryPath)) { throwToolExit('Cannot find coverage directory at $coverageDirectoryPath'); } coverageDirectory = globals.fs.directory(coverageDirectoryPath); } // Put the tester shell where runTests expects it. // TODO(garymm): Switch to a Fuchsia-specific Artifacts impl. final Artifacts artifacts = globals.artifacts!; final Link testerDestLink = globals.fs.link(artifacts.getArtifactPath(Artifact.flutterTester)); testerDestLink.parent.createSync(recursive: true); testerDestLink.createSync(globals.fs.path.absolute(shellPath)); final Directory sdkRootDest = globals.fs.directory(artifacts.getArtifactPath(Artifact.flutterPatchedSdkPath)); sdkRootDest.createSync(recursive: true); for (final FileSystemEntity artifact in sdkRootSrc.listSync()) { globals.fs.link(sdkRootDest.childFile(artifact.basename).path).createSync(artifact.path); } // TODO(tvolkert): Remove once flutter_tester no longer looks for this. globals.fs.link(sdkRootDest.childFile('platform.dill').path).createSync('platform_strong.dill'); Directory? testDirectory; CoverageCollector? collector; if (argResults['coverage'] as bool? ?? false) { // If we have a specified coverage directory then accept all libraries by // setting libraryNames to null. final Set<String>? libraryNames = coverageDirectory != null ? null : <String>{FlutterProject.current().manifest.appName}; final String packagesPath = globals.fs.path.normalize(globals.fs.path.absolute(argResults[_kOptionPackages] as String)); collector = CoverageCollector( packagesPath: packagesPath, libraryNames: libraryNames, resolver: await CoverageCollector.getResolver(packagesPath)); if (!argResults.options.contains(_kOptionTestDirectory)) { throwToolExit('Use of --coverage requires setting --test-directory'); } testDirectory = globals.fs.directory(argResults[_kOptionTestDirectory]); } final Map<String, String> tests = <String, String>{}; final List<Map<String, dynamic>> jsonList = List<Map<String, dynamic>>.from( (json.decode(globals.fs.file(argResults[_kOptionTests]).readAsStringSync()) as List<dynamic>).cast<Map<String, dynamic>>()); for (final Map<String, dynamic> map in jsonList) { final String source = globals.fs.file(map['source']).resolveSymbolicLinksSync(); final String dill = globals.fs.file(map['dill']).resolveSymbolicLinksSync(); tests[source] = dill; } // TODO(dnfield): This should be injected. exitCode = await const FlutterTestRunner().runTests( const TestWrapper(), tests.keys.map(Uri.file).toList(), debuggingOptions: DebuggingOptions.enabled( BuildInfo( BuildMode.debug, '', treeShakeIcons: false, packagesPath: globals.fs.path.normalize(globals.fs.path.absolute(argResults[_kOptionPackages] as String)), ), ), watcher: collector, enableVmService: collector != null, precompiledDillFiles: tests, concurrency: math.max(1, globals.platform.numberOfProcessors - 2), icudtlPath: globals.fs.path.absolute(argResults[_kOptionIcudtl] as String), coverageDirectory: coverageDirectory, nativeAssetsBuilder: const TestCompilerNativeAssetsBuilderImpl(), ); if (collector != null) { // collector expects currentDirectory to be the root of the dart // package (i.e. contains lib/ and test/ sub-dirs). In some cases, // test files may appear to be in the root directory. if (coverageDirectory == null) { globals.fs.currentDirectory = testDirectory!.parent; } else { globals.fs.currentDirectory = testDirectory; } if (!await collector.collectCoverageData(argResults[_kOptionCoveragePath] as String?, coverageDirectory: coverageDirectory)) { throwToolExit('Failed to collect coverage data'); } } } finally { tempDir.deleteSync(recursive: true); } // TODO(ianh): There's apparently some sort of lost async task keeping the // process open. Remove the next line once that's been resolved. exit(exitCode); }
flutter/packages/flutter_tools/bin/fuchsia_tester.dart/0
{ "file_path": "flutter/packages/flutter_tools/bin/fuchsia_tester.dart", "repo_id": "flutter", "token_count": 2796 }
347
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file exists solely for the compatibility with projects that have // not migrated to the declarative apply of the Flutter Gradle Plugin. logger.error("You are applying Flutter's main Gradle plugin imperatively using \ the apply script method, which is deprecated and will be removed in a future \ release. Migrate to applying Gradle plugins with the declarative plugins \ block: https://flutter.dev/go/flutter-gradle-plugin-apply\n") def pathToThisDirectory = buildscript.sourceFile.parentFile apply from: "$pathToThisDirectory/src/main/groovy/flutter.groovy"
flutter/packages/flutter_tools/gradle/flutter.gradle/0
{ "file_path": "flutter/packages/flutter_tools/gradle/flutter.gradle", "repo_id": "flutter", "token_count": 191 }
348
<component name="ProjectRunConfigurationManager"> <configuration default="false" name="catalog - animated_list" type="FlutterRunConfigurationType" factoryName="Flutter"> <option name="filePath" value="$PROJECT_DIR$/examples/catalog/lib/animated_list.dart" /> <method /> </configuration> </component>
flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/catalog___animated_list.xml.copy.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/catalog___animated_list.xml.copy.tmpl", "repo_id": "flutter", "token_count": 95 }
349
<component name="ProjectRunConfigurationManager"> <configuration default="false" name="layers - sectors" type="FlutterRunConfigurationType" factoryName="Flutter"> <option name="filePath" value="$PROJECT_DIR$/examples/layers/widgets/sectors.dart" /> <method /> </configuration> </component>
flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/layers___sectors.xml.copy.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/layers___sectors.xml.copy.tmpl", "repo_id": "flutter", "token_count": 92 }
350
<component name="ProjectRunConfigurationManager"> <configuration default="false" name="platform_channel" type="FlutterRunConfigurationType" factoryName="Flutter"> <option name="filePath" value="$PROJECT_DIR$/examples/platform_channel/lib/main.dart" /> <method /> </configuration> </component>
flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/platform_channel.xml.copy.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/platform_channel.xml.copy.tmpl", "repo_id": "flutter", "token_count": 90 }
351
<?xml version="1.0" encoding="UTF-8"?> <module type="JAVA_MODULE" version="4"> <component name="NewModuleRootManager" inherit-compiler-output="true"> <exclude-output /> <content url="file://$MODULE_DIR$/android"> <sourceFolder url="file://$MODULE_DIR$/android/app/src/main/java" isTestSource="false" /> </content> <orderEntry type="jdk" jdkName="Android API 29 Platform" jdkType="Android SDK" /> <orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="library" name="Flutter for Android" level="project" /> </component> </module>
flutter/packages/flutter_tools/ide_templates/intellij/examples/platform_channel/android.iml.copy.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/ide_templates/intellij/examples/platform_channel/android.iml.copy.tmpl", "repo_id": "flutter", "token_count": 205 }
352
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. final RegExp _whitespace = RegExp(r'\s+'); /// Convert adb device names into more human readable descriptions. String cleanAdbDeviceName(String name) { // Some emulators use `___` in the name as separators. name = name.replaceAll('___', ', '); // Convert `Nexus_7` / `Nexus_5X` style names to `Nexus 7` ones. name = name.replaceAll('_', ' '); name = name.replaceAll(_whitespace, ' ').trim(); return name; }
flutter/packages/flutter_tools/lib/src/android/adb.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/android/adb.dart", "repo_id": "flutter", "token_count": 188 }
353
// Copyright 2014 The Flutter 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'; import 'package:crypto/crypto.dart'; import 'package:meta/meta.dart'; import 'package:process/process.dart'; import 'package:unified_analytics/unified_analytics.dart'; import 'package:xml/xml.dart'; import '../artifacts.dart'; import '../base/analyze_size.dart'; import '../base/common.dart'; import '../base/deferred_component.dart'; import '../base/file_system.dart'; import '../base/io.dart'; import '../base/logger.dart'; import '../base/net.dart'; import '../base/platform.dart'; import '../base/process.dart'; import '../base/project_migrator.dart'; import '../base/terminal.dart'; import '../base/utils.dart'; import '../build_info.dart'; import '../cache.dart'; import '../convert.dart'; import '../flutter_manifest.dart'; import '../globals.dart' as globals; import '../project.dart'; import '../reporting/reporting.dart'; import 'android_builder.dart'; import 'android_studio.dart'; import 'gradle_errors.dart'; import 'gradle_utils.dart'; import 'java.dart'; import 'migrations/android_studio_java_gradle_conflict_migration.dart'; import 'migrations/min_sdk_version_migration.dart'; import 'migrations/multidex_removal_migration.dart'; import 'migrations/top_level_gradle_build_file_migration.dart'; /// The regex to grab variant names from printBuildVariants gradle task /// /// The task is defined in flutter/packages/flutter_tools/gradle/src/main/groovy/flutter.groovy /// /// The expected output from the task should be similar to: /// /// BuildVariant: debug /// BuildVariant: release /// BuildVariant: profile final RegExp _kBuildVariantRegex = RegExp('^BuildVariant: (?<$_kBuildVariantRegexGroupName>.*)\$'); const String _kBuildVariantRegexGroupName = 'variant'; const String _kBuildVariantTaskName = 'printBuildVariants'; String _getOutputAppLinkSettingsTaskFor(String buildVariant) { return _taskForBuildVariant('output', buildVariant, 'AppLinkSettings'); } /// The directory where the APK artifact is generated. Directory getApkDirectory(FlutterProject project) { return project.isModule ? project.android.buildDirectory .childDirectory('host') .childDirectory('outputs') .childDirectory('apk') : project.android.buildDirectory .childDirectory('app') .childDirectory('outputs') .childDirectory('flutter-apk'); } /// The directory where the app bundle artifact is generated. @visibleForTesting Directory getBundleDirectory(FlutterProject project) { return project.isModule ? project.android.buildDirectory .childDirectory('host') .childDirectory('outputs') .childDirectory('bundle') : project.android.buildDirectory .childDirectory('app') .childDirectory('outputs') .childDirectory('bundle'); } /// The directory where the repo is generated. /// Only applicable to AARs. Directory getRepoDirectory(Directory buildDirectory) { return buildDirectory .childDirectory('outputs') .childDirectory('repo'); } /// Returns the name of Gradle task that starts with [prefix]. String _taskFor(String prefix, BuildInfo buildInfo) { final String buildType = camelCase(buildInfo.modeName); final String productFlavor = buildInfo.flavor ?? ''; return _taskForBuildVariant(prefix, '$productFlavor${sentenceCase(buildType)}'); } String _taskForBuildVariant(String prefix, String buildVariant, [String suffix = '']) { return '$prefix${sentenceCase(buildVariant)}$suffix'; } /// Returns the task to build an APK. @visibleForTesting String getAssembleTaskFor(BuildInfo buildInfo) { return _taskFor('assemble', buildInfo); } /// Returns the task to build an AAB. @visibleForTesting String getBundleTaskFor(BuildInfo buildInfo) { return _taskFor('bundle', buildInfo); } /// Returns the task to build an AAR. @visibleForTesting String getAarTaskFor(BuildInfo buildInfo) { return _taskFor('assembleAar', buildInfo); } /// Returns the output APK file names for a given [AndroidBuildInfo]. /// /// For example, when [splitPerAbi] is true, multiple APKs are created. Iterable<String> _apkFilesFor(AndroidBuildInfo androidBuildInfo) { final String buildType = camelCase(androidBuildInfo.buildInfo.modeName); final String productFlavor = androidBuildInfo.buildInfo.lowerCasedFlavor ?? ''; final String flavorString = productFlavor.isEmpty ? '' : '-$productFlavor'; if (androidBuildInfo.splitPerAbi) { return androidBuildInfo.targetArchs.map<String>((AndroidArch arch) { final String abi = arch.archName; return 'app$flavorString-$abi-$buildType.apk'; }); } return <String>['app$flavorString-$buildType.apk']; } // The maximum time to wait before the tool retries a Gradle build. const Duration kMaxRetryTime = Duration(seconds: 10); /// An implementation of the [AndroidBuilder] that delegates to gradle. class AndroidGradleBuilder implements AndroidBuilder { AndroidGradleBuilder({ required Java? java, required Logger logger, required ProcessManager processManager, required FileSystem fileSystem, required Artifacts artifacts, required Usage usage, required Analytics analytics, required GradleUtils gradleUtils, required Platform platform, required AndroidStudio? androidStudio, }) : _java = java, _logger = logger, _fileSystem = fileSystem, _artifacts = artifacts, _usage = usage, _analytics = analytics, _gradleUtils = gradleUtils, _androidStudio = androidStudio, _fileSystemUtils = FileSystemUtils(fileSystem: fileSystem, platform: platform), _processUtils = ProcessUtils(logger: logger, processManager: processManager); final Java? _java; final Logger _logger; final ProcessUtils _processUtils; final FileSystem _fileSystem; final Artifacts _artifacts; final Usage _usage; final Analytics _analytics; final GradleUtils _gradleUtils; final FileSystemUtils _fileSystemUtils; final AndroidStudio? _androidStudio; /// Builds the AAR and POM files for the current Flutter module or plugin. @override Future<void> buildAar({ required FlutterProject project, required Set<AndroidBuildInfo> androidBuildInfo, required String target, String? outputDirectoryPath, required String buildNumber, }) async { Directory outputDirectory = _fileSystem.directory(outputDirectoryPath ?? project.android.buildDirectory); if (project.isModule) { // Module projects artifacts are located in `build/host`. outputDirectory = outputDirectory.childDirectory('host'); } for (final AndroidBuildInfo androidBuildInfo in androidBuildInfo) { await buildGradleAar( project: project, androidBuildInfo: androidBuildInfo, target: target, outputDirectory: outputDirectory, buildNumber: buildNumber, ); } printHowToConsumeAar( buildModes: androidBuildInfo .map<String>((AndroidBuildInfo androidBuildInfo) { return androidBuildInfo.buildInfo.modeName; }).toSet(), androidPackage: project.manifest.androidPackage, repoDirectory: getRepoDirectory(outputDirectory), buildNumber: buildNumber, logger: _logger, fileSystem: _fileSystem, ); } /// Builds the APK. @override Future<void> buildApk({ required FlutterProject project, required AndroidBuildInfo androidBuildInfo, required String target, bool configOnly = false, }) async { await buildGradleApp( project: project, androidBuildInfo: androidBuildInfo, target: target, isBuildingBundle: false, localGradleErrors: gradleErrors, configOnly: configOnly, maxRetries: 1, ); } /// Builds the App Bundle. @override Future<void> buildAab({ required FlutterProject project, required AndroidBuildInfo androidBuildInfo, required String target, bool validateDeferredComponents = true, bool deferredComponentsEnabled = false, bool configOnly = false, }) async { await buildGradleApp( project: project, androidBuildInfo: androidBuildInfo, target: target, isBuildingBundle: true, localGradleErrors: gradleErrors, validateDeferredComponents: validateDeferredComponents, deferredComponentsEnabled: deferredComponentsEnabled, configOnly: configOnly, maxRetries: 1, ); } Future<RunResult> _runGradleTask( String taskName, { List<String> options = const <String>[], required FlutterProject project }) async { final Status status = _logger.startProgress( "Running Gradle task '$taskName'...", ); final List<String> command = <String>[ _gradleUtils.getExecutable(project), ...options, // suppresses gradle output. taskName, ]; RunResult result; try { result = await _processUtils.run( command, workingDirectory: project.android.hostAppGradleRoot.path, allowReentrantFlutter: true, environment: _java?.environment, ); } finally { status.stop(); } return result; } /// Builds an app. /// /// * [project] is typically [FlutterProject.current()]. /// * [androidBuildInfo] is the build configuration. /// * [target] is the target dart entry point. Typically, `lib/main.dart`. /// * If [isBuildingBundle] is `true`, then the output artifact is an `*.aab`, /// otherwise the output artifact is an `*.apk`. /// * [maxRetries] If not `null`, this is the max number of build retries in case a retry is triggered. Future<void> buildGradleApp({ required FlutterProject project, required AndroidBuildInfo androidBuildInfo, required String target, required bool isBuildingBundle, required List<GradleHandledError> localGradleErrors, required bool configOnly, bool validateDeferredComponents = true, bool deferredComponentsEnabled = false, int retry = 0, @visibleForTesting int? maxRetries, }) async { if (!project.android.isSupportedVersion) { _exitWithUnsupportedProjectMessage(_usage, _logger.terminal, analytics: _analytics); } final List<ProjectMigrator> migrators = <ProjectMigrator>[ TopLevelGradleBuildFileMigration(project.android, _logger), AndroidStudioJavaGradleConflictMigration(_logger, project: project.android, androidStudio: _androidStudio, java: globals.java), MinSdkVersionMigration(project.android, _logger), MultidexRemovalMigration(project.android, _logger), ]; final ProjectMigration migration = ProjectMigration(migrators); await migration.run(); final bool usesAndroidX = isAppUsingAndroidX(project.android.hostAppGradleRoot); if (usesAndroidX) { BuildEvent('app-using-android-x', type: 'gradle', flutterUsage: _usage).send(); _analytics.send(Event.flutterBuildInfo(label: 'app-using-android-x', buildType: 'gradle')); } else if (!usesAndroidX) { BuildEvent('app-not-using-android-x', type: 'gradle', flutterUsage: _usage).send(); _analytics.send(Event.flutterBuildInfo(label: 'app-not-using-android-x', buildType: 'gradle')); _logger.printStatus("${_logger.terminal.warningMark} Your app isn't using AndroidX.", emphasis: true); _logger.printStatus( 'To avoid potential build failures, you can quickly migrate your app ' 'by following the steps on https://goo.gl/CP92wY .', indent: 4, ); } // The default Gradle script reads the version name and number // from the local.properties file. updateLocalProperties( project: project, buildInfo: androidBuildInfo.buildInfo); final List<String> command = <String>[ // This does more than get gradlewrapper. It creates the file, ensures it // exists and verifies the file is executable. _gradleUtils.getExecutable(project), ]; // All automatically created files should exist. if (configOnly) { _logger.printStatus('Config complete.'); return; } // Assembly work starts here. final BuildInfo buildInfo = androidBuildInfo.buildInfo; final String assembleTask = isBuildingBundle ? getBundleTaskFor(buildInfo) : getAssembleTaskFor(buildInfo); final Status status = _logger.startProgress( "Running Gradle task '$assembleTask'...", ); if (_logger.isVerbose) { command.add('--full-stacktrace'); command.add('--info'); command.add('-Pverbose=true'); } else { command.add('-q'); } if (!buildInfo.androidGradleDaemon) { command.add('--no-daemon'); } if (buildInfo.androidSkipBuildDependencyValidation) { command.add('-PskipDependencyChecks=true'); } final LocalEngineInfo? localEngineInfo = _artifacts.localEngineInfo; if (localEngineInfo != null) { final Directory localEngineRepo = _getLocalEngineRepo( engineOutPath: localEngineInfo.targetOutPath, androidBuildInfo: androidBuildInfo, fileSystem: _fileSystem, ); _logger.printTrace( 'Using local engine: ${localEngineInfo.targetOutPath}\n' 'Local Maven repo: ${localEngineRepo.path}' ); command.add('-Plocal-engine-repo=${localEngineRepo.path}'); command.add('-Plocal-engine-build-mode=${buildInfo.modeName}'); command.add('-Plocal-engine-out=${localEngineInfo.targetOutPath}'); command.add('-Plocal-engine-host-out=${localEngineInfo.hostOutPath}'); command.add('-Ptarget-platform=${_getTargetPlatformByLocalEnginePath( localEngineInfo.targetOutPath)}'); } else if (androidBuildInfo.targetArchs.isNotEmpty) { final String targetPlatforms = androidBuildInfo .targetArchs .map((AndroidArch e) => e.platformName).join(','); command.add('-Ptarget-platform=$targetPlatforms'); } command.add('-Ptarget=$target'); // If using v1 embedding, we want to use FlutterApplication as the base app. final String baseApplicationName = project.android.getEmbeddingVersion() == AndroidEmbeddingVersion.v2 ? 'android.app.Application' : 'io.flutter.app.FlutterApplication'; command.add('-Pbase-application-name=$baseApplicationName'); final List<DeferredComponent>? deferredComponents = project.manifest.deferredComponents; if (deferredComponents != null) { if (deferredComponentsEnabled) { command.add('-Pdeferred-components=true'); androidBuildInfo.buildInfo.dartDefines.add('validate-deferred-components=$validateDeferredComponents'); } // Pass in deferred components regardless of building split aot to satisfy // android dynamic features registry in build.gradle. final List<String> componentNames = <String>[]; for (final DeferredComponent component in deferredComponents) { componentNames.add(component.name); } if (componentNames.isNotEmpty) { command.add('-Pdeferred-component-names=${componentNames.join(',')}'); // Multi-apk applications cannot use shrinking. This is only relevant when using // android dynamic feature modules. _logger.printStatus( 'Shrinking has been disabled for this build due to deferred components. Shrinking is ' 'not available for multi-apk applications. This limitation is expected to be removed ' 'when Gradle plugin 4.2+ is available in Flutter.', color: TerminalColor.yellow); command.add('-Pshrink=false'); } } command.addAll(androidBuildInfo.buildInfo.toGradleConfig()); if (buildInfo.fileSystemRoots.isNotEmpty) { command.add('-Pfilesystem-roots=${buildInfo.fileSystemRoots.join('|')}'); } if (buildInfo.fileSystemScheme != null) { command.add('-Pfilesystem-scheme=${buildInfo.fileSystemScheme}'); } if (androidBuildInfo.splitPerAbi) { command.add('-Psplit-per-abi=true'); } if (androidBuildInfo.fastStart) { command.add('-Pfast-start=true'); } command.add(assembleTask); GradleHandledError? detectedGradleError; String? detectedGradleErrorLine; String? consumeLog(String line) { if (detectedGradleError != null) { // Pipe stdout/stderr from Gradle. return line; } for (final GradleHandledError gradleError in localGradleErrors) { if (gradleError.test(line)) { detectedGradleErrorLine = line; detectedGradleError = gradleError; // The first error match wins. break; } } // Pipe stdout/stderr from Gradle. return line; } final Stopwatch sw = Stopwatch() ..start(); int exitCode = 1; try { exitCode = await _processUtils.stream( command, workingDirectory: project.android.hostAppGradleRoot.path, allowReentrantFlutter: true, environment: _java?.environment, mapFunction: consumeLog, ); } on ProcessException catch (exception) { consumeLog(exception.toString()); // Rethrow the exception if the error isn't handled by any of the // `localGradleErrors`. if (detectedGradleError == null) { rethrow; } } finally { status.stop(); } final Duration elapsedDuration = sw.elapsed; _usage.sendTiming('build', 'gradle', elapsedDuration); _analytics.send(Event.timing( workflow: 'build', variableName: 'gradle', elapsedMilliseconds: elapsedDuration.inMilliseconds, )); if (exitCode != 0) { if (detectedGradleError == null) { BuildEvent('gradle-unknown-failure', type: 'gradle', flutterUsage: _usage).send(); _analytics.send(Event.flutterBuildInfo(label: 'gradle-unknown-failure', buildType: 'gradle')); throwToolExit( 'Gradle task $assembleTask failed with exit code $exitCode', exitCode: exitCode, ); } final GradleBuildStatus status = await detectedGradleError!.handler( line: detectedGradleErrorLine!, project: project, usesAndroidX: usesAndroidX, ); if (maxRetries == null || retry < maxRetries) { switch (status) { case GradleBuildStatus.retry: // Use binary exponential backoff before retriggering the build. // The expected wait times are: 100ms, 200ms, 400ms, and so on... final int waitTime = min(pow(2, retry).toInt() * 100, kMaxRetryTime.inMicroseconds); retry += 1; _logger.printStatus('Retrying Gradle Build: #$retry, wait time: ${waitTime}ms'); await Future<void>.delayed(Duration(milliseconds: waitTime)); await buildGradleApp( project: project, androidBuildInfo: androidBuildInfo, target: target, isBuildingBundle: isBuildingBundle, localGradleErrors: localGradleErrors, retry: retry, maxRetries: maxRetries, configOnly: configOnly, ); final String successEventLabel = 'gradle-${detectedGradleError!.eventLabel}-success'; BuildEvent(successEventLabel, type: 'gradle', flutterUsage: _usage).send(); _analytics.send(Event.flutterBuildInfo(label: successEventLabel, buildType: 'gradle')); return; case GradleBuildStatus.exit: // Continue and throw tool exit. } } final String usageLabel = 'gradle-${detectedGradleError?.eventLabel}-failure'; BuildEvent(usageLabel, type: 'gradle', flutterUsage: _usage).send(); _analytics.send(Event.flutterBuildInfo(label: usageLabel, buildType: 'gradle')); throwToolExit( 'Gradle task $assembleTask failed with exit code $exitCode', exitCode: exitCode, ); } if (isBuildingBundle) { final File bundleFile = findBundleFile(project, buildInfo, _logger, _usage, _analytics); final String appSize = (buildInfo.mode == BuildMode.debug) ? '' // Don't display the size when building a debug variant. : ' (${getSizeAsPlatformMB(bundleFile.lengthSync())})'; if (buildInfo.codeSizeDirectory != null) { await _performCodeSizeAnalysis('aab', bundleFile, androidBuildInfo); } _logger.printStatus( '${_logger.terminal.successMark} ' 'Built ${_fileSystem.path.relative(bundleFile.path)}$appSize', color: TerminalColor.green, ); return; } // Gradle produced APKs. final Iterable<String> apkFilesPaths = project.isModule ? findApkFilesModule(project, androidBuildInfo, _logger, _usage, _analytics) : listApkPaths(androidBuildInfo); final Directory apkDirectory = getApkDirectory(project); // Generate sha1 for every generated APKs. for (final File apkFile in apkFilesPaths.map(apkDirectory.childFile)) { if (!apkFile.existsSync()) { _exitWithExpectedFileNotFound( project: project, fileExtension: '.apk', logger: _logger, usage: _usage, analytics: _analytics, ); } final String filename = apkFile.basename; _logger.printTrace('Calculate SHA1: $apkDirectory/$filename'); final File apkShaFile = apkDirectory.childFile('$filename.sha1'); apkShaFile.writeAsStringSync(_calculateSha(apkFile)); final String appSize = (buildInfo.mode == BuildMode.debug) ? '' // Don't display the size when building a debug variant. : ' (${getSizeAsPlatformMB(apkFile.lengthSync())})'; _logger.printStatus( '${_logger.terminal.successMark} ' 'Built ${_fileSystem.path.relative(apkFile.path)}$appSize', color: TerminalColor.green, ); if (buildInfo.codeSizeDirectory != null) { await _performCodeSizeAnalysis('apk', apkFile, androidBuildInfo); } } } Future<void> _performCodeSizeAnalysis(String kind, File zipFile, AndroidBuildInfo androidBuildInfo,) async { final SizeAnalyzer sizeAnalyzer = SizeAnalyzer( fileSystem: _fileSystem, logger: _logger, flutterUsage: _usage, analytics: _analytics, ); final String archName = androidBuildInfo.targetArchs.single.archName; final BuildInfo buildInfo = androidBuildInfo.buildInfo; final File aotSnapshot = _fileSystem.directory(buildInfo.codeSizeDirectory) .childFile('snapshot.$archName.json'); final File precompilerTrace = _fileSystem.directory(buildInfo.codeSizeDirectory) .childFile('trace.$archName.json'); final Map<String, Object?> output = await sizeAnalyzer.analyzeZipSizeAndAotSnapshot( zipFile: zipFile, aotSnapshot: aotSnapshot, precompilerTrace: precompilerTrace, kind: kind, ); final File outputFile = _fileSystemUtils.getUniqueFile( _fileSystem .directory(_fileSystemUtils.homeDirPath) .childDirectory('.flutter-devtools'), '$kind-code-size-analysis', 'json', ) ..writeAsStringSync(jsonEncode(output)); // This message is used as a sentinel in analyze_apk_size_test.dart _logger.printStatus( 'A summary of your ${kind.toUpperCase()} analysis can be found at: ${outputFile.path}', ); // DevTools expects a file path relative to the .flutter-devtools/ dir. final String relativeAppSizePath = outputFile.path .split('.flutter-devtools/') .last .trim(); _logger.printStatus( '\nTo analyze your app size in Dart DevTools, run the following command:\n' 'dart devtools --appSizeBase=$relativeAppSizePath' ); } /// Builds AAR and POM files. /// /// * [project] is typically [FlutterProject.current()]. /// * [androidBuildInfo] is the build configuration. /// * [outputDir] is the destination of the artifacts, /// * [buildNumber] is the build number of the output aar, Future<void> buildGradleAar({ required FlutterProject project, required AndroidBuildInfo androidBuildInfo, required String target, required Directory outputDirectory, required String buildNumber, }) async { final FlutterManifest manifest = project.manifest; if (!manifest.isModule) { throwToolExit('AARs can only be built for module projects.'); } final BuildInfo buildInfo = androidBuildInfo.buildInfo; final String aarTask = getAarTaskFor(buildInfo); final Status status = _logger.startProgress( "Running Gradle task '$aarTask'...", ); final String flutterRoot = _fileSystem.path.absolute(Cache.flutterRoot!); final String initScript = _fileSystem.path.join( flutterRoot, 'packages', 'flutter_tools', 'gradle', 'aar_init_script.gradle', ); final List<String> command = <String>[ _gradleUtils.getExecutable(project), '-I=$initScript', '-Pflutter-root=$flutterRoot', '-Poutput-dir=${outputDirectory.path}', '-Pis-plugin=${manifest.isPlugin}', '-PbuildNumber=$buildNumber', ]; if (_logger.isVerbose) { command.add('--full-stacktrace'); command.add('--info'); command.add('-Pverbose=true'); } else { command.add('-q'); } if (!buildInfo.androidGradleDaemon) { command.add('--no-daemon'); } if (target.isNotEmpty) { command.add('-Ptarget=$target'); } command.addAll(androidBuildInfo.buildInfo.toGradleConfig()); if (buildInfo.dartObfuscation && buildInfo.mode != BuildMode.release) { _logger.printStatus( 'Dart obfuscation is not supported in ${sentenceCase(buildInfo.friendlyModeName)}' ' mode, building as un-obfuscated.', ); } final LocalEngineInfo? localEngineInfo = _artifacts.localEngineInfo; if (localEngineInfo != null) { final Directory localEngineRepo = _getLocalEngineRepo( engineOutPath: localEngineInfo.targetOutPath, androidBuildInfo: androidBuildInfo, fileSystem: _fileSystem, ); _logger.printTrace( 'Using local engine: ${localEngineInfo.targetOutPath}\n' 'Local Maven repo: ${localEngineRepo.path}' ); command.add('-Plocal-engine-repo=${localEngineRepo.path}'); command.add('-Plocal-engine-build-mode=${buildInfo.modeName}'); command.add('-Plocal-engine-out=${localEngineInfo.targetOutPath}'); command.add('-Plocal-engine-host-out=${localEngineInfo.hostOutPath}'); // Copy the local engine repo in the output directory. try { copyDirectory( localEngineRepo, getRepoDirectory(outputDirectory), ); } on FileSystemException catch (error, st) { throwToolExit( 'Failed to copy the local engine ${localEngineRepo.path} repo ' 'in ${outputDirectory.path}: $error, $st' ); } command.add('-Ptarget-platform=${_getTargetPlatformByLocalEnginePath( localEngineInfo.targetOutPath)}'); } else if (androidBuildInfo.targetArchs.isNotEmpty) { final String targetPlatforms = androidBuildInfo.targetArchs .map((AndroidArch e) => e.platformName).join(','); command.add('-Ptarget-platform=$targetPlatforms'); } command.add(aarTask); final Stopwatch sw = Stopwatch() ..start(); RunResult result; try { result = await _processUtils.run( command, workingDirectory: project.android.hostAppGradleRoot.path, allowReentrantFlutter: true, environment: _java?.environment, ); } finally { status.stop(); } final Duration elapsedDuration = sw.elapsed; _usage.sendTiming('build', 'gradle-aar', elapsedDuration); _analytics.send(Event.timing( workflow: 'build', variableName: 'gradle-aar', elapsedMilliseconds: elapsedDuration.inMilliseconds, )); if (result.exitCode != 0) { _logger.printStatus(result.stdout, wrap: false); _logger.printError(result.stderr, wrap: false); throwToolExit( 'Gradle task $aarTask failed with exit code ${result.exitCode}.', exitCode: result.exitCode, ); } final Directory repoDirectory = getRepoDirectory(outputDirectory); if (!repoDirectory.existsSync()) { _logger.printStatus(result.stdout, wrap: false); _logger.printError(result.stderr, wrap: false); throwToolExit( 'Gradle task $aarTask failed to produce $repoDirectory.', exitCode: exitCode, ); } _logger.printStatus( '${_logger.terminal.successMark} ' 'Built ${_fileSystem.path.relative(repoDirectory.path)}', color: TerminalColor.green, ); } @override Future<List<String>> getBuildVariants({required FlutterProject project}) async { final Stopwatch sw = Stopwatch() ..start(); final RunResult result = await _runGradleTask( _kBuildVariantTaskName, options: const <String>['-q'], project: project, ); final Duration elapsedDuration = sw.elapsed; _usage.sendTiming('print', 'android build variants', elapsedDuration); _analytics.send(Event.timing( workflow: 'print', variableName: 'android build variants', elapsedMilliseconds: elapsedDuration.inMilliseconds, )); if (result.exitCode != 0) { _logger.printStatus(result.stdout, wrap: false); _logger.printError(result.stderr, wrap: false); return const <String>[]; } return <String>[ for (final String line in LineSplitter.split(result.stdout)) if (_kBuildVariantRegex.firstMatch(line) case final RegExpMatch match) match.namedGroup(_kBuildVariantRegexGroupName)!, ]; } @override Future<String> outputsAppLinkSettings( String buildVariant, { required FlutterProject project, }) async { final String taskName = _getOutputAppLinkSettingsTaskFor(buildVariant); final Directory directory = await project.buildDirectory .childDirectory('deeplink_data').create(recursive: true); final String outputPath = globals.fs.path.join( directory.absolute.path, 'app-link-settings-$buildVariant.json', ); final Stopwatch sw = Stopwatch() ..start(); final RunResult result = await _runGradleTask( taskName, options: <String>['-q', '-PoutputPath=$outputPath'], project: project, ); final Duration elapsedDuration = sw.elapsed; _usage.sendTiming('outputs', 'app link settings', elapsedDuration); _analytics.send(Event.timing( workflow: 'outputs', variableName: 'app link settings', elapsedMilliseconds: elapsedDuration.inMilliseconds, )); if (result.exitCode != 0) { _logger.printStatus(result.stdout, wrap: false); _logger.printError(result.stderr, wrap: false); throwToolExit(result.stderr); } return outputPath; } } /// Prints how to consume the AAR from a host app. void printHowToConsumeAar({ required Set<String> buildModes, String? androidPackage = 'unknown', required Directory repoDirectory, required Logger logger, required FileSystem fileSystem, String? buildNumber, }) { assert(buildModes.isNotEmpty); buildNumber ??= '1.0'; logger.printStatus('\nConsuming the Module', emphasis: true); logger.printStatus(''' 1. Open ${fileSystem.path.join('<host>', 'app', 'build.gradle')} 2. Ensure you have the repositories configured, otherwise add them: String storageUrl = System.env.$kFlutterStorageBaseUrl ?: "https://storage.googleapis.com" repositories { maven { url '${repoDirectory.path}' } maven { url "\$storageUrl/download.flutter.io" } } 3. Make the host app depend on the Flutter module: dependencies {'''); for (final String buildMode in buildModes) { logger.printStatus(""" ${buildMode}Implementation '$androidPackage:flutter_$buildMode:$buildNumber'"""); } logger.printStatus(''' } '''); if (buildModes.contains('profile')) { logger.printStatus(''' 4. Add the `profile` build type: android { buildTypes { profile { initWith debug } } } '''); } logger.printStatus('To learn more, visit https://flutter.dev/go/build-aar'); } String _hex(List<int> bytes) { final StringBuffer result = StringBuffer(); for (final int part in bytes) { result.write('${part < 16 ? '0' : ''}${part.toRadixString(16)}'); } return result.toString(); } String _calculateSha(File file) { final List<int> bytes = file.readAsBytesSync(); return _hex(sha1.convert(bytes).bytes); } void _exitWithUnsupportedProjectMessage(Usage usage, Terminal terminal, {required Analytics analytics}) { BuildEvent('unsupported-project', type: 'gradle', eventError: 'gradle-plugin', flutterUsage: usage).send(); analytics.send(Event.flutterBuildInfo( label: 'unsupported-project', buildType: 'gradle', error: 'gradle-plugin', )); throwToolExit( '${terminal.warningMark} Your app is using an unsupported Gradle project. ' 'To fix this problem, create a new project by running `flutter create -t app <app-directory>` ' 'and then move the dart code, assets and pubspec.yaml to the new project.', ); } /// Returns [true] if the current app uses AndroidX. // TODO(egarciad): https://github.com/flutter/flutter/issues/40800 // Remove `FlutterManifest.usesAndroidX` and provide a unified `AndroidProject.usesAndroidX`. bool isAppUsingAndroidX(Directory androidDirectory) { final File properties = androidDirectory.childFile('gradle.properties'); if (!properties.existsSync()) { return false; } return properties.readAsStringSync().contains('android.useAndroidX=true'); } /// Returns the APK files for a given [FlutterProject] and [AndroidBuildInfo]. @visibleForTesting Iterable<String> findApkFilesModule( FlutterProject project, AndroidBuildInfo androidBuildInfo, Logger logger, Usage usage, Analytics analytics, ) { final Iterable<String> apkFileNames = _apkFilesFor(androidBuildInfo); final Directory apkDirectory = getApkDirectory(project); final Iterable<File> apks = apkFileNames.expand<File>((String apkFileName) { File apkFile = apkDirectory.childFile(apkFileName); if (apkFile.existsSync()) { return <File>[apkFile]; } final BuildInfo buildInfo = androidBuildInfo.buildInfo; final String modeName = camelCase(buildInfo.modeName); apkFile = apkDirectory .childDirectory(modeName) .childFile(apkFileName); if (apkFile.existsSync()) { return <File>[apkFile]; } final String? flavor = buildInfo.flavor; if (flavor != null) { // Android Studio Gradle plugin v3 adds flavor to path. apkFile = apkDirectory .childDirectory(flavor) .childDirectory(modeName) .childFile(apkFileName); if (apkFile.existsSync()) { return <File>[apkFile]; } } return const <File>[]; }); if (apks.isEmpty) { _exitWithExpectedFileNotFound( project: project, fileExtension: '.apk', logger: logger, usage: usage, analytics: analytics, ); } return apks.map((File file) => file.path); } /// Returns the APK files for a given [FlutterProject] and [AndroidBuildInfo]. /// /// The flutter.gradle plugin will copy APK outputs into: /// `$buildDir/app/outputs/flutter-apk/app-<abi>-<flavor-flag>-<build-mode-flag>.apk` @visibleForTesting Iterable<String> listApkPaths( AndroidBuildInfo androidBuildInfo, ) { final String buildType = camelCase(androidBuildInfo.buildInfo.modeName); final List<String> apkPartialName = <String>[ if (androidBuildInfo.buildInfo.flavor?.isNotEmpty ?? false) androidBuildInfo.buildInfo.lowerCasedFlavor!, '$buildType.apk', ]; if (androidBuildInfo.splitPerAbi) { return <String>[ for (final AndroidArch androidArch in androidBuildInfo.targetArchs) <String>[ 'app', androidArch.archName, ...apkPartialName, ].join('-'), ]; } return <String>[ <String>[ 'app', ...apkPartialName, ].join('-'), ]; } @visibleForTesting File findBundleFile(FlutterProject project, BuildInfo buildInfo, Logger logger, Usage usage, Analytics analytics) { final List<File> fileCandidates = <File>[ getBundleDirectory(project) .childDirectory(camelCase(buildInfo.modeName)) .childFile('app.aab'), getBundleDirectory(project) .childDirectory(camelCase(buildInfo.modeName)) .childFile('app-${buildInfo.modeName}.aab'), ]; if (buildInfo.flavor != null) { // The Android Gradle plugin 3.0.0 adds the flavor name to the path. // For example: In release mode, if the flavor name is `foo_bar`, then // the directory name is `foo_barRelease`. fileCandidates.add( getBundleDirectory(project) .childDirectory('${buildInfo.lowerCasedFlavor}${camelCase('_${buildInfo.modeName}')}') .childFile('app.aab')); // The Android Gradle plugin 3.5.0 adds the flavor name to file name. // For example: In release mode, if the flavor name is `foo_bar`, then // the file name is `app-foo_bar-release.aab`. fileCandidates.add( getBundleDirectory(project) .childDirectory('${buildInfo.lowerCasedFlavor}${camelCase('_${buildInfo.modeName}')}') .childFile('app-${buildInfo.lowerCasedFlavor}-${buildInfo.modeName}.aab')); // The Android Gradle plugin 4.1.0 does only lowercase the first character of flavor name. fileCandidates.add(getBundleDirectory(project) .childDirectory('${buildInfo.uncapitalizedFlavor}${camelCase('_${buildInfo.modeName}')}') .childFile('app-${buildInfo.uncapitalizedFlavor}-${buildInfo.modeName}.aab')); // The Android Gradle plugin uses kebab-case and lowercases the first character of the flavor name // when multiple flavor dimensions are used: // e.g. // flavorDimensions "dimension1","dimension2" // productFlavors { // foo { // dimension "dimension1" // } // bar { // dimension "dimension2" // } // } fileCandidates.add(getBundleDirectory(project) .childDirectory('${buildInfo.uncapitalizedFlavor}${camelCase('_${buildInfo.modeName}')}') .childFile('app-${kebabCase(buildInfo.uncapitalizedFlavor!)}-${buildInfo.modeName}.aab')); } for (final File bundleFile in fileCandidates) { if (bundleFile.existsSync()) { return bundleFile; } } _exitWithExpectedFileNotFound( project: project, fileExtension: '.aab', logger: logger, usage: usage, analytics: analytics, ); } /// Throws a [ToolExit] exception and logs the event. Never _exitWithExpectedFileNotFound({ required FlutterProject project, required String fileExtension, required Logger logger, required Usage usage, required Analytics analytics, }) { final String androidGradlePluginVersion = getGradleVersionForAndroidPlugin(project.android.hostAppGradleRoot, logger); final String gradleBuildSettings = 'androidGradlePluginVersion: $androidGradlePluginVersion, ' 'fileExtension: $fileExtension'; BuildEvent('gradle-expected-file-not-found', type: 'gradle', settings: gradleBuildSettings, flutterUsage: usage, ).send(); analytics.send(Event.flutterBuildInfo( label: 'gradle-expected-file-not-found', buildType: 'gradle', settings: gradleBuildSettings, )); throwToolExit( 'Gradle build failed to produce an $fileExtension file. ' "It's likely that this file was generated under ${project.android.buildDirectory.path}, " "but the tool couldn't find it." ); } void _createSymlink(String targetPath, String linkPath, FileSystem fileSystem) { final File targetFile = fileSystem.file(targetPath); if (!targetFile.existsSync()) { throwToolExit("The file $targetPath wasn't found in the local engine out directory."); } final File linkFile = fileSystem.file(linkPath); final Link symlink = linkFile.parent.childLink(linkFile.basename); try { symlink.createSync(targetPath, recursive: true); } on FileSystemException catch (exception) { throwToolExit( 'Failed to create the symlink $linkPath->$targetPath: $exception' ); } } String _getLocalArtifactVersion(String pomPath, FileSystem fileSystem) { final File pomFile = fileSystem.file(pomPath); if (!pomFile.existsSync()) { throwToolExit("The file $pomPath wasn't found in the local engine out directory."); } XmlDocument document; try { document = XmlDocument.parse(pomFile.readAsStringSync()); } on XmlException { throwToolExit( 'Error parsing $pomPath. Please ensure that this is a valid XML document.' ); } on FileSystemException { throwToolExit( 'Error reading $pomPath. Please ensure that you have read permission to this ' 'file and try again.'); } final Iterable<XmlElement> project = document.findElements('project'); assert(project.isNotEmpty); for (final XmlElement versionElement in document.findAllElements('version')) { if (versionElement.parent == project.first) { return versionElement.innerText; } } throwToolExit('Error while parsing the <version> element from $pomPath'); } /// Returns the local Maven repository for a local engine build. /// For example, if the engine is built locally at <home>/engine/src/out/android_release_unopt /// This method generates symlinks in the temp directory to the engine artifacts /// following the convention specified on https://maven.apache.org/pom.html#Repositories Directory _getLocalEngineRepo({ required String engineOutPath, required AndroidBuildInfo androidBuildInfo, required FileSystem fileSystem, }) { final String abi = _getAbiByLocalEnginePath(engineOutPath); final Directory localEngineRepo = fileSystem.systemTempDirectory .createTempSync('flutter_tool_local_engine_repo.'); final String buildMode = androidBuildInfo.buildInfo.modeName; final String artifactVersion = _getLocalArtifactVersion( fileSystem.path.join( engineOutPath, 'flutter_embedding_$buildMode.pom', ), fileSystem, ); for (final String artifact in const <String>['pom', 'jar']) { // The Android embedding artifacts. _createSymlink( fileSystem.path.join( engineOutPath, 'flutter_embedding_$buildMode.$artifact', ), fileSystem.path.join( localEngineRepo.path, 'io', 'flutter', 'flutter_embedding_$buildMode', artifactVersion, 'flutter_embedding_$buildMode-$artifactVersion.$artifact', ), fileSystem, ); // The engine artifacts (libflutter.so). _createSymlink( fileSystem.path.join( engineOutPath, '${abi}_$buildMode.$artifact', ), fileSystem.path.join( localEngineRepo.path, 'io', 'flutter', '${abi}_$buildMode', artifactVersion, '${abi}_$buildMode-$artifactVersion.$artifact', ), fileSystem, ); } for (final String artifact in <String>['flutter_embedding_$buildMode', '${abi}_$buildMode']) { _createSymlink( fileSystem.path.join( engineOutPath, '$artifact.maven-metadata.xml', ), fileSystem.path.join( localEngineRepo.path, 'io', 'flutter', artifact, 'maven-metadata.xml', ), fileSystem, ); } return localEngineRepo; } String _getAbiByLocalEnginePath(String engineOutPath) { String result = 'armeabi_v7a'; if (engineOutPath.contains('x86')) { result = 'x86'; } else if (engineOutPath.contains('x64')) { result = 'x86_64'; } else if (engineOutPath.contains('arm64')) { result = 'arm64_v8a'; } return result; } String _getTargetPlatformByLocalEnginePath(String engineOutPath) { String result = 'android-arm'; if (engineOutPath.contains('x86')) { result = 'android-x86'; } else if (engineOutPath.contains('x64')) { result = 'android-x64'; } else if (engineOutPath.contains('arm64')) { result = 'android-arm64'; } return result; }
flutter/packages/flutter_tools/lib/src/android/gradle.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/android/gradle.dart", "repo_id": "flutter", "token_count": 16480 }
354
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /// Throw a specialized exception for expected situations /// where the tool should exit with a clear message to the user /// and no stack trace unless the --verbose option is specified. /// For example: network errors. Never throwToolExit(String? message, { int? exitCode }) { throw ToolExit(message, exitCode: exitCode); } /// Specialized exception for expected situations /// where the tool should exit with a clear message to the user /// and no stack trace unless the --verbose option is specified. /// For example: network errors. class ToolExit implements Exception { ToolExit(this.message, { this.exitCode }); final String? message; final int? exitCode; @override String toString() => 'Error: $message'; }
flutter/packages/flutter_tools/lib/src/base/common.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/base/common.dart", "repo_id": "flutter", "token_count": 224 }
355
// Copyright 2014 The Flutter 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:meta/meta.dart'; import '../base/process.dart'; import '../globals.dart' as globals; import 'async_guard.dart'; import 'io.dart'; typedef SignalHandler = FutureOr<void> Function(ProcessSignal signal); /// A class that manages signal handlers. /// /// Signal handlers are run in the order that they were added. abstract class Signals { @visibleForTesting factory Signals.test({ List<ProcessSignal> exitSignals = defaultExitSignals, ShutdownHooks? shutdownHooks, }) => LocalSignals._(exitSignals, shutdownHooks: shutdownHooks); // The default list of signals that should cause the process to exit. static const List<ProcessSignal> defaultExitSignals = <ProcessSignal>[ ProcessSignal.sigterm, ProcessSignal.sigint, ]; /// Adds a signal handler to run on receipt of signal. /// /// The handler will run after all handlers that were previously added for the /// signal. The function returns an abstract token that should be provided to /// removeHandler to remove the handler. Object addHandler(ProcessSignal signal, SignalHandler handler); /// Removes a signal handler. /// /// Removes the signal handler for the signal identified by the abstract /// token parameter. Returns true if the handler was removed and false /// otherwise. Future<bool> removeHandler(ProcessSignal signal, Object token); /// If a [SignalHandler] throws an error, either synchronously or /// asynchronously, it will be added to this stream instead of propagated. Stream<Object> get errors; } /// A class that manages the real dart:io signal handlers. /// /// We use a singleton instance of this class to ensure that all handlers for /// fatal signals run before this class calls exit(). class LocalSignals implements Signals { LocalSignals._( this.exitSignals, { ShutdownHooks? shutdownHooks, }) : _shutdownHooks = shutdownHooks ?? globals.shutdownHooks; static LocalSignals instance = LocalSignals._( Signals.defaultExitSignals, ); final List<ProcessSignal> exitSignals; final ShutdownHooks _shutdownHooks; // A table mapping (signal, token) -> signal handler. final Map<ProcessSignal, Map<Object, SignalHandler>> _handlersTable = <ProcessSignal, Map<Object, SignalHandler>>{}; // A table mapping (signal) -> signal handler list. The list is in the order // that the signal handlers should be run. final Map<ProcessSignal, List<SignalHandler>> _handlersList = <ProcessSignal, List<SignalHandler>>{}; // A table mapping (signal) -> low-level signal event stream. final Map<ProcessSignal, StreamSubscription<ProcessSignal>> _streamSubscriptions = <ProcessSignal, StreamSubscription<ProcessSignal>>{}; // The stream controller for errors coming from signal handlers. final StreamController<Object> _errorStreamController = StreamController<Object>.broadcast(); @override Stream<Object> get errors => _errorStreamController.stream; @override Object addHandler(ProcessSignal signal, SignalHandler handler) { final Object token = Object(); _handlersTable.putIfAbsent(signal, () => <Object, SignalHandler>{}); _handlersTable[signal]![token] = handler; _handlersList.putIfAbsent(signal, () => <SignalHandler>[]); _handlersList[signal]!.add(handler); // If we added the first one, then call signal.watch(), listen, and cache // the stream controller. if (_handlersList[signal]!.length == 1) { _streamSubscriptions[signal] = signal.watch().listen( _handleSignal, onError: (Object e) { _handlersTable[signal]?.remove(token); _handlersList[signal]?.remove(handler); }, ); } return token; } @override Future<bool> removeHandler(ProcessSignal signal, Object token) async { // We don't know about this signal. if (!_handlersTable.containsKey(signal)) { return false; } // We don't know about this token. if (!_handlersTable[signal]!.containsKey(token)) { return false; } final SignalHandler? handler = _handlersTable[signal]!.remove(token); if (handler == null) { return false; } final bool removed = _handlersList[signal]!.remove(handler); if (!removed) { return false; } // If _handlersList[signal] is empty, then lookup the cached stream // controller and unsubscribe from the stream. if (_handlersList.isEmpty) { await _streamSubscriptions[signal]?.cancel(); } return true; } Future<void> _handleSignal(ProcessSignal s) async { final List<SignalHandler>? handlers = _handlersList[s]; if (handlers != null) { final List<SignalHandler> handlersCopy = handlers.toList(); for (final SignalHandler handler in handlersCopy) { try { await asyncGuard<void>(() async => handler(s)); } on Exception catch (e) { if (_errorStreamController.hasListener) { _errorStreamController.add(e); } } } } // If this was a signal that should cause the process to go down, then // call exit(); if (_shouldExitFor(s)) { await exitWithHooks(0, shutdownHooks: _shutdownHooks); } } bool _shouldExitFor(ProcessSignal signal) => exitSignals.contains(signal); }
flutter/packages/flutter_tools/lib/src/base/signals.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/base/signals.dart", "repo_id": "flutter", "token_count": 1788 }
356
// Copyright 2014 The Flutter 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 '../artifacts.dart'; import '../base/file_system.dart'; import '../build_info.dart'; import 'build_system.dart'; import 'exceptions.dart'; /// A set of source files. abstract class ResolvedFiles { /// Whether any of the sources we evaluated contained a missing depfile. /// /// If so, the build system needs to rerun the visitor after executing the /// build to ensure all hashes are up to date. bool get containsNewDepfile; /// The resolved source files. List<File> get sources; } /// Collects sources for a [Target] into a single list of [FileSystemEntities]. class SourceVisitor implements ResolvedFiles { /// Create a new [SourceVisitor] from an [Environment]. SourceVisitor(this.environment, [ this.inputs = true ]); /// The current environment. final Environment environment; /// Whether we are visiting inputs or outputs. /// /// Defaults to `true`. final bool inputs; @override final List<File> sources = <File>[]; @override bool get containsNewDepfile => _containsNewDepfile; bool _containsNewDepfile = false; /// Visit a depfile which contains both input and output files. /// /// If the file is missing, this visitor is marked as [containsNewDepfile]. /// This is used by the [Node] class to tell the [BuildSystem] to /// defer hash computation until after executing the target. // depfile logic adopted from https://github.com/flutter/flutter/blob/7065e4330624a5a216c8ffbace0a462617dc1bf5/dev/devicelab/lib/framework/apk_utils.dart#L390 void visitDepfile(String name) { final File depfile = environment.buildDir.childFile(name); if (!depfile.existsSync()) { _containsNewDepfile = true; return; } final String contents = depfile.readAsStringSync(); final List<String> colonSeparated = contents.split(': '); if (colonSeparated.length != 2) { environment.logger.printError('Invalid depfile: ${depfile.path}'); return; } if (inputs) { sources.addAll(_processList(colonSeparated[1].trim())); } else { sources.addAll(_processList(colonSeparated[0].trim())); } } final RegExp _separatorExpr = RegExp(r'([^\\]) '); final RegExp _escapeExpr = RegExp(r'\\(.)'); Iterable<File> _processList(String rawText) { return rawText // Put every file on right-hand side on the separate line .replaceAllMapped(_separatorExpr, (Match match) => '${match.group(1)}\n') .split('\n') // Expand escape sequences, so that '\ ', for example,ß becomes ' ' .map<String>((String path) => path.replaceAllMapped(_escapeExpr, (Match match) => match.group(1)!).trim()) .where((String path) => path.isNotEmpty) .toSet() .map(environment.fileSystem.file); } /// Visit a [Source] which contains a file URL. /// /// The URL may include constants defined in an [Environment]. If /// [optional] is true, the file is not required to exist. In this case, it /// is never resolved as an input. void visitPattern(String pattern, bool optional) { // perform substitution of the environmental values and then // of the local values. final List<String> rawParts = pattern.split('/'); final bool hasWildcard = rawParts.last.contains('*'); String? wildcardFile; if (hasWildcard) { wildcardFile = rawParts.removeLast(); } final List<String> segments = <String>[ ...environment.fileSystem.path.split(switch (rawParts.first) { // flutter root will not contain a symbolic link. Environment.kFlutterRootDirectory => environment.flutterRootDir.absolute.path, Environment.kProjectDirectory => environment.projectDir.resolveSymbolicLinksSync(), Environment.kBuildDirectory => environment.buildDir.resolveSymbolicLinksSync(), Environment.kCacheDirectory => environment.cacheDir.resolveSymbolicLinksSync(), Environment.kOutputDirectory => environment.outputDir.resolveSymbolicLinksSync(), // If the pattern does not start with an env variable, then we have nothing // to resolve it to, error out. _ => throw InvalidPatternException(pattern), }), ...rawParts.skip(1), ]; final String filePath = environment.fileSystem.path.joinAll(segments); if (!hasWildcard) { if (optional && !environment.fileSystem.isFileSync(filePath)) { return; } sources.add(environment.fileSystem.file( environment.fileSystem.path.normalize(filePath))); return; } // Perform a simple match by splitting the wildcard containing file one // the `*`. For example, for `/*.dart`, we get [.dart]. We then check // that part of the file matches. If there are values before and after // the `*` we need to check that both match without overlapping. For // example, `foo_*_.dart`. We want to match `foo_b_.dart` but not // `foo_.dart`. To do so, we first subtract the first section from the // string if the first segment matches. final List<String> wildcardSegments = wildcardFile?.split('*') ?? <String>[]; if (wildcardSegments.length > 2) { throw InvalidPatternException(pattern); } if (!environment.fileSystem.directory(filePath).existsSync()) { environment.fileSystem.directory(filePath).createSync(recursive: true); } for (final FileSystemEntity entity in environment.fileSystem.directory(filePath).listSync()) { final String filename = environment.fileSystem.path.basename(entity.path); if (wildcardSegments.isEmpty) { sources.add(environment.fileSystem.file(entity.absolute)); } else if (wildcardSegments.length == 1) { if (filename.startsWith(wildcardSegments[0]) || filename.endsWith(wildcardSegments[0])) { sources.add(environment.fileSystem.file(entity.absolute)); } } else if (filename.startsWith(wildcardSegments[0])) { if (filename.substring(wildcardSegments[0].length).endsWith(wildcardSegments[1])) { sources.add(environment.fileSystem.file(entity.absolute)); } } } } /// Visit a [Source] which is defined by an [Artifact] from the flutter cache. /// /// If the [Artifact] points to a directory then all child files are included. /// To increase the performance of builds that use a known revision of Flutter, /// these are updated to point towards the engine.version file instead of /// the artifact itself. void visitArtifact(Artifact artifact, TargetPlatform? platform, BuildMode? mode) { // This is not a local engine. if (environment.engineVersion != null) { sources.add(environment.flutterRootDir .childDirectory('bin') .childDirectory('internal') .childFile('engine.version'), ); return; } final String path = environment.artifacts .getArtifactPath(artifact, platform: platform, mode: mode); if (environment.fileSystem.isDirectorySync(path)) { sources.addAll(<File>[ for (final FileSystemEntity entity in environment.fileSystem.directory(path).listSync(recursive: true)) if (entity is File) entity, ]); return; } sources.add(environment.fileSystem.file(path)); } /// Visit a [Source] which is defined by an [HostArtifact] from the flutter cache. /// /// If the [Artifact] points to a directory then all child files are included. /// To increase the performance of builds that use a known revision of Flutter, /// these are updated to point towards the engine.version file instead of /// the artifact itself. void visitHostArtifact(HostArtifact artifact) { // This is not a local engine. if (environment.engineVersion != null) { sources.add(environment.flutterRootDir .childDirectory('bin') .childDirectory('internal') .childFile('engine.version'), ); return; } final FileSystemEntity entity = environment.artifacts.getHostArtifact(artifact); if (entity is Directory) { sources.addAll(<File>[ for (final FileSystemEntity entity in entity.listSync(recursive: true)) if (entity is File) entity, ]); return; } sources.add(entity as File); } } /// A description of an input or output of a [Target]. abstract class Source { /// This source is a file URL which contains some references to magic /// environment variables. const factory Source.pattern(String pattern, { bool optional }) = _PatternSource; /// The source is provided by an [Artifact]. /// /// If [artifact] points to a directory then all child files are included. const factory Source.artifact(Artifact artifact, {TargetPlatform? platform, BuildMode? mode}) = _ArtifactSource; /// The source is provided by an [HostArtifact]. /// /// If [artifact] points to a directory then all child files are included. const factory Source.hostArtifact(HostArtifact artifact) = _HostArtifactSource; /// Visit the particular source type. void accept(SourceVisitor visitor); /// Whether the output source provided can be known before executing the rule. /// /// This does not apply to inputs, which are always explicit and must be /// evaluated before the build. /// /// For example, [Source.pattern] and [Source.version] are not implicit /// provided they do not use any wildcards. bool get implicit; } class _PatternSource implements Source { const _PatternSource(this.value, { this.optional = false }); final String value; final bool optional; @override void accept(SourceVisitor visitor) => visitor.visitPattern(value, optional); @override bool get implicit => value.contains('*'); } class _ArtifactSource implements Source { const _ArtifactSource(this.artifact, { this.platform, this.mode }); final Artifact artifact; final TargetPlatform? platform; final BuildMode? mode; @override void accept(SourceVisitor visitor) => visitor.visitArtifact(artifact, platform, mode); @override bool get implicit => false; } class _HostArtifactSource implements Source { const _HostArtifactSource(this.artifact); final HostArtifact artifact; @override void accept(SourceVisitor visitor) => visitor.visitHostArtifact(artifact); @override bool get implicit => false; }
flutter/packages/flutter_tools/lib/src/build_system/source.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/build_system/source.dart", "repo_id": "flutter", "token_count": 3432 }
357
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:math' as math; import 'dart:typed_data'; import 'package:meta/meta.dart'; import 'package:pool/pool.dart'; import 'package:process/process.dart'; import '../../artifacts.dart'; import '../../base/error_handling_io.dart'; import '../../base/file_system.dart'; import '../../base/io.dart'; import '../../base/logger.dart'; import '../../convert.dart'; import '../../devfs.dart'; import '../build_system.dart'; /// A wrapper around [SceneImporter] to support hot reload of 3D models. class DevelopmentSceneImporter { DevelopmentSceneImporter({ required SceneImporter sceneImporter, required FileSystem fileSystem, @visibleForTesting math.Random? random, }) : _sceneImporter = sceneImporter, _fileSystem = fileSystem, _random = random ?? math.Random(); final SceneImporter _sceneImporter; final FileSystem _fileSystem; final Pool _compilationPool = Pool(4); final math.Random _random; /// Recompile the input ipscene and return a devfs content that should be /// synced to the attached device in its place. Future<DevFSContent?> reimportScene(DevFSContent inputScene) async { final File output = _fileSystem.systemTempDirectory.childFile('${_random.nextDouble()}.temp'); late File inputFile; bool cleanupInput = false; Uint8List result; PoolResource? resource; try { resource = await _compilationPool.request(); if (inputScene is DevFSFileContent) { inputFile = inputScene.file as File; } else { inputFile = _fileSystem.systemTempDirectory.childFile('${_random.nextDouble()}.temp'); inputFile.writeAsBytesSync(await inputScene.contentsAsBytes()); cleanupInput = true; } final bool success = await _sceneImporter.importScene( input: inputFile, outputPath: output.path, fatal: false, ); if (!success) { return null; } result = output.readAsBytesSync(); } finally { resource?.release(); ErrorHandlingFileSystem.deleteIfExists(output); if (cleanupInput) { ErrorHandlingFileSystem.deleteIfExists(inputFile); } } return DevFSByteContent(result); } } /// A class the wraps the functionality of the Impeller Scene importer scenec. class SceneImporter { SceneImporter({ required ProcessManager processManager, required Logger logger, required FileSystem fileSystem, required Artifacts artifacts, }) : _processManager = processManager, _logger = logger, _fs = fileSystem, _artifacts = artifacts; final ProcessManager _processManager; final Logger _logger; final FileSystem _fs; final Artifacts _artifacts; /// The [Source] inputs that targets using this should depend on. /// /// See [Target.inputs]. static const List<Source> inputs = <Source>[ Source.pattern( '{FLUTTER_ROOT}/packages/flutter_tools/lib/src/build_system/tools/scene_importer.dart'), Source.hostArtifact(HostArtifact.scenec), ]; /// Calls scenec, which transforms the [input] 3D model into an imported /// ipscene at [outputPath]. /// /// All parameters are required. /// /// If the scene importer subprocess fails, it will print the stdout and /// stderr to the log and throw a [SceneImporterException]. Otherwise, it /// will return true. Future<bool> importScene({ required File input, required String outputPath, bool fatal = true, }) async { final File scenec = _fs.file( _artifacts.getHostArtifact(HostArtifact.scenec), ); if (!scenec.existsSync()) { throw SceneImporterException._( 'The scenec utility is missing at "${scenec.path}". ' 'Run "flutter doctor".', ); } final List<String> cmd = <String>[ scenec.path, '--input=${input.path}', '--output=$outputPath', ]; _logger.printTrace('scenec command: $cmd'); final Process scenecProcess = await _processManager.start(cmd); final int code = await scenecProcess.exitCode; if (code != 0) { final String stdout = await utf8.decodeStream(scenecProcess.stdout); final String stderr = await utf8.decodeStream(scenecProcess.stderr); _logger.printTrace(stdout); _logger.printError(stderr); if (fatal) { throw SceneImporterException._( 'Scene import of "${input.path}" to "$outputPath" ' 'failed with exit code $code.\n' 'scenec stdout:\n$stdout\n' 'scenec stderr:\n$stderr', ); } return false; } return true; } } class SceneImporterException implements Exception { SceneImporterException._(this.message); final String message; @override String toString() => 'SceneImporterException: $message\n\n'; }
flutter/packages/flutter_tools/lib/src/build_system/tools/scene_importer.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/build_system/tools/scene_importer.dart", "repo_id": "flutter", "token_count": 1791 }
358
// Copyright 2014 The Flutter 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:unified_analytics/unified_analytics.dart'; import '../android/android_builder.dart'; import '../android/build_validation.dart'; import '../android/gradle_utils.dart'; import '../build_info.dart'; import '../cache.dart'; import '../globals.dart' as globals; import '../project.dart'; import '../reporting/reporting.dart'; import '../runner/flutter_command.dart' show FlutterCommandResult; import 'build.dart'; class BuildApkCommand extends BuildSubCommand { BuildApkCommand({ required super.logger, bool verboseHelp = false }) : super(verboseHelp: verboseHelp) { addTreeShakeIconsFlag(); usesTargetOption(); addBuildModeFlags(verboseHelp: verboseHelp); usesFlavorOption(); usesPubOption(); usesBuildNumberOption(); usesBuildNameOption(); addShrinkingFlag(verboseHelp: verboseHelp); addSplitDebugInfoOption(); addDartObfuscationOption(); usesDartDefineOption(); usesExtraDartFlagOptions(verboseHelp: verboseHelp); addBundleSkSLPathOption(hide: !verboseHelp); addEnableExperimentation(hide: !verboseHelp); addBuildPerformanceFile(hide: !verboseHelp); addNullSafetyModeOptions(hide: !verboseHelp); usesAnalyzeSizeFlag(); addAndroidSpecificBuildOptions(hide: !verboseHelp); addIgnoreDeprecationOption(); argParser ..addFlag('split-per-abi', negatable: false, help: 'Whether to split the APKs per ABIs. ' 'To learn more, see: https://developer.android.com/studio/build/configure-apk-splits#configure-abi-split', ) ..addFlag('config-only', help: 'Generate build files used by flutter but ' 'do not build any artifacts.') ..addMultiOption('target-platform', defaultsTo: <String>['android-arm', 'android-arm64', 'android-x64'], allowed: <String>['android-arm', 'android-arm64', 'android-x86', 'android-x64'], help: 'The target platform for which the app is compiled.', ); usesTrackWidgetCreation(verboseHelp: verboseHelp); } @override final String name = 'apk'; @override DeprecationBehavior get deprecationBehavior => boolArg('ignore-deprecation') ? DeprecationBehavior.ignore : DeprecationBehavior.exit; bool get configOnly => boolArg('config-only'); @override Future<Set<DevelopmentArtifact>> get requiredArtifacts async => <DevelopmentArtifact>{ DevelopmentArtifact.androidGenSnapshot, }; @override final String description = 'Build an Android APK file from your app.\n\n' "This command can build debug and release versions of your application. 'debug' builds support " "debugging and a quick development cycle. 'release' builds don't support debugging and are " 'suitable for deploying to app stores. If you are deploying the app to the Play Store, ' "it's recommended to use app bundles or split the APK to reduce the APK size. Learn more at:\n\n" ' * https://developer.android.com/guide/app-bundle\n' ' * https://developer.android.com/studio/build/configure-apk-splits#configure-abi-split'; @override Future<CustomDimensions> get usageValues async { String buildMode; if (boolArg('release')) { buildMode = 'release'; } else if (boolArg('debug')) { buildMode = 'debug'; } else if (boolArg('profile')) { buildMode = 'profile'; } else { // The build defaults to release. buildMode = 'release'; } return CustomDimensions( commandBuildApkTargetPlatform: stringsArg('target-platform').join(','), commandBuildApkBuildMode: buildMode, commandBuildApkSplitPerAbi: boolArg('split-per-abi'), ); } @override Future<Event> unifiedAnalyticsUsageValues(String commandPath) async { final String buildMode; if (boolArg('release')) { buildMode = 'release'; } else if (boolArg('debug')) { buildMode = 'debug'; } else if (boolArg('profile')) { buildMode = 'profile'; } else { // The build defaults to release. buildMode = 'release'; } return Event.commandUsageValues( workflow: commandPath, commandHasTerminal: hasTerminal, buildApkTargetPlatform: stringsArg('target-platform').join(','), buildApkBuildMode: buildMode, buildApkSplitPerAbi: boolArg('split-per-abi'), ); } @override Future<FlutterCommandResult> runCommand() async { if (globals.androidSdk == null) { exitWithNoSdkMessage(); } final BuildInfo buildInfo = await getBuildInfo(); final AndroidBuildInfo androidBuildInfo = AndroidBuildInfo( buildInfo, splitPerAbi: boolArg('split-per-abi'), targetArchs: stringsArg('target-platform').map<AndroidArch>(getAndroidArchForName), ); validateBuild(androidBuildInfo); displayNullSafetyMode(androidBuildInfo.buildInfo); globals.terminal.usesTerminalUi = true; await androidBuilder?.buildApk( project: FlutterProject.current(), target: targetFile, androidBuildInfo: androidBuildInfo, configOnly: configOnly, ); return FlutterCommandResult.success(); } }
flutter/packages/flutter_tools/lib/src/commands/build_apk.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/commands/build_apk.dart", "repo_id": "flutter", "token_count": 1861 }
359
// Copyright 2014 The Flutter 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:async/async.dart'; import 'package:meta/meta.dart'; import 'package:process/process.dart'; import '../base/common.dart'; import '../base/error_handling_io.dart'; import '../base/file_system.dart'; import '../base/io.dart'; import '../base/logger.dart'; import '../base/os.dart'; import '../base/platform.dart'; import '../base/terminal.dart'; import '../convert.dart'; import '../custom_devices/custom_device.dart'; import '../custom_devices/custom_device_config.dart'; import '../custom_devices/custom_devices_config.dart'; import '../device_port_forwarder.dart'; import '../features.dart'; import '../runner/flutter_command.dart'; import '../runner/flutter_command_runner.dart'; /// just the function signature of the [print] function. /// The Object arg may be null. typedef PrintFn = void Function(Object); class CustomDevicesCommand extends FlutterCommand { factory CustomDevicesCommand({ required CustomDevicesConfig customDevicesConfig, required OperatingSystemUtils operatingSystemUtils, required Terminal terminal, required Platform platform, required ProcessManager processManager, required FileSystem fileSystem, required Logger logger, required FeatureFlags featureFlags, }) { return CustomDevicesCommand._common( customDevicesConfig: customDevicesConfig, operatingSystemUtils: operatingSystemUtils, terminal: terminal, platform: platform, processManager: processManager, fileSystem: fileSystem, logger: logger, featureFlags: featureFlags ); } @visibleForTesting factory CustomDevicesCommand.test({ required CustomDevicesConfig customDevicesConfig, required OperatingSystemUtils operatingSystemUtils, required Terminal terminal, required Platform platform, required ProcessManager processManager, required FileSystem fileSystem, required Logger logger, required FeatureFlags featureFlags, PrintFn usagePrintFn = print }) { return CustomDevicesCommand._common( customDevicesConfig: customDevicesConfig, operatingSystemUtils: operatingSystemUtils, terminal: terminal, platform: platform, processManager: processManager, fileSystem: fileSystem, logger: logger, featureFlags: featureFlags, usagePrintFn: usagePrintFn ); } CustomDevicesCommand._common({ required CustomDevicesConfig customDevicesConfig, required OperatingSystemUtils operatingSystemUtils, required Terminal terminal, required Platform platform, required ProcessManager processManager, required FileSystem fileSystem, required Logger logger, required FeatureFlags featureFlags, PrintFn usagePrintFn = print, }) : _customDevicesConfig = customDevicesConfig, _featureFlags = featureFlags, _usagePrintFn = usagePrintFn { addSubcommand(CustomDevicesListCommand( customDevicesConfig: customDevicesConfig, featureFlags: featureFlags, logger: logger, )); addSubcommand(CustomDevicesResetCommand( customDevicesConfig: customDevicesConfig, featureFlags: featureFlags, fileSystem: fileSystem, logger: logger, )); addSubcommand(CustomDevicesAddCommand( customDevicesConfig: customDevicesConfig, operatingSystemUtils: operatingSystemUtils, terminal: terminal, platform: platform, featureFlags: featureFlags, processManager: processManager, fileSystem: fileSystem, logger: logger, )); addSubcommand(CustomDevicesDeleteCommand( customDevicesConfig: customDevicesConfig, featureFlags: featureFlags, fileSystem: fileSystem, logger: logger, )); } final CustomDevicesConfig _customDevicesConfig; final FeatureFlags _featureFlags; final PrintFn _usagePrintFn; @override String get description { String configFileLine; if (_featureFlags.areCustomDevicesEnabled) { configFileLine = '\nMakes changes to the config file at "${_customDevicesConfig.configPath}".\n'; } else { configFileLine = ''; } return ''' List, reset, add and delete custom devices. $configFileLine This is just a collection of commonly used shorthands for things like adding ssh devices, resetting (with backup) and checking the config file. For advanced configuration or more complete documentation, edit the config file with an editor that supports JSON schemas like VS Code. Requires the custom devices feature to be enabled. You can enable it using "flutter config --enable-custom-devices". '''; } @override String get name => 'custom-devices'; @override String get category => FlutterCommandCategory.tools; @override Future<FlutterCommandResult> runCommand() async { return FlutterCommandResult.success(); } @override void printUsage() { _usagePrintFn(usage); } } /// This class is meant to provide some commonly used utility functions /// to the subcommands, like backing up the config file & checking if the /// feature is enabled. abstract class CustomDevicesCommandBase extends FlutterCommand { CustomDevicesCommandBase({ required this.customDevicesConfig, required this.featureFlags, required this.fileSystem, required this.logger, }); @protected final CustomDevicesConfig customDevicesConfig; @protected final FeatureFlags featureFlags; @protected final FileSystem? fileSystem; @protected final Logger logger; /// The path to the (potentially non-existing) backup of the config file. @protected String get configBackupPath => '${customDevicesConfig.configPath}.bak'; /// Copies the current config file to [configBackupPath], overwriting it /// if necessary. Returns false and does nothing if the current config file /// doesn't exist. (True otherwise) @protected bool backup() { final File configFile = fileSystem!.file(customDevicesConfig.configPath); if (configFile.existsSync()) { configFile.copySync(configBackupPath); return true; } return false; } /// Checks if the custom devices feature is enabled and returns true/false /// accordingly. Additionally, logs an error if it's not enabled with a hint /// on how to enable it. @protected void checkFeatureEnabled() { if (!featureFlags.areCustomDevicesEnabled) { throwToolExit( 'Custom devices feature must be enabled. ' 'Enable using `flutter config --enable-custom-devices`.' ); } } } class CustomDevicesListCommand extends CustomDevicesCommandBase { CustomDevicesListCommand({ required super.customDevicesConfig, required super.featureFlags, required super.logger, }) : super( fileSystem: null ); @override String get description => ''' List the currently configured custom devices, both enabled and disabled, reachable or not. '''; @override String get name => 'list'; @override Future<FlutterCommandResult> runCommand() async { checkFeatureEnabled(); late List<CustomDeviceConfig> devices; try { devices = customDevicesConfig.devices; } on Exception { throwToolExit('Could not list custom devices.'); } if (devices.isEmpty) { logger.printStatus('No custom devices found in "${customDevicesConfig.configPath}"'); } else { logger.printStatus('List of custom devices in "${customDevicesConfig.configPath}":'); for (final CustomDeviceConfig device in devices) { logger.printStatus('id: ${device.id}, label: ${device.label}, enabled: ${device.enabled}', indent: 2, hangingIndent: 2); } } return FlutterCommandResult.success(); } } class CustomDevicesResetCommand extends CustomDevicesCommandBase { CustomDevicesResetCommand({ required super.customDevicesConfig, required super.featureFlags, required FileSystem super.fileSystem, required super.logger, }); @override String get description => ''' Reset the config file to the default. The current config file will be backed up to the same path, but with a `.bak` appended. If a file already exists at the backup location, it will be overwritten. '''; @override String get name => 'reset'; @override Future<FlutterCommandResult> runCommand() async { checkFeatureEnabled(); final bool wasBackedUp = backup(); ErrorHandlingFileSystem.deleteIfExists(fileSystem!.file(customDevicesConfig.configPath)); customDevicesConfig.ensureFileExists(); logger.printStatus( wasBackedUp ? 'Successfully reset the custom devices config file and created a ' 'backup at "$configBackupPath".' : 'Successfully reset the custom devices config file.' ); return FlutterCommandResult.success(); } } class CustomDevicesAddCommand extends CustomDevicesCommandBase { CustomDevicesAddCommand({ required super.customDevicesConfig, required OperatingSystemUtils operatingSystemUtils, required Terminal terminal, required Platform platform, required super.featureFlags, required ProcessManager processManager, required FileSystem super.fileSystem, required super.logger, }) : _operatingSystemUtils = operatingSystemUtils, _terminal = terminal, _platform = platform, _processManager = processManager { argParser.addFlag( _kCheck, help: 'Make sure the config actually works. This will execute some of the ' 'commands in the config (if necessary with dummy arguments). This ' 'flag is enabled by default when "--json" is not specified. If ' '"--json" is given, it is disabled by default.\n' 'For example, a config with "null" as the "runDebug" command is ' 'invalid. If the "runDebug" command is valid (so it is an array of ' 'strings) but the command is not found (because you have a typo, for ' 'example), the config won\'t work and "--check" will spot that.' ); argParser.addOption( _kJson, help: 'Add the custom device described by this JSON-encoded string to the ' 'list of custom-devices instead of using the normal, interactive way ' 'of configuring. Useful if you want to use the "flutter custom-devices ' 'add" command from a script, or use it non-interactively for some ' 'other reason.\n' "By default, this won't check whether the passed in config actually " 'works. For more info see the "--check" option.', valueHelp: '{"id": "pi", ...}', aliases: _kJsonAliases ); argParser.addFlag( _kSsh, help: 'Add a ssh-device. This will automatically fill out some of the config ' 'options for you with good defaults, and in other cases save you some ' "typing. So you'll only need to enter some things like hostname and " 'username of the remote device instead of entering each individual ' 'command.', defaultsTo: true, negatable: false ); } static const String _kJson = 'json'; static const List<String> _kJsonAliases = <String>['js']; static const String _kCheck = 'check'; static const String _kSsh = 'ssh'; // A hostname consists of one or more "names", separated by a dot. // A name may consist of alpha-numeric characters. Hyphens are also allowed, // but not as the first or last character of the name. static final RegExp _hostnameRegex = RegExp(r'^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$'); final OperatingSystemUtils _operatingSystemUtils; final Terminal _terminal; final Platform _platform; final ProcessManager _processManager; late StreamQueue<String> inputs; @override String get description => 'Add a new device the custom devices config file.'; @override String get name => 'add'; void _printConfigCheckingError(String err) { logger.printError(err); } /// Check this config by executing some of the commands, see if they run /// fine. Future<bool> _checkConfigWithLogging(final CustomDeviceConfig config) async { final CustomDevice device = CustomDevice( config: config, logger: logger, processManager: _processManager ); bool result = true; try { final bool reachable = await device.tryPing(); if (!reachable) { _printConfigCheckingError("Couldn't ping device."); result = false; } } on Exception catch (e) { _printConfigCheckingError('While executing ping command: $e'); result = false; } final Directory temp = await fileSystem!.systemTempDirectory.createTemp(); try { final bool ok = await device.tryInstall( localPath: temp.path, appName: temp.basename ); if (!ok) { _printConfigCheckingError("Couldn't install test app on device."); result = false; } } on Exception catch (e) { _printConfigCheckingError('While executing install command: $e'); result = false; } await temp.delete(); try { final bool ok = await device.tryUninstall(appName: temp.basename); if (!ok) { _printConfigCheckingError("Couldn't uninstall test app from device."); result = false; } } on Exception catch (e) { _printConfigCheckingError('While executing uninstall command: $e'); result = false; } if (config.usesPortForwarding) { final CustomDevicePortForwarder portForwarder = CustomDevicePortForwarder( deviceName: device.name, forwardPortCommand: config.forwardPortCommand!, forwardPortSuccessRegex: config.forwardPortSuccessRegex!, processManager: _processManager, logger: logger, ); try { // find a random port we can forward final int port = await _operatingSystemUtils.findFreePort(); final ForwardedPort? forwardedPort = await portForwarder.tryForward(port, port); if (forwardedPort == null) { _printConfigCheckingError("Couldn't forward test port $port from device.",); result = false; } else { await portForwarder.unforward(forwardedPort); } } on Exception catch (e) { _printConfigCheckingError( 'While forwarding/unforwarding device port: $e', ); result = false; } } if (result) { logger.printStatus('Passed all checks successfully.'); } return result; } /// Run non-interactively (useful if running from scripts or bots), /// add value of the `--json` arg to the config. /// /// Only check if `--check` is explicitly specified. (Don't check by default) Future<FlutterCommandResult> runNonInteractively() async { final String jsonStr = stringArg(_kJson)!; final bool shouldCheck = boolArg(_kCheck); dynamic json; try { json = jsonDecode(jsonStr); } on FormatException catch (e) { throwToolExit('Could not decode json: $e'); } late CustomDeviceConfig config; try { config = CustomDeviceConfig.fromJson(json); } on CustomDeviceRevivalException catch (e) { throwToolExit('Invalid custom device config: $e'); } if (shouldCheck && !await _checkConfigWithLogging(config)) { throwToolExit("Custom device didn't pass all checks."); } customDevicesConfig.add(config); printSuccessfullyAdded(); return FlutterCommandResult.success(); } void printSuccessfullyAdded() { logger.printStatus('Successfully added custom device to config file at "${customDevicesConfig.configPath}".'); } bool _isValidHostname(String s) => _hostnameRegex.hasMatch(s); bool _isValidIpAddr(String s) => InternetAddress.tryParse(s) != null; /// Ask the user to input a string. Future<String?> askForString( String name, { String? description, String? example, String? defaultsTo, Future<bool> Function(String)? validator, }) async { String msg = description ?? name; final String exampleOrDefault = <String>[ if (example != null) 'example: $example', if (defaultsTo != null) 'empty for $defaultsTo', ].join(', '); if (exampleOrDefault.isNotEmpty) { msg += ' ($exampleOrDefault)'; } logger.printStatus(msg); while (true) { if (!await inputs.hasNext) { return null; } final String input = await inputs.next; if (validator != null && !await validator(input)) { logger.printStatus('Invalid input. Please enter $name:'); } else { return input; } } } /// Ask the user for a y(es) / n(o) or empty input. Future<bool> askForBool( String name, { String? description, bool defaultsTo = true, }) async { final String defaultsToStr = defaultsTo ? '[Y/n]' : '[y/N]'; logger.printStatus('$description $defaultsToStr (empty for default)'); while (true) { final String input = await inputs.next; if (input.isEmpty) { return defaultsTo; } else if (input.toLowerCase() == 'y') { return true; } else if (input.toLowerCase() == 'n') { return false; } else { logger.printStatus('Invalid input. Expected is either y, n or empty for default. $name? $defaultsToStr'); } } } /// Ask the user if he wants to apply the config. /// Shows a different prompt if errors or warnings exist in the config. Future<bool> askApplyConfig({bool hasErrorsOrWarnings = false}) { return askForBool( 'apply', description: hasErrorsOrWarnings ? 'Warnings or errors exist in custom device. ' 'Would you like to add the custom device to the config anyway?' : 'Would you like to add the custom device to the config now?', defaultsTo: !hasErrorsOrWarnings ); } /// Run interactively (with user prompts), the target device should be /// connected to via ssh. Future<FlutterCommandResult> runInteractivelySsh() async { final bool shouldCheck = boolArg(_kCheck); // Listen to the keystrokes stream as late as possible, since it's a // single-subscription stream apparently. // Also, _terminal.keystrokes can be closed unexpectedly, which will result // in StreamQueue.next throwing a StateError when make the StreamQueue listen // to that directly. // This caused errors when using Ctrl+C to terminate while the // custom-devices add command is waiting for user input. // So instead, we add the keystrokes stream events to a new single-subscription // stream and listen to that instead. final StreamController<String> nonClosingKeystrokes = StreamController<String>(); final StreamSubscription<String> keystrokesSubscription = _terminal.keystrokes.listen( (String s) => nonClosingKeystrokes.add(s.trim()), cancelOnError: true ); inputs = StreamQueue<String>(nonClosingKeystrokes.stream); final String id = (await askForString( 'id', description: 'Please enter the id you want to device to have. Must contain only ' 'alphanumeric or underscore characters.', example: 'pi', validator: (String s) async => RegExp(r'^\w+$').hasMatch(s), ))!; final String label = (await askForString( 'label', description: 'Please enter the label of the device, which is a slightly more verbose ' 'name for the device.', example: 'Raspberry Pi', ))!; final String sdkNameAndVersion = (await askForString( 'SDK name and version', example: 'Raspberry Pi 4 Model B+', ))!; final bool enabled = await askForBool( 'enabled', description: 'Should the device be enabled?', ); final String targetStr = (await askForString( 'target', description: 'Please enter the hostname or IPv4/v6 address of the device.', example: 'raspberrypi', validator: (String s) async => _isValidHostname(s) || _isValidIpAddr(s) ))!; final InternetAddress? targetIp = InternetAddress.tryParse(targetStr); final bool useIp = targetIp != null; final bool ipv6 = useIp && targetIp.type == InternetAddressType.IPv6; final InternetAddress loopbackIp = ipv6 ? InternetAddress.loopbackIPv6 : InternetAddress.loopbackIPv4; final String username = (await askForString( 'username', description: 'Please enter the username used for ssh-ing into the remote device.', example: 'pi', defaultsTo: 'no username', ))!; final String remoteRunDebugCommand = (await askForString( 'run command', description: 'Please enter the command executed on the remote device for starting ' r'the app. "/tmp/${appName}" is the path to the asset bundle.', example: r'flutter-pi /tmp/${appName}' ))!; final bool usePortForwarding = await askForBool( 'use port forwarding', description: 'Should the device use port forwarding? ' 'Using port forwarding is the default because it works in all cases, however if your ' 'remote device has a static IP address and you have a way of ' 'specifying the "--vm-service-host=<ip>" engine option, you might prefer ' 'not using port forwarding.', ); final String screenshotCommand = (await askForString( 'screenshot command', description: 'Enter the command executed on the remote device for taking a screenshot.', example: r"fbgrab /tmp/screenshot.png && cat /tmp/screenshot.png | base64 | tr -d ' \n\t'", defaultsTo: 'no screenshotting support', ))!; // SSH expects IPv6 addresses to use the bracket syntax like URIs do too, // but the IPv6 the user enters is a raw IPv6 address, so we need to wrap it. final String sshTarget = (username.isNotEmpty ? '$username@' : '') + (ipv6 ? '[${targetIp.address}]' : targetStr); final String formattedLoopbackIp = ipv6 ? '[${loopbackIp.address}]' : loopbackIp.address; CustomDeviceConfig config = CustomDeviceConfig( id: id, label: label, sdkNameAndVersion: sdkNameAndVersion, enabled: enabled, // host-platform specific, filled out later pingCommand: const <String>[], postBuildCommand: const <String>[], // just install to /tmp/${appName} by default installCommand: <String>[ 'scp', '-r', '-o', 'BatchMode=yes', if (ipv6) '-6', r'${localPath}', '$sshTarget:/tmp/\${appName}', ], uninstallCommand: <String>[ 'ssh', '-o', 'BatchMode=yes', if (ipv6) '-6', sshTarget, r'rm -rf "/tmp/${appName}"', ], runDebugCommand: <String>[ 'ssh', '-o', 'BatchMode=yes', if (ipv6) '-6', sshTarget, remoteRunDebugCommand, ], forwardPortCommand: usePortForwarding ? <String>[ 'ssh', '-o', 'BatchMode=yes', '-o', 'ExitOnForwardFailure=yes', if (ipv6) '-6', '-L', '$formattedLoopbackIp:\${hostPort}:$formattedLoopbackIp:\${devicePort}', sshTarget, "echo 'Port forwarding success'; read", ] : null, forwardPortSuccessRegex: usePortForwarding ? RegExp('Port forwarding success') : null, screenshotCommand: screenshotCommand.isNotEmpty ? <String>[ 'ssh', '-o', 'BatchMode=yes', if (ipv6) '-6', sshTarget, screenshotCommand, ] : null ); if (_platform.isWindows) { config = config.copyWith( pingCommand: <String>[ 'ping', if (ipv6) '-6', '-n', '1', '-w', '500', targetStr, ], explicitPingSuccessRegex: true, pingSuccessRegex: RegExp(r'[<=]\d+ms') ); } else if (_platform.isLinux || _platform.isMacOS) { config = config.copyWith( pingCommand: <String>[ 'ping', if (ipv6) '-6', '-c', '1', '-w', '1', targetStr, ], explicitPingSuccessRegex: true, ); } else { throw UnsupportedError('Unsupported operating system'); } final bool apply = await askApplyConfig( hasErrorsOrWarnings: shouldCheck && !(await _checkConfigWithLogging(config)) ); unawaited(keystrokesSubscription.cancel()); unawaited(nonClosingKeystrokes.close()); if (apply) { customDevicesConfig.add(config); printSuccessfullyAdded(); } return FlutterCommandResult.success(); } @override Future<FlutterCommandResult> runCommand() async { checkFeatureEnabled(); if (stringArg(_kJson) != null) { return runNonInteractively(); } if (boolArg(_kSsh)) { return runInteractivelySsh(); } throw UnsupportedError('Unknown run mode'); } } class CustomDevicesDeleteCommand extends CustomDevicesCommandBase { CustomDevicesDeleteCommand({ required super.customDevicesConfig, required super.featureFlags, required FileSystem super.fileSystem, required super.logger, }); @override String get description => ''' Delete a device from the config file. '''; @override String get name => 'delete'; @override Future<FlutterCommandResult> runCommand() async { checkFeatureEnabled(); final String? id = globalResults![FlutterGlobalOptions.kDeviceIdOption] as String?; if (id == null || !customDevicesConfig.contains(id)) { throwToolExit('Couldn\'t find device with id "$id" in config at "${customDevicesConfig.configPath}"'); } backup(); customDevicesConfig.remove(id); logger.printStatus('Successfully removed device with id "$id" from config at "${customDevicesConfig.configPath}"'); return FlutterCommandResult.success(); } }
flutter/packages/flutter_tools/lib/src/commands/custom_devices.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/commands/custom_devices.dart", "repo_id": "flutter", "token_count": 9313 }
360
// Copyright 2014 The Flutter 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 '../base/common.dart'; import '../base/logger.dart'; import '../base/platform.dart'; import '../cache.dart'; import '../features.dart'; import '../runner/flutter_command.dart'; /// The flutter precache command allows downloading of cache artifacts without /// the use of device/artifact autodetection. class PrecacheCommand extends FlutterCommand { PrecacheCommand({ bool verboseHelp = false, required Cache cache, required Platform platform, required Logger logger, required FeatureFlags featureFlags, }) : _cache = cache, _platform = platform, _logger = logger, _featureFlags = featureFlags { argParser.addFlag('all-platforms', abbr: 'a', negatable: false, help: 'Precache artifacts for all host platforms.', aliases: const <String>['all']); argParser.addFlag('force', abbr: 'f', negatable: false, help: 'Force re-downloading of artifacts.'); argParser.addFlag('android', help: 'Precache artifacts for Android development.', hide: !verboseHelp); argParser.addFlag('android_gen_snapshot', help: 'Precache gen_snapshot for Android development.', hide: !verboseHelp); argParser.addFlag('android_maven', help: 'Precache Gradle dependencies for Android development.', hide: !verboseHelp); argParser.addFlag('android_internal_build', help: 'Precache dependencies for internal Android development.', hide: !verboseHelp); argParser.addFlag('ios', help: 'Precache artifacts for iOS development.'); argParser.addFlag('web', help: 'Precache artifacts for web development.'); argParser.addFlag('linux', help: 'Precache artifacts for Linux desktop development.'); argParser.addFlag('windows', help: 'Precache artifacts for Windows desktop development.'); argParser.addFlag('macos', help: 'Precache artifacts for macOS desktop development.'); argParser.addFlag('fuchsia', help: 'Precache artifacts for Fuchsia development.'); argParser.addFlag('universal', defaultsTo: true, help: 'Precache artifacts required for any development platform.'); argParser.addFlag('flutter_runner', help: 'Precache the flutter runner artifacts.', hide: !verboseHelp); argParser.addFlag('use-unsigned-mac-binaries', help: 'Precache the unsigned macOS binaries when available.', hide: !verboseHelp); } final Cache _cache; final Logger _logger; final Platform _platform; final FeatureFlags _featureFlags; @override final String name = 'precache'; @override final String description = "Populate the Flutter tool's cache of binary artifacts.\n\n" 'If no explicit platform flags are provided, this command will download the artifacts ' 'for all currently enabled platforms'; @override final String category = FlutterCommandCategory.sdk; @override bool get shouldUpdateCache => false; /// Some flags are umbrella names that expand to include multiple artifacts. static const Map<String, List<String>> _expandedArtifacts = <String, List<String>>{ 'android': <String>[ 'android_gen_snapshot', 'android_maven', 'android_internal_build', ], }; /// Returns a reverse mapping of _expandedArtifacts, from child artifact name /// to umbrella name. Map<String, String> _umbrellaForArtifactMap() { return <String, String>{ for (final MapEntry<String, List<String>> entry in _expandedArtifacts.entries) for (final String childArtifactName in entry.value) childArtifactName: entry.key, }; } /// Returns the name of all artifacts that were explicitly chosen via flags. /// /// If an umbrella is chosen, its children will be included as well. Set<String> _explicitArtifactSelections() { final Map<String, String> umbrellaForArtifact = _umbrellaForArtifactMap(); final Set<String> selections = <String>{}; bool explicitlySelected(String name) => boolArg(name) && argResults!.wasParsed(name); for (final DevelopmentArtifact artifact in DevelopmentArtifact.values) { final String? umbrellaName = umbrellaForArtifact[artifact.name]; if (explicitlySelected(artifact.name) || (umbrellaName != null && explicitlySelected(umbrellaName))) { selections.add(artifact.name); } } return selections; } @override Future<void> validateCommand() { _expandedArtifacts.forEach((String umbrellaName, List<String> childArtifactNames) { if (!argResults!.arguments.contains('--no-$umbrellaName')) { return; } for (final String childArtifactName in childArtifactNames) { if (argResults!.arguments.contains('--$childArtifactName')) { throwToolExit('--$childArtifactName requires --$umbrellaName'); } } }); return super.validateCommand(); } @override Future<FlutterCommandResult> runCommand() async { // Re-lock the cache. if (_platform.environment['FLUTTER_ALREADY_LOCKED'] != 'true') { await _cache.lock(); } if (boolArg('force')) { _cache.clearStampFiles(); } final bool includeAllPlatforms = boolArg('all-platforms'); if (includeAllPlatforms) { _cache.includeAllPlatforms = true; } if (boolArg('use-unsigned-mac-binaries')) { _cache.useUnsignedMacBinaries = true; } final Set<String> explicitlyEnabled = _explicitArtifactSelections(); _cache.platformOverrideArtifacts = explicitlyEnabled; // If the user did not provide any artifact flags, then download // all artifacts that correspond to an enabled platform. final bool downloadDefaultArtifacts = explicitlyEnabled.isEmpty; final Map<String, String> umbrellaForArtifact = _umbrellaForArtifactMap(); final Set<DevelopmentArtifact> requiredArtifacts = <DevelopmentArtifact>{}; for (final DevelopmentArtifact artifact in DevelopmentArtifact.values) { if (artifact.feature != null && !_featureFlags.isEnabled(artifact.feature!)) { continue; } final String argumentName = umbrellaForArtifact[artifact.name] ?? artifact.name; if (includeAllPlatforms || boolArg(argumentName) || downloadDefaultArtifacts) { requiredArtifacts.add(artifact); } } if (!await _cache.isUpToDate()) { await _cache.updateAll(requiredArtifacts); } else { _logger.printStatus('Already up-to-date.'); } return FlutterCommandResult.success(); } }
flutter/packages/flutter_tools/lib/src/commands/precache.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/commands/precache.dart", "repo_id": "flutter", "token_count": 2268 }
361
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:typed_data'; import 'package:meta/meta.dart'; import 'base/common.dart'; import 'base/io.dart'; import 'base/logger.dart'; import 'base/utils.dart'; import 'convert.dart'; /// A single message passed through the [DaemonConnection]. class DaemonMessage { DaemonMessage(this.data, [this.binary]); /// Content of the JSON message in the message. final Map<String, Object?> data; /// Stream of the binary content of the message. /// /// Must be listened to if binary data is present. final Stream<List<int>>? binary; } /// Data of an event passed through the [DaemonConnection]. class DaemonEventData { DaemonEventData(this.eventName, this.data, [this.binary]); /// The name of the event. final String eventName; /// The data of the event. final Object? data; /// Stream of the binary content of the event. /// /// Must be listened to if binary data is present. final Stream<List<int>>? binary; } const String _binaryLengthKey = '_binaryLength'; enum _InputStreamParseState { json, binary, } /// Converts a binary stream to a stream of [DaemonMessage]. /// /// The daemon JSON-RPC protocol is defined as follows: every single line of /// text that starts with `[{` and ends with `}]` will be parsed as a JSON /// message. The array should contain only one single object which contains the /// message data. /// /// If the JSON object contains the key [_binaryLengthKey] with an integer /// value (will be referred to as N), the following N bytes after the newline /// character will contain the binary part of the message. @visibleForTesting class DaemonInputStreamConverter { DaemonInputStreamConverter(this.inputStream) { // Lazily listen to the input stream. _controller.onListen = () { final StreamSubscription<List<int>> subscription = inputStream.listen((List<int> chunk) { _processChunk(chunk); }, onError: (Object error, StackTrace stackTrace) { _controller.addError(error, stackTrace); }, onDone: () { unawaited(_controller.close()); }); _controller.onCancel = subscription.cancel; // We should not handle onPause or onResume. When the stream is paused, we // still need to read from the input stream. }; } final Stream<List<int>> inputStream; final StreamController<DaemonMessage> _controller = StreamController<DaemonMessage>(); Stream<DaemonMessage> get convertedStream => _controller.stream; // Internal states /// The current parse state, whether we are expecting JSON or binary data. _InputStreamParseState state = _InputStreamParseState.json; /// The binary stream that is being transferred. late StreamController<List<int>> currentBinaryStream; /// Remaining length in bytes that have to be sent to the binary stream. int remainingBinaryLength = 0; /// Buffer to hold the current line of input data. final BytesBuilder bytesBuilder = BytesBuilder(copy: false); // Processes a single chunk received in the input stream. void _processChunk(List<int> chunk) { int start = 0; while (start < chunk.length) { switch (state) { case _InputStreamParseState.json: start += _processChunkInJsonMode(chunk, start); case _InputStreamParseState.binary: final int bytesSent = _addBinaryChunk(chunk, start, remainingBinaryLength); start += bytesSent; remainingBinaryLength -= bytesSent; if (remainingBinaryLength <= 0) { assert(remainingBinaryLength == 0); unawaited(currentBinaryStream.close()); state = _InputStreamParseState.json; } } } } /// Processes a chunk in JSON mode, and returns the number of bytes processed. int _processChunkInJsonMode(List<int> chunk, int start) { const int LF = 10; // The '\n' character // Search for newline character. final int indexOfNewLine = chunk.indexOf(LF, start); if (indexOfNewLine < 0) { bytesBuilder.add(chunk.sublist(start)); return chunk.length - start; } bytesBuilder.add(chunk.sublist(start, indexOfNewLine + 1)); // Process chunk here final Uint8List combinedChunk = bytesBuilder.takeBytes(); String jsonString = utf8.decode(combinedChunk).trim(); if (jsonString.startsWith('[{') && jsonString.endsWith('}]')) { jsonString = jsonString.substring(1, jsonString.length - 1); final Map<String, Object?>? value = castStringKeyedMap(json.decode(jsonString)); if (value != null) { // Check if we need to consume another binary blob. if (value[_binaryLengthKey] != null) { remainingBinaryLength = value[_binaryLengthKey]! as int; currentBinaryStream = StreamController<List<int>>(); state = _InputStreamParseState.binary; _controller.add(DaemonMessage(value, currentBinaryStream.stream)); } else { _controller.add(DaemonMessage(value)); } } } return indexOfNewLine + 1 - start; } int _addBinaryChunk(List<int> chunk, int start, int maximumSizeToRead) { if (start == 0 && chunk.length <= remainingBinaryLength) { currentBinaryStream.add(chunk); return chunk.length; } else { final int chunkRemainingLength = chunk.length - start; final int sizeToRead = chunkRemainingLength < remainingBinaryLength ? chunkRemainingLength : remainingBinaryLength; currentBinaryStream.add(chunk.sublist(start, start + sizeToRead)); return sizeToRead; } } } /// A stream that a [DaemonConnection] uses to communicate with each other. class DaemonStreams { DaemonStreams( Stream<List<int>> rawInputStream, StreamSink<List<int>> outputSink, { required Logger logger, }) : _outputSink = outputSink, inputStream = DaemonInputStreamConverter(rawInputStream).convertedStream, _logger = logger; /// Creates a [DaemonStreams] that uses stdin and stdout as the underlying streams. DaemonStreams.fromStdio(Stdio stdio, { required Logger logger }) : this(stdio.stdin, stdio.stdout, logger: logger); /// Creates a [DaemonStreams] that uses [Socket] as the underlying streams. DaemonStreams.fromSocket(Socket socket, { required Logger logger }) : this(socket, socket, logger: logger); /// Connects to a server and creates a [DaemonStreams] from the connection as the underlying streams. factory DaemonStreams.connect(String host, int port, { required Logger logger }) { final Future<Socket> socketFuture = Socket.connect(host, port); final StreamController<List<int>> inputStreamController = StreamController<List<int>>(); final StreamController<List<int>> outputStreamController = StreamController<List<int>>(); socketFuture.then<void>((Socket socket) { inputStreamController.addStream(socket); socket.addStream(outputStreamController.stream); }, onError: (Object error, StackTrace stackTrace) { logger.printError('Socket error: $error'); logger.printTrace('$stackTrace'); // Propagate the error to the streams. inputStreamController.addError(error, stackTrace); unawaited(outputStreamController.close()); }); return DaemonStreams(inputStreamController.stream, outputStreamController.sink, logger: logger); } final StreamSink<List<int>> _outputSink; final Logger _logger; /// Stream that contains input to the [DaemonConnection]. final Stream<DaemonMessage> inputStream; /// Outputs a message through the connection. void send(Map<String, Object?> message, [ List<int>? binary ]) { try { if (binary != null) { message[_binaryLengthKey] = binary.length; } _outputSink.add(utf8.encode('[${json.encode(message)}]\n')); if (binary != null) { _outputSink.add(binary); } } on StateError catch (error) { _logger.printError('Failed to write daemon command response: $error'); // Failed to send, close the connection _outputSink.close(); } on IOException catch (error) { _logger.printError('Failed to write daemon command response: $error'); // Failed to send, close the connection _outputSink.close(); } } /// Cleans up any resources used. Future<void> dispose() async { unawaited(_outputSink.close()); } } /// Connection between a flutter daemon and a client. class DaemonConnection { DaemonConnection({ required DaemonStreams daemonStreams, required Logger logger, }): _logger = logger, _daemonStreams = daemonStreams { _commandSubscription = daemonStreams.inputStream.listen( _handleMessage, onError: (Object error, StackTrace stackTrace) { // We have to listen for on error otherwise the error on the socket // will end up in the Zone error handler. // Do nothing here and let the stream close handlers handle shutting // down the daemon. } ); } final DaemonStreams _daemonStreams; final Logger _logger; late final StreamSubscription<DaemonMessage> _commandSubscription; int _outgoingRequestId = 0; final Map<String, Completer<Object?>> _outgoingRequestCompleters = <String, Completer<Object?>>{}; final StreamController<DaemonEventData> _events = StreamController<DaemonEventData>.broadcast(); final StreamController<DaemonMessage> _incomingCommands = StreamController<DaemonMessage>(); /// A stream that contains all the incoming requests. Stream<DaemonMessage> get incomingCommands => _incomingCommands.stream; /// Listens to the event with the event name [eventToListen]. Stream<DaemonEventData> listenToEvent(String eventToListen) { return _events.stream .where((DaemonEventData event) => event.eventName == eventToListen); } /// Sends a request to the other end of the connection. /// /// Returns a [Future] that resolves with the content. Future<Object?> sendRequest(String method, [Object? params, List<int>? binary]) async { final String id = '${++_outgoingRequestId}'; final Completer<Object?> completer = Completer<Object?>(); _outgoingRequestCompleters[id] = completer; final Map<String, Object?> data = <String, Object?>{ 'id': id, 'method': method, if (params != null) 'params': params, }; _logger.printTrace('-> Sending to daemon, id = $id, method = $method'); _daemonStreams.send(data, binary); return completer.future; } /// Sends a response to the other end of the connection. void sendResponse(Object id, [Object? result]) { _daemonStreams.send(<String, Object?>{ 'id': id, if (result != null) 'result': result, }); } /// Sends an error response to the other end of the connection. void sendErrorResponse(Object id, Object? error, StackTrace trace) { _daemonStreams.send(<String, Object?>{ 'id': id, 'error': error, 'trace': '$trace', }); } /// Sends an event to the client. void sendEvent(String name, [ Object? params, List<int>? binary ]) { _daemonStreams.send(<String, Object?>{ 'event': name, if (params != null) 'params': params, }, binary); } /// Handles the input from the stream. /// /// There are three kinds of data: Request, Response, Event. /// /// Request: /// {"id": <Object>. "method": <String>, "params": <optional, Object?>} /// /// Response: /// {"id": <Object>. "result": <optional, Object?>} for a successful response. /// {"id": <Object>. "error": <Object>, "stackTrace": <String>} for an error response. /// /// Event: /// {"event": <String>. "params": <optional, Object?>} void _handleMessage(DaemonMessage message) { final Map<String, Object?> data = message.data; if (data['id'] != null) { if (data['method'] == null) { // This is a response to previously sent request. final String id = data['id']! as String; if (data['error'] != null) { // This is an error response. _logger.printTrace('<- Error response received from daemon, id = $id'); final Object error = data['error']!; final String stackTrace = data['trace'] as String? ?? ''; _outgoingRequestCompleters.remove(id)?.completeError(error, StackTrace.fromString(stackTrace)); } else { _logger.printTrace('<- Response received from daemon, id = $id'); final Object? result = data['result']; _outgoingRequestCompleters.remove(id)?.complete(result); } } else { _incomingCommands.add(message); } } else if (data['event'] != null) { // This is an event _logger.printTrace('<- Event received: ${data['event']}'); final Object? eventName = data['event']; if (eventName is String) { _events.add(DaemonEventData( eventName, data['params'], message.binary, )); } else { throwToolExit('event name received is not string!'); } } else { _logger.printError('Unknown data received from daemon'); } } /// Cleans up any resources used in the connection. Future<void> dispose() async { await _commandSubscription.cancel(); await _daemonStreams.dispose(); unawaited(_events.close()); unawaited(_incomingCommands.close()); } }
flutter/packages/flutter_tools/lib/src/daemon.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/daemon.dart", "repo_id": "flutter", "token_count": 4650 }
362
// Copyright 2014 The Flutter 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:package_config/package_config.dart'; import 'package:process/process.dart'; import 'package:vm_service/vm_service.dart' as vm_service; import 'artifacts.dart'; import 'asset.dart'; import 'base/config.dart'; import 'base/context.dart'; import 'base/file_system.dart'; import 'base/io.dart'; import 'base/logger.dart'; import 'base/net.dart'; import 'base/os.dart'; import 'build_info.dart'; import 'build_system/tools/asset_transformer.dart'; import 'build_system/tools/scene_importer.dart'; import 'build_system/tools/shader_compiler.dart'; import 'compile.dart'; import 'convert.dart' show base64, utf8; import 'vmservice.dart'; const String _kFontManifest = 'FontManifest.json'; class DevFSConfig { /// Should DevFS assume that symlink targets are stable? bool cacheSymlinks = false; /// Should DevFS assume that there are no symlinks to directories? bool noDirectorySymlinks = false; } DevFSConfig? get devFSConfig => context.get<DevFSConfig>(); /// Common superclass for content copied to the device. abstract class DevFSContent { /// Return true if this is the first time this method is called /// or if the entry has been modified since this method was last called. bool get isModified; /// Return true if this is the first time this method is called /// or if the entry has been modified after the given time /// or if the given time is null. bool isModifiedAfter(DateTime time); int get size; Future<List<int>> contentsAsBytes(); Stream<List<int>> contentsAsStream(); Stream<List<int>> contentsAsCompressedStream( OperatingSystemUtils osUtils, ) { return osUtils.gzipLevel1Stream(contentsAsStream()); } } // File content to be copied to the device. class DevFSFileContent extends DevFSContent { DevFSFileContent(this.file); final FileSystemEntity file; File? _linkTarget; FileStat? _fileStat; File _getFile() { final File? linkTarget = _linkTarget; if (linkTarget != null) { return linkTarget; } if (file is Link) { // The link target. return file.fileSystem.file(file.resolveSymbolicLinksSync()); } return file as File; } void _stat() { final File? linkTarget = _linkTarget; if (linkTarget != null) { // Stat the cached symlink target. final FileStat fileStat = linkTarget.statSync(); if (fileStat.type == FileSystemEntityType.notFound) { _linkTarget = null; } else { _fileStat = fileStat; return; } } final FileStat fileStat = file.statSync(); _fileStat = fileStat.type == FileSystemEntityType.notFound ? null : fileStat; if (_fileStat != null && _fileStat?.type == FileSystemEntityType.link) { // Resolve, stat, and maybe cache the symlink target. final String resolved = file.resolveSymbolicLinksSync(); final File linkTarget = file.fileSystem.file(resolved); // Stat the link target. final FileStat fileStat = linkTarget.statSync(); if (fileStat.type == FileSystemEntityType.notFound) { _fileStat = null; _linkTarget = null; } else if (devFSConfig?.cacheSymlinks ?? false) { _linkTarget = linkTarget; } } } @override bool get isModified { final FileStat? oldFileStat = _fileStat; _stat(); final FileStat? newFileStat = _fileStat; if (oldFileStat == null && newFileStat == null) { return false; } return oldFileStat == null || newFileStat == null || newFileStat.modified.isAfter(oldFileStat.modified); } @override bool isModifiedAfter(DateTime time) { final FileStat? oldFileStat = _fileStat; _stat(); final FileStat? newFileStat = _fileStat; if (oldFileStat == null && newFileStat == null) { return false; } return oldFileStat == null || newFileStat == null || newFileStat.modified.isAfter(time); } @override int get size { if (_fileStat == null) { _stat(); } // Can still be null if the file wasn't found. return _fileStat?.size ?? 0; } @override Future<List<int>> contentsAsBytes() async => _getFile().readAsBytes(); @override Stream<List<int>> contentsAsStream() => _getFile().openRead(); } /// Byte content to be copied to the device. class DevFSByteContent extends DevFSContent { DevFSByteContent(this._bytes); final List<int> _bytes; final DateTime _creationTime = DateTime.now(); bool _isModified = true; List<int> get bytes => _bytes; /// Return true only once so that the content is written to the device only once. @override bool get isModified { final bool modified = _isModified; _isModified = false; return modified; } @override bool isModifiedAfter(DateTime time) { return _creationTime.isAfter(time); } @override int get size => _bytes.length; @override Future<List<int>> contentsAsBytes() async => _bytes; @override Stream<List<int>> contentsAsStream() => Stream<List<int>>.fromIterable(<List<int>>[_bytes]); } /// String content to be copied to the device. class DevFSStringContent extends DevFSByteContent { DevFSStringContent(String string) : _string = string, super(utf8.encode(string)); final String _string; String get string => _string; } /// A string compressing DevFSContent. /// /// A specialized DevFSContent similar to DevFSByteContent where the contents /// are the compressed bytes of a string. Its difference is that the original /// uncompressed string can be compared with directly without the indirection /// of a compute-expensive uncompress/decode and compress/encode to compare /// the strings. /// /// The `hintString` parameter is a zlib dictionary hinting mechanism to suggest /// the most common string occurrences to potentially assist with compression. class DevFSStringCompressingBytesContent extends DevFSContent { DevFSStringCompressingBytesContent(this._string, { String? hintString }) : _compressor = ZLibEncoder( dictionary: hintString == null ? null : utf8.encode(hintString), gzip: true, level: 9, ); final String _string; final ZLibEncoder _compressor; final DateTime _creationTime = DateTime.now(); bool _isModified = true; late final List<int> bytes = _compressor.convert(utf8.encode(_string)); /// Return true only once so that the content is written to the device only once. @override bool get isModified { final bool modified = _isModified; _isModified = false; return modified; } @override bool isModifiedAfter(DateTime time) { return _creationTime.isAfter(time); } @override int get size => bytes.length; @override Future<List<int>> contentsAsBytes() async => bytes; @override Stream<List<int>> contentsAsStream() => Stream<List<int>>.value(bytes); /// This checks the source string with another string. bool equals(String string) => _string == string; } class DevFSException implements Exception { DevFSException(this.message, [this.error, this.stackTrace]); final String message; final dynamic error; final StackTrace? stackTrace; @override String toString() => 'DevFSException($message, $error, $stackTrace)'; } /// Interface responsible for syncing asset files to a development device. abstract class DevFSWriter { /// Write the assets in [entries] to the target device. /// /// The keys of the map are relative from the [baseUri]. /// /// Throws a [DevFSException] if the process fails to complete. Future<void> write(Map<Uri, DevFSContent> entries, Uri baseUri, DevFSWriter parent); } class _DevFSHttpWriter implements DevFSWriter { _DevFSHttpWriter( this.fsName, FlutterVmService serviceProtocol, { required OperatingSystemUtils osUtils, required HttpClient httpClient, required Logger logger, Duration? uploadRetryThrottle, }) : httpAddress = serviceProtocol.httpAddress, _client = httpClient, _osUtils = osUtils, _uploadRetryThrottle = uploadRetryThrottle, _logger = logger; final HttpClient _client; final OperatingSystemUtils _osUtils; final Logger _logger; final Duration? _uploadRetryThrottle; final String fsName; final Uri? httpAddress; // 3 was chosen to try to limit the variance in the time it takes to execute // `await request.close()` since there is a known bug in Dart where it doesn't // always return a status code in response to a PUT request: // https://github.com/dart-lang/sdk/issues/43525. static const int kMaxInFlight = 3; int _inFlight = 0; late Map<Uri, DevFSContent> _outstanding; late Completer<void> _completer; @override Future<void> write(Map<Uri, DevFSContent> entries, Uri devFSBase, [DevFSWriter? parent]) async { try { _client.maxConnectionsPerHost = kMaxInFlight; _completer = Completer<void>(); _outstanding = Map<Uri, DevFSContent>.of(entries); _scheduleWrites(); await _completer.future; } on SocketException catch (socketException, stackTrace) { _logger.printTrace('DevFS sync failed. Lost connection to device: $socketException'); throw DevFSException('Lost connection to device.', socketException, stackTrace); } on Exception catch (exception, stackTrace) { _logger.printError('Could not update files on device: $exception'); throw DevFSException('Sync failed', exception, stackTrace); } } void _scheduleWrites() { while ((_inFlight < kMaxInFlight) && (!_completer.isCompleted) && _outstanding.isNotEmpty) { final Uri deviceUri = _outstanding.keys.first; final DevFSContent content = _outstanding.remove(deviceUri)!; _startWrite(deviceUri, content, retry: 10); _inFlight += 1; } if ((_inFlight == 0) && (!_completer.isCompleted) && _outstanding.isEmpty) { _completer.complete(); } } Future<void> _startWrite( Uri deviceUri, DevFSContent content, { int retry = 0, }) async { while (true) { try { final HttpClientRequest request = await _client.putUrl(httpAddress!); request.headers.removeAll(HttpHeaders.acceptEncodingHeader); request.headers.add('dev_fs_name', fsName); request.headers.add('dev_fs_uri_b64', base64.encode(utf8.encode('$deviceUri'))); final Stream<List<int>> contents = content.contentsAsCompressedStream( _osUtils, ); await request.addStream(contents); // Once the bug in Dart is solved we can remove the timeout // (https://github.com/dart-lang/sdk/issues/43525). try { final HttpClientResponse response = await request.close().timeout( const Duration(seconds: 60)); response.listen((_) {}, onError: (dynamic error) { _logger.printTrace('error: $error'); }, cancelOnError: true, ); } on TimeoutException { request.abort(); // This should throw "HttpException: Request has been aborted". await request.done; // Just to be safe we rethrow the TimeoutException. rethrow; } break; } on Exception catch (error, trace) { if (!_completer.isCompleted) { _logger.printTrace('Error writing "$deviceUri" to DevFS: $error'); if (retry > 0) { retry--; _logger.printTrace('trying again in a few - $retry more attempts left'); await Future<void>.delayed(_uploadRetryThrottle ?? const Duration(milliseconds: 500)); continue; } _completer.completeError(error, trace); } } } _inFlight -= 1; _scheduleWrites(); } } // Basic statistics for DevFS update operation. class UpdateFSReport { UpdateFSReport({ bool success = false, int invalidatedSourcesCount = 0, int syncedBytes = 0, int scannedSourcesCount = 0, Duration compileDuration = Duration.zero, Duration transferDuration = Duration.zero, Duration findInvalidatedDuration = Duration.zero, }) : _success = success, _invalidatedSourcesCount = invalidatedSourcesCount, _syncedBytes = syncedBytes, _scannedSourcesCount = scannedSourcesCount, _compileDuration = compileDuration, _transferDuration = transferDuration, _findInvalidatedDuration = findInvalidatedDuration; bool get success => _success; int get invalidatedSourcesCount => _invalidatedSourcesCount; int get syncedBytes => _syncedBytes; int get scannedSourcesCount => _scannedSourcesCount; Duration get compileDuration => _compileDuration; Duration get transferDuration => _transferDuration; Duration get findInvalidatedDuration => _findInvalidatedDuration; bool _success; int _invalidatedSourcesCount; int _syncedBytes; int _scannedSourcesCount; Duration _compileDuration; Duration _transferDuration; Duration _findInvalidatedDuration; void incorporateResults(UpdateFSReport report) { if (!report._success) { _success = false; } _invalidatedSourcesCount += report._invalidatedSourcesCount; _syncedBytes += report._syncedBytes; _scannedSourcesCount += report._scannedSourcesCount; _compileDuration += report._compileDuration; _transferDuration += report._transferDuration; _findInvalidatedDuration += report._findInvalidatedDuration; } } class DevFS { /// Create a [DevFS] named [fsName] for the local files in [rootDirectory]. /// /// Failed uploads are retried after [uploadRetryThrottle] duration, defaults to 500ms. DevFS( FlutterVmService serviceProtocol, this.fsName, this.rootDirectory, { required OperatingSystemUtils osUtils, required Logger logger, required FileSystem fileSystem, required ProcessManager processManager, required Artifacts artifacts, required BuildMode buildMode, HttpClient? httpClient, Duration? uploadRetryThrottle, StopwatchFactory stopwatchFactory = const StopwatchFactory(), Config? config, }) : _vmService = serviceProtocol, _logger = logger, _fileSystem = fileSystem, _httpWriter = _DevFSHttpWriter( fsName, serviceProtocol, osUtils: osUtils, logger: logger, uploadRetryThrottle: uploadRetryThrottle, httpClient: httpClient ?? ((context.get<HttpClientFactory>() == null) ? HttpClient() : context.get<HttpClientFactory>()!())), _stopwatchFactory = stopwatchFactory, _config = config, _assetTransformer = DevelopmentAssetTransformer( transformer: AssetTransformer( processManager: processManager, fileSystem: fileSystem, dartBinaryPath: artifacts.getArtifactPath(Artifact.engineDartBinary), buildMode: buildMode, ), fileSystem: fileSystem, logger: logger, ); final FlutterVmService _vmService; final _DevFSHttpWriter _httpWriter; final Logger _logger; final FileSystem _fileSystem; final StopwatchFactory _stopwatchFactory; final Config? _config; final DevelopmentAssetTransformer _assetTransformer; final String fsName; final Directory rootDirectory; final Set<String> assetPathsToEvict = <String>{}; final Set<String> shaderPathsToEvict = <String>{}; final Set<String> scenePathsToEvict = <String>{}; // A flag to indicate whether we have called `setAssetDirectory` on the target device. bool hasSetAssetDirectory = false; /// Whether the font manifest was uploaded during [update]. bool didUpdateFontManifest = false; List<Uri> sources = <Uri>[]; DateTime? lastCompiled; DateTime? _previousCompiled; PackageConfig? lastPackageConfig; Uri? _baseUri; Uri? get baseUri => _baseUri; Uri deviceUriToHostUri(Uri deviceUri) { final String deviceUriString = deviceUri.toString(); final String baseUriString = baseUri.toString(); if (deviceUriString.startsWith(baseUriString)) { final String deviceUriSuffix = deviceUriString.substring(baseUriString.length); return rootDirectory.uri.resolve(deviceUriSuffix); } return deviceUri; } Future<Uri> create() async { _logger.printTrace('DevFS: Creating new filesystem on the device ($_baseUri)'); try { final vm_service.Response response = await _vmService.createDevFS(fsName); _baseUri = Uri.parse(response.json!['uri'] as String); } on vm_service.RPCError catch (rpcException) { if (rpcException.code == RPCErrorCodes.kServiceDisappeared) { // This can happen if the device has been disconnected, so translate to // a DevFSException, which the caller will handle. throw DevFSException('Service disconnected', rpcException); } // 1001 is kFileSystemAlreadyExists in //dart/runtime/vm/json_stream.h if (rpcException.code != 1001) { // Other RPCErrors are unexpected. Rethrow so it will hit crash // logging. rethrow; } _logger.printTrace('DevFS: Creating failed. Destroying and trying again'); await destroy(); final vm_service.Response response = await _vmService.createDevFS(fsName); _baseUri = Uri.parse(response.json!['uri'] as String); } _logger.printTrace('DevFS: Created new filesystem on the device ($_baseUri)'); return _baseUri!; } Future<void> destroy() async { _logger.printTrace('DevFS: Deleting filesystem on the device ($_baseUri)'); await _vmService.deleteDevFS(fsName); _logger.printTrace('DevFS: Deleted filesystem on the device ($_baseUri)'); } /// Mark the [lastCompiled] time to the previous successful compile. /// /// Sometimes a hot reload will be rejected by the VM due to a change in the /// structure of the code not supporting the hot reload. In these cases, /// the best resolution is a hot restart. However, the resident runner /// will not recognize this file as having been changed since the delta /// will already have been accepted. Instead, reset the compile time so /// that the last updated files are included in subsequent compilations until /// a reload is accepted. void resetLastCompiled() { lastCompiled = _previousCompiled; } /// Updates files on the device. /// /// Returns the number of bytes synced. Future<UpdateFSReport> update({ required Uri mainUri, required ResidentCompiler generator, required bool trackWidgetCreation, required String pathToReload, required List<Uri> invalidatedFiles, required PackageConfig packageConfig, required String dillOutputPath, required DevelopmentShaderCompiler shaderCompiler, DevelopmentSceneImporter? sceneImporter, DevFSWriter? devFSWriter, String? target, AssetBundle? bundle, bool bundleFirstUpload = false, bool fullRestart = false, File? dartPluginRegistrant, }) async { final DateTime candidateCompileTime = DateTime.now(); didUpdateFontManifest = false; lastPackageConfig = packageConfig; // Update modified files final Map<Uri, DevFSContent> dirtyEntries = <Uri, DevFSContent>{}; final List<Future<void>> pendingAssetBuilds = <Future<void>>[]; bool assetBuildFailed = false; int syncedBytes = 0; if (fullRestart) { generator.reset(); } // On a full restart, or on an initial compile for the attach based workflow, // this will produce a full dill. Subsequent invocations will produce incremental // dill files that depend on the invalidated files. _logger.printTrace('Compiling dart to kernel with ${invalidatedFiles.length} updated files'); // Await the compiler response after checking if the bundle is updated. This allows the file // stating to be done while waiting for the frontend_server response. final Stopwatch compileTimer = _stopwatchFactory.createStopwatch('compile')..start(); final Future<CompilerOutput?> pendingCompilerOutput = generator.recompile( mainUri, invalidatedFiles, outputPath: dillOutputPath, fs: _fileSystem, projectRootPath: rootDirectory.path, packageConfig: packageConfig, checkDartPluginRegistry: true, // The entry point is assumed not to have changed. dartPluginRegistrant: dartPluginRegistrant, ).then((CompilerOutput? result) { compileTimer.stop(); return result; }); if (bundle != null) { // Mark processing of bundle started for testability of starting the compile // before processing bundle. _logger.printTrace('Processing bundle.'); // await null to give time for telling the compiler to compile. await null; // The tool writes the assets into the AssetBundle working dir so that they // are in the same location in DevFS and the iOS simulator. final String assetDirectory = getAssetBuildDirectory(_config, _fileSystem); final String assetBuildDirPrefix = _asUriPath(assetDirectory); bundle.entries.forEach((String archivePath, AssetBundleEntry entry) { // If the content is backed by a real file, isModified will file stat and return true if // it was modified since the last time this was called. if (!entry.content.isModified || bundleFirstUpload) { return; } // Modified shaders must be recompiled per-target platform. final Uri deviceUri = _fileSystem.path.toUri(_fileSystem.path.join(assetDirectory, archivePath)); if (deviceUri.path.startsWith(assetBuildDirPrefix)) { archivePath = deviceUri.path.substring(assetBuildDirPrefix.length); } // If the font manifest is updated, mark this as true so the hot runner // can invoke a service extension to force the engine to reload fonts. if (archivePath == _kFontManifest) { didUpdateFontManifest = true; } final AssetKind? kind = bundle.entries[archivePath]?.kind; switch (kind) { case AssetKind.shader: final Future<DevFSContent?> pending = shaderCompiler.recompileShader(entry.content); pendingAssetBuilds.add(pending); pending.then((DevFSContent? content) { if (content == null) { assetBuildFailed = true; return; } dirtyEntries[deviceUri] = content; syncedBytes += content.size; if (!bundleFirstUpload) { shaderPathsToEvict.add(archivePath); } }); case AssetKind.model: if (sceneImporter == null) { break; } final Future<DevFSContent?> pending = sceneImporter.reimportScene(entry.content); pendingAssetBuilds.add(pending); pending.then((DevFSContent? content) { if (content == null) { assetBuildFailed = true; return; } dirtyEntries[deviceUri] = content; syncedBytes += content.size; if (!bundleFirstUpload) { scenePathsToEvict.add(archivePath); } }); case AssetKind.regular: case AssetKind.font: case null: final Future<DevFSContent?> pending = (() async { if (entry.transformers.isEmpty || kind != AssetKind.regular) { return entry.content; } return _assetTransformer.retransformAsset( inputAssetKey: archivePath, inputAssetContent: entry.content, transformerEntries: entry.transformers, workingDirectory: rootDirectory.path, ); })(); pendingAssetBuilds.add(pending); pending.then((DevFSContent? content) { if (content == null) { assetBuildFailed = true; return; } dirtyEntries[deviceUri] = content; syncedBytes += content.size; if (!bundleFirstUpload) { assetPathsToEvict.add(archivePath); } }); } }); // Mark processing of bundle done for testability of starting the compile // before processing bundle. _logger.printTrace('Bundle processing done.'); } final CompilerOutput? compilerOutput = await pendingCompilerOutput; if (compilerOutput == null || compilerOutput.errorCount > 0) { return UpdateFSReport(); } // Only update the last compiled time if we successfully compiled. _previousCompiled = lastCompiled; lastCompiled = candidateCompileTime; // list of sources that needs to be monitored are in [compilerOutput.sources] sources = compilerOutput.sources; // // Don't send full kernel file that would overwrite what VM already // started loading from. if (!bundleFirstUpload) { final String compiledBinary = compilerOutput.outputFilename; if (compiledBinary.isNotEmpty) { final Uri entryUri = _fileSystem.path.toUri(pathToReload); final DevFSFileContent content = DevFSFileContent(_fileSystem.file(compiledBinary)); syncedBytes += content.size; dirtyEntries[entryUri] = content; } } _logger.printTrace('Updating files.'); final Stopwatch transferTimer = _stopwatchFactory.createStopwatch('transfer')..start(); await Future.wait(pendingAssetBuilds); if (assetBuildFailed) { return UpdateFSReport(); } _logger.printTrace('Pending asset builds completed. Writing dirty entries.'); if (dirtyEntries.isNotEmpty) { await (devFSWriter ?? _httpWriter).write(dirtyEntries, _baseUri!, _httpWriter); } transferTimer.stop(); _logger.printTrace('DevFS: Sync finished'); return UpdateFSReport( success: true, syncedBytes: syncedBytes, invalidatedSourcesCount: invalidatedFiles.length, compileDuration: compileTimer.elapsed, transferDuration: transferTimer.elapsed, ); } /// Converts a platform-specific file path to a platform-independent URL path. String _asUriPath(String filePath) => '${_fileSystem.path.toUri(filePath).path}/'; } /// An implementation of a devFS writer which copies physical files for devices /// running on the same host. /// /// DevFS entries which correspond to physical files are copied using [File.copySync], /// while entries that correspond to arbitrary string/byte values are written from /// memory. /// /// Requires that the file system is the same for both the tool and application. class LocalDevFSWriter implements DevFSWriter { LocalDevFSWriter({ required FileSystem fileSystem, }) : _fileSystem = fileSystem; final FileSystem _fileSystem; @override Future<void> write(Map<Uri, DevFSContent> entries, Uri baseUri, [DevFSWriter? parent]) async { try { for (final MapEntry<Uri, DevFSContent> entry in entries.entries) { final Uri uri = entry.key; final DevFSContent devFSContent = entry.value; final File destination = _fileSystem.file(baseUri.resolveUri(uri)); if (!destination.parent.existsSync()) { destination.parent.createSync(recursive: true); } if (devFSContent is DevFSFileContent) { final File content = devFSContent.file as File; content.copySync(destination.path); continue; } destination.writeAsBytesSync(await devFSContent.contentsAsBytes()); } } on FileSystemException catch (err) { throw DevFSException(err.toString()); } } }
flutter/packages/flutter_tools/lib/src/devfs.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/devfs.dart", "repo_id": "flutter", "token_count": 10040 }
363
// Copyright 2014 The Flutter 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:meta/meta.dart'; import 'package:package_config/package_config.dart'; import 'package:path/path.dart' as path; // flutter_ignore: package_path_import import 'package:pub_semver/pub_semver.dart' as semver; import 'package:yaml/yaml.dart'; import 'android/gradle.dart'; import 'base/common.dart'; import 'base/error_handling_io.dart'; import 'base/file_system.dart'; import 'base/os.dart'; import 'base/platform.dart'; import 'base/template.dart'; import 'base/version.dart'; import 'cache.dart'; import 'convert.dart'; import 'dart/language_version.dart'; import 'dart/package_map.dart'; import 'features.dart'; import 'globals.dart' as globals; import 'macos/darwin_dependency_management.dart'; import 'macos/swift_package_manager.dart'; import 'platform_plugins.dart'; import 'plugins.dart'; import 'project.dart'; Future<void> _renderTemplateToFile( String template, Object? context, File file, TemplateRenderer templateRenderer, ) async { final String renderedTemplate = templateRenderer .renderString(template, context); await file.create(recursive: true); await file.writeAsString(renderedTemplate); } Future<Plugin?> _pluginFromPackage(String name, Uri packageRoot, Set<String> appDependencies, {FileSystem? fileSystem}) async { final FileSystem fs = fileSystem ?? globals.fs; final File pubspecFile = fs.file(packageRoot.resolve('pubspec.yaml')); if (!pubspecFile.existsSync()) { return null; } Object? pubspec; try { pubspec = loadYaml(await pubspecFile.readAsString()); } on YamlException catch (err) { globals.printTrace('Failed to parse plugin manifest for $name: $err'); // Do nothing, potentially not a plugin. } if (pubspec == null || pubspec is! YamlMap) { return null; } final Object? flutterConfig = pubspec['flutter']; if (flutterConfig == null || flutterConfig is! YamlMap || !flutterConfig.containsKey('plugin')) { return null; } final String? flutterConstraintText = (pubspec['environment'] as YamlMap?)?['flutter'] as String?; final semver.VersionConstraint? flutterConstraint = flutterConstraintText == null ? null : semver.VersionConstraint.parse(flutterConstraintText); final String packageRootPath = fs.path.fromUri(packageRoot); final YamlMap? dependencies = pubspec['dependencies'] as YamlMap?; globals.printTrace('Found plugin $name at $packageRootPath'); return Plugin.fromYaml( name, packageRootPath, flutterConfig['plugin'] as YamlMap?, flutterConstraint, dependencies == null ? <String>[] : <String>[...dependencies.keys.cast<String>()], fileSystem: fs, appDependencies: appDependencies, ); } Future<List<Plugin>> findPlugins(FlutterProject project, { bool throwOnError = true}) async { final List<Plugin> plugins = <Plugin>[]; final FileSystem fs = project.directory.fileSystem; final String packagesFile = fs.path.join( project.directory.path, '.packages', ); final PackageConfig packageConfig = await loadPackageConfigWithLogging( fs.file(packagesFile), logger: globals.logger, throwOnError: throwOnError, ); for (final Package package in packageConfig.packages) { final Uri packageRoot = package.packageUriRoot.resolve('..'); final Plugin? plugin = await _pluginFromPackage( package.name, packageRoot, project.manifest.dependencies, fileSystem: fs, ); if (plugin != null) { plugins.add(plugin); } } return plugins; } // Key strings for the .flutter-plugins-dependencies file. const String _kFlutterPluginsPluginListKey = 'plugins'; const String _kFlutterPluginsNameKey = 'name'; const String _kFlutterPluginsPathKey = 'path'; const String _kFlutterPluginsDependenciesKey = 'dependencies'; const String _kFlutterPluginsHasNativeBuildKey = 'native_build'; const String _kFlutterPluginsSharedDarwinSource = 'shared_darwin_source'; /// Writes the .flutter-plugins-dependencies file based on the list of plugins. /// If there aren't any plugins, then the files aren't written to disk. The resulting /// file looks something like this (order of keys is not guaranteed): /// { /// "info": "This is a generated file; do not edit or check into version control.", /// "plugins": { /// "ios": [ /// { /// "name": "test", /// "path": "test_path", /// "dependencies": [ /// "plugin-a", /// "plugin-b" /// ], /// "native_build": true /// } /// ], /// "android": [], /// "macos": [], /// "linux": [], /// "windows": [], /// "web": [] /// }, /// "dependencyGraph": [ /// { /// "name": "plugin-a", /// "dependencies": [ /// "plugin-b", /// "plugin-c" /// ] /// }, /// { /// "name": "plugin-b", /// "dependencies": [ /// "plugin-c" /// ] /// }, /// { /// "name": "plugin-c", /// "dependencies": [] /// } /// ], /// "date_created": "1970-01-01 00:00:00.000", /// "version": "0.0.0-unknown" /// } /// /// /// Finally, returns [true] if the plugins list has changed, otherwise returns [false]. bool _writeFlutterPluginsList( FlutterProject project, List<Plugin> plugins, { bool forceCocoaPodsOnly = false, }) { final File pluginsFile = project.flutterPluginsDependenciesFile; if (plugins.isEmpty) { return ErrorHandlingFileSystem.deleteIfExists(pluginsFile); } final Iterable<String> platformKeys = <String>[ project.ios.pluginConfigKey, project.android.pluginConfigKey, project.macos.pluginConfigKey, project.linux.pluginConfigKey, project.windows.pluginConfigKey, project.web.pluginConfigKey, ]; final Map<String, Object> pluginsMap = <String, Object>{}; for (final String platformKey in platformKeys) { pluginsMap[platformKey] = _createPluginMapOfPlatform(plugins, platformKey); } final Map<String, Object> result = <String, Object>{}; result['info'] = 'This is a generated file; do not edit or check into version control.'; result[_kFlutterPluginsPluginListKey] = pluginsMap; /// The dependencyGraph object is kept for backwards compatibility, but /// should be removed once migration is complete. /// https://github.com/flutter/flutter/issues/48918 result['dependencyGraph'] = _createPluginLegacyDependencyGraph(plugins); result['date_created'] = globals.systemClock.now().toString(); result['version'] = globals.flutterVersion.frameworkVersion; result['swift_package_manager_enabled'] = !forceCocoaPodsOnly && project.usesSwiftPackageManager; // Only notify if the plugins list has changed. [date_created] will always be different, // [version] is not relevant for this check. final String? oldPluginsFileStringContent = _readFileContent(pluginsFile); bool pluginsChanged = true; if (oldPluginsFileStringContent != null) { pluginsChanged = oldPluginsFileStringContent.contains(pluginsMap.toString()); } final String pluginFileContent = json.encode(result); pluginsFile.writeAsStringSync(pluginFileContent, flush: true); return pluginsChanged; } /// Creates a map representation of the [plugins] for those supported by [platformKey]. List<Map<String, Object>> _createPluginMapOfPlatform( List<Plugin> plugins, String platformKey, ) { final Iterable<Plugin> resolvedPlatformPlugins = plugins.where((Plugin p) { return p.platforms.containsKey(platformKey); }); final Set<String> pluginNames = resolvedPlatformPlugins.map((Plugin plugin) => plugin.name).toSet(); final List<Map<String, Object>> pluginInfo = <Map<String, Object>>[]; for (final Plugin plugin in resolvedPlatformPlugins) { // This is guaranteed to be non-null due to the `where` filter above. final PluginPlatform platformPlugin = plugin.platforms[platformKey]!; pluginInfo.add(<String, Object>{ _kFlutterPluginsNameKey: plugin.name, _kFlutterPluginsPathKey: globals.fsUtils.escapePath(plugin.path), if (platformPlugin is DarwinPlugin && (platformPlugin as DarwinPlugin).sharedDarwinSource) _kFlutterPluginsSharedDarwinSource: (platformPlugin as DarwinPlugin).sharedDarwinSource, if (platformPlugin is NativeOrDartPlugin) _kFlutterPluginsHasNativeBuildKey: (platformPlugin as NativeOrDartPlugin).hasMethodChannel() || (platformPlugin as NativeOrDartPlugin).hasFfi(), _kFlutterPluginsDependenciesKey: <String>[...plugin.dependencies.where(pluginNames.contains)], }); } return pluginInfo; } List<Object?> _createPluginLegacyDependencyGraph(List<Plugin> plugins) { final List<Object> directAppDependencies = <Object>[]; final Set<String> pluginNames = plugins.map((Plugin plugin) => plugin.name).toSet(); for (final Plugin plugin in plugins) { directAppDependencies.add(<String, Object>{ 'name': plugin.name, // Extract the plugin dependencies which happen to be plugins. 'dependencies': <String>[...plugin.dependencies.where(pluginNames.contains)], }); } return directAppDependencies; } // The .flutter-plugins file will be DEPRECATED in favor of .flutter-plugins-dependencies. // TODO(franciscojma): Remove this method once deprecated. // https://github.com/flutter/flutter/issues/48918 // /// Writes the .flutter-plugins files based on the list of plugins. /// If there aren't any plugins, then the files aren't written to disk. /// /// Finally, returns [true] if .flutter-plugins has changed, otherwise returns [false]. bool _writeFlutterPluginsListLegacy(FlutterProject project, List<Plugin> plugins) { final File pluginsFile = project.flutterPluginsFile; if (plugins.isEmpty) { return ErrorHandlingFileSystem.deleteIfExists(pluginsFile); } const String info = 'This is a generated file; do not edit or check into version control.'; final StringBuffer flutterPluginsBuffer = StringBuffer('# $info\n'); for (final Plugin plugin in plugins) { flutterPluginsBuffer.write('${plugin.name}=${globals.fsUtils.escapePath(plugin.path)}\n'); } final String? oldPluginFileContent = _readFileContent(pluginsFile); final String pluginFileContent = flutterPluginsBuffer.toString(); pluginsFile.writeAsStringSync(pluginFileContent, flush: true); return oldPluginFileContent != _readFileContent(pluginsFile); } /// Returns the contents of [File] or [null] if that file does not exist. String? _readFileContent(File file) { return file.existsSync() ? file.readAsStringSync() : null; } const String _androidPluginRegistryTemplateNewEmbedding = ''' package io.flutter.plugins; import androidx.annotation.Keep; import androidx.annotation.NonNull; import io.flutter.Log; import io.flutter.embedding.engine.FlutterEngine; /** * Generated file. Do not edit. * This file is generated by the Flutter tool based on the * plugins that support the Android platform. */ @Keep public final class GeneratedPluginRegistrant { private static final String TAG = "GeneratedPluginRegistrant"; public static void registerWith(@NonNull FlutterEngine flutterEngine) { {{#methodChannelPlugins}} {{#supportsEmbeddingV2}} try { flutterEngine.getPlugins().add(new {{package}}.{{class}}()); } catch (Exception e) { Log.e(TAG, "Error registering plugin {{name}}, {{package}}.{{class}}", e); } {{/supportsEmbeddingV2}} {{/methodChannelPlugins}} } } '''; List<Map<String, Object?>> _extractPlatformMaps(List<Plugin> plugins, String type) { return <Map<String, Object?>>[ for (final Plugin plugin in plugins) if (plugin.platforms[type] case final PluginPlatform platformPlugin) platformPlugin.toMap(), ]; } Future<void> _writeAndroidPluginRegistrant(FlutterProject project, List<Plugin> plugins) async { final List<Plugin> methodChannelPlugins = _filterMethodChannelPlugins(plugins, AndroidPlugin.kConfigKey); final List<Map<String, Object?>> androidPlugins = _extractPlatformMaps(methodChannelPlugins, AndroidPlugin.kConfigKey); final Map<String, Object> templateContext = <String, Object>{ 'methodChannelPlugins': androidPlugins, 'androidX': isAppUsingAndroidX(project.android.hostAppGradleRoot), }; final String javaSourcePath = globals.fs.path.join( project.android.pluginRegistrantHost.path, 'src', 'main', 'java', ); final String registryPath = globals.fs.path.join( javaSourcePath, 'io', 'flutter', 'plugins', 'GeneratedPluginRegistrant.java', ); const String templateContent = _androidPluginRegistryTemplateNewEmbedding; globals.printTrace('Generating $registryPath'); await _renderTemplateToFile( templateContent, templateContext, globals.fs.file(registryPath), globals.templateRenderer, ); } const String _objcPluginRegistryHeaderTemplate = ''' // // Generated file. Do not edit. // // clang-format off #ifndef GeneratedPluginRegistrant_h #define GeneratedPluginRegistrant_h #import <{{framework}}/{{framework}}.h> NS_ASSUME_NONNULL_BEGIN @interface GeneratedPluginRegistrant : NSObject + (void)registerWithRegistry:(NSObject<FlutterPluginRegistry>*)registry; @end NS_ASSUME_NONNULL_END #endif /* GeneratedPluginRegistrant_h */ '''; const String _objcPluginRegistryImplementationTemplate = ''' // // Generated file. Do not edit. // // clang-format off #import "GeneratedPluginRegistrant.h" {{#methodChannelPlugins}} #if __has_include(<{{name}}/{{class}}.h>) #import <{{name}}/{{class}}.h> #else @import {{name}}; #endif {{/methodChannelPlugins}} @implementation GeneratedPluginRegistrant + (void)registerWithRegistry:(NSObject<FlutterPluginRegistry>*)registry { {{#methodChannelPlugins}} [{{prefix}}{{class}} registerWithRegistrar:[registry registrarForPlugin:@"{{prefix}}{{class}}"]]; {{/methodChannelPlugins}} } @end '''; const String _swiftPluginRegistryTemplate = ''' // // Generated file. Do not edit. // import {{framework}} import Foundation {{#methodChannelPlugins}} import {{name}} {{/methodChannelPlugins}} func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { {{#methodChannelPlugins}} {{class}}.register(with: registry.registrar(forPlugin: "{{class}}")) {{/methodChannelPlugins}} } '''; const String _pluginRegistrantPodspecTemplate = ''' # # Generated file, do not edit. # Pod::Spec.new do |s| s.name = 'FlutterPluginRegistrant' s.version = '0.0.1' s.summary = 'Registers plugins with your Flutter app' s.description = <<-DESC Depends on all your plugins, and provides a function to register them. DESC s.homepage = 'https://flutter.dev' s.license = { :type => 'BSD' } s.author = { 'Flutter Dev Team' => 'flutter-dev@googlegroups.com' } s.{{os}}.deployment_target = '{{deploymentTarget}}' s.source_files = "Classes", "Classes/**/*.{h,m}" s.source = { :path => '.' } s.public_header_files = './Classes/**/*.h' s.static_framework = true s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' } s.dependency '{{framework}}' {{#methodChannelPlugins}} s.dependency '{{name}}' {{/methodChannelPlugins}} end '''; const String _noopDartPluginRegistryTemplate = ''' // Flutter web plugin registrant file. // // Generated file. Do not edit. // // ignore_for_file: type=lint void registerPlugins() {} '''; const String _dartPluginRegistryTemplate = ''' // Flutter web plugin registrant file. // // Generated file. Do not edit. // // @dart = 2.13 // ignore_for_file: type=lint {{#methodChannelPlugins}} import 'package:{{name}}/{{file}}'; {{/methodChannelPlugins}} import 'package:flutter_web_plugins/flutter_web_plugins.dart'; void registerPlugins([final Registrar? pluginRegistrar]) { final Registrar registrar = pluginRegistrar ?? webPluginRegistrar; {{#methodChannelPlugins}} {{class}}.registerWith(registrar); {{/methodChannelPlugins}} registrar.registerMessageHandler(); } '''; const String _cppPluginRegistryHeaderTemplate = ''' // // Generated file. Do not edit. // // clang-format off #ifndef GENERATED_PLUGIN_REGISTRANT_ #define GENERATED_PLUGIN_REGISTRANT_ #include <flutter/plugin_registry.h> // Registers Flutter plugins. void RegisterPlugins(flutter::PluginRegistry* registry); #endif // GENERATED_PLUGIN_REGISTRANT_ '''; const String _cppPluginRegistryImplementationTemplate = ''' // // Generated file. Do not edit. // // clang-format off #include "generated_plugin_registrant.h" {{#methodChannelPlugins}} #include <{{name}}/{{filename}}.h> {{/methodChannelPlugins}} void RegisterPlugins(flutter::PluginRegistry* registry) { {{#methodChannelPlugins}} {{class}}RegisterWithRegistrar( registry->GetRegistrarForPlugin("{{class}}")); {{/methodChannelPlugins}} } '''; const String _linuxPluginRegistryHeaderTemplate = ''' // // Generated file. Do not edit. // // clang-format off #ifndef GENERATED_PLUGIN_REGISTRANT_ #define GENERATED_PLUGIN_REGISTRANT_ #include <flutter_linux/flutter_linux.h> // Registers Flutter plugins. void fl_register_plugins(FlPluginRegistry* registry); #endif // GENERATED_PLUGIN_REGISTRANT_ '''; const String _linuxPluginRegistryImplementationTemplate = ''' // // Generated file. Do not edit. // // clang-format off #include "generated_plugin_registrant.h" {{#methodChannelPlugins}} #include <{{name}}/{{filename}}.h> {{/methodChannelPlugins}} void fl_register_plugins(FlPluginRegistry* registry) { {{#methodChannelPlugins}} g_autoptr(FlPluginRegistrar) {{name}}_registrar = fl_plugin_registry_get_registrar_for_plugin(registry, "{{class}}"); {{filename}}_register_with_registrar({{name}}_registrar); {{/methodChannelPlugins}} } '''; const String _pluginCmakefileTemplate = r''' # # Generated file, do not edit. # list(APPEND FLUTTER_PLUGIN_LIST {{#methodChannelPlugins}} {{name}} {{/methodChannelPlugins}} ) list(APPEND FLUTTER_FFI_PLUGIN_LIST {{#ffiPlugins}} {{name}} {{/ffiPlugins}} ) set(PLUGIN_BUNDLED_LIBRARIES) foreach(plugin ${FLUTTER_PLUGIN_LIST}) add_subdirectory({{pluginsDir}}/${plugin}/{{os}} plugins/${plugin}) target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) list(APPEND PLUGIN_BUNDLED_LIBRARIES $<TARGET_FILE:${plugin}_plugin>) list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) endforeach(plugin) foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) add_subdirectory({{pluginsDir}}/${ffi_plugin}/{{os}} plugins/${ffi_plugin}) list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) endforeach(ffi_plugin) '''; const String _dartPluginRegisterWith = r''' try { {{dartClass}}.registerWith(); } catch (err) { print( '`{{pluginName}}` threw an error: $err. ' 'The app may not function as expected until you remove this plugin from pubspec.yaml' ); } '''; // TODO(egarciad): Evaluate merging the web and non-web plugin registry templates. // https://github.com/flutter/flutter/issues/80406 const String _dartPluginRegistryForNonWebTemplate = ''' // // Generated file. Do not edit. // This file is generated from template in file `flutter_tools/lib/src/flutter_plugins.dart`. // // @dart = {{dartLanguageVersion}} import 'dart:io'; // flutter_ignore: dart_io_import. {{#android}} import 'package:{{pluginName}}/{{pluginName}}.dart'; {{/android}} {{#ios}} import 'package:{{pluginName}}/{{pluginName}}.dart'; {{/ios}} {{#linux}} import 'package:{{pluginName}}/{{pluginName}}.dart'; {{/linux}} {{#macos}} import 'package:{{pluginName}}/{{pluginName}}.dart'; {{/macos}} {{#windows}} import 'package:{{pluginName}}/{{pluginName}}.dart'; {{/windows}} @pragma('vm:entry-point') class _PluginRegistrant { @pragma('vm:entry-point') static void register() { if (Platform.isAndroid) { {{#android}} $_dartPluginRegisterWith {{/android}} } else if (Platform.isIOS) { {{#ios}} $_dartPluginRegisterWith {{/ios}} } else if (Platform.isLinux) { {{#linux}} $_dartPluginRegisterWith {{/linux}} } else if (Platform.isMacOS) { {{#macos}} $_dartPluginRegisterWith {{/macos}} } else if (Platform.isWindows) { {{#windows}} $_dartPluginRegisterWith {{/windows}} } } } '''; Future<void> _writeIOSPluginRegistrant(FlutterProject project, List<Plugin> plugins) async { final List<Plugin> methodChannelPlugins = _filterMethodChannelPlugins(plugins, IOSPlugin.kConfigKey); final List<Map<String, Object?>> iosPlugins = _extractPlatformMaps(methodChannelPlugins, IOSPlugin.kConfigKey); final Map<String, Object> context = <String, Object>{ 'os': 'ios', 'deploymentTarget': '12.0', 'framework': 'Flutter', 'methodChannelPlugins': iosPlugins, }; if (project.isModule) { final Directory registryDirectory = project.ios.pluginRegistrantHost; await _renderTemplateToFile( _pluginRegistrantPodspecTemplate, context, registryDirectory.childFile('FlutterPluginRegistrant.podspec'), globals.templateRenderer, ); } await _renderTemplateToFile( _objcPluginRegistryHeaderTemplate, context, project.ios.pluginRegistrantHeader, globals.templateRenderer, ); await _renderTemplateToFile( _objcPluginRegistryImplementationTemplate, context, project.ios.pluginRegistrantImplementation, globals.templateRenderer, ); } /// The relative path from a project's main CMake file to the plugin symlink /// directory to use in the generated plugin CMake file. /// /// Because the generated file is checked in, it can't use absolute paths. It is /// designed to be included by the main CMakeLists.txt, so it relative to /// that file, rather than the generated file. String _cmakeRelativePluginSymlinkDirectoryPath(CmakeBasedProject project) { final FileSystem fileSystem = project.pluginSymlinkDirectory.fileSystem; final String makefileDirPath = project.cmakeFile.parent.absolute.path; // CMake always uses posix-style path separators, regardless of the platform. final path.Context cmakePathContext = path.Context(style: path.Style.posix); final List<String> relativePathComponents = fileSystem.path.split(fileSystem.path.relative( project.pluginSymlinkDirectory.absolute.path, from: makefileDirPath, )); return cmakePathContext.joinAll(relativePathComponents); } Future<void> _writeLinuxPluginFiles(FlutterProject project, List<Plugin> plugins) async { final List<Plugin> methodChannelPlugins = _filterMethodChannelPlugins(plugins, LinuxPlugin.kConfigKey); final List<Map<String, Object?>> linuxMethodChannelPlugins = _extractPlatformMaps(methodChannelPlugins, LinuxPlugin.kConfigKey); final List<Plugin> ffiPlugins = _filterFfiPlugins(plugins, LinuxPlugin.kConfigKey)..removeWhere(methodChannelPlugins.contains); final List<Map<String, Object?>> linuxFfiPlugins = _extractPlatformMaps(ffiPlugins, LinuxPlugin.kConfigKey); final Map<String, Object> context = <String, Object>{ 'os': 'linux', 'methodChannelPlugins': linuxMethodChannelPlugins, 'ffiPlugins': linuxFfiPlugins, 'pluginsDir': _cmakeRelativePluginSymlinkDirectoryPath(project.linux), }; await _writeLinuxPluginRegistrant(project.linux.managedDirectory, context); await _writePluginCmakefile(project.linux.generatedPluginCmakeFile, context, globals.templateRenderer); } Future<void> _writeLinuxPluginRegistrant(Directory destination, Map<String, Object> templateContext) async { await _renderTemplateToFile( _linuxPluginRegistryHeaderTemplate, templateContext, destination.childFile('generated_plugin_registrant.h'), globals.templateRenderer, ); await _renderTemplateToFile( _linuxPluginRegistryImplementationTemplate, templateContext, destination.childFile('generated_plugin_registrant.cc'), globals.templateRenderer, ); } Future<void> _writePluginCmakefile(File destinationFile, Map<String, Object> templateContext, TemplateRenderer templateRenderer) async { await _renderTemplateToFile( _pluginCmakefileTemplate, templateContext, destinationFile, templateRenderer, ); } Future<void> _writeMacOSPluginRegistrant(FlutterProject project, List<Plugin> plugins) async { final List<Plugin> methodChannelPlugins = _filterMethodChannelPlugins(plugins, MacOSPlugin.kConfigKey); final List<Map<String, Object?>> macosMethodChannelPlugins = _extractPlatformMaps(methodChannelPlugins, MacOSPlugin.kConfigKey); final Map<String, Object> context = <String, Object>{ 'os': 'macos', 'framework': 'FlutterMacOS', 'methodChannelPlugins': macosMethodChannelPlugins, }; await _renderTemplateToFile( _swiftPluginRegistryTemplate, context, project.macos.managedDirectory.childFile('GeneratedPluginRegistrant.swift'), globals.templateRenderer, ); } /// Filters out any plugins that don't use method channels, and thus shouldn't be added to the native generated registrants. List<Plugin> _filterMethodChannelPlugins(List<Plugin> plugins, String platformKey) { return plugins.where((Plugin element) { final PluginPlatform? plugin = element.platforms[platformKey]; if (plugin == null) { return false; } if (plugin is NativeOrDartPlugin) { return (plugin as NativeOrDartPlugin).hasMethodChannel(); } // Not all platforms have the ability to create Dart-only plugins. Therefore, any plugin that doesn't // implement NativeOrDartPlugin is always native. return true; }).toList(); } /// Filters out Dart-only and method channel plugins. /// /// FFI plugins do not need native code registration, but their binaries need to be bundled. List<Plugin> _filterFfiPlugins(List<Plugin> plugins, String platformKey) { return plugins.where((Plugin element) { final PluginPlatform? plugin = element.platforms[platformKey]; if (plugin == null) { return false; } if (plugin is NativeOrDartPlugin) { final NativeOrDartPlugin plugin_ = plugin as NativeOrDartPlugin; return plugin_.hasFfi(); } return false; }).toList(); } /// Returns only the plugins with the given platform variant. List<Plugin> _filterPluginsByVariant(List<Plugin> plugins, String platformKey, PluginPlatformVariant variant) { return plugins.where((Plugin element) { final PluginPlatform? platformPlugin = element.platforms[platformKey]; if (platformPlugin == null) { return false; } assert(platformPlugin is VariantPlatformPlugin); return (platformPlugin as VariantPlatformPlugin).supportedVariants.contains(variant); }).toList(); } @visibleForTesting Future<void> writeWindowsPluginFiles( FlutterProject project, List<Plugin> plugins, TemplateRenderer templateRenderer, { Iterable<String>? allowedPlugins, }) async { final List<Plugin> methodChannelPlugins = _filterMethodChannelPlugins(plugins, WindowsPlugin.kConfigKey); if (allowedPlugins != null) { final List<Plugin> disallowedPlugins = methodChannelPlugins .toList() ..removeWhere((Plugin plugin) => allowedPlugins.contains(plugin.name)); if (disallowedPlugins.isNotEmpty) { final StringBuffer buffer = StringBuffer(); buffer.writeln('The Flutter Preview device does not support the following plugins from your pubspec.yaml:'); buffer.writeln(); buffer.writeln(disallowedPlugins.map((Plugin p) => p.name).toList().toString()); buffer.writeln(); buffer.writeln('In order to build a Flutter app with plugins, you must use another target platform,'); buffer.writeln('such as Windows. Type `flutter doctor` into your terminal to see which target platforms'); buffer.writeln('are ready to be used, and how to get required dependencies for other platforms.'); throwToolExit(buffer.toString()); } } final List<Plugin> win32Plugins = _filterPluginsByVariant(methodChannelPlugins, WindowsPlugin.kConfigKey, PluginPlatformVariant.win32); final List<Map<String, Object?>> windowsMethodChannelPlugins = _extractPlatformMaps(win32Plugins, WindowsPlugin.kConfigKey); final List<Plugin> ffiPlugins = _filterFfiPlugins(plugins, WindowsPlugin.kConfigKey)..removeWhere(methodChannelPlugins.contains); final List<Map<String, Object?>> windowsFfiPlugins = _extractPlatformMaps(ffiPlugins, WindowsPlugin.kConfigKey); final Map<String, Object> context = <String, Object>{ 'os': 'windows', 'methodChannelPlugins': windowsMethodChannelPlugins, 'ffiPlugins': windowsFfiPlugins, 'pluginsDir': _cmakeRelativePluginSymlinkDirectoryPath(project.windows), }; await _writeCppPluginRegistrant(project.windows.managedDirectory, context, templateRenderer); await _writePluginCmakefile(project.windows.generatedPluginCmakeFile, context, templateRenderer); } Future<void> _writeCppPluginRegistrant(Directory destination, Map<String, Object> templateContext, TemplateRenderer templateRenderer) async { await _renderTemplateToFile( _cppPluginRegistryHeaderTemplate, templateContext, destination.childFile('generated_plugin_registrant.h'), templateRenderer, ); await _renderTemplateToFile( _cppPluginRegistryImplementationTemplate, templateContext, destination.childFile('generated_plugin_registrant.cc'), templateRenderer, ); } Future<void> _writeWebPluginRegistrant(FlutterProject project, List<Plugin> plugins, Directory destination) async { final List<Map<String, Object?>> webPlugins = _extractPlatformMaps(plugins, WebPlugin.kConfigKey); final Map<String, Object> context = <String, Object>{ 'methodChannelPlugins': webPlugins, }; final File pluginFile = destination.childFile('web_plugin_registrant.dart'); final String template = webPlugins.isEmpty ? _noopDartPluginRegistryTemplate : _dartPluginRegistryTemplate; await _renderTemplateToFile( template, context, pluginFile, globals.templateRenderer, ); } /// For each platform that uses them, creates symlinks within the platform /// directory to each plugin used on that platform. /// /// If |force| is true, the symlinks will be recreated, otherwise they will /// be created only if missing. /// /// This uses [project.flutterPluginsDependenciesFile], so it should only be /// run after [refreshPluginsList] has been run since the last plugin change. void createPluginSymlinks(FlutterProject project, {bool force = false, @visibleForTesting FeatureFlags? featureFlagsOverride}) { final FeatureFlags localFeatureFlags = featureFlagsOverride ?? featureFlags; Map<String, Object?>? platformPlugins; final String? pluginFileContent = _readFileContent(project.flutterPluginsDependenciesFile); if (pluginFileContent != null) { final Map<String, Object?>? pluginInfo = json.decode(pluginFileContent) as Map<String, Object?>?; platformPlugins = pluginInfo?[_kFlutterPluginsPluginListKey] as Map<String, Object?>?; } platformPlugins ??= <String, Object?>{}; if (localFeatureFlags.isWindowsEnabled && project.windows.existsSync()) { _createPlatformPluginSymlinks( project.windows.pluginSymlinkDirectory, platformPlugins[project.windows.pluginConfigKey] as List<Object?>?, force: force, ); } if (localFeatureFlags.isLinuxEnabled && project.linux.existsSync()) { _createPlatformPluginSymlinks( project.linux.pluginSymlinkDirectory, platformPlugins[project.linux.pluginConfigKey] as List<Object?>?, force: force, ); } } /// Handler for symlink failures which provides specific instructions for known /// failure cases. @visibleForTesting void handleSymlinkException(FileSystemException e, { required Platform platform, required OperatingSystemUtils os, required String destination, required String source, }) { if (platform.isWindows) { // ERROR_ACCESS_DENIED if (e.osError?.errorCode == 5) { throwToolExit( 'ERROR_ACCESS_DENIED file system exception thrown while trying to ' 'create a symlink from $source to $destination', ); } // ERROR_PRIVILEGE_NOT_HELD, user cannot symlink if (e.osError?.errorCode == 1314) { final String? versionString = RegExp(r'[\d.]+').firstMatch(os.name)?.group(0); final Version? version = Version.parse(versionString); // Windows 10 14972 is the oldest version that allows creating symlinks // just by enabling developer mode; before that it requires running the // terminal as Administrator. // https://blogs.windows.com/windowsdeveloper/2016/12/02/symlinks-windows-10/ final String instructions = (version != null && version >= Version(10, 0, 14972)) ? 'Please enable Developer Mode in your system settings. Run\n' ' start ms-settings:developers\n' 'to open settings.' : 'You must build from a terminal run as administrator.'; throwToolExit('Building with plugins requires symlink support.\n\n$instructions'); } // ERROR_INVALID_FUNCTION, trying to link across drives, which is not supported if (e.osError?.errorCode == 1) { throwToolExit( 'Creating symlink from $source to $destination failed with ' 'ERROR_INVALID_FUNCTION. Try moving your Flutter project to the same ' 'drive as your Flutter SDK.', ); } } } /// Creates [symlinkDirectory] containing symlinks to each plugin listed in [platformPlugins]. /// /// If [force] is true, the directory will be created only if missing. void _createPlatformPluginSymlinks(Directory symlinkDirectory, List<Object?>? platformPlugins, {bool force = false}) { if (force && symlinkDirectory.existsSync()) { // Start fresh to avoid stale links. symlinkDirectory.deleteSync(recursive: true); } symlinkDirectory.createSync(recursive: true); if (platformPlugins == null) { return; } for (final Map<String, Object?> pluginInfo in platformPlugins.cast<Map<String, Object?>>()) { final String name = pluginInfo[_kFlutterPluginsNameKey]! as String; final String path = pluginInfo[_kFlutterPluginsPathKey]! as String; final Link link = symlinkDirectory.childLink(name); if (link.existsSync()) { continue; } try { link.createSync(path); } on FileSystemException catch (e) { handleSymlinkException( e, platform: globals.platform, os: globals.os, destination: 'dest', source: 'source', ); rethrow; } } } /// Rewrites the `.flutter-plugins` file of [project] based on the plugin /// dependencies declared in `pubspec.yaml`. /// /// Assumes `pub get` has been executed since last change to `pubspec.yaml`. Future<void> refreshPluginsList( FlutterProject project, { bool iosPlatform = false, bool macOSPlatform = false, bool forceCocoaPodsOnly = false, }) async { final List<Plugin> plugins = await findPlugins(project); // Sort the plugins by name to keep ordering stable in generated files. plugins.sort((Plugin left, Plugin right) => left.name.compareTo(right.name)); // TODO(franciscojma): Remove once migration is complete. // Write the legacy plugin files to avoid breaking existing apps. final bool legacyChanged = _writeFlutterPluginsListLegacy(project, plugins); final bool changed = _writeFlutterPluginsList( project, plugins, forceCocoaPodsOnly: forceCocoaPodsOnly, ); if (changed || legacyChanged || forceCocoaPodsOnly) { createPluginSymlinks(project, force: true); if (iosPlatform) { globals.cocoaPods?.invalidatePodInstallOutput(project.ios); } if (macOSPlatform) { globals.cocoaPods?.invalidatePodInstallOutput(project.macos); } } } /// Injects plugins found in `pubspec.yaml` into the platform-specific projects /// only at build-time. /// /// This method is similar to [injectPlugins], but used only for platforms where /// the plugin files are not required when the app is created (currently: Web). /// /// This method will create files in the temporary flutter build directory /// specified by `destination`. /// /// In the Web platform, `destination` can point to a real filesystem (`flutter build`) /// or an in-memory filesystem (`flutter run`). /// /// This method is also used by [WebProject.ensureReadyForPlatformSpecificTooling] /// to inject a copy of the plugin registrant for web into .dart_tool/dartpad so /// dartpad can get the plugin registrant without needing to build the complete /// project. See: https://github.com/dart-lang/dart-services/pull/874 Future<void> injectBuildTimePluginFiles( FlutterProject project, { required Directory destination, bool webPlatform = false, }) async { final List<Plugin> plugins = await findPlugins(project); // Sort the plugins by name to keep ordering stable in generated files. plugins.sort((Plugin left, Plugin right) => left.name.compareTo(right.name)); if (webPlatform) { await _writeWebPluginRegistrant(project, plugins, destination); } } /// Injects plugins found in `pubspec.yaml` into the platform-specific projects. /// /// The injected files are required by the flutter app as soon as possible, so /// it can be built. /// /// Files written by this method end up in platform-specific locations that are /// configured by each [FlutterProject] subclass (except for the Web). /// /// Web tooling uses [injectBuildTimePluginFiles] instead, which places files in the /// current build (temp) directory, and doesn't modify the users' working copy. /// /// Assumes [refreshPluginsList] has been called since last change to `pubspec.yaml`. Future<void> injectPlugins( FlutterProject project, { bool androidPlatform = false, bool iosPlatform = false, bool linuxPlatform = false, bool macOSPlatform = false, bool windowsPlatform = false, Iterable<String>? allowedPlugins, DarwinDependencyManagement? darwinDependencyManagement, }) async { final List<Plugin> plugins = await findPlugins(project); // Sort the plugins by name to keep ordering stable in generated files. plugins.sort((Plugin left, Plugin right) => left.name.compareTo(right.name)); if (androidPlatform) { await _writeAndroidPluginRegistrant(project, plugins); } if (iosPlatform) { await _writeIOSPluginRegistrant(project, plugins); } if (linuxPlatform) { await _writeLinuxPluginFiles(project, plugins); } if (macOSPlatform) { await _writeMacOSPluginRegistrant(project, plugins); } if (windowsPlatform) { await writeWindowsPluginFiles(project, plugins, globals.templateRenderer, allowedPlugins: allowedPlugins); } if (iosPlatform || macOSPlatform) { final DarwinDependencyManagement darwinDependencyManagerSetup = darwinDependencyManagement ?? DarwinDependencyManagement( project: project, plugins: plugins, cocoapods: globals.cocoaPods!, swiftPackageManager: SwiftPackageManager( fileSystem: globals.fs, templateRenderer: globals.templateRenderer, ), fileSystem: globals.fs, logger: globals.logger, ); if (iosPlatform) { await darwinDependencyManagerSetup.setUp( platform: SupportedPlatform.ios, ); } if (macOSPlatform) { await darwinDependencyManagerSetup.setUp( platform: SupportedPlatform.macos, ); } } } /// Returns whether the specified Flutter [project] has any plugin dependencies. /// /// Assumes [refreshPluginsList] has been called since last change to `pubspec.yaml`. bool hasPlugins(FlutterProject project) { return _readFileContent(project.flutterPluginsFile) != null; } /// Resolves the platform implementation for Dart-only plugins. /// /// * If there is only one dependency on a package that implements the /// frontend plugin for the current platform, use that. /// * If there is a single direct dependency on a package that implements the /// frontend plugin for the current platform, use that. /// * If there is no direct dependency on a package that implements the /// frontend plugin, but there is a default for the current platform, /// use that. /// * Else fail. /// /// For more details, https://flutter.dev/go/federated-plugins. // TODO(stuartmorgan): Expand implementation to apply to all implementations, // not just Dart-only, per the federated plugin spec. List<PluginInterfaceResolution> resolvePlatformImplementation( List<Plugin> plugins, ) { const Iterable<String> platformKeys = <String>[ AndroidPlugin.kConfigKey, IOSPlugin.kConfigKey, LinuxPlugin.kConfigKey, MacOSPlugin.kConfigKey, WindowsPlugin.kConfigKey, ]; final List<PluginInterfaceResolution> pluginResolutions = <PluginInterfaceResolution>[]; bool hasResolutionError = false; bool hasPluginPubspecError = false; for (final String platformKey in platformKeys) { // Key: the plugin name, value: the list of plugin candidates for the implementation of [platformKey]. final Map<String, List<Plugin>> pluginImplCandidates = <String, List<Plugin>>{}; // Key: the plugin name, value: the plugin name of the default implementation of [platformKey]. final Map<String, String> defaultImplementations = <String, String>{}; for (final Plugin plugin in plugins) { final String? error = _validatePlugin(plugin, platformKey); if (error != null) { globals.printError(error); hasPluginPubspecError = true; continue; } final String? implementsPluginName = _getImplementedPlugin(plugin, platformKey); final String? defaultImplPluginName = _getDefaultImplPlugin(plugin, platformKey); if (defaultImplPluginName != null) { // Each plugin can only have one default implementation for this [platformKey]. defaultImplementations[plugin.name] = defaultImplPluginName; } if (implementsPluginName != null) { pluginImplCandidates.putIfAbsent(implementsPluginName, () => <Plugin>[]); pluginImplCandidates[implementsPluginName]!.add(plugin); } } final Map<String, Plugin> pluginResolution = <String, Plugin>{}; // Now resolve all the possible resolutions to a single option for each // plugin, or throw if that's not possible. for (final MapEntry<String, List<Plugin>> implCandidatesEntry in pluginImplCandidates.entries) { final (Plugin? resolution, String? error) = _resolveImplementationOfPlugin( platformKey: platformKey, pluginName: implCandidatesEntry.key, candidates: implCandidatesEntry.value, defaultPackageName: defaultImplementations[implCandidatesEntry.key], ); if (error != null) { globals.printError(error); hasResolutionError = true; } else if (resolution != null) { pluginResolution[implCandidatesEntry.key] = resolution; } } pluginResolutions.addAll( pluginResolution.values.map((Plugin plugin) { return PluginInterfaceResolution(plugin: plugin, platform: platformKey); }), ); } if (hasPluginPubspecError) { throwToolExit('Please resolve the plugin pubspec errors'); } if (hasResolutionError) { throwToolExit('Please resolve the plugin implementation selection errors'); } return pluginResolutions; } /// Validates conflicting plugin parameters in pubspec, such as /// `dartPluginClass`, `default_package` and `implements`. /// /// Returns an error, if failing. String? _validatePlugin(Plugin plugin, String platformKey) { final String? implementsPackage = plugin.implementsPackage; final String? defaultImplPluginName = plugin.defaultPackagePlatforms[platformKey]; if (plugin.name == implementsPackage && plugin.name == defaultImplPluginName) { // Allow self implementing and self as platform default. return null; } if (defaultImplPluginName != null) { if (implementsPackage != null && implementsPackage.isNotEmpty) { return 'Plugin ${plugin.name}:$platformKey provides an implementation for $implementsPackage ' 'and also references a default implementation for $defaultImplPluginName, which is currently not supported. ' 'Ask the maintainers of ${plugin.name} to either remove the implementation via `implements: $implementsPackage` ' 'or avoid referencing a default implementation via `platforms: $platformKey: default_package: $defaultImplPluginName`.\n'; } if (_hasPluginInlineDartImpl(plugin, platformKey)) { return 'Plugin ${plugin.name}:$platformKey which provides an inline implementation ' 'cannot also reference a default implementation for $defaultImplPluginName. ' 'Ask the maintainers of ${plugin.name} to either remove the implementation via `platforms: $platformKey: dartPluginClass` ' 'or avoid referencing a default implementation via `platforms: $platformKey: default_package: $defaultImplPluginName`.\n'; } } return null; } /// Determine if this [plugin] serves as implementation for an app-facing /// package for the given platform [platformKey]. /// /// If so, return the package name, which the [plugin] implements. /// /// Options: /// * The [plugin] (e.g. 'url_launcher_linux') serves as implementation for /// an app-facing package (e.g. 'url_launcher'). /// * The [plugin] (e.g. 'url_launcher') implements itself and then also /// serves as its own default implementation. /// * The [plugin] does not provide an implementation. String? _getImplementedPlugin(Plugin plugin, String platformKey) { final bool hasInlineDartImpl = _hasPluginInlineDartImpl(plugin, platformKey); if (hasInlineDartImpl) { final String? implementsPackage = plugin.implementsPackage; // Only can serve, if the plugin has a dart inline implementation. if (implementsPackage != null && implementsPackage.isNotEmpty) { return implementsPackage; } if (_isEligibleDartSelfImpl(plugin, platformKey)) { // The inline Dart plugin implements itself. return plugin.name; } } return null; } /// Determine if this [plugin] (or package) references a default plugin with an /// implementation for the given platform [platformKey]. /// /// If so, return the plugin name, which provides the default implementation. /// /// Options: /// * The [plugin] (e.g. 'url_launcher') references a default implementation /// (e.g. 'url_launcher_linux'). /// * The [plugin] (e.g. 'url_launcher') implements itself and then also /// serves as its own default implementation. /// * The [plugin] does not reference a default implementation. String? _getDefaultImplPlugin(Plugin plugin, String platformKey) { final String? defaultImplPluginName = plugin.defaultPackagePlatforms[platformKey]; if (defaultImplPluginName != null) { return defaultImplPluginName; } if (_hasPluginInlineDartImpl(plugin, platformKey) && _isEligibleDartSelfImpl(plugin, platformKey)) { // The inline Dart plugin serves as its own default implementation. return plugin.name; } return null; } /// Determine if the [plugin]'s inline dart implementation for the /// [platformKey] is eligible to serve as its own default. /// /// An app-facing package (i.e., one with no 'implements') with an /// inline implementation should be its own default implementation. /// Desktop platforms originally did not work that way, and enabling /// it unconditionally would break existing published plugins, so /// only treat it as such if either: /// - the platform is not desktop, or /// - the plugin requires at least Flutter 2.11 (when this opt-in logic /// was added), so that existing plugins continue to work. /// See https://github.com/flutter/flutter/issues/87862 for details. bool _isEligibleDartSelfImpl(Plugin plugin, String platformKey) { final bool isDesktop = platformKey == 'linux' || platformKey == 'macos' || platformKey == 'windows'; final semver.VersionConstraint? flutterConstraint = plugin.flutterConstraint; final semver.Version? minFlutterVersion = flutterConstraint != null && flutterConstraint is semver.VersionRange ? flutterConstraint.min : null; final bool hasMinVersionForImplementsRequirement = minFlutterVersion != null && minFlutterVersion.compareTo(semver.Version(2, 11, 0)) >= 0; return !isDesktop || hasMinVersionForImplementsRequirement; } /// Determine if the plugin provides an inline dart implementation. bool _hasPluginInlineDartImpl(Plugin plugin, String platformKey) { return plugin.pluginDartClassPlatforms[platformKey] != null && plugin.pluginDartClassPlatforms[platformKey] != 'none'; } /// Get the resolved plugin [resolution] from the [candidates] serving as implementation for /// [pluginName]. /// /// Returns an [error] string, if failing. (Plugin? resolution, String? error) _resolveImplementationOfPlugin({ required String platformKey, required String pluginName, required List<Plugin> candidates, String? defaultPackageName, }) { // If there's only one candidate, use it. if (candidates.length == 1) { return (candidates.first, null); } // Next, try direct dependencies of the resolving application. final Iterable<Plugin> directDependencies = candidates.where((Plugin plugin) { return plugin.isDirectDependency; }); if (directDependencies.isNotEmpty) { if (directDependencies.length > 1) { // Allow overriding an app-facing package with an inline implementation (which is a direct dependency) // with another direct dependency which implements the app-facing package. final Iterable<Plugin> implementingPackage = directDependencies.where((Plugin plugin) => plugin.implementsPackage != null && plugin.implementsPackage!.isNotEmpty); final Set<Plugin> appFacingPackage = directDependencies.toSet()..removeAll(implementingPackage); if (implementingPackage.length == 1 && appFacingPackage.length == 1) { return (implementingPackage.first, null); } return ( null, 'Plugin $pluginName:$platformKey has conflicting direct dependency implementations:\n' '${directDependencies.map((Plugin plugin) => ' ${plugin.name}\n').join()}' 'To fix this issue, remove all but one of these dependencies from pubspec.yaml.\n', ); } else { return (directDependencies.first, null); } } // Next, defer to the default implementation if there is one. if (defaultPackageName != null) { final int defaultIndex = candidates .indexWhere((Plugin plugin) => plugin.name == defaultPackageName); if (defaultIndex != -1) { return (candidates[defaultIndex], null); } } // Otherwise, require an explicit choice. if (candidates.length > 1) { return ( null, 'Plugin $pluginName:$platformKey has multiple possible implementations:\n' '${candidates.map((Plugin plugin) => ' ${plugin.name}\n').join()}' 'To fix this issue, add one of these dependencies to pubspec.yaml.\n', ); } // No implementation provided return (null, null); } /// Generates the Dart plugin registrant, which allows to bind a platform /// implementation of a Dart only plugin to its interface. /// The new entrypoint wraps [currentMainUri], adds the [_PluginRegistrant] class, /// and writes the file to [newMainDart]. /// /// [mainFile] is the main entrypoint file. e.g. /<app>/lib/main.dart. /// /// A successful run will create a new generate_main.dart file or update the existing file. /// Throws [ToolExit] if unable to generate the file. /// /// For more details, see https://flutter.dev/go/federated-plugins. Future<void> generateMainDartWithPluginRegistrant( FlutterProject rootProject, PackageConfig packageConfig, String currentMainUri, File mainFile, ) async { final List<Plugin> plugins = await findPlugins(rootProject); final List<PluginInterfaceResolution> resolutions = resolvePlatformImplementation( plugins, ); final LanguageVersion entrypointVersion = determineLanguageVersion( mainFile, packageConfig.packageOf(mainFile.absolute.uri), Cache.flutterRoot!, ); final Map<String, Object> templateContext = <String, Object>{ 'mainEntrypoint': currentMainUri, 'dartLanguageVersion': entrypointVersion.toString(), AndroidPlugin.kConfigKey: <Object?>[], IOSPlugin.kConfigKey: <Object?>[], LinuxPlugin.kConfigKey: <Object?>[], MacOSPlugin.kConfigKey: <Object?>[], WindowsPlugin.kConfigKey: <Object?>[], }; final File newMainDart = rootProject.dartPluginRegistrant; if (resolutions.isEmpty) { try { if (await newMainDart.exists()) { await newMainDart.delete(); } } on FileSystemException catch (error) { globals.printWarning( 'Unable to remove ${newMainDart.path}, received error: $error.\n' 'You might need to run flutter clean.', ); rethrow; } return; } for (final PluginInterfaceResolution resolution in resolutions) { assert(templateContext.containsKey(resolution.platform)); (templateContext[resolution.platform] as List<Object?>?)?.add(resolution.toMap()); } try { await _renderTemplateToFile( _dartPluginRegistryForNonWebTemplate, templateContext, newMainDart, globals.templateRenderer, ); } on FileSystemException catch (error) { globals.printError('Unable to write ${newMainDart.path}, received error: $error'); rethrow; } }
flutter/packages/flutter_tools/lib/src/flutter_plugins.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/flutter_plugins.dart", "repo_id": "flutter", "token_count": 17468 }
364
// Copyright 2014 The Flutter 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:meta/meta.dart'; import 'package:process/process.dart'; import '../base/error_handling_io.dart'; import '../base/file_system.dart'; import '../base/io.dart'; import '../base/logger.dart'; import '../base/process.dart'; import '../convert.dart'; import '../device.dart'; import '../macos/xcode.dart'; /// A wrapper around the `devicectl` command line tool. /// /// CoreDevice is a device connectivity stack introduced in Xcode 15. Devices /// with iOS 17 or greater are CoreDevices. /// /// `devicectl` (CoreDevice Device Control) is an Xcode CLI tool used for /// interacting with CoreDevices. class IOSCoreDeviceControl { IOSCoreDeviceControl({ required Logger logger, required ProcessManager processManager, required Xcode xcode, required FileSystem fileSystem, }) : _logger = logger, _processUtils = ProcessUtils(logger: logger, processManager: processManager), _xcode = xcode, _fileSystem = fileSystem; final Logger _logger; final ProcessUtils _processUtils; final Xcode _xcode; final FileSystem _fileSystem; /// When the `--timeout` flag is used with `devicectl`, it must be at /// least 5 seconds. If lower than 5 seconds, `devicectl` will error and not /// run the command. static const int _minimumTimeoutInSeconds = 5; /// Executes `devicectl` command to get list of devices. The command will /// likely complete before [timeout] is reached. If [timeout] is reached, /// the command will be stopped as a failure. Future<List<Object?>> _listCoreDevices({ Duration timeout = const Duration(seconds: _minimumTimeoutInSeconds), }) async { if (!_xcode.isDevicectlInstalled) { _logger.printError('devicectl is not installed.'); return <Object?>[]; } // Default to minimum timeout if needed to prevent error. Duration validTimeout = timeout; if (timeout.inSeconds < _minimumTimeoutInSeconds) { _logger.printError( 'Timeout of ${timeout.inSeconds} seconds is below the minimum timeout value ' 'for devicectl. Changing the timeout to the minimum value of $_minimumTimeoutInSeconds.'); validTimeout = const Duration(seconds: _minimumTimeoutInSeconds); } final Directory tempDirectory = _fileSystem.systemTempDirectory.createTempSync('core_devices.'); final File output = tempDirectory.childFile('core_device_list.json'); output.createSync(); final List<String> command = <String>[ ..._xcode.xcrunCommand(), 'devicectl', 'list', 'devices', '--timeout', validTimeout.inSeconds.toString(), '--json-output', output.path, ]; try { final RunResult result = await _processUtils.run(command, throwOnError: true); if (!output.existsSync()) { _logger.printError('After running the command ${command.join(' ')} the file'); _logger.printError('${output.path} was expected to exist, but it did not.'); _logger.printError('The process exited with code ${result.exitCode} and'); _logger.printError('Stdout:\n\n${result.stdout.trim()}\n'); _logger.printError('Stderr:\n\n${result.stderr.trim()}'); throw StateError('Expected the file ${output.path} to exist but it did not'); } final String stringOutput = output.readAsStringSync(); _logger.printTrace(stringOutput); try { final Object? decodeResult = (json.decode(stringOutput) as Map<String, Object?>)['result']; if (decodeResult is Map<String, Object?>) { final Object? decodeDevices = decodeResult['devices']; if (decodeDevices is List<Object?>) { return decodeDevices; } } _logger.printError('devicectl returned unexpected JSON response: $stringOutput'); return <Object?>[]; } on FormatException { // We failed to parse the devicectl output, or it returned junk. _logger.printError('devicectl returned non-JSON response: $stringOutput'); return <Object?>[]; } } on ProcessException catch (err) { _logger.printError('Error executing devicectl: $err'); return <Object?>[]; } finally { ErrorHandlingFileSystem.deleteIfExists(tempDirectory, recursive: true); } } Future<List<IOSCoreDevice>> getCoreDevices({ Duration timeout = const Duration(seconds: _minimumTimeoutInSeconds), }) async { final List<Object?> devicesSection = await _listCoreDevices(timeout: timeout); return <IOSCoreDevice>[ for (final Object? deviceObject in devicesSection) if (deviceObject is Map<String, Object?>) IOSCoreDevice.fromBetaJson(deviceObject, logger: _logger), ]; } /// Executes `devicectl` command to get list of apps installed on the device. /// If [bundleId] is provided, it will only return apps matching the bundle /// identifier exactly. Future<List<Object?>> _listInstalledApps({ required String deviceId, String? bundleId, }) async { if (!_xcode.isDevicectlInstalled) { _logger.printError('devicectl is not installed.'); return <Object?>[]; } final Directory tempDirectory = _fileSystem.systemTempDirectory.createTempSync('core_devices.'); final File output = tempDirectory.childFile('core_device_app_list.json'); output.createSync(); final List<String> command = <String>[ ..._xcode.xcrunCommand(), 'devicectl', 'device', 'info', 'apps', '--device', deviceId, if (bundleId != null) '--bundle-id', bundleId!, '--json-output', output.path, ]; try { await _processUtils.run(command, throwOnError: true); final String stringOutput = output.readAsStringSync(); try { final Object? decodeResult = (json.decode(stringOutput) as Map<String, Object?>)['result']; if (decodeResult is Map<String, Object?>) { final Object? decodeApps = decodeResult['apps']; if (decodeApps is List<Object?>) { return decodeApps; } } _logger.printError('devicectl returned unexpected JSON response: $stringOutput'); return <Object?>[]; } on FormatException { // We failed to parse the devicectl output, or it returned junk. _logger.printError('devicectl returned non-JSON response: $stringOutput'); return <Object?>[]; } } on ProcessException catch (err) { _logger.printError('Error executing devicectl: $err'); return <Object?>[]; } finally { tempDirectory.deleteSync(recursive: true); } } @visibleForTesting Future<List<IOSCoreDeviceInstalledApp>> getInstalledApps({ required String deviceId, String? bundleId, }) async { final List<Object?> appsData = await _listInstalledApps(deviceId: deviceId, bundleId: bundleId); return <IOSCoreDeviceInstalledApp>[ for (final Object? appObject in appsData) if (appObject is Map<String, Object?>) IOSCoreDeviceInstalledApp.fromBetaJson(appObject), ]; } Future<bool> isAppInstalled({ required String deviceId, required String bundleId, }) async { final List<IOSCoreDeviceInstalledApp> apps = await getInstalledApps( deviceId: deviceId, bundleId: bundleId, ); if (apps.isNotEmpty) { return true; } return false; } Future<bool> installApp({ required String deviceId, required String bundlePath, }) async { if (!_xcode.isDevicectlInstalled) { _logger.printError('devicectl is not installed.'); return false; } final Directory tempDirectory = _fileSystem.systemTempDirectory.createTempSync('core_devices.'); final File output = tempDirectory.childFile('install_results.json'); output.createSync(); final List<String> command = <String>[ ..._xcode.xcrunCommand(), 'devicectl', 'device', 'install', 'app', '--device', deviceId, bundlePath, '--json-output', output.path, ]; try { await _processUtils.run(command, throwOnError: true); final String stringOutput = output.readAsStringSync(); try { final Object? decodeResult = (json.decode(stringOutput) as Map<String, Object?>)['info']; if (decodeResult is Map<String, Object?> && decodeResult['outcome'] == 'success') { return true; } _logger.printError('devicectl returned unexpected JSON response: $stringOutput'); return false; } on FormatException { // We failed to parse the devicectl output, or it returned junk. _logger.printError('devicectl returned non-JSON response: $stringOutput'); return false; } } on ProcessException catch (err) { _logger.printError('Error executing devicectl: $err'); return false; } finally { tempDirectory.deleteSync(recursive: true); } } /// Uninstalls the app from the device. Will succeed even if the app is not /// currently installed on the device. Future<bool> uninstallApp({ required String deviceId, required String bundleId, }) async { if (!_xcode.isDevicectlInstalled) { _logger.printError('devicectl is not installed.'); return false; } final Directory tempDirectory = _fileSystem.systemTempDirectory.createTempSync('core_devices.'); final File output = tempDirectory.childFile('uninstall_results.json'); output.createSync(); final List<String> command = <String>[ ..._xcode.xcrunCommand(), 'devicectl', 'device', 'uninstall', 'app', '--device', deviceId, bundleId, '--json-output', output.path, ]; try { await _processUtils.run(command, throwOnError: true); final String stringOutput = output.readAsStringSync(); try { final Object? decodeResult = (json.decode(stringOutput) as Map<String, Object?>)['info']; if (decodeResult is Map<String, Object?> && decodeResult['outcome'] == 'success') { return true; } _logger.printError('devicectl returned unexpected JSON response: $stringOutput'); return false; } on FormatException { // We failed to parse the devicectl output, or it returned junk. _logger.printError('devicectl returned non-JSON response: $stringOutput'); return false; } } on ProcessException catch (err) { _logger.printError('Error executing devicectl: $err'); return false; } finally { tempDirectory.deleteSync(recursive: true); } } Future<bool> launchApp({ required String deviceId, required String bundleId, List<String> launchArguments = const <String>[], }) async { if (!_xcode.isDevicectlInstalled) { _logger.printError('devicectl is not installed.'); return false; } final Directory tempDirectory = _fileSystem.systemTempDirectory.createTempSync('core_devices.'); final File output = tempDirectory.childFile('launch_results.json'); output.createSync(); final List<String> command = <String>[ ..._xcode.xcrunCommand(), 'devicectl', 'device', 'process', 'launch', '--device', deviceId, bundleId, if (launchArguments.isNotEmpty) ...launchArguments, '--json-output', output.path, ]; try { await _processUtils.run(command, throwOnError: true); final String stringOutput = output.readAsStringSync(); try { final Object? decodeResult = (json.decode(stringOutput) as Map<String, Object?>)['info']; if (decodeResult is Map<String, Object?> && decodeResult['outcome'] == 'success') { return true; } _logger.printError('devicectl returned unexpected JSON response: $stringOutput'); return false; } on FormatException { // We failed to parse the devicectl output, or it returned junk. _logger.printError('devicectl returned non-JSON response: $stringOutput'); return false; } } on ProcessException catch (err) { _logger.printError('Error executing devicectl: $err'); return false; } finally { tempDirectory.deleteSync(recursive: true); } } } class IOSCoreDevice { IOSCoreDevice._({ required this.capabilities, required this.connectionProperties, required this.deviceProperties, required this.hardwareProperties, required this.coreDeviceIdentifier, required this.visibilityClass, }); /// Parse JSON from `devicectl list devices --json-output` while it's in beta preview mode. /// /// Example: /// { /// "capabilities" : [ /// ], /// "connectionProperties" : { /// }, /// "deviceProperties" : { /// }, /// "hardwareProperties" : { /// }, /// "identifier" : "123456BB5-AEDE-7A22-B890-1234567890DD", /// "visibilityClass" : "default" /// } factory IOSCoreDevice.fromBetaJson( Map<String, Object?> data, { required Logger logger, }) { final List<_IOSCoreDeviceCapability> capabilitiesList = <_IOSCoreDeviceCapability>[ if (data['capabilities'] case final List<Object?> capabilitiesData) for (final Object? capabilityData in capabilitiesData) if (capabilityData != null && capabilityData is Map<String, Object?>) _IOSCoreDeviceCapability.fromBetaJson(capabilityData), ]; _IOSCoreDeviceConnectionProperties? connectionProperties; if (data['connectionProperties'] is Map<String, Object?>) { final Map<String, Object?> connectionPropertiesData = data['connectionProperties']! as Map<String, Object?>; connectionProperties = _IOSCoreDeviceConnectionProperties.fromBetaJson( connectionPropertiesData, logger: logger, ); } IOSCoreDeviceProperties? deviceProperties; if (data['deviceProperties'] is Map<String, Object?>) { final Map<String, Object?> devicePropertiesData = data['deviceProperties']! as Map<String, Object?>; deviceProperties = IOSCoreDeviceProperties.fromBetaJson(devicePropertiesData); } _IOSCoreDeviceHardwareProperties? hardwareProperties; if (data['hardwareProperties'] is Map<String, Object?>) { final Map<String, Object?> hardwarePropertiesData = data['hardwareProperties']! as Map<String, Object?>; hardwareProperties = _IOSCoreDeviceHardwareProperties.fromBetaJson( hardwarePropertiesData, logger: logger, ); } return IOSCoreDevice._( capabilities: capabilitiesList, connectionProperties: connectionProperties, deviceProperties: deviceProperties, hardwareProperties: hardwareProperties, coreDeviceIdentifier: data['identifier']?.toString(), visibilityClass: data['visibilityClass']?.toString(), ); } String? get udid => hardwareProperties?.udid; DeviceConnectionInterface? get connectionInterface { return switch (connectionProperties?.transportType?.toLowerCase()) { 'localnetwork' => DeviceConnectionInterface.wireless, 'wired' => DeviceConnectionInterface.attached, _ => null, }; } @visibleForTesting final List<_IOSCoreDeviceCapability> capabilities; @visibleForTesting final _IOSCoreDeviceConnectionProperties? connectionProperties; final IOSCoreDeviceProperties? deviceProperties; @visibleForTesting final _IOSCoreDeviceHardwareProperties? hardwareProperties; final String? coreDeviceIdentifier; final String? visibilityClass; } class _IOSCoreDeviceCapability { _IOSCoreDeviceCapability._({ required this.featureIdentifier, required this.name, }); /// Parse `capabilities` section of JSON from `devicectl list devices --json-output` /// while it's in beta preview mode. /// /// Example: /// "capabilities" : [ /// { /// "featureIdentifier" : "com.apple.coredevice.feature.spawnexecutable", /// "name" : "Spawn Executable" /// }, /// { /// "featureIdentifier" : "com.apple.coredevice.feature.launchapplication", /// "name" : "Launch Application" /// } /// ] factory _IOSCoreDeviceCapability.fromBetaJson(Map<String, Object?> data) { return _IOSCoreDeviceCapability._( featureIdentifier: data['featureIdentifier']?.toString(), name: data['name']?.toString(), ); } final String? featureIdentifier; final String? name; } class _IOSCoreDeviceConnectionProperties { _IOSCoreDeviceConnectionProperties._({ required this.authenticationType, required this.isMobileDeviceOnly, required this.lastConnectionDate, required this.localHostnames, required this.pairingState, required this.potentialHostnames, required this.transportType, required this.tunnelIPAddress, required this.tunnelState, required this.tunnelTransportProtocol, }); /// Parse `connectionProperties` section of JSON from `devicectl list devices --json-output` /// while it's in beta preview mode. /// /// Example: /// "connectionProperties" : { /// "authenticationType" : "manualPairing", /// "isMobileDeviceOnly" : false, /// "lastConnectionDate" : "2023-06-15T15:29:00.082Z", /// "localHostnames" : [ /// "iPadName.coredevice.local", /// "00001234-0001234A3C03401E.coredevice.local", /// "12345BB5-AEDE-4A22-B653-6037262550DD.coredevice.local" /// ], /// "pairingState" : "paired", /// "potentialHostnames" : [ /// "00001234-0001234A3C03401E.coredevice.local", /// "12345BB5-AEDE-4A22-B653-6037262550DD.coredevice.local" /// ], /// "transportType" : "wired", /// "tunnelIPAddress" : "fdf1:23c4:cd56::1", /// "tunnelState" : "connected", /// "tunnelTransportProtocol" : "tcp" /// } factory _IOSCoreDeviceConnectionProperties.fromBetaJson( Map<String, Object?> data, { required Logger logger, }) { List<String>? localHostnames; if (data['localHostnames'] is List<Object?>) { final List<Object?> values = data['localHostnames']! as List<Object?>; try { localHostnames = List<String>.from(values); } on TypeError { logger.printTrace('Error parsing localHostnames value: $values'); } } List<String>? potentialHostnames; if (data['potentialHostnames'] is List<Object?>) { final List<Object?> values = data['potentialHostnames']! as List<Object?>; try { potentialHostnames = List<String>.from(values); } on TypeError { logger.printTrace('Error parsing potentialHostnames value: $values'); } } return _IOSCoreDeviceConnectionProperties._( authenticationType: data['authenticationType']?.toString(), isMobileDeviceOnly: data['isMobileDeviceOnly'] is bool? ? data['isMobileDeviceOnly'] as bool? : null, lastConnectionDate: data['lastConnectionDate']?.toString(), localHostnames: localHostnames, pairingState: data['pairingState']?.toString(), potentialHostnames: potentialHostnames, transportType: data['transportType']?.toString(), tunnelIPAddress: data['tunnelIPAddress']?.toString(), tunnelState: data['tunnelState']?.toString(), tunnelTransportProtocol: data['tunnelTransportProtocol']?.toString(), ); } final String? authenticationType; final bool? isMobileDeviceOnly; final String? lastConnectionDate; final List<String>? localHostnames; final String? pairingState; final List<String>? potentialHostnames; final String? transportType; final String? tunnelIPAddress; final String? tunnelState; final String? tunnelTransportProtocol; } @visibleForTesting class IOSCoreDeviceProperties { IOSCoreDeviceProperties._({ required this.bootedFromSnapshot, required this.bootedSnapshotName, required this.bootState, required this.ddiServicesAvailable, required this.developerModeStatus, required this.hasInternalOSBuild, required this.name, required this.osBuildUpdate, required this.osVersionNumber, required this.rootFileSystemIsWritable, required this.screenViewingURL, }); /// Parse `deviceProperties` section of JSON from `devicectl list devices --json-output` /// while it's in beta preview mode. /// /// Example: /// "deviceProperties" : { /// "bootedFromSnapshot" : true, /// "bootedSnapshotName" : "com.apple.os.update-B5336980824124F599FD39FE91016493A74331B09F475250BB010B276FE2439E3DE3537349A3A957D3FF2A4B623B4ECC", /// "bootState" : "booted", /// "ddiServicesAvailable" : true, /// "developerModeStatus" : "enabled", /// "hasInternalOSBuild" : false, /// "name" : "iPadName", /// "osBuildUpdate" : "21A5248v", /// "osVersionNumber" : "17.0", /// "rootFileSystemIsWritable" : false, /// "screenViewingURL" : "coredevice-devices:/viewDeviceByUUID?uuid=123456BB5-AEDE-7A22-B890-1234567890DD" /// } factory IOSCoreDeviceProperties.fromBetaJson(Map<String, Object?> data) { return IOSCoreDeviceProperties._( bootedFromSnapshot: data['bootedFromSnapshot'] is bool? ? data['bootedFromSnapshot'] as bool? : null, bootedSnapshotName: data['bootedSnapshotName']?.toString(), bootState: data['bootState']?.toString(), ddiServicesAvailable: data['ddiServicesAvailable'] is bool? ? data['ddiServicesAvailable'] as bool? : null, developerModeStatus: data['developerModeStatus']?.toString(), hasInternalOSBuild: data['hasInternalOSBuild'] is bool? ? data['hasInternalOSBuild'] as bool? : null, name: data['name']?.toString(), osBuildUpdate: data['osBuildUpdate']?.toString(), osVersionNumber: data['osVersionNumber']?.toString(), rootFileSystemIsWritable: data['rootFileSystemIsWritable'] is bool? ? data['rootFileSystemIsWritable'] as bool? : null, screenViewingURL: data['screenViewingURL']?.toString(), ); } final bool? bootedFromSnapshot; final String? bootedSnapshotName; final String? bootState; final bool? ddiServicesAvailable; final String? developerModeStatus; final bool? hasInternalOSBuild; final String? name; final String? osBuildUpdate; final String? osVersionNumber; final bool? rootFileSystemIsWritable; final String? screenViewingURL; } class _IOSCoreDeviceHardwareProperties { _IOSCoreDeviceHardwareProperties._({ required this.cpuType, required this.deviceType, required this.ecid, required this.hardwareModel, required this.internalStorageCapacity, required this.marketingName, required this.platform, required this.productType, required this.serialNumber, required this.supportedCPUTypes, required this.supportedDeviceFamilies, required this.thinningProductType, required this.udid, }); /// Parse `hardwareProperties` section of JSON from `devicectl list devices --json-output` /// while it's in beta preview mode. /// /// Example: /// "hardwareProperties" : { /// "cpuType" : { /// "name" : "arm64e", /// "subType" : 2, /// "type" : 16777228 /// }, /// "deviceType" : "iPad", /// "ecid" : 12345678903408542, /// "hardwareModel" : "J617AP", /// "internalStorageCapacity" : 128000000000, /// "marketingName" : "iPad Pro (11-inch) (4th generation)\"", /// "platform" : "iOS", /// "productType" : "iPad14,3", /// "serialNumber" : "HC123DHCQV", /// "supportedCPUTypes" : [ /// { /// "name" : "arm64e", /// "subType" : 2, /// "type" : 16777228 /// }, /// { /// "name" : "arm64", /// "subType" : 0, /// "type" : 16777228 /// } /// ], /// "supportedDeviceFamilies" : [ /// 1, /// 2 /// ], /// "thinningProductType" : "iPad14,3-A", /// "udid" : "00001234-0001234A3C03401E" /// } factory _IOSCoreDeviceHardwareProperties.fromBetaJson( Map<String, Object?> data, { required Logger logger, }) { _IOSCoreDeviceCPUType? cpuType; if (data['cpuType'] case final Map<String, Object?> betaJson) { cpuType = _IOSCoreDeviceCPUType.fromBetaJson(betaJson); } List<_IOSCoreDeviceCPUType>? supportedCPUTypes; if (data['supportedCPUTypes'] case final List<Object?> values) { supportedCPUTypes = <_IOSCoreDeviceCPUType>[ for (final Object? cpuTypeData in values) if (cpuTypeData is Map<String, Object?>) _IOSCoreDeviceCPUType.fromBetaJson(cpuTypeData), ]; } List<int>? supportedDeviceFamilies; if (data['supportedDeviceFamilies'] is List<Object?>) { final List<Object?> values = data['supportedDeviceFamilies']! as List<Object?>; try { supportedDeviceFamilies = List<int>.from(values); } on TypeError { logger.printTrace('Error parsing supportedDeviceFamilies value: $values'); } } return _IOSCoreDeviceHardwareProperties._( cpuType: cpuType, deviceType: data['deviceType']?.toString(), ecid: data['ecid'] is int? ? data['ecid'] as int? : null, hardwareModel: data['hardwareModel']?.toString(), internalStorageCapacity: data['internalStorageCapacity'] is int? ? data['internalStorageCapacity'] as int? : null, marketingName: data['marketingName']?.toString(), platform: data['platform']?.toString(), productType: data['productType']?.toString(), serialNumber: data['serialNumber']?.toString(), supportedCPUTypes: supportedCPUTypes, supportedDeviceFamilies: supportedDeviceFamilies, thinningProductType: data['thinningProductType']?.toString(), udid: data['udid']?.toString(), ); } final _IOSCoreDeviceCPUType? cpuType; final String? deviceType; final int? ecid; final String? hardwareModel; final int? internalStorageCapacity; final String? marketingName; final String? platform; final String? productType; final String? serialNumber; final List<_IOSCoreDeviceCPUType>? supportedCPUTypes; final List<int>? supportedDeviceFamilies; final String? thinningProductType; final String? udid; } class _IOSCoreDeviceCPUType { _IOSCoreDeviceCPUType._({ this.name, this.subType, this.cpuType, }); /// Parse `hardwareProperties.cpuType` and `hardwareProperties.supportedCPUTypes` /// sections of JSON from `devicectl list devices --json-output` while it's in beta preview mode. /// /// Example: /// "cpuType" : { /// "name" : "arm64e", /// "subType" : 2, /// "type" : 16777228 /// } factory _IOSCoreDeviceCPUType.fromBetaJson(Map<String, Object?> data) { return _IOSCoreDeviceCPUType._( name: data['name']?.toString(), subType: data['subType'] is int? ? data['subType'] as int? : null, cpuType: data['type'] is int? ? data['type'] as int? : null, ); } final String? name; final int? subType; final int? cpuType; } @visibleForTesting class IOSCoreDeviceInstalledApp { IOSCoreDeviceInstalledApp._({ required this.appClip, required this.builtByDeveloper, required this.bundleIdentifier, required this.bundleVersion, required this.defaultApp, required this.hidden, required this.internalApp, required this.name, required this.removable, required this.url, required this.version, }); /// Parse JSON from `devicectl device info apps --json-output` while it's in /// beta preview mode. /// /// Example: /// { /// "appClip" : false, /// "builtByDeveloper" : true, /// "bundleIdentifier" : "com.example.flutterApp", /// "bundleVersion" : "1", /// "defaultApp" : false, /// "hidden" : false, /// "internalApp" : false, /// "name" : "Flutter App", /// "removable" : true, /// "url" : "file:///private/var/containers/Bundle/Application/12345E6A-7F89-0C12-345E-F6A7E890CFF1/Runner.app/", /// "version" : "1.0.0" /// } factory IOSCoreDeviceInstalledApp.fromBetaJson(Map<String, Object?> data) { return IOSCoreDeviceInstalledApp._( appClip: data['appClip'] is bool? ? data['appClip'] as bool? : null, builtByDeveloper: data['builtByDeveloper'] is bool? ? data['builtByDeveloper'] as bool? : null, bundleIdentifier: data['bundleIdentifier']?.toString(), bundleVersion: data['bundleVersion']?.toString(), defaultApp: data['defaultApp'] is bool? ? data['defaultApp'] as bool? : null, hidden: data['hidden'] is bool? ? data['hidden'] as bool? : null, internalApp: data['internalApp'] is bool? ? data['internalApp'] as bool? : null, name: data['name']?.toString(), removable: data['removable'] is bool? ? data['removable'] as bool? : null, url: data['url']?.toString(), version: data['version']?.toString(), ); } final bool? appClip; final bool? builtByDeveloper; final String? bundleIdentifier; final String? bundleVersion; final bool? defaultApp; final bool? hidden; final bool? internalApp; final String? name; final bool? removable; final String? url; final String? version; }
flutter/packages/flutter_tools/lib/src/ios/core_devices.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/ios/core_devices.dart", "repo_id": "flutter", "token_count": 10798 }
365
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:math' as math; import 'package:meta/meta.dart'; import 'package:process/process.dart'; import '../application_package.dart'; import '../base/common.dart'; import '../base/file_system.dart'; import '../base/io.dart'; import '../base/logger.dart'; import '../base/process.dart'; import '../base/utils.dart'; import '../base/version.dart'; import '../build_info.dart'; import '../convert.dart'; import '../devfs.dart'; import '../device.dart'; import '../device_port_forwarder.dart'; import '../device_vm_service_discovery_for_attach.dart'; import '../globals.dart' as globals; import '../macos/xcode.dart'; import '../project.dart'; import '../protocol_discovery.dart'; import 'application_package.dart'; import 'mac.dart'; import 'plist_parser.dart'; const String iosSimulatorId = 'apple_ios_simulator'; class IOSSimulators extends PollingDeviceDiscovery { IOSSimulators({ required IOSSimulatorUtils iosSimulatorUtils, }) : _iosSimulatorUtils = iosSimulatorUtils, super('iOS simulators'); final IOSSimulatorUtils _iosSimulatorUtils; @override bool get supportsPlatform => globals.platform.isMacOS; @override bool get canListAnything => globals.iosWorkflow?.canListDevices ?? false; @override Future<List<Device>> pollingGetDevices({ Duration? timeout }) async => _iosSimulatorUtils.getAttachedDevices(); @override List<String> get wellKnownIds => const <String>[]; } class IOSSimulatorUtils { IOSSimulatorUtils({ required Xcode xcode, required Logger logger, required ProcessManager processManager, }) : _simControl = SimControl( logger: logger, processManager: processManager, xcode: xcode, ), _xcode = xcode; final SimControl _simControl; final Xcode _xcode; Future<List<IOSSimulator>> getAttachedDevices() async { if (!_xcode.isInstalledAndMeetsVersionCheck) { return <IOSSimulator>[]; } final List<BootedSimDevice> connected = await _simControl.getConnectedDevices(); return connected.map<IOSSimulator?>((BootedSimDevice device) { final String? udid = device.udid; final String? name = device.name; if (udid == null) { globals.printTrace('Could not parse simulator udid'); return null; } if (name == null) { globals.printTrace('Could not parse simulator name'); return null; } return IOSSimulator( udid, name: name, simControl: _simControl, simulatorCategory: device.category, ); }).whereType<IOSSimulator>().toList(); } Future<List<IOSSimulatorRuntime>> getAvailableIOSRuntimes() async { if (!_xcode.isInstalledAndMeetsVersionCheck) { return <IOSSimulatorRuntime>[]; } return _simControl.listAvailableIOSRuntimes(); } } /// A wrapper around the `simctl` command line tool. class SimControl { SimControl({ required Logger logger, required ProcessManager processManager, required Xcode xcode, }) : _logger = logger, _xcode = xcode, _processUtils = ProcessUtils(processManager: processManager, logger: logger); final Logger _logger; final ProcessUtils _processUtils; final Xcode _xcode; /// Runs `simctl list --json` and returns the JSON of the corresponding /// [section]. Future<Map<String, Object?>> _listBootedDevices() async { // Sample output from `simctl list available booted --json`: // // { // "devices" : { // "com.apple.CoreSimulator.SimRuntime.iOS-14-0" : [ // { // "lastBootedAt" : "2022-07-26T01:46:23Z", // "dataPath" : "\/Users\/magder\/Library\/Developer\/CoreSimulator\/Devices\/9EC90A99-6924-472D-8CDD-4D8234AB4779\/data", // "dataPathSize" : 1620578304, // "logPath" : "\/Users\/magder\/Library\/Logs\/CoreSimulator\/9EC90A99-6924-472D-8CDD-4D8234AB4779", // "udid" : "9EC90A99-6924-472D-8CDD-4D8234AB4779", // "isAvailable" : true, // "logPathSize" : 9740288, // "deviceTypeIdentifier" : "com.apple.CoreSimulator.SimDeviceType.iPhone-11", // "state" : "Booted", // "name" : "iPhone 11" // } // ], // "com.apple.CoreSimulator.SimRuntime.iOS-13-0" : [ // // ], // "com.apple.CoreSimulator.SimRuntime.iOS-12-4" : [ // // ], // "com.apple.CoreSimulator.SimRuntime.iOS-16-0" : [ // // ] // } // } final List<String> command = <String>[ ..._xcode.xcrunCommand(), 'simctl', 'list', 'devices', 'booted', 'iOS', '--json', ]; _logger.printTrace(command.join(' ')); final RunResult results = await _processUtils.run(command); if (results.exitCode != 0) { _logger.printError('Error executing simctl: ${results.exitCode}\n${results.stderr}'); return <String, Map<String, Object?>>{}; } try { final Object? decodeResult = (json.decode(results.stdout) as Map<String, Object?>)['devices']; if (decodeResult is Map<String, Object?>) { return decodeResult; } _logger.printError('simctl returned unexpected JSON response: ${results.stdout}'); return <String, Object>{}; } on FormatException { // We failed to parse the simctl output, or it returned junk. // One known message is "Install Started" isn't valid JSON but is // returned sometimes. _logger.printError('simctl returned non-JSON response: ${results.stdout}'); return <String, Object>{}; } } /// Returns all the connected simulator devices. Future<List<BootedSimDevice>> getConnectedDevices() async { final Map<String, Object?> devicesSection = await _listBootedDevices(); return <BootedSimDevice>[ for (final String deviceCategory in devicesSection.keys) if (devicesSection[deviceCategory] case final List<Object?> devicesData) for (final Object? data in devicesData.map<Map<String, Object?>?>(castStringKeyedMap)) if (data is Map<String, Object?>) BootedSimDevice(deviceCategory, data), ]; } Future<bool> isInstalled(String deviceId, String appId) { return _processUtils.exitsHappy(<String>[ ..._xcode.xcrunCommand(), 'simctl', 'get_app_container', deviceId, appId, ]); } Future<RunResult> install(String deviceId, String appPath) async { RunResult result; try { result = await _processUtils.run( <String>[ ..._xcode.xcrunCommand(), 'simctl', 'install', deviceId, appPath, ], throwOnError: true, ); } on ProcessException catch (exception) { throwToolExit('Unable to install $appPath on $deviceId. This is sometimes caused by a malformed plist file:\n$exception'); } return result; } Future<RunResult> uninstall(String deviceId, String appId) async { RunResult result; try { result = await _processUtils.run( <String>[ ..._xcode.xcrunCommand(), 'simctl', 'uninstall', deviceId, appId, ], throwOnError: true, ); } on ProcessException catch (exception) { throwToolExit('Unable to uninstall $appId from $deviceId:\n$exception'); } return result; } Future<RunResult> launch(String deviceId, String appIdentifier, [ List<String>? launchArgs ]) async { RunResult result; try { result = await _processUtils.run( <String>[ ..._xcode.xcrunCommand(), 'simctl', 'launch', deviceId, appIdentifier, ...?launchArgs, ], throwOnError: true, ); } on ProcessException catch (exception) { throwToolExit('Unable to launch $appIdentifier on $deviceId:\n$exception'); } return result; } Future<RunResult> stopApp(String deviceId, String appIdentifier) async { RunResult result; try { result = await _processUtils.run( <String>[ ..._xcode.xcrunCommand(), 'simctl', 'terminate', deviceId, appIdentifier, ], throwOnError: true, ); } on ProcessException catch (exception) { throwToolExit('Unable to terminate $appIdentifier on $deviceId:\n$exception'); } return result; } Future<void> takeScreenshot(String deviceId, String outputPath) async { try { await _processUtils.run( <String>[ ..._xcode.xcrunCommand(), 'simctl', 'io', deviceId, 'screenshot', outputPath, ], throwOnError: true, ); } on ProcessException catch (exception) { _logger.printError('Unable to take screenshot of $deviceId:\n$exception'); } } /// Runs `simctl list runtimes available iOS --json` and returns all available iOS simulator runtimes. Future<List<IOSSimulatorRuntime>> listAvailableIOSRuntimes() async { final List<IOSSimulatorRuntime> runtimes = <IOSSimulatorRuntime>[]; final RunResult results = await _processUtils.run( <String>[ ..._xcode.xcrunCommand(), 'simctl', 'list', 'runtimes', 'available', 'iOS', '--json', ], ); if (results.exitCode != 0) { _logger.printError('Error executing simctl: ${results.exitCode}\n${results.stderr}'); return runtimes; } try { final Object? decodeResult = (json.decode(results.stdout) as Map<String, Object?>)['runtimes']; if (decodeResult is List<Object?>) { for (final Object? runtimeData in decodeResult) { if (runtimeData is Map<String, Object?>) { runtimes.add(IOSSimulatorRuntime.fromJson(runtimeData)); } } } return runtimes; } on FormatException { // We failed to parse the simctl output, or it returned junk. // One known message is "Install Started" isn't valid JSON but is // returned sometimes. _logger.printError('simctl returned non-JSON response: ${results.stdout}'); return runtimes; } } } class BootedSimDevice { BootedSimDevice(this.category, this.data); final String category; final Map<String, Object?> data; String? get name => data['name']?.toString(); String? get udid => data['udid']?.toString(); } class IOSSimulator extends Device { IOSSimulator( super.id, { required this.name, required this.simulatorCategory, required SimControl simControl, }) : _simControl = simControl, super( category: Category.mobile, platformType: PlatformType.ios, ephemeral: true, ); @override final String name; final String simulatorCategory; final SimControl _simControl; @override DevFSWriter createDevFSWriter(ApplicationPackage? app, String? userIdentifier) { return LocalDevFSWriter(fileSystem: globals.fs); } @override Future<bool> get isLocalEmulator async => true; @override Future<String> get emulatorId async => iosSimulatorId; @override bool get supportsHotReload => true; @override bool get supportsHotRestart => true; @override bool get supportsFlavors => true; @override Future<bool> get supportsHardwareRendering async => false; @override bool supportsRuntimeMode(BuildMode buildMode) => buildMode == BuildMode.debug; final Map<IOSApp?, DeviceLogReader> _logReaders = <IOSApp?, DeviceLogReader>{}; _IOSSimulatorDevicePortForwarder? _portForwarder; @override Future<bool> isAppInstalled( ApplicationPackage app, { String? userIdentifier, }) { return _simControl.isInstalled(id, app.id); } @override Future<bool> isLatestBuildInstalled(ApplicationPackage app) async => false; @override Future<bool> installApp( covariant IOSApp app, { String? userIdentifier, }) async { try { await _simControl.install(id, app.simulatorBundlePath); return true; } on Exception { return false; } } @override Future<bool> uninstallApp( ApplicationPackage app, { String? userIdentifier, }) async { try { await _simControl.uninstall(id, app.id); return true; } on Exception { return false; } } @override bool isSupported() { if (!globals.platform.isMacOS) { _supportMessage = 'iOS devices require a Mac host machine.'; return false; } // Check if the device is part of a blocked category. // We do not yet support WatchOS or tvOS devices. final RegExp blocklist = RegExp(r'Apple (TV|Watch)', caseSensitive: false); if (blocklist.hasMatch(name)) { _supportMessage = 'Flutter does not support Apple TV or Apple Watch.'; return false; } return true; } String? _supportMessage; @override String supportMessage() { if (isSupported()) { return 'Supported'; } return _supportMessage ?? 'Unknown'; } @override Future<LaunchResult> startApp( IOSApp package, { String? mainPath, String? route, required DebuggingOptions debuggingOptions, Map<String, Object?> platformArgs = const <String, Object?>{}, bool prebuiltApplication = false, bool ipv6 = false, String? userIdentifier, }) async { if (!prebuiltApplication && package is BuildableIOSApp) { globals.printTrace('Building ${package.name} for $id.'); try { await _setupUpdatedApplicationBundle(package, debuggingOptions.buildInfo, mainPath); } on ToolExit catch (e) { globals.printError('${e.message}'); return LaunchResult.failed(); } } else { if (!await installApp(package)) { return LaunchResult.failed(); } } // Prepare launch arguments. final List<String> launchArguments = debuggingOptions.getIOSLaunchArguments( EnvironmentType.simulator, route, platformArgs, ); ProtocolDiscovery? vmServiceDiscovery; if (debuggingOptions.debuggingEnabled) { vmServiceDiscovery = ProtocolDiscovery.vmService( getLogReader(app: package), ipv6: ipv6, hostPort: debuggingOptions.hostVmServicePort, devicePort: debuggingOptions.deviceVmServicePort, logger: globals.logger, ); } // Launch the updated application in the simulator. try { // Use the built application's Info.plist to get the bundle identifier, // which should always yield the correct value and does not require // parsing the xcodeproj or configuration files. // See https://github.com/flutter/flutter/issues/31037 for more information. final String plistPath = globals.fs.path.join(package.simulatorBundlePath, 'Info.plist'); final String? bundleIdentifier = globals.plistParser.getValueFromFile<String>(plistPath, PlistParser.kCFBundleIdentifierKey); if (bundleIdentifier == null) { globals.printError('Invalid prebuilt iOS app. Info.plist does not contain bundle identifier'); return LaunchResult.failed(); } await _simControl.launch(id, bundleIdentifier, launchArguments); } on Exception catch (error) { globals.printError('$error'); return LaunchResult.failed(); } if (!debuggingOptions.debuggingEnabled) { return LaunchResult.succeeded(); } // Wait for the service protocol port here. This will complete once the // device has printed "Dart VM Service is listening on..." globals.printTrace('Waiting for VM Service port to be available...'); try { final Uri? deviceUri = await vmServiceDiscovery?.uri; if (deviceUri != null) { return LaunchResult.succeeded(vmServiceUri: deviceUri); } globals.printError( 'Error waiting for a debug connection: ' 'The log reader failed unexpectedly', ); } on Exception catch (error) { globals.printError('Error waiting for a debug connection: $error'); } finally { await vmServiceDiscovery?.cancel(); } return LaunchResult.failed(); } Future<void> _setupUpdatedApplicationBundle(BuildableIOSApp app, BuildInfo buildInfo, String? mainPath) async { // Step 1: Build the Xcode project. // The build mode for the simulator is always debug. assert(buildInfo.isDebug); final XcodeBuildResult buildResult = await buildXcodeProject( app: app, buildInfo: buildInfo, targetOverride: mainPath, environmentType: EnvironmentType.simulator, deviceID: id, ); if (!buildResult.success) { await diagnoseXcodeBuildFailure( buildResult, analytics: globals.analytics, fileSystem: globals.fs, flutterUsage: globals.flutterUsage, logger: globals.logger, platform: SupportedPlatform.ios, project: app.project.parent, ); throwToolExit('Could not build the application for the simulator.'); } // Step 2: Assert that the Xcode project was successfully built. final Directory bundle = globals.fs.directory(app.simulatorBundlePath); final bool bundleExists = bundle.existsSync(); if (!bundleExists) { throwToolExit('Could not find the built application bundle at ${bundle.path}.'); } // Step 3: Install the updated bundle to the simulator. await _simControl.install(id, globals.fs.path.absolute(bundle.path)); } @override Future<bool> stopApp( ApplicationPackage? app, { String? userIdentifier, }) async { if (app == null) { return false; } return (await _simControl.stopApp(id, app.id)).exitCode == 0; } String get logFilePath { final String? logPath = globals.platform.environment['IOS_SIMULATOR_LOG_FILE_PATH']; return logPath != null ? logPath.replaceAll('%{id}', id) : globals.fs.path.join( globals.fsUtils.homeDirPath!, 'Library', 'Logs', 'CoreSimulator', id, 'system.log', ); } @override Future<TargetPlatform> get targetPlatform async => TargetPlatform.ios; @override Future<String> get sdkNameAndVersion async => simulatorCategory; final RegExp _iosSdkRegExp = RegExp(r'iOS( |-)(\d+)'); Future<int> get sdkMajorVersion async { final Match? sdkMatch = _iosSdkRegExp.firstMatch(await sdkNameAndVersion); return int.parse(sdkMatch?.group(2) ?? '11'); } @override DeviceLogReader getLogReader({ covariant IOSApp? app, bool includePastLogs = false, }) { assert(!includePastLogs, 'Past log reading not supported on iOS simulators.'); return _logReaders.putIfAbsent(app, () => _IOSSimulatorLogReader(this, app)); } @override DevicePortForwarder get portForwarder => _portForwarder ??= _IOSSimulatorDevicePortForwarder(this); @override void clearLogs() { final File logFile = globals.fs.file(logFilePath); if (logFile.existsSync()) { final RandomAccessFile randomFile = logFile.openSync(mode: FileMode.write); randomFile.truncateSync(0); randomFile.closeSync(); } } Future<void> ensureLogsExists() async { if (await sdkMajorVersion < 11) { final File logFile = globals.fs.file(logFilePath); if (!logFile.existsSync()) { logFile.writeAsBytesSync(<int>[]); } } } @override VMServiceDiscoveryForAttach getVMServiceDiscoveryForAttach({ String? appId, String? fuchsiaModule, int? filterDevicePort, int? expectedHostPort, required bool ipv6, required Logger logger, }) { final MdnsVMServiceDiscoveryForAttach mdnsVMServiceDiscoveryForAttach = MdnsVMServiceDiscoveryForAttach( device: this, appId: appId, deviceVmservicePort: filterDevicePort, hostVmservicePort: expectedHostPort, usesIpv6: ipv6, useDeviceIPAsHost: false, ); return DelegateVMServiceDiscoveryForAttach(<VMServiceDiscoveryForAttach>[ mdnsVMServiceDiscoveryForAttach, super.getVMServiceDiscoveryForAttach( appId: appId, fuchsiaModule: fuchsiaModule, filterDevicePort: filterDevicePort, expectedHostPort: expectedHostPort, ipv6: ipv6, logger: logger, ), ]); } @override bool get supportsScreenshot => true; @override Future<void> takeScreenshot(File outputFile) { return _simControl.takeScreenshot(id, outputFile.path); } @override bool isSupportedForProject(FlutterProject flutterProject) { return flutterProject.ios.existsSync(); } @override Future<void> dispose() async { for (final DeviceLogReader logReader in _logReaders.values) { logReader.dispose(); } await _portForwarder?.dispose(); } } class IOSSimulatorRuntime { IOSSimulatorRuntime._({ this.bundlePath, this.buildVersion, this.platform, this.runtimeRoot, this.identifier, this.version, this.isInternal, this.isAvailable, this.name, }); // Example: // { // "bundlePath" : "\/Library\/Developer\/CoreSimulator\/Volumes\/iOS_21A5277g\/Library\/Developer\/CoreSimulator\/Profiles\/Runtimes\/iOS 17.0.simruntime", // "buildversion" : "21A5277g", // "platform" : "iOS", // "runtimeRoot" : "\/Library\/Developer\/CoreSimulator\/Volumes\/iOS_21A5277g\/Library\/Developer\/CoreSimulator\/Profiles\/Runtimes\/iOS 17.0.simruntime\/Contents\/Resources\/RuntimeRoot", // "identifier" : "com.apple.CoreSimulator.SimRuntime.iOS-17-0", // "version" : "17.0", // "isInternal" : false, // "isAvailable" : true, // "name" : "iOS 17.0", // "supportedDeviceTypes" : [ // { // "bundlePath" : "\/Applications\/Xcode.app\/Contents\/Developer\/Platforms\/iPhoneOS.platform\/Library\/Developer\/CoreSimulator\/Profiles\/DeviceTypes\/iPhone 8.simdevicetype", // "name" : "iPhone 8", // "identifier" : "com.apple.CoreSimulator.SimDeviceType.iPhone-8", // "productFamily" : "iPhone" // } // ] // }, factory IOSSimulatorRuntime.fromJson(Map<String, Object?> data) { return IOSSimulatorRuntime._( bundlePath: data['bundlePath']?.toString(), buildVersion: data['buildversion']?.toString(), platform: data['platform']?.toString(), runtimeRoot: data['runtimeRoot']?.toString(), identifier: data['identifier']?.toString(), version: Version.parse(data['version']?.toString()), isInternal: data['isInternal'] is bool? ? data['isInternal'] as bool? : null, isAvailable: data['isAvailable'] is bool? ? data['isAvailable'] as bool? : null, name: data['name']?.toString(), ); } final String? bundlePath; final String? buildVersion; final String? platform; final String? runtimeRoot; final String? identifier; final Version? version; final bool? isInternal; final bool? isAvailable; final String? name; } /// Launches the device log reader process on the host and parses the syslog. @visibleForTesting Future<Process> launchDeviceSystemLogTool(IOSSimulator device) async { return globals.processUtils.start(<String>['tail', '-n', '0', '-F', device.logFilePath]); } /// Launches the device log reader process on the host and parses unified logging. @visibleForTesting Future<Process> launchDeviceUnifiedLogging (IOSSimulator device, String? appName) async { // Make NSPredicate concatenation easier to read. String orP(List<String> clauses) => '(${clauses.join(" OR ")})'; String andP(List<String> clauses) => clauses.join(' AND '); String notP(String clause) => 'NOT($clause)'; final String predicate = andP(<String>[ 'eventType = logEvent', if (appName != null) 'processImagePath ENDSWITH "$appName"', // Either from Flutter or Swift (maybe assertion or fatal error) or from the app itself. orP(<String>[ 'senderImagePath ENDSWITH "/Flutter"', 'senderImagePath ENDSWITH "/libswiftCore.dylib"', 'processImageUUID == senderImageUUID', ]), // Filter out some messages that clearly aren't related to Flutter. notP('eventMessage CONTAINS ": could not find icon for representation -> com.apple."'), notP('eventMessage BEGINSWITH "assertion failed: "'), notP('eventMessage CONTAINS " libxpc.dylib "'), ]); return globals.processUtils.start(<String>[ ...globals.xcode!.xcrunCommand(), 'simctl', 'spawn', device.id, 'log', 'stream', '--style', 'json', '--predicate', predicate, ]); } @visibleForTesting Future<Process?> launchSystemLogTool(IOSSimulator device) async { // Versions of iOS prior to 11 tail the simulator syslog file. if (await device.sdkMajorVersion < 11) { return globals.processUtils.start(<String>['tail', '-n', '0', '-F', '/private/var/log/system.log']); } // For iOS 11 and later, all relevant detail is in the device log. return null; } class _IOSSimulatorLogReader extends DeviceLogReader { _IOSSimulatorLogReader(this.device, IOSApp? app) : _appName = app?.name?.replaceAll('.app', ''); final IOSSimulator device; final String? _appName; late final StreamController<String> _linesController = StreamController<String>.broadcast( onListen: _start, onCancel: _stop, ); // We log from two files: the device and the system log. Process? _deviceProcess; Process? _systemProcess; @override Stream<String> get logLines => _linesController.stream; @override String get name => device.name; Future<void> _start() async { // Unified logging iOS 11 and greater (introduced in iOS 10). if (await device.sdkMajorVersion >= 11) { _deviceProcess = await launchDeviceUnifiedLogging(device, _appName); _deviceProcess?.stdout.transform<String>(utf8.decoder).transform<String>(const LineSplitter()).listen(_onUnifiedLoggingLine); _deviceProcess?.stderr.transform<String>(utf8.decoder).transform<String>(const LineSplitter()).listen(_onUnifiedLoggingLine); } else { // Fall back to syslog parsing. await device.ensureLogsExists(); _deviceProcess = await launchDeviceSystemLogTool(device); _deviceProcess?.stdout.transform<String>(utf8.decoder).transform<String>(const LineSplitter()).listen(_onSysLogDeviceLine); _deviceProcess?.stderr.transform<String>(utf8.decoder).transform<String>(const LineSplitter()).listen(_onSysLogDeviceLine); } // Track system.log crashes. // ReportCrash[37965]: Saved crash report for FlutterRunner[37941]... _systemProcess = await launchSystemLogTool(device); if (_systemProcess != null) { _systemProcess?.stdout.transform<String>(utf8.decoder).transform<String>(const LineSplitter()).listen(_onSystemLine); _systemProcess?.stderr.transform<String>(utf8.decoder).transform<String>(const LineSplitter()).listen(_onSystemLine); } // We don't want to wait for the process or its callback. Best effort // cleanup in the callback. unawaited(_deviceProcess?.exitCode.whenComplete(() { if (_linesController.hasListener) { _linesController.close(); } })); } // Match the log prefix (in order to shorten it): // * Xcode 8: Sep 13 15:28:51 cbracken-macpro localhost Runner[37195]: (Flutter) The Dart VM service is listening on http://127.0.0.1:57701/ // * Xcode 9: 2017-09-13 15:26:57.228948-0700 localhost Runner[37195]: (Flutter) The Dart VM service is listening on http://127.0.0.1:57701/ static final RegExp _mapRegex = RegExp(r'\S+ +\S+ +(?:\S+) (.+?(?=\[))\[\d+\]\)?: (\(.*?\))? *(.*)$'); // Jan 31 19:23:28 --- last message repeated 1 time --- static final RegExp _lastMessageSingleRegex = RegExp(r'\S+ +\S+ +\S+ --- last message repeated 1 time ---$'); static final RegExp _lastMessageMultipleRegex = RegExp(r'\S+ +\S+ +\S+ --- last message repeated (\d+) times ---$'); static final RegExp _flutterRunnerRegex = RegExp(r' FlutterRunner\[\d+\] '); // Remember what we did with the last line, in case we need to process // a multiline record bool _lastLineMatched = false; String? _filterDeviceLine(String string) { final Match? match = _mapRegex.matchAsPrefix(string); if (match != null) { // The category contains the text between the date and the PID. Depending on which version of iOS being run, // it can contain "hostname App Name" or just "App Name". final String? category = match.group(1); final String? tag = match.group(2); final String? content = match.group(3); // Filter out log lines from an app other than this one (category doesn't match the app name). // If the hostname is included in the category, check that it doesn't end with the app name. final String? appName = _appName; if (appName != null && category != null && !category.endsWith(appName)) { return null; } if (tag != null && tag != '(Flutter)') { return null; } // Filter out some messages that clearly aren't related to Flutter. if (string.contains(': could not find icon for representation -> com.apple.')) { return null; } // assertion failed: 15G1212 13E230: libxpc.dylib + 57882 [66C28065-C9DB-3C8E-926F-5A40210A6D1B]: 0x7d if (content != null && content.startsWith('assertion failed: ') && content.contains(' libxpc.dylib ')) { return null; } if (appName == null) { return '$category: $content'; } else if (category != null && (category == appName || category.endsWith(' $appName'))) { return content; } return null; } if (string.startsWith('Filtering the log data using ')) { return null; } if (string.startsWith('Timestamp (process)[PID]')) { return null; } if (_lastMessageSingleRegex.matchAsPrefix(string) != null) { return null; } if (RegExp(r'assertion failed: .* libxpc.dylib .* 0x7d$').matchAsPrefix(string) != null) { return null; } // Starts with space(s) - continuation of the multiline message if (RegExp(r'\s+').matchAsPrefix(string) != null && !_lastLineMatched) { return null; } return string; } String? _lastLine; void _onSysLogDeviceLine(String line) { globals.printTrace('[DEVICE LOG] $line'); final Match? multi = _lastMessageMultipleRegex.matchAsPrefix(line); if (multi != null) { if (_lastLine != null) { int repeat = int.parse(multi.group(1)!); repeat = math.max(0, math.min(100, repeat)); for (int i = 1; i < repeat; i++) { _linesController.add(_lastLine!); } } } else { _lastLine = _filterDeviceLine(line); if (_lastLine != null) { _linesController.add(_lastLine!); _lastLineMatched = true; } else { _lastLineMatched = false; } } } // "eventMessage" : "flutter: 21", static final RegExp _unifiedLoggingEventMessageRegex = RegExp(r'.*"eventMessage" : (".*")'); void _onUnifiedLoggingLine(String line) { // The log command predicate handles filtering, so every log eventMessage should be decoded and added. final Match? eventMessageMatch = _unifiedLoggingEventMessageRegex.firstMatch(line); if (eventMessageMatch != null) { final String message = eventMessageMatch.group(1)!; try { final Object? decodedJson = jsonDecode(message); if (decodedJson is String) { _linesController.add(decodedJson); } } on FormatException { globals.printError('Logger returned non-JSON response: $message'); } } } String _filterSystemLog(String string) { final Match? match = _mapRegex.matchAsPrefix(string); return match == null ? string : '${match.group(1)}: ${match.group(2)}'; } void _onSystemLine(String line) { globals.printTrace('[SYS LOG] $line'); if (!_flutterRunnerRegex.hasMatch(line)) { return; } final String filteredLine = _filterSystemLog(line); _linesController.add(filteredLine); } void _stop() { _deviceProcess?.kill(); _systemProcess?.kill(); } @override void dispose() { _stop(); } } class _IOSSimulatorDevicePortForwarder extends DevicePortForwarder { _IOSSimulatorDevicePortForwarder(this.device); final IOSSimulator device; final List<ForwardedPort> _ports = <ForwardedPort>[]; @override List<ForwardedPort> get forwardedPorts => _ports; @override Future<int> forward(int devicePort, { int? hostPort }) async { if (hostPort == null || hostPort == 0) { hostPort = devicePort; } assert(devicePort == hostPort); _ports.add(ForwardedPort(devicePort, hostPort)); return hostPort; } @override Future<void> unforward(ForwardedPort forwardedPort) async { _ports.remove(forwardedPort); } @override Future<void> dispose() async { final List<ForwardedPort> portsCopy = List<ForwardedPort>.of(_ports); for (final ForwardedPort port in portsCopy) { await unforward(port); } } }
flutter/packages/flutter_tools/lib/src/ios/simulators.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/ios/simulators.dart", "repo_id": "flutter", "token_count": 12688 }
366
// Copyright 2014 The Flutter 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:native_assets_builder/native_assets_builder.dart' hide NativeAssetsBuildRunner; import 'package:native_assets_cli/native_assets_cli_internal.dart'; import '../../../base/file_system.dart'; import '../../../build_info.dart'; import '../../../globals.dart' as globals; import '../../../windows/visual_studio.dart'; import '../native_assets.dart'; /// Dry run the native builds. /// /// This does not build native assets, it only simulates what the final paths /// of all assets will be so that this can be embedded in the kernel file. Future<Uri?> dryRunNativeAssetsWindows({ required NativeAssetsBuildRunner buildRunner, required Uri projectUri, bool flutterTester = false, required FileSystem fileSystem, }) { return dryRunNativeAssetsSingleArchitecture( buildRunner: buildRunner, projectUri: projectUri, flutterTester: flutterTester, fileSystem: fileSystem, os: OSImpl.windows, ); } Future<Iterable<KernelAsset>> dryRunNativeAssetsWindowsInternal( FileSystem fileSystem, Uri projectUri, bool flutterTester, NativeAssetsBuildRunner buildRunner, ) { return dryRunNativeAssetsSingleArchitectureInternal( fileSystem, projectUri, flutterTester, buildRunner, OSImpl.windows, ); } Future<(Uri? nativeAssetsYaml, List<Uri> dependencies)> buildNativeAssetsWindows({ required NativeAssetsBuildRunner buildRunner, TargetPlatform? targetPlatform, required Uri projectUri, required BuildMode buildMode, bool flutterTester = false, Uri? yamlParentDirectory, required FileSystem fileSystem, }) { return buildNativeAssetsSingleArchitecture( buildRunner: buildRunner, targetPlatform: targetPlatform, projectUri: projectUri, buildMode: buildMode, flutterTester: flutterTester, yamlParentDirectory: yamlParentDirectory, fileSystem: fileSystem, ); } Future<CCompilerConfigImpl> cCompilerConfigWindows() async { final VisualStudio visualStudio = VisualStudio( fileSystem: globals.fs, platform: globals.platform, logger: globals.logger, processManager: globals.processManager, osUtils: globals.os, ); return CCompilerConfigImpl( compiler: _toOptionalFileUri(visualStudio.clPath), linker: _toOptionalFileUri(visualStudio.linkPath), archiver: _toOptionalFileUri(visualStudio.libPath), envScript: _toOptionalFileUri(visualStudio.vcvarsPath), envScriptArgs: <String>[], ); } Uri? _toOptionalFileUri(String? string) { if (string == null) { return null; } return Uri.file(string); }
flutter/packages/flutter_tools/lib/src/isolated/native_assets/windows/native_assets.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/isolated/native_assets/windows/native_assets.dart", "repo_id": "flutter", "token_count": 897 }
367
// Copyright 2014 The Flutter 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 '../base/error_handling_io.dart'; import '../base/fingerprint.dart'; import '../build_info.dart'; import '../cache.dart'; import '../flutter_plugins.dart'; import '../globals.dart' as globals; import '../project.dart'; /// For a given build, determines whether dependencies have changed since the /// last call to processPods, then calls processPods with that information. Future<void> processPodsIfNeeded( XcodeBasedProject xcodeProject, String buildDirectory, BuildMode buildMode, { bool forceCocoaPodsOnly = false, }) async { final FlutterProject project = xcodeProject.parent; // When using Swift Package Manager, the Podfile may not exist so if there // isn't a Podfile, skip processing pods. if (project.usesSwiftPackageManager && !xcodeProject.podfile.existsSync() && !forceCocoaPodsOnly) { return; } // Ensure that the plugin list is up to date, since hasPlugins relies on it. await refreshPluginsList( project, iosPlatform: project.ios.existsSync(), macOSPlatform: project.macos.existsSync(), forceCocoaPodsOnly: forceCocoaPodsOnly, ); // If there are no plugins and if the project is a not module with an existing // podfile, skip processing pods if (!hasPlugins(project) && !(project.isModule && xcodeProject.podfile.existsSync())) { return; } // If forcing the use of only CocoaPods, but the project is using Swift // Package Manager, print a warning that CocoaPods will be used. if (forceCocoaPodsOnly && project.usesSwiftPackageManager) { globals.logger.printWarning( 'Swift Package Manager does not yet support this command. ' 'CocoaPods will be used instead.'); // If CocoaPods has been deintegrated, add it back. if (!xcodeProject.podfile.existsSync()) { await globals.cocoaPods?.setupPodfile(xcodeProject); } // Delete Swift Package Manager manifest to invalidate fingerprinter ErrorHandlingFileSystem.deleteIfExists( xcodeProject.flutterPluginSwiftPackageManifest, ); } // If the Xcode project, Podfile, generated plugin Swift Package, or podhelper // have changed since last run, pods should be updated. final Fingerprinter fingerprinter = Fingerprinter( fingerprintPath: globals.fs.path.join(buildDirectory, 'pod_inputs.fingerprint'), paths: <String>[ xcodeProject.xcodeProjectInfoFile.path, xcodeProject.podfile.path, if (xcodeProject.flutterPluginSwiftPackageManifest.existsSync()) xcodeProject.flutterPluginSwiftPackageManifest.path, globals.fs.path.join( Cache.flutterRoot!, 'packages', 'flutter_tools', 'bin', 'podhelper.rb', ), ], fileSystem: globals.fs, logger: globals.logger, ); final bool didPodInstall = await globals.cocoaPods?.processPods( xcodeProject: xcodeProject, buildMode: buildMode, dependenciesChanged: !fingerprinter.doesFingerprintMatch(), ) ?? false; if (didPodInstall) { fingerprinter.writeFingerprint(); } }
flutter/packages/flutter_tools/lib/src/macos/cocoapod_utils.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/macos/cocoapod_utils.dart", "repo_id": "flutter", "token_count": 1080 }
368
// Copyright 2014 The Flutter 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:meta/meta.dart'; import 'package:multicast_dns/multicast_dns.dart'; import 'package:unified_analytics/unified_analytics.dart'; import 'base/common.dart'; import 'base/context.dart'; import 'base/io.dart'; import 'base/logger.dart'; import 'build_info.dart'; import 'convert.dart'; import 'device.dart'; import 'reporting/reporting.dart'; /// A wrapper around [MDnsClient] to find a Dart VM Service instance. class MDnsVmServiceDiscovery { /// Creates a new [MDnsVmServiceDiscovery] object. /// /// The [_client] parameter will be defaulted to a new [MDnsClient] if null. MDnsVmServiceDiscovery({ MDnsClient? mdnsClient, MDnsClient? preliminaryMDnsClient, required Logger logger, required Usage flutterUsage, required Analytics analytics, }) : _client = mdnsClient ?? MDnsClient(), _preliminaryClient = preliminaryMDnsClient, _logger = logger, _flutterUsage = flutterUsage, _analytics = analytics; final MDnsClient _client; // Used when discovering VM services with `queryForAttach` to do a preliminary // check for already running services so that results are not cached in _client. final MDnsClient? _preliminaryClient; final Logger _logger; final Usage _flutterUsage; final Analytics _analytics; @visibleForTesting static const String dartVmServiceName = '_dartVmService._tcp.local'; static MDnsVmServiceDiscovery? get instance => context.get<MDnsVmServiceDiscovery>(); /// Executes an mDNS query for Dart VM Services. /// Checks for services that have already been launched. /// If none are found, it will listen for new services to become active /// and return the first it finds that match the parameters. /// /// The [applicationId] parameter may be used to specify which application /// to find. For Android, it refers to the package name; on iOS, it refers to /// the bundle ID. /// /// The [deviceVmservicePort] parameter may be used to specify which port /// to find. /// /// The [useDeviceIPAsHost] parameter flags whether to get the device IP /// and the [ipv6] parameter flags whether to get an iPv6 address /// (otherwise it will get iPv4). /// /// The [timeout] parameter determines how long to continue to wait for /// services to become active. /// /// If [applicationId] is not null, this method will find the port and authentication code /// of the Dart VM Service for that application. If it cannot find a service matching /// that application identifier after the [timeout], it will call [throwToolExit]. /// /// If [applicationId] is null and there are multiple Dart VM Services available, /// the user will be prompted with a list of available services with the respective /// app-id and device-vmservice-port to use and asked to select one. /// /// If it is null and there is only one available or it's the first found instance /// of Dart VM Service, it will return that instance's information regardless of /// what application the service instance is for. @visibleForTesting Future<MDnsVmServiceDiscoveryResult?> queryForAttach({ String? applicationId, int? deviceVmservicePort, bool ipv6 = false, bool useDeviceIPAsHost = false, Duration timeout = const Duration(minutes: 10), }) async { // Poll for 5 seconds to see if there are already services running. // Use a new instance of MDnsClient so results don't get cached in _client. // If no results are found, poll for a longer duration to wait for connections. // If more than 1 result is found, throw an error since it can't be determined which to pick. // If only one is found, return it. final List<MDnsVmServiceDiscoveryResult> results = await _pollingVmService( _preliminaryClient ?? MDnsClient(), applicationId: applicationId, deviceVmservicePort: deviceVmservicePort, ipv6: ipv6, useDeviceIPAsHost: useDeviceIPAsHost, timeout: const Duration(seconds: 5), ); if (results.isEmpty) { return firstMatchingVmService( _client, applicationId: applicationId, deviceVmservicePort: deviceVmservicePort, ipv6: ipv6, useDeviceIPAsHost: useDeviceIPAsHost, timeout: timeout, ); } else if (results.length > 1) { final StringBuffer buffer = StringBuffer(); buffer.writeln('There are multiple Dart VM Services available.'); buffer.writeln('Rerun this command with one of the following passed in as the app-id and device-vmservice-port:'); buffer.writeln(); for (final MDnsVmServiceDiscoveryResult result in results) { buffer.writeln( ' flutter attach --app-id "${result.domainName.replaceAll('.$dartVmServiceName', '')}" --device-vmservice-port ${result.port}'); } throwToolExit(buffer.toString()); } return results.first; } /// Executes an mDNS query for Dart VM Services. /// Listens for new services to become active and returns the first it finds that /// match the parameters. /// /// The [applicationId] parameter must be set to specify which application /// to find. For Android, it refers to the package name; on iOS, it refers to /// the bundle ID. /// /// The [deviceVmservicePort] parameter must be set to specify which port /// to find. /// /// [applicationId] and either [deviceVmservicePort] or [deviceName] are /// required for launch so that if multiple flutter apps are running on /// different devices, it will only match with the device running the desired app. /// /// The [useDeviceIPAsHost] parameter flags whether to get the device IP /// and the [ipv6] parameter flags whether to get an iPv6 address /// (otherwise it will get iPv4). /// /// The [timeout] parameter determines how long to continue to wait for /// services to become active. /// /// If a Dart VM Service matching the [applicationId] and /// [deviceVmservicePort]/[deviceName] cannot be found before the [timeout] /// is reached, it will call [throwToolExit]. @visibleForTesting Future<MDnsVmServiceDiscoveryResult?> queryForLaunch({ required String applicationId, int? deviceVmservicePort, String? deviceName, bool ipv6 = false, bool useDeviceIPAsHost = false, Duration timeout = const Duration(minutes: 10), }) async { // Either the device port or the device name must be provided. assert(deviceVmservicePort != null || deviceName != null); // Query for a specific application matching on either device port or device name. return firstMatchingVmService( _client, applicationId: applicationId, deviceVmservicePort: deviceVmservicePort, deviceName: deviceName, ipv6: ipv6, useDeviceIPAsHost: useDeviceIPAsHost, timeout: timeout, ); } /// Polls for Dart VM Services and returns the first it finds that match /// the [applicationId]/[deviceVmservicePort] (if applicable). /// Returns null if no results are found. @visibleForTesting Future<MDnsVmServiceDiscoveryResult?> firstMatchingVmService( MDnsClient client, { String? applicationId, int? deviceVmservicePort, String? deviceName, bool ipv6 = false, bool useDeviceIPAsHost = false, Duration timeout = const Duration(minutes: 10), }) async { final List<MDnsVmServiceDiscoveryResult> results = await _pollingVmService( client, applicationId: applicationId, deviceVmservicePort: deviceVmservicePort, deviceName: deviceName, ipv6: ipv6, useDeviceIPAsHost: useDeviceIPAsHost, timeout: timeout, quitOnFind: true, ); if (results.isEmpty) { return null; } return results.first; } Future<List<MDnsVmServiceDiscoveryResult>> _pollingVmService( MDnsClient client, { String? applicationId, int? deviceVmservicePort, String? deviceName, bool ipv6 = false, bool useDeviceIPAsHost = false, required Duration timeout, bool quitOnFind = false, }) async { _logger.printTrace('Checking for advertised Dart VM Services...'); try { await client.start(); final List<MDnsVmServiceDiscoveryResult> results = <MDnsVmServiceDiscoveryResult>[]; // uniqueDomainNames is used to track all domain names of Dart VM services // It is later used in this function to determine whether or not to throw an error. // We do not want to throw the error if it was unable to find any domain // names because that indicates it may be a problem with mDNS, which has // a separate error message in _checkForIPv4LinkLocal. final Set<String> uniqueDomainNames = <String>{}; // uniqueDomainNamesInResults is used to filter out duplicates with exactly // the same domain name from the results. final Set<String> uniqueDomainNamesInResults = <String>{}; // Listen for mDNS connections until timeout. final Stream<PtrResourceRecord> ptrResourceStream = client.lookup<PtrResourceRecord>( ResourceRecordQuery.serverPointer(dartVmServiceName), timeout: timeout ); await for (final PtrResourceRecord ptr in ptrResourceStream) { uniqueDomainNames.add(ptr.domainName); String? domainName; if (applicationId != null) { // If applicationId is set, only use records that match it if (ptr.domainName.toLowerCase().startsWith(applicationId.toLowerCase())) { domainName = ptr.domainName; } else { continue; } } else { domainName = ptr.domainName; } // Result with same domain name was already found, skip it. if (uniqueDomainNamesInResults.contains(domainName)) { continue; } _logger.printTrace('Checking for available port on $domainName'); final List<SrvResourceRecord> srvRecords = await client .lookup<SrvResourceRecord>( ResourceRecordQuery.service(domainName), ) .toList(); if (srvRecords.isEmpty) { continue; } // If more than one SrvResourceRecord found, it should just be a duplicate. final SrvResourceRecord srvRecord = srvRecords.first; if (srvRecords.length > 1) { _logger.printWarning( 'Unexpectedly found more than one Dart VM Service report for $domainName ' '- using first one (${srvRecord.port}).'); } // If deviceVmservicePort is set, only use records that match it if (deviceVmservicePort != null && srvRecord.port != deviceVmservicePort) { continue; } // If deviceName is set, only use records that match it if (deviceName != null && !deviceNameMatchesTargetName(deviceName, srvRecord.target)) { continue; } // Get the IP address of the device if using the IP as the host. InternetAddress? ipAddress; if (useDeviceIPAsHost) { List<IPAddressResourceRecord> ipAddresses = await client .lookup<IPAddressResourceRecord>( ipv6 ? ResourceRecordQuery.addressIPv6(srvRecord.target) : ResourceRecordQuery.addressIPv4(srvRecord.target), ) .toList(); if (ipAddresses.isEmpty) { throwToolExit('Did not find IP for service ${srvRecord.target}.'); } // Filter out link-local addresses. if (ipAddresses.length > 1) { ipAddresses = ipAddresses.where((IPAddressResourceRecord element) => !element.address.isLinkLocal).toList(); } ipAddress = ipAddresses.first.address; if (ipAddresses.length > 1) { _logger.printWarning( 'Unexpectedly found more than one IP for Dart VM Service ${srvRecord.target} ' '- using first one ($ipAddress).'); } } _logger.printTrace('Checking for authentication code for $domainName'); final List<TxtResourceRecord> txt = await client .lookup<TxtResourceRecord>( ResourceRecordQuery.text(domainName), ) .toList(); String authCode = ''; if (txt.isNotEmpty) { authCode = _getAuthCode(txt.first.text); } results.add(MDnsVmServiceDiscoveryResult( domainName, srvRecord.port, authCode, ipAddress: ipAddress )); uniqueDomainNamesInResults.add(domainName); if (quitOnFind) { return results; } } // If applicationId is set and quitOnFind is true and no results matching // the applicationId were found but other results were found, throw an error. if (applicationId != null && quitOnFind && results.isEmpty && uniqueDomainNames.isNotEmpty) { String message = 'Did not find a Dart VM Service advertised for $applicationId'; if (deviceVmservicePort != null) { message += ' on port $deviceVmservicePort'; } throwToolExit('$message.'); } return results; } finally { client.stop(); } } @visibleForTesting bool deviceNameMatchesTargetName(String deviceName, String targetName) { // Remove `.local` from the name along with any non-word, non-digit characters. final RegExp cleanedNameRegex = RegExp(r'\.local|\W'); final String cleanedDeviceName = deviceName.trim().toLowerCase().replaceAll(cleanedNameRegex, ''); final String cleanedTargetName = targetName.toLowerCase().replaceAll(cleanedNameRegex, ''); return cleanedDeviceName == cleanedTargetName; } String _getAuthCode(String txtRecord) { const String authCodePrefix = 'authCode='; final Iterable<String> matchingRecords = LineSplitter.split(txtRecord).where((String record) => record.startsWith(authCodePrefix)); if (matchingRecords.isEmpty) { return ''; } String authCode = matchingRecords.first.substring(authCodePrefix.length); // The Dart VM Service currently expects a trailing '/' as part of the // URI, otherwise an invalid authentication code response is given. if (!authCode.endsWith('/')) { authCode += '/'; } return authCode; } /// Gets Dart VM Service Uri for `flutter attach`. /// Executes an mDNS query and waits until a Dart VM Service is found. /// /// When [useDeviceIPAsHost] is true, it will use the device's IP as the /// host and will not forward the port. /// /// Differs from [getVMServiceUriForLaunch] because it can search for any available Dart VM Service. /// Since [applicationId] and [deviceVmservicePort] are optional, it can either look for any service /// or a specific service matching [applicationId]/[deviceVmservicePort]. /// It may find more than one service, which will throw an error listing the found services. Future<Uri?> getVMServiceUriForAttach( String? applicationId, Device device, { bool usesIpv6 = false, int? hostVmservicePort, int? deviceVmservicePort, bool useDeviceIPAsHost = false, Duration timeout = const Duration(minutes: 10), }) async { final MDnsVmServiceDiscoveryResult? result = await queryForAttach( applicationId: applicationId, deviceVmservicePort: deviceVmservicePort, ipv6: usesIpv6, useDeviceIPAsHost: useDeviceIPAsHost, timeout: timeout, ); return _handleResult( result, device, applicationId: applicationId, deviceVmservicePort: deviceVmservicePort, hostVmservicePort: hostVmservicePort, usesIpv6: usesIpv6, useDeviceIPAsHost: useDeviceIPAsHost ); } /// Gets Dart VM Service Uri for `flutter run`. /// Executes an mDNS query and waits until the Dart VM Service service is found. /// /// When [useDeviceIPAsHost] is true, it will use the device's IP as the /// host and will not forward the port. /// /// Differs from [getVMServiceUriForAttach] because it only searches for a specific service. /// This is enforced by [applicationId] being required and using either the /// [deviceVmservicePort] or the [device]'s name to query. Future<Uri?> getVMServiceUriForLaunch( String applicationId, Device device, { bool usesIpv6 = false, int? hostVmservicePort, int? deviceVmservicePort, bool useDeviceIPAsHost = false, Duration timeout = const Duration(minutes: 10), }) async { final MDnsVmServiceDiscoveryResult? result = await queryForLaunch( applicationId: applicationId, deviceVmservicePort: deviceVmservicePort, deviceName: deviceVmservicePort == null ? device.name : null, ipv6: usesIpv6, useDeviceIPAsHost: useDeviceIPAsHost, timeout: timeout, ); return _handleResult( result, device, applicationId: applicationId, deviceVmservicePort: deviceVmservicePort, hostVmservicePort: hostVmservicePort, usesIpv6: usesIpv6, useDeviceIPAsHost: useDeviceIPAsHost ); } Future<Uri?> _handleResult( MDnsVmServiceDiscoveryResult? result, Device device, { String? applicationId, int? deviceVmservicePort, int? hostVmservicePort, bool usesIpv6 = false, bool useDeviceIPAsHost = false, }) async { if (result == null) { await _checkForIPv4LinkLocal(device); return null; } final String host; final InternetAddress? ipAddress = result.ipAddress; if (useDeviceIPAsHost && ipAddress != null) { host = ipAddress.address; } else { host = usesIpv6 ? InternetAddress.loopbackIPv6.address : InternetAddress.loopbackIPv4.address; } return buildVMServiceUri( device, host, result.port, hostVmservicePort, result.authCode, useDeviceIPAsHost, ); } // If there's not an ipv4 link local address in `NetworkInterfaces.list`, // then request user interventions with a `printError()` if possible. Future<void> _checkForIPv4LinkLocal(Device device) async { _logger.printTrace( 'mDNS query failed. Checking for an interface with a ipv4 link local address.' ); final List<NetworkInterface> interfaces = await listNetworkInterfaces( includeLinkLocal: true, type: InternetAddressType.IPv4, ); if (_logger.isVerbose) { _logInterfaces(interfaces); } final bool hasIPv4LinkLocal = interfaces.any( (NetworkInterface interface) => interface.addresses.any( (InternetAddress address) => address.isLinkLocal, ), ); if (hasIPv4LinkLocal) { _logger.printTrace('An interface with an ipv4 link local address was found.'); return; } final TargetPlatform targetPlatform = await device.targetPlatform; switch (targetPlatform) { case TargetPlatform.ios: UsageEvent('ios-mdns', 'no-ipv4-link-local', flutterUsage: _flutterUsage).send(); _analytics.send(Event.appleUsageEvent(workflow: 'ios-mdns', parameter: 'no-ipv4-link-local')); _logger.printError( 'The mDNS query for an attached iOS device failed. It may ' 'be necessary to disable the "Personal Hotspot" on the device, and ' 'to ensure that the "Disable unless needed" setting is unchecked ' 'under System Preferences > Network > iPhone USB. ' 'See https://github.com/flutter/flutter/issues/46698 for details.' ); case TargetPlatform.android: case TargetPlatform.android_arm: case TargetPlatform.android_arm64: case TargetPlatform.android_x64: case TargetPlatform.android_x86: case TargetPlatform.darwin: case TargetPlatform.fuchsia_arm64: case TargetPlatform.fuchsia_x64: case TargetPlatform.linux_arm64: case TargetPlatform.linux_x64: case TargetPlatform.tester: case TargetPlatform.web_javascript: case TargetPlatform.windows_x64: case TargetPlatform.windows_arm64: _logger.printTrace('No interface with an ipv4 link local address was found.'); } } void _logInterfaces(List<NetworkInterface> interfaces) { for (final NetworkInterface interface in interfaces) { if (_logger.isVerbose) { _logger.printTrace('Found interface "${interface.name}":'); for (final InternetAddress address in interface.addresses) { final String linkLocal = address.isLinkLocal ? 'link local' : ''; _logger.printTrace('\tBound address: "${address.address}" $linkLocal'); } } } } } class MDnsVmServiceDiscoveryResult { MDnsVmServiceDiscoveryResult( this.domainName, this.port, this.authCode, { this.ipAddress }); final String domainName; final int port; final String authCode; final InternetAddress? ipAddress; } Future<Uri> buildVMServiceUri( Device device, String host, int devicePort, [ int? hostVmservicePort, String? authCode, bool useDeviceIPAsHost = false, ]) async { String path = '/'; if (authCode != null) { path = authCode; } // Not having a trailing slash can cause problems in some situations. // Ensure that there's one present. if (!path.endsWith('/')) { path += '/'; } hostVmservicePort ??= 0; final int? actualHostPort; if (useDeviceIPAsHost) { // When using the device's IP as the host, port forwarding is not required // so just use the device's port. actualHostPort = devicePort; } else { actualHostPort = hostVmservicePort == 0 ? await device.portForwarder?.forward(devicePort) : hostVmservicePort; } return Uri(scheme: 'http', host: host, port: actualHostPort, path: path); }
flutter/packages/flutter_tools/lib/src/mdns_discovery.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/mdns_discovery.dart", "repo_id": "flutter", "token_count": 7913 }
369
// Copyright 2014 The Flutter 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:collection'; import 'package:process/process.dart'; import 'base/file_system.dart'; import 'base/io.dart'; import 'base/logger.dart'; import 'base/platform.dart'; import 'cache.dart'; import 'convert.dart'; import 'dart_pub_json_formatter.dart'; import 'flutter_manifest.dart'; import 'project.dart'; import 'project_validator_result.dart'; import 'version.dart'; abstract class ProjectValidator { const ProjectValidator(); String get title; bool get machineOutput => false; bool supportsProject(FlutterProject project); /// Can return more than one result in case a file/command have a lot of info to share to the user Future<List<ProjectValidatorResult>> start(FlutterProject project); } abstract class MachineProjectValidator extends ProjectValidator { const MachineProjectValidator(); @override bool get machineOutput => true; } /// Validator run for all platforms that extract information from the pubspec.yaml. /// /// Specific info from different platforms should be written in their own ProjectValidator. class VariableDumpMachineProjectValidator extends MachineProjectValidator { VariableDumpMachineProjectValidator({ required this.logger, required this.fileSystem, required this.platform, }); final Logger logger; final FileSystem fileSystem; final Platform platform; String _toJsonValue(Object? obj) { String value = obj.toString(); if (obj is String) { value = '"$obj"'; } value = value.replaceAll(r'\', r'\\'); return value; } @override Future<List<ProjectValidatorResult>> start(FlutterProject project) async { final FlutterVersion version = FlutterVersion( flutterRoot: Cache.flutterRoot!, fs: fileSystem, ); final Map<String, Object?> result = <String, Object?>{ 'FlutterProject.directory': project.directory.absolute.path, 'FlutterProject.metadataFile': project.metadataFile.absolute.path, 'FlutterProject.android.exists': project.android.existsSync(), 'FlutterProject.ios.exists': project.ios.exists, 'FlutterProject.web.exists': project.web.existsSync(), 'FlutterProject.macos.exists': project.macos.existsSync(), 'FlutterProject.linux.exists': project.linux.existsSync(), 'FlutterProject.windows.exists': project.windows.existsSync(), 'FlutterProject.fuchsia.exists': project.fuchsia.existsSync(), 'FlutterProject.android.isKotlin': project.android.isKotlin, 'FlutterProject.ios.isSwift': project.ios.isSwift, 'FlutterProject.isModule': project.isModule, 'FlutterProject.isPlugin': project.isPlugin, 'FlutterProject.manifest.appname': project.manifest.appName, // FlutterVersion 'FlutterVersion.frameworkRevision': version.frameworkRevision, // Platform 'Platform.operatingSystem': platform.operatingSystem, 'Platform.isAndroid': platform.isAndroid, 'Platform.isIOS': platform.isIOS, 'Platform.isWindows': platform.isWindows, 'Platform.isMacOS': platform.isMacOS, 'Platform.isFuchsia': platform.isFuchsia, 'Platform.pathSeparator': platform.pathSeparator, // Cache 'Cache.flutterRoot': Cache.flutterRoot, }; return <ProjectValidatorResult>[ for (final String key in result.keys) ProjectValidatorResult( name: key, value: _toJsonValue(result[key]), status: StatusProjectValidator.info, ), ]; } @override bool supportsProject(FlutterProject project) { // this validator will run for any type of project return true; } @override String get title => 'Machine JSON variable dump'; } /// Validator run for all platforms that extract information from the pubspec.yaml. /// /// Specific info from different platforms should be written in their own ProjectValidator. class GeneralInfoProjectValidator extends ProjectValidator { @override Future<List<ProjectValidatorResult>> start(FlutterProject project) async { final FlutterManifest flutterManifest = project.manifest; final List<ProjectValidatorResult> result = <ProjectValidatorResult>[]; final ProjectValidatorResult appNameValidatorResult = _getAppNameResult(flutterManifest); result.add(appNameValidatorResult); final String supportedPlatforms = _getSupportedPlatforms(project); if (supportedPlatforms.isEmpty) { return result; } final ProjectValidatorResult supportedPlatformsResult = ProjectValidatorResult( name: 'Supported Platforms', value: supportedPlatforms, status: StatusProjectValidator.success ); final ProjectValidatorResult isFlutterPackage = _isFlutterPackageValidatorResult(flutterManifest); result.addAll(<ProjectValidatorResult>[supportedPlatformsResult, isFlutterPackage]); if (flutterManifest.flutterDescriptor.isNotEmpty) { result.add(_materialDesignResult(flutterManifest)); result.add(_pluginValidatorResult(flutterManifest)); } result.add(await project.android.validateJavaAndGradleAgpVersions()); return result; } ProjectValidatorResult _getAppNameResult(FlutterManifest flutterManifest) { final String appName = flutterManifest.appName; const String name = 'App Name'; if (appName.isEmpty) { return const ProjectValidatorResult( name: name, value: 'name not found', status: StatusProjectValidator.error ); } return ProjectValidatorResult( name: name, value: appName, status: StatusProjectValidator.success ); } ProjectValidatorResult _isFlutterPackageValidatorResult(FlutterManifest flutterManifest) { final String value; final StatusProjectValidator status; if (flutterManifest.flutterDescriptor.isNotEmpty) { value = 'yes'; status = StatusProjectValidator.success; } else { value = 'no'; status = StatusProjectValidator.warning; } return ProjectValidatorResult( name: 'Is Flutter Package', value: value, status: status ); } ProjectValidatorResult _materialDesignResult(FlutterManifest flutterManifest) { return ProjectValidatorResult( name: 'Uses Material Design', value: flutterManifest.usesMaterialDesign? 'yes' : 'no', status: StatusProjectValidator.success ); } String _getSupportedPlatforms(FlutterProject project) { return project.getSupportedPlatforms().map((SupportedPlatform platform) => platform.name).join(', '); } ProjectValidatorResult _pluginValidatorResult(FlutterManifest flutterManifest) { return ProjectValidatorResult( name: 'Is Plugin', value: flutterManifest.isPlugin? 'yes' : 'no', status: StatusProjectValidator.success ); } @override bool supportsProject(FlutterProject project) { // this validator will run for any type of project return true; } @override String get title => 'General Info'; } class PubDependenciesProjectValidator extends ProjectValidator { const PubDependenciesProjectValidator(this._processManager); final ProcessManager _processManager; @override Future<List<ProjectValidatorResult>> start(FlutterProject project) async { const String name = 'Dart dependencies'; final ProcessResult processResult = await _processManager.run(<String>['dart', 'pub', 'deps', '--json']); if (processResult.stdout is! String) { return <ProjectValidatorResult>[ _createProjectValidatorError(name, 'Command dart pub deps --json failed') ]; } final LinkedHashMap<String, dynamic> jsonResult; final List<ProjectValidatorResult> result = <ProjectValidatorResult>[]; try { jsonResult = json.decode( processResult.stdout.toString() ) as LinkedHashMap<String, dynamic>; } on FormatException { result.add(_createProjectValidatorError(name, processResult.stderr.toString())); return result; } final DartPubJson dartPubJson = DartPubJson(jsonResult); final List <String> dependencies = <String>[]; // Information retrieved from the pubspec.lock file if a dependency comes from // the hosted url https://pub.dartlang.org we ignore it or if the package // is the current directory being analyzed (root). final Set<String> hostedDependencies = <String>{'hosted', 'root'}; for (final DartDependencyPackage package in dartPubJson.packages) { if (!hostedDependencies.contains(package.source)) { dependencies.addAll(package.dependencies); } } final String value; if (dependencies.isNotEmpty) { final String verb = dependencies.length == 1 ? 'is' : 'are'; value = '${dependencies.join(', ')} $verb not hosted'; } else { value = 'All pub dependencies are hosted on https://pub.dartlang.org'; } result.add( ProjectValidatorResult( name: name, value: value, status: StatusProjectValidator.info, ) ); return result; } @override bool supportsProject(FlutterProject project) { return true; } @override String get title => 'Pub dependencies'; ProjectValidatorResult _createProjectValidatorError(String name, String value) { return ProjectValidatorResult(name: name, value: value, status: StatusProjectValidator.error); } }
flutter/packages/flutter_tools/lib/src/project_validator.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/project_validator.dart", "repo_id": "flutter", "token_count": 3386 }
370
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. part of 'reporting.dart'; const String _kFlutterUA = 'UA-67589403-6'; abstract class Usage { /// Create a new Usage instance; [versionOverride], [configDirOverride], and /// [logFile] are used for testing. factory Usage({ String settingsName = 'flutter', String? versionOverride, String? configDirOverride, String? logFile, AnalyticsFactory? analyticsIOFactory, FirstRunMessenger? firstRunMessenger, required bool runningOnBot, }) => _DefaultUsage.initialize( settingsName: settingsName, versionOverride: versionOverride, configDirOverride: configDirOverride, logFile: logFile, analyticsIOFactory: analyticsIOFactory, runningOnBot: runningOnBot, firstRunMessenger: firstRunMessenger, ); /// Uses the global [Usage] instance to send a 'command' to analytics. static void command(String command, { CustomDimensions? parameters, }) => globals.flutterUsage.sendCommand(command, parameters: parameters); /// Whether analytics reporting should be suppressed. bool get suppressAnalytics; /// Suppress analytics for this session. set suppressAnalytics(bool value); /// Whether analytics reporting is enabled. bool get enabled; /// Enable or disable reporting analytics. set enabled(bool value); /// A stable randomly generated UUID used to deduplicate multiple identical /// reports coming from the same computer. String get clientId; /// Sends a 'command' to the underlying analytics implementation. /// /// Using [command] above is preferred to ensure that the parameter /// keys are well-defined in [CustomDimensions] above. void sendCommand( String command, { CustomDimensions? parameters, }); /// Sends an 'event' to the underlying analytics implementation. /// /// This method should not be used directly, instead see the /// event types defined in this directory in `events.dart`. @visibleForOverriding @visibleForTesting void sendEvent( String category, String parameter, { String? label, int? value, CustomDimensions? parameters, }); /// Sends timing information to the underlying analytics implementation. void sendTiming( String category, String variableName, Duration duration, { String? label, }); /// Sends an exception to the underlying analytics implementation. void sendException(dynamic exception); /// Fires whenever analytics data is sent over the network. @visibleForTesting Stream<Map<String, dynamic>> get onSend; /// Returns when the last analytics event has been sent, or after a fixed /// (short) delay, whichever is less. Future<void> ensureAnalyticsSent(); /// Prints a welcome message that informs the tool user about the collection /// of anonymous usage information. void printWelcome(); } typedef AnalyticsFactory = Analytics Function( String trackingId, String applicationName, String applicationVersion, { String analyticsUrl, Directory? documentDirectory, }); Analytics _defaultAnalyticsIOFactory( String trackingId, String applicationName, String applicationVersion, { String? analyticsUrl, Directory? documentDirectory, }) { return AnalyticsIO( trackingId, applicationName, applicationVersion, analyticsUrl: analyticsUrl, documentDirectory: documentDirectory, ); } class _DefaultUsage implements Usage { _DefaultUsage._({ required bool suppressAnalytics, required Analytics analytics, required this.firstRunMessenger, required SystemClock clock, }) : _suppressAnalytics = suppressAnalytics, _analytics = analytics, _clock = clock; static _DefaultUsage initialize({ String settingsName = 'flutter', String? versionOverride, String? configDirOverride, String? logFile, AnalyticsFactory? analyticsIOFactory, required FirstRunMessenger? firstRunMessenger, required bool runningOnBot, }) { final FlutterVersion flutterVersion = globals.flutterVersion; final String version = versionOverride ?? flutterVersion.getVersionString(redactUnknownBranches: true); final bool suppressEnvFlag = globals.platform.environment['FLUTTER_SUPPRESS_ANALYTICS'] == 'true'; final String? logFilePath = logFile ?? globals.platform.environment['FLUTTER_ANALYTICS_LOG_FILE']; final bool usingLogFile = logFilePath != null && logFilePath.isNotEmpty; final AnalyticsFactory analyticsFactory = analyticsIOFactory ?? _defaultAnalyticsIOFactory; bool suppressAnalytics = false; bool skipAnalyticsSessionSetup = false; Analytics? setupAnalytics; if (// To support testing, only allow other signals to suppress analytics // when analytics are not being shunted to a file. !usingLogFile && ( // Ignore local user branches. version.startsWith('[user-branch]') || // Many CI systems don't do a full git checkout. version.endsWith('/unknown') || // Ignore bots. runningOnBot || // Ignore when suppressed by FLUTTER_SUPPRESS_ANALYTICS. suppressEnvFlag )) { // If we think we're running on a CI system, suppress sending analytics. suppressAnalytics = true; setupAnalytics = AnalyticsMock(); skipAnalyticsSessionSetup = true; } if (usingLogFile) { setupAnalytics ??= LogToFileAnalytics(logFilePath); } else { try { ErrorHandlingFileSystem.noExitOnFailure(() { setupAnalytics = analyticsFactory( _kFlutterUA, settingsName, version, documentDirectory: configDirOverride != null ? globals.fs.directory(configDirOverride) : null, ); }); } on Exception catch (e) { globals.printTrace('Failed to initialize analytics reporting: $e'); suppressAnalytics = true; setupAnalytics ??= AnalyticsMock(); skipAnalyticsSessionSetup = true; } } final Analytics analytics = setupAnalytics!; if (!skipAnalyticsSessionSetup) { // Report a more detailed OS version string than package:usage does by default. analytics.setSessionValue( CustomDimensionsEnum.sessionHostOsDetails.cdKey, globals.os.name, ); // Send the branch name as the "channel". analytics.setSessionValue( CustomDimensionsEnum.sessionChannelName.cdKey, flutterVersion.getBranchName(redactUnknownBranches: true), ); // For each flutter experimental feature, record a session value in a comma // separated list. final String enabledFeatures = allFeatures .where((Feature feature) { final String? configSetting = feature.configSetting; return configSetting != null && globals.config.getValue(configSetting) == true; }) .map((Feature feature) => feature.configSetting) .join(','); analytics.setSessionValue( CustomDimensionsEnum.enabledFlutterFeatures.cdKey, enabledFeatures, ); // Record the host as the application installer ID - the context that flutter_tools is running in. if (globals.platform.environment.containsKey('FLUTTER_HOST')) { analytics.setSessionValue('aiid', globals.platform.environment['FLUTTER_HOST']); } analytics.analyticsOpt = AnalyticsOpt.optOut; } return _DefaultUsage._( suppressAnalytics: suppressAnalytics, analytics: analytics, firstRunMessenger: firstRunMessenger, clock: globals.systemClock, ); } final Analytics _analytics; final FirstRunMessenger? firstRunMessenger; bool _printedWelcome = false; bool _suppressAnalytics = false; final SystemClock _clock; @override bool get suppressAnalytics => _suppressAnalytics || _analytics.firstRun; @override set suppressAnalytics(bool value) { _suppressAnalytics = value; } @override bool get enabled => _analytics.enabled; @override set enabled(bool value) { _analytics.enabled = value; } @override String get clientId => _analytics.clientId; @override void sendCommand(String command, { CustomDimensions? parameters }) { if (suppressAnalytics) { return; } _analytics.sendScreenView( command, parameters: CustomDimensions(localTime: formatDateTime(_clock.now())) .merge(parameters) .toMap(), ); } @override void sendEvent( String category, String parameter, { String? label, int? value, CustomDimensions? parameters, }) { if (suppressAnalytics) { return; } _analytics.sendEvent( category, parameter, label: label, value: value, parameters: CustomDimensions(localTime: formatDateTime(_clock.now())) .merge(parameters) .toMap(), ); } @override void sendTiming( String category, String variableName, Duration duration, { String? label, }) { if (suppressAnalytics) { return; } _analytics.sendTiming( variableName, duration.inMilliseconds, category: category, label: label, ); } @override void sendException(dynamic exception) { if (suppressAnalytics) { return; } _analytics.sendException(exception.runtimeType.toString()); } @override Stream<Map<String, dynamic>> get onSend => _analytics.onSend; @override Future<void> ensureAnalyticsSent() async { // TODO(devoncarew): This may delay tool exit and could cause some analytics // events to not be reported. Perhaps we could send the analytics pings // out-of-process from flutter_tools? await _analytics.waitForLastPing(timeout: const Duration(milliseconds: 250)); } @override void printWelcome() { // Only print once per run. if (_printedWelcome) { return; } // Display the welcome message if this is the first run of the tool or if // the license terms have changed since it was last displayed. final FirstRunMessenger? messenger = firstRunMessenger; if (messenger != null && messenger.shouldDisplayLicenseTerms()) { globals.printStatus(''); globals.printStatus(messenger.licenseTerms, emphasis: true); _printedWelcome = true; messenger.confirmLicenseTermsDisplayed(); } } } // An Analytics mock that logs to file. Unimplemented methods goes to stdout. // But stdout can't be used for testing since wrapper scripts like // xcode_backend.sh etc manipulates them. class LogToFileAnalytics extends AnalyticsMock { LogToFileAnalytics(String logFilePath) : logFile = globals.fs.file(logFilePath)..createSync(recursive: true), super(true); final File logFile; final Map<String, String> _sessionValues = <String, String>{}; final StreamController<Map<String, dynamic>> _sendController = StreamController<Map<String, dynamic>>.broadcast(sync: true); @override Stream<Map<String, dynamic>> get onSend => _sendController.stream; @override Future<void> sendScreenView(String viewName, { Map<String, String>? parameters, }) { if (!enabled) { return Future<void>.value(); } parameters ??= <String, String>{}; parameters['viewName'] = viewName; parameters.addAll(_sessionValues); _sendController.add(parameters); logFile.writeAsStringSync('screenView $parameters\n', mode: FileMode.append); return Future<void>.value(); } @override Future<void> sendEvent(String category, String action, {String? label, int? value, Map<String, String>? parameters}) { if (!enabled) { return Future<void>.value(); } parameters ??= <String, String>{}; parameters['category'] = category; parameters['action'] = action; _sendController.add(parameters); logFile.writeAsStringSync('event $parameters\n', mode: FileMode.append); return Future<void>.value(); } @override Future<void> sendTiming(String variableName, int time, {String? category, String? label}) { if (!enabled) { return Future<void>.value(); } final Map<String, String> parameters = <String, String>{ 'variableName': variableName, 'time': '$time', if (category != null) 'category': category, if (label != null) 'label': label, }; _sendController.add(parameters); logFile.writeAsStringSync('timing $parameters\n', mode: FileMode.append); return Future<void>.value(); } @override void setSessionValue(String param, dynamic value) { _sessionValues[param] = value.toString(); } } /// Create a testing Usage instance. /// /// All sent events, exceptions, timings, and pages are /// buffered on the object and can be inspected later. @visibleForTesting class TestUsage implements Usage { final List<TestUsageCommand> commands = <TestUsageCommand>[]; final List<TestUsageEvent> events = <TestUsageEvent>[]; final List<dynamic> exceptions = <dynamic>[]; final List<TestTimingEvent> timings = <TestTimingEvent>[]; int ensureAnalyticsSentCalls = 0; bool _printedWelcome = false; @override bool enabled = true; @override bool suppressAnalytics = false; @override String get clientId => 'test-client'; /// Confirms if the [printWelcome] method was invoked. bool get printedWelcome => _printedWelcome; @override Future<void> ensureAnalyticsSent() async { ensureAnalyticsSentCalls++; } @override Stream<Map<String, dynamic>> get onSend => throw UnimplementedError(); @override void printWelcome() { _printedWelcome = true; } @override void sendCommand(String command, {CustomDimensions? parameters}) { commands.add(TestUsageCommand(command, parameters: parameters)); } @override void sendEvent(String category, String parameter, {String? label, int? value, CustomDimensions? parameters}) { events.add(TestUsageEvent(category, parameter, label: label, value: value, parameters: parameters)); } @override void sendException(dynamic exception) { exceptions.add(exception); } @override void sendTiming(String category, String variableName, Duration duration, {String? label}) { timings.add(TestTimingEvent(category, variableName, duration, label: label)); } } @visibleForTesting @immutable class TestUsageCommand { const TestUsageCommand(this.command, {this.parameters}); final String command; final CustomDimensions? parameters; @override bool operator ==(Object other) { return other is TestUsageCommand && other.command == command && other.parameters == parameters; } @override int get hashCode => Object.hash(command, parameters); @override String toString() => 'TestUsageCommand($command, parameters:$parameters)'; } @visibleForTesting @immutable class TestUsageEvent { const TestUsageEvent(this.category, this.parameter, {this.label, this.value, this.parameters}); final String category; final String parameter; final String? label; final int? value; final CustomDimensions? parameters; @override bool operator ==(Object other) { return other is TestUsageEvent && other.category == category && other.parameter == parameter && other.label == label && other.value == value && other.parameters == parameters; } @override int get hashCode => Object.hash(category, parameter, label, value, parameters); @override String toString() => 'TestUsageEvent($category, $parameter, label:$label, value:$value, parameters:$parameters)'; } @visibleForTesting @immutable class TestTimingEvent { const TestTimingEvent(this.category, this.variableName, this.duration, {this.label}); final String category; final String variableName; final Duration duration; final String? label; @override bool operator ==(Object other) { return other is TestTimingEvent && other.category == category && other.variableName == variableName && other.duration == duration && other.label == label; } @override int get hashCode => Object.hash(category, variableName, duration, label); @override String toString() => 'TestTimingEvent($category, $variableName, $duration, label:$label)'; } bool _mapsEqual(Map<dynamic, dynamic>? a, Map<dynamic, dynamic>? b) { if (a == b) { return true; } if (a == null || b == null) { return false; } if (a.length != b.length) { return false; } for (final dynamic k in a.keys) { final dynamic bValue = b[k]; if (bValue == null && !b.containsKey(k)) { return false; } if (bValue != a[k]) { return false; } } return true; }
flutter/packages/flutter_tools/lib/src/reporting/usage.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/reporting/usage.dart", "repo_id": "flutter", "token_count": 5592 }
371
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:typed_data'; import 'package:async/async.dart'; import 'package:http_multi_server/http_multi_server.dart'; import 'package:mime/mime.dart' as mime; import 'package:package_config/package_config.dart'; import 'package:pool/pool.dart'; import 'package:process/process.dart'; import 'package:shelf/shelf.dart' as shelf; import 'package:shelf/shelf_io.dart' as shelf_io; import 'package:shelf_web_socket/shelf_web_socket.dart'; import 'package:stream_channel/stream_channel.dart'; import 'package:test_core/src/platform.dart'; // ignore: implementation_imports import 'package:web_socket_channel/web_socket_channel.dart'; import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart' hide StackTrace; import '../artifacts.dart'; import '../base/common.dart'; import '../base/file_system.dart'; import '../base/io.dart'; import '../base/logger.dart'; import '../build_info.dart'; import '../cache.dart'; import '../convert.dart'; import '../dart/package_map.dart'; import '../project.dart'; import '../web/bootstrap.dart'; import '../web/chrome.dart'; import '../web/compile.dart'; import '../web/memory_fs.dart'; import 'flutter_web_goldens.dart'; import 'test_compiler.dart'; import 'test_time_recorder.dart'; shelf.Handler createDirectoryHandler(Directory directory, { required bool crossOriginIsolated} ) { final mime.MimeTypeResolver resolver = mime.MimeTypeResolver(); final FileSystem fileSystem = directory.fileSystem; return (shelf.Request request) async { String uriPath = request.requestedUri.path; // Strip any leading slashes if (uriPath.startsWith('/')) { uriPath = uriPath.substring(1); } final String filePath = fileSystem.path.join( directory.path, uriPath, ); final File file = fileSystem.file(filePath); if (!file.existsSync()) { return shelf.Response.notFound('Not Found'); } final String? contentType = resolver.lookup(file.path); final bool needsCrossOriginIsolated = crossOriginIsolated && uriPath.endsWith('.html'); return shelf.Response.ok( file.openRead(), headers: <String, String>{ if (contentType != null) 'Content-Type': contentType, if (needsCrossOriginIsolated) ...<String, String>{ 'Cross-Origin-Opener-Policy': 'same-origin', 'Cross-Origin-Embedder-Policy': 'require-corp', }, }, ); }; } class FlutterWebPlatform extends PlatformPlugin { FlutterWebPlatform._(this._server, this._config, this._root, { FlutterProject? flutterProject, String? shellPath, this.updateGoldens, this.nullAssertions, required this.buildInfo, required this.webMemoryFS, required FileSystem fileSystem, required Directory buildDirectory, required File testDartJs, required File testHostDartJs, required ChromiumLauncher chromiumLauncher, required Logger logger, required Artifacts? artifacts, required ProcessManager processManager, required this.webRenderer, required this.useWasm, TestTimeRecorder? testTimeRecorder, }) : _fileSystem = fileSystem, _buildDirectory = buildDirectory, _testDartJs = testDartJs, _testHostDartJs = testHostDartJs, _chromiumLauncher = chromiumLauncher, _logger = logger, _artifacts = artifacts { final shelf.Cascade cascade = shelf.Cascade() .add(_webSocketHandler.handler) .add(createDirectoryHandler( fileSystem.directory(fileSystem.path.join(Cache.flutterRoot!, 'packages', 'flutter_tools')), crossOriginIsolated: webRenderer == WebRendererMode.skwasm, )) .add(_handleStaticArtifact) .add(_localCanvasKitHandler) .add(_goldenFileHandler) .add(_wrapperHandler) .add(_handleTestRequest) .add(createDirectoryHandler( fileSystem.directory(fileSystem.path.join(fileSystem.currentDirectory.path, 'test')), crossOriginIsolated: webRenderer == WebRendererMode.skwasm, )) .add(_packageFilesHandler); _server.mount(cascade.handler); _testGoldenComparator = TestGoldenComparator( shellPath, () => TestCompiler(buildInfo, flutterProject, testTimeRecorder: testTimeRecorder), fileSystem: _fileSystem, logger: _logger, processManager: processManager, webRenderer: webRenderer, ); } final WebMemoryFS webMemoryFS; final BuildInfo buildInfo; final FileSystem _fileSystem; final Directory _buildDirectory; final File _testDartJs; final File _testHostDartJs; final ChromiumLauncher _chromiumLauncher; final Logger _logger; final Artifacts? _artifacts; final bool? updateGoldens; final bool? nullAssertions; final OneOffHandler _webSocketHandler = OneOffHandler(); final AsyncMemoizer<void> _closeMemo = AsyncMemoizer<void>(); final String _root; final WebRendererMode webRenderer; final bool useWasm; /// Allows only one test suite (typically one test file) to be loaded and run /// at any given point in time. Loading more than one file at a time is known /// to lead to flaky tests. final Pool _suiteLock = Pool(1); BrowserManager? _browserManager; late TestGoldenComparator _testGoldenComparator; static Future<shelf.Server> defaultServerFactory() async { return shelf_io.IOServer(await HttpMultiServer.loopback(0)); } static Future<FlutterWebPlatform> start(String root, { FlutterProject? flutterProject, String? shellPath, bool updateGoldens = false, bool pauseAfterLoad = false, bool nullAssertions = false, required BuildInfo buildInfo, required WebMemoryFS webMemoryFS, required FileSystem fileSystem, required Directory buildDirectory, required Logger logger, required ChromiumLauncher chromiumLauncher, required Artifacts? artifacts, required ProcessManager processManager, required WebRendererMode webRenderer, required bool useWasm, TestTimeRecorder? testTimeRecorder, Uri? testPackageUri, Future<shelf.Server> Function() serverFactory = defaultServerFactory, }) async { final shelf.Server server = await serverFactory(); if (testPackageUri == null) { final PackageConfig packageConfig = await loadPackageConfigWithLogging( fileSystem.file(fileSystem.path.join( Cache.flutterRoot!, 'packages', 'flutter_tools', '.dart_tool', 'package_config.json', )), logger: logger, ); testPackageUri = packageConfig['test']!.packageUriRoot; } final File testDartJs = fileSystem.file(fileSystem.path.join( testPackageUri.toFilePath(), 'dart.js', )); final File testHostDartJs = fileSystem.file(fileSystem.path.join( testPackageUri.toFilePath(), 'src', 'runner', 'browser', 'static', 'host.dart.js', )); return FlutterWebPlatform._( server, Configuration.current.change(pauseAfterLoad: pauseAfterLoad), root, flutterProject: flutterProject, shellPath: shellPath, updateGoldens: updateGoldens, buildInfo: buildInfo, webMemoryFS: webMemoryFS, testDartJs: testDartJs, testHostDartJs: testHostDartJs, fileSystem: fileSystem, buildDirectory: buildDirectory, chromiumLauncher: chromiumLauncher, artifacts: artifacts, logger: logger, nullAssertions: nullAssertions, processManager: processManager, webRenderer: webRenderer, useWasm: useWasm, testTimeRecorder: testTimeRecorder, ); } bool get _closed => _closeMemo.hasRun; NullSafetyMode get _nullSafetyMode { return buildInfo.nullSafetyMode == NullSafetyMode.sound ? NullSafetyMode.sound : NullSafetyMode.unsound; } final Configuration _config; final shelf.Server _server; Uri get url => _server.url; /// The ahem text file. File get _ahem => _fileSystem.file(_fileSystem.path.join( Cache.flutterRoot!, 'packages', 'flutter_tools', 'static', 'Ahem.ttf', )); /// The require js binary. File get _requireJs => _fileSystem.file(_fileSystem.path.join( _artifacts!.getArtifactPath(Artifact.engineDartSdkPath, platform: TargetPlatform.web_javascript), 'lib', 'dev_compiler', 'amd', 'require.js', )); /// The ddc module loader js binary. File get _ddcModuleLoaderJs => _fileSystem.file(_fileSystem.path.join( _artifacts!.getArtifactPath(Artifact.engineDartSdkPath, platform: TargetPlatform.web_javascript), 'lib', 'dev_compiler', 'ddc', 'ddc_module_loader.js', )); /// The ddc to dart stack trace mapper. File get _stackTraceMapper => _fileSystem.file(_fileSystem.path.join( _artifacts!.getArtifactPath(Artifact.engineDartSdkPath, platform: TargetPlatform.web_javascript), 'lib', 'dev_compiler', 'web', 'dart_stack_trace_mapper.js', )); File get _flutterJs => _fileSystem.file(_fileSystem.path.join( _artifacts!.getHostArtifact(HostArtifact.flutterJsDirectory).path, 'flutter.js', )); File get _dartSdk { final Map<WebRendererMode, Map<NullSafetyMode, HostArtifact>> dartSdkArtifactMap = buildInfo.ddcModuleFormat == DdcModuleFormat.ddc ? kDdcDartSdkJsArtifactMap : kAmdDartSdkJsArtifactMap; return _fileSystem.file(_artifacts!.getHostArtifact(dartSdkArtifactMap[webRenderer]![_nullSafetyMode]!)); } File get _dartSdkSourcemaps { final Map<WebRendererMode, Map<NullSafetyMode, HostArtifact>> dartSdkArtifactMap = buildInfo.ddcModuleFormat == DdcModuleFormat.ddc ? kDdcDartSdkJsMapArtifactMap : kAmdDartSdkJsMapArtifactMap; return _fileSystem.file(_artifacts!.getHostArtifact(dartSdkArtifactMap[webRenderer]![_nullSafetyMode]!)); } File _canvasKitFile(String relativePath) { final String canvasKitPath = _fileSystem.path.join( _artifacts!.getHostArtifact(HostArtifact.flutterWebSdk).path, 'canvaskit', ); final File canvasKitFile = _fileSystem.file(_fileSystem.path.join( canvasKitPath, relativePath, )); return canvasKitFile; } Future<shelf.Response> _handleTestRequest(shelf.Request request) async { if (request.url.path.endsWith('main.dart.browser_test.dart.js')) { return shelf.Response.ok(generateTestBootstrapFileContents( '/main.dart.bootstrap.js', 'require.js', 'dart_stack_trace_mapper.js'), headers: <String, String>{ HttpHeaders.contentTypeHeader: 'text/javascript', } ); } if (request.url.path.endsWith('main.dart.bootstrap.js')) { return shelf.Response.ok(generateMainModule( nullAssertions: nullAssertions!, nativeNullAssertions: true, bootstrapModule: 'main.dart.bootstrap', entrypoint: '/main.dart.js' ), headers: <String, String>{ HttpHeaders.contentTypeHeader: 'text/javascript', }); } if (request.url.path.endsWith('.dart.js')) { final String path = request.url.path.split('.dart.js')[0]; return shelf.Response.ok(webMemoryFS.files['$path.dart.lib.js'], headers: <String, String>{ HttpHeaders.contentTypeHeader: 'text/javascript', }); } if (request.url.path.endsWith('.lib.js.map')) { return shelf.Response.ok(webMemoryFS.sourcemaps[request.url.path], headers: <String, String>{ HttpHeaders.contentTypeHeader: 'text/plain', }); } return shelf.Response.notFound(''); } Future<shelf.Response> _handleStaticArtifact(shelf.Request request) async { if (request.requestedUri.path.contains('require.js')) { return shelf.Response.ok( _requireJs.openRead(), headers: <String, String>{'Content-Type': 'text/javascript'}, ); } else if (request.requestedUri.path.contains('ddc_module_loader.js')) { return shelf.Response.ok( _ddcModuleLoaderJs.openRead(), headers: <String, String>{'Content-Type': 'text/javascript'}, ); } else if (request.requestedUri.path.contains('ahem.ttf')) { return shelf.Response.ok(_ahem.openRead()); } else if (request.requestedUri.path.contains('dart_sdk.js')) { return shelf.Response.ok( _dartSdk.openRead(), headers: <String, String>{'Content-Type': 'text/javascript'}, ); } else if (request.requestedUri.path.contains('dart_sdk.js.map')) { return shelf.Response.ok( _dartSdkSourcemaps.openRead(), headers: <String, String>{'Content-Type': 'text/javascript'}, ); } else if (request.requestedUri.path .contains('dart_stack_trace_mapper.js')) { return shelf.Response.ok( _stackTraceMapper.openRead(), headers: <String, String>{'Content-Type': 'text/javascript'}, ); } else if (request.requestedUri.path.contains('static/dart.js')) { return shelf.Response.ok( _testDartJs.openRead(), headers: <String, String>{'Content-Type': 'text/javascript'}, ); } else if (request.requestedUri.path.contains('host.dart.js')) { return shelf.Response.ok( _testHostDartJs.openRead(), headers: <String, String>{'Content-Type': 'text/javascript'}, ); } else if (request.requestedUri.path.contains('flutter.js')) { return shelf.Response.ok( _flutterJs.openRead(), headers: <String, String>{'Content-Type': 'text/javascript'}, ); } else if (request.requestedUri.path.contains('main.dart.mjs')) { return shelf.Response.ok( _buildDirectory.childFile('main.dart.mjs').openRead(), headers: <String, String>{'Content-Type': 'text/javascript'}, ); } else if (request.requestedUri.path.contains('main.dart.wasm')) { return shelf.Response.ok( _buildDirectory.childFile('main.dart.wasm').openRead(), headers: <String, String>{'Content-Type': 'application/wasm'}, ); } else { return shelf.Response.notFound('Not Found'); } } FutureOr<shelf.Response> _packageFilesHandler(shelf.Request request) async { if (request.requestedUri.pathSegments.first == 'packages') { final Uri? fileUri = buildInfo.packageConfig.resolve(Uri( scheme: 'package', pathSegments: request.requestedUri.pathSegments.skip(1), )); if (fileUri != null) { final String dirname = _fileSystem.path.dirname(fileUri.toFilePath()); final String basename = _fileSystem.path.basename(fileUri.toFilePath()); final shelf.Handler handler = createDirectoryHandler( _fileSystem.directory(dirname), crossOriginIsolated: webRenderer == WebRendererMode.skwasm, ); final shelf.Request modifiedRequest = shelf.Request( request.method, request.requestedUri.replace(path: basename), protocolVersion: request.protocolVersion, headers: request.headers, handlerPath: request.handlerPath, url: request.url.replace(path: basename), encoding: request.encoding, context: request.context, ); return handler(modifiedRequest); } } return shelf.Response.notFound('Not Found'); } Future<shelf.Response> _goldenFileHandler(shelf.Request request) async { if (request.url.path.contains('flutter_goldens')) { final Map<String, Object?> body = json.decode(await request.readAsString()) as Map<String, Object?>; final Uri goldenKey = Uri.parse(body['key']! as String); final Uri testUri = Uri.parse(body['testUri']! as String); final num? width = body['width'] as num?; final num? height = body['height'] as num?; Uint8List bytes; if (body.containsKey('bytes')) { bytes = base64.decode(body['bytes']! as String); } else { // TODO(hterkelsen): Do not use browser screenshots for testing on the // web once we transition off the HTML renderer. See: // https://github.com/flutter/flutter/issues/135700 try { final ChromeTab chromeTab = (await _browserManager!._browser.chromeConnection.getTab((ChromeTab tab) { return tab.url.contains(_browserManager!._browser.url!); }))!; final WipConnection connection = await chromeTab.connect(); final WipResponse response = await connection.sendCommand('Page.captureScreenshot', <String, Object>{ // Clip the screenshot to include only the element. // Prior to taking a screenshot, we are calling `window.render()` in // `_matchers_web.dart` to only render the element on screen. That // will make sure that the element will always be displayed on the // origin of the screen. 'clip': <String, Object>{ 'x': 0.0, 'y': 0.0, 'width': width!.toDouble(), 'height': height!.toDouble(), 'scale': 1.0, }, }); bytes = base64.decode(response.result!['data'] as String); } on WipError catch (ex) { _logger.printError('Caught WIPError: $ex'); return shelf.Response.ok('WIP error: $ex'); } on FormatException catch (ex) { _logger.printError('Caught FormatException: $ex'); return shelf.Response.ok('Caught exception: $ex'); } } final String? errorMessage = await _testGoldenComparator.compareGoldens(testUri, bytes, goldenKey, updateGoldens); return shelf.Response.ok(errorMessage ?? 'true'); } else { return shelf.Response.notFound('Not Found'); } } /// Serves a local build of CanvasKit, replacing the CDN build, which can /// cause test flakiness due to reliance on network. shelf.Response _localCanvasKitHandler(shelf.Request request) { final String fullPath = _fileSystem.path.fromUri(request.url); if (!fullPath.startsWith('canvaskit/')) { return shelf.Response.notFound('Not a CanvasKit file request'); } final String relativePath = fullPath.replaceFirst('canvaskit/', ''); final String extension = _fileSystem.path.extension(relativePath); String contentType; switch (extension) { case '.js': contentType = 'text/javascript'; case '.wasm': contentType = 'application/wasm'; default: final String error = 'Failed to determine Content-Type for "${request.url.path}".'; _logger.printError(error); return shelf.Response.internalServerError(body: error); } final File canvasKitFile = _canvasKitFile(relativePath); return shelf.Response.ok( canvasKitFile.openRead(), headers: <String, Object>{ HttpHeaders.contentTypeHeader: contentType, }, ); } String _makeBuildConfigString() { return useWasm ? ''' { compileTarget: "dart2wasm", renderer: "${webRenderer.name}", mainWasmPath: "main.dart.wasm", jsSupportRuntimePath: "main.dart.mjs", } ''' : ''' { compileTarget: "dartdevc", renderer: "${webRenderer.name}", mainJsPath: "main.dart.browser_test.dart.js", } '''; } // A handler that serves wrapper files used to bootstrap tests. shelf.Response _wrapperHandler(shelf.Request request) { final String path = _fileSystem.path.fromUri(request.url); if (path.endsWith('.html')) { final String test = '${_fileSystem.path.withoutExtension(path)}.dart'; return shelf.Response.ok(''' <!DOCTYPE html> <html> <head> <title>${htmlEscape.convert(test)} Test</title> <script src="flutter.js"></script> <script> _flutter.buildConfig = { builds: [ ${_makeBuildConfigString()} ] } window.testSelector = "$test"; _flutter.loader.load({ config: { canvasKitBaseUrl: "/canvaskit/", } }); </script> </head> </html> ''', headers: <String, String>{ 'Content-Type': 'text/html', if (webRenderer == WebRendererMode.skwasm) ...<String, String>{ 'Cross-Origin-Opener-Policy': 'same-origin', 'Cross-Origin-Embedder-Policy': 'require-corp', } }); } return shelf.Response.notFound('Not found.'); } @override Future<RunnerSuite> load( String path, SuitePlatform platform, SuiteConfiguration suiteConfig, Object message, ) async { if (_closed) { throw StateError('Load called on a closed FlutterWebPlatform'); } final String pathFromTest = _fileSystem.path.relative(path, from: _fileSystem.path.join(_root, 'test')); final Uri suiteUrl = url.resolveUri(_fileSystem.path.toUri('${_fileSystem.path.withoutExtension(pathFromTest)}.html')); final String relativePath = _fileSystem.path.relative(_fileSystem.path.normalize(path), from: _fileSystem.currentDirectory.path); if (_logger.isVerbose) { _logger.printTrace('Loading test suite $relativePath.'); } final PoolResource lockResource = await _suiteLock.request(); final Runtime browser = platform.runtime; try { _browserManager = await _launchBrowser(browser); } on Error catch (_) { await _suiteLock.close(); rethrow; } if (_closed) { throw StateError('Load called on a closed FlutterWebPlatform'); } if (_logger.isVerbose) { _logger.printTrace('Running test suite $relativePath.'); } final RunnerSuite suite = await _browserManager!.load(relativePath, suiteUrl, suiteConfig, message, onDone: () async { await _browserManager!.close(); _browserManager = null; lockResource.release(); if (_logger.isVerbose) { _logger.printTrace('Test suite $relativePath finished.'); } }); if (_closed) { throw StateError('Load called on a closed FlutterWebPlatform'); } return suite; } /// Returns the [BrowserManager] for [runtime], which should be a browser. /// /// If no browser manager is running yet, starts one. Future<BrowserManager> _launchBrowser(Runtime browser) { if (_browserManager != null) { throw StateError('Another browser is currently running.'); } final Completer<WebSocketChannel> completer = Completer<WebSocketChannel>.sync(); final String path = _webSocketHandler.create(webSocketHandler(completer.complete)); final Uri webSocketUrl = url.replace(scheme: 'ws').resolve(path); final Uri hostUrl = url .resolve('static/index.html') .replace(queryParameters: <String, String>{ 'managerUrl': webSocketUrl.toString(), 'debug': _config.pauseAfterLoad.toString(), }); _logger.printTrace('Serving tests at $hostUrl'); return BrowserManager.start( _chromiumLauncher, browser, hostUrl, completer.future, headless: !_config.pauseAfterLoad, ); } @override Future<void> closeEphemeral() async { if (_browserManager != null) { await _browserManager!.close(); } } @override Future<void> close() => _closeMemo.runOnce(() async { await Future.wait<void>(<Future<dynamic>>[ if (_browserManager != null) _browserManager!.close(), _server.close(), _testGoldenComparator.close(), ]); }); } class OneOffHandler { /// A map from URL paths to handlers. final Map<String, shelf.Handler> _handlers = <String, shelf.Handler>{}; /// The counter of handlers that have been activated. int _counter = 0; /// The actual [shelf.Handler] that dispatches requests. shelf.Handler get handler => _onRequest; /// Creates a new one-off handler that forwards to [handler]. /// /// Returns a string that's the URL path for hitting this handler, relative to /// the URL for the one-off handler itself. /// /// [handler] will be unmounted as soon as it receives a request. String create(shelf.Handler handler) { final String path = _counter.toString(); _handlers[path] = handler; _counter++; return path; } /// Dispatches [request] to the appropriate handler. FutureOr<shelf.Response> _onRequest(shelf.Request request) { final List<String> components = request.url.path.split('/'); if (components.isEmpty) { return shelf.Response.notFound(null); } final String path = components.removeAt(0); final FutureOr<shelf.Response> Function(shelf.Request)? handler = _handlers.remove(path); if (handler == null) { return shelf.Response.notFound(null); } return handler(request.change(path: path)); } } class BrowserManager { /// Creates a new BrowserManager that communicates with [browser] over /// [webSocket]. BrowserManager._(this._browser, this._runtime, WebSocketChannel webSocket) { // The duration should be short enough that the debugging console is open as // soon as the user is done setting breakpoints, but long enough that a test // doing a lot of synchronous work doesn't trigger a false positive. // // Start this canceled because we don't want it to start ticking until we // get some response from the iframe. _timer = RestartableTimer(const Duration(seconds: 3), () { for (final RunnerSuiteController controller in _controllers) { controller.setDebugging(true); } }) ..cancel(); // Whenever we get a message, no matter which child channel it's for, we know // the browser is still running code which means the user isn't debugging. _channel = MultiChannel<dynamic>( webSocket.cast<String>().transform(jsonDocument).changeStream((Stream<Object?> stream) { return stream.map((Object? message) { if (!_closed) { _timer.reset(); } for (final RunnerSuiteController controller in _controllers) { controller.setDebugging(false); } return message; }); }), ); _environment = _loadBrowserEnvironment(); _channel.stream.listen(_onMessage, onDone: close); } /// The browser instance that this is connected to via [_channel]. final Chromium _browser; final Runtime _runtime; /// The channel used to communicate with the browser. /// /// This is connected to a page running `static/host.dart`. late MultiChannel<dynamic> _channel; /// The ID of the next suite to be loaded. /// /// This is used to ensure that the suites can be referred to consistently /// across the client and server. int _suiteID = 0; /// Whether the channel to the browser has closed. bool _closed = false; /// The completer for [_BrowserEnvironment.displayPause]. /// /// This will be `null` as long as the browser isn't displaying a pause /// screen. CancelableCompleter<dynamic>? _pauseCompleter; /// The controller for [_BrowserEnvironment.onRestart]. final StreamController<dynamic> _onRestartController = StreamController<dynamic>.broadcast(); /// The environment to attach to each suite. late Future<_BrowserEnvironment> _environment; /// Controllers for every suite in this browser. /// /// These are used to mark suites as debugging or not based on the browser's /// pings. final Set<RunnerSuiteController> _controllers = <RunnerSuiteController>{}; // A timer that's reset whenever we receive a message from the browser. // // Because the browser stops running code when the user is actively debugging, // this lets us detect whether they're debugging reasonably accurately. late RestartableTimer _timer; final AsyncMemoizer<dynamic> _closeMemoizer = AsyncMemoizer<dynamic>(); /// Starts the browser identified by [runtime] and has it connect to [url]. /// /// [url] should serve a page that establishes a WebSocket connection with /// this process. That connection, once established, should be emitted via /// [future]. If [debug] is true, starts the browser in debug mode, with its /// debugger interfaces on and detected. /// /// The browser will start in headless mode if [headless] is true. /// /// Add arbitrary browser flags via [webBrowserFlags]. /// /// The [settings] indicate how to invoke this browser's executable. /// /// Returns the browser manager, or throws an [ApplicationException] if a /// connection fails to be established. static Future<BrowserManager> start( ChromiumLauncher chromiumLauncher, Runtime runtime, Uri url, Future<WebSocketChannel> future, { bool debug = false, bool headless = true, List<String> webBrowserFlags = const <String>[], }) async { final Chromium chrome = await chromiumLauncher.launch( url.toString(), headless: headless, webBrowserFlags: webBrowserFlags, ); final Completer<BrowserManager> completer = Completer<BrowserManager>(); unawaited(chrome.onExit.then<Object?>( (int? browserExitCode) { throwToolExit('${runtime.name} exited with code $browserExitCode before connecting.'); }, ).then( (Object? obj) => obj, onError: (Object error, StackTrace stackTrace) { if (!completer.isCompleted) { completer.completeError(error, stackTrace); } return null; }, )); unawaited(future.then( (WebSocketChannel webSocket) { if (completer.isCompleted) { return; } completer.complete(BrowserManager._(chrome, runtime, webSocket)); }, onError: (Object error, StackTrace stackTrace) { chrome.close(); if (!completer.isCompleted) { completer.completeError(error, stackTrace); } }, )); return completer.future; } /// Loads [_BrowserEnvironment]. Future<_BrowserEnvironment> _loadBrowserEnvironment() async { return _BrowserEnvironment( this, null, _browser.chromeConnection.url, _onRestartController.stream); } /// Tells the browser to load a test suite from the URL [url]. /// /// [url] should be an HTML page with a reference to the JS-compiled test /// suite. [path] is the path of the original test suite file, which is used /// for reporting. [suiteConfig] is the configuration for the test suite. /// /// If [mapper] is passed, it's used to map stack traces for errors coming /// from this test suite. Future<RunnerSuite> load( String path, Uri url, SuiteConfiguration suiteConfig, Object message, { Future<void> Function()? onDone, } ) async { url = url.replace(fragment: Uri.encodeFull(jsonEncode(<String, Object>{ 'metadata': suiteConfig.metadata.serialize(), 'browser': _runtime.identifier, }))); final int suiteID = _suiteID++; RunnerSuiteController? controller; void closeIframe() { if (_closed) { return; } _controllers.remove(controller); _channel.sink .add(<String, Object>{'command': 'closeSuite', 'id': suiteID}); } // The virtual channel will be closed when the suite is closed, in which // case we should unload the iframe. final VirtualChannel<dynamic> virtualChannel = _channel.virtualChannel(); final int suiteChannelID = virtualChannel.id; final StreamChannel<dynamic> suiteChannel = virtualChannel.transformStream( StreamTransformer<dynamic, dynamic>.fromHandlers(handleDone: (EventSink<dynamic> sink) { closeIframe(); sink.close(); onDone!(); }), ); _channel.sink.add(<String, Object>{ 'command': 'loadSuite', 'url': url.toString(), 'id': suiteID, 'channel': suiteChannelID, }); try { controller = deserializeSuite(path, SuitePlatform(Runtime.chrome), suiteConfig, await _environment, suiteChannel, message); _controllers.add(controller); return await controller.suite; // Not limiting to catching Exception because the exception is rethrown. } catch (_) { // ignore: avoid_catches_without_on_clauses closeIframe(); rethrow; } } /// An implementation of [Environment.displayPause]. CancelableOperation<dynamic> _displayPause() { if (_pauseCompleter != null) { return _pauseCompleter!.operation; } _pauseCompleter = CancelableCompleter<dynamic>(onCancel: () { _channel.sink.add(<String, String>{'command': 'resume'}); _pauseCompleter = null; }); _pauseCompleter!.operation.value.whenComplete(() { _pauseCompleter = null; }); _channel.sink.add(<String, String>{'command': 'displayPause'}); return _pauseCompleter!.operation; } /// The callback for handling messages received from the host page. void _onMessage(dynamic message) { assert(message is Map<String, dynamic>); if (message is Map<String, dynamic>) { switch (message['command'] as String?) { case 'ping': break; case 'restart': _onRestartController.add(null); case 'resume': if (_pauseCompleter != null) { _pauseCompleter!.complete(); } default: // Unreachable. assert(false); break; } } } /// Closes the manager and releases any resources it owns, including closing /// the browser. Future<dynamic> close() { return _closeMemoizer.runOnce(() { _closed = true; _timer.cancel(); if (_pauseCompleter != null) { _pauseCompleter!.complete(); } _pauseCompleter = null; _controllers.clear(); return _browser.close(); }); } } /// An implementation of [Environment] for the browser. /// /// All methods forward directly to [BrowserManager]. class _BrowserEnvironment implements Environment { _BrowserEnvironment( this._manager, this.observatoryUrl, this.remoteDebuggerUrl, this.onRestart, ); final BrowserManager _manager; @override final bool supportsDebugging = true; @override final Uri? observatoryUrl; @override final Uri remoteDebuggerUrl; @override final Stream<dynamic> onRestart; @override CancelableOperation<dynamic> displayPause() => _manager._displayPause(); }
flutter/packages/flutter_tools/lib/src/test/flutter_web_platform.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/test/flutter_web_platform.dart", "repo_id": "flutter", "token_count": 13009 }
372
// Copyright 2014 The Flutter 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:meta/meta.dart'; import 'package:process/process.dart'; import '../base/file_system.dart'; import '../base/io.dart'; import '../base/platform.dart'; import '../base/utils.dart'; import '../base/version.dart'; import '../convert.dart'; import '../doctor_validator.dart'; const String extensionIdentifier = 'Dart-Code.flutter'; const String extensionMarketplaceUrl = 'https://marketplace.visualstudio.com/items?itemName=$extensionIdentifier'; class VsCode { VsCode._(this.directory, this.extensionDirectory, { this.version, this.edition, required FileSystem fileSystem}) { if (!fileSystem.isDirectorySync(directory)) { _validationMessages.add(ValidationMessage.error('VS Code not found at $directory')); return; } else { _validationMessages.add(ValidationMessage('VS Code at $directory')); } // If the extensions directory doesn't exist at all, the listSync() // below will fail, so just bail out early. const ValidationMessage notInstalledMessage = ValidationMessage( 'Flutter extension can be installed from:', contextUrl: extensionMarketplaceUrl, ); if (!fileSystem.isDirectorySync(extensionDirectory)) { _validationMessages.add(notInstalledMessage); return; } // Check for presence of extension. final String extensionIdentifierLower = extensionIdentifier.toLowerCase(); final Iterable<FileSystemEntity> extensionDirs = fileSystem .directory(extensionDirectory) .listSync() .whereType<Directory>() .where((Directory d) => d.basename.toLowerCase().startsWith(extensionIdentifierLower)); if (extensionDirs.isNotEmpty) { final FileSystemEntity extensionDir = extensionDirs.first; _extensionVersion = Version.parse( extensionDir.basename.substring('$extensionIdentifier-'.length)); _validationMessages.add(ValidationMessage('Flutter extension version $_extensionVersion')); } else { _validationMessages.add(notInstalledMessage); } } factory VsCode.fromDirectory( String installPath, String extensionDirectory, { String? edition, required FileSystem fileSystem, }) { final String packageJsonPath = fileSystem.path.join(installPath, 'resources', 'app', 'package.json'); final String? versionString = _getVersionFromPackageJson(packageJsonPath, fileSystem); Version? version; if (versionString != null) { version = Version.parse(versionString); } return VsCode._(installPath, extensionDirectory, version: version, edition: edition, fileSystem: fileSystem); } final String directory; final String extensionDirectory; final Version? version; final String? edition; Version? _extensionVersion; final List<ValidationMessage> _validationMessages = <ValidationMessage>[]; String get productName => 'VS Code${edition != null ? ', $edition' : ''}'; Iterable<ValidationMessage> get validationMessages => _validationMessages; static List<VsCode> allInstalled( FileSystem fileSystem, Platform platform, ProcessManager processManager, ) { if (platform.isMacOS) { return _installedMacOS(fileSystem, platform, processManager); } if (platform.isWindows) { return _installedWindows(fileSystem, platform); } if (platform.isLinux) { return _installedLinux(fileSystem, platform); } // VS Code isn't supported on the other platforms. return <VsCode>[]; } // macOS: // /Applications/Visual Studio Code.app/Contents/ // /Applications/Visual Studio Code - Insiders.app/Contents/ // $HOME/Applications/Visual Studio Code.app/Contents/ // $HOME/Applications/Visual Studio Code - Insiders.app/Contents/ // macOS Extensions: // $HOME/.vscode/extensions // $HOME/.vscode-insiders/extensions static List<VsCode> _installedMacOS(FileSystem fileSystem, Platform platform, ProcessManager processManager) { final String? homeDirPath = FileSystemUtils(fileSystem: fileSystem, platform: platform).homeDirPath; String vsCodeSpotlightResult = ''; String vsCodeInsiderSpotlightResult = ''; // Query Spotlight for unexpected installation locations. try { final ProcessResult vsCodeSpotlightQueryResult = processManager.runSync(<String>[ 'mdfind', 'kMDItemCFBundleIdentifier="com.microsoft.VSCode"', ]); vsCodeSpotlightResult = vsCodeSpotlightQueryResult.stdout as String; final ProcessResult vsCodeInsidersSpotlightQueryResult = processManager.runSync(<String>[ 'mdfind', 'kMDItemCFBundleIdentifier="com.microsoft.VSCodeInsiders"', ]); vsCodeInsiderSpotlightResult = vsCodeInsidersSpotlightQueryResult.stdout as String; } on ProcessException { // The Spotlight query is a nice-to-have, continue checking known installation locations. } // De-duplicated set. return _findInstalled(<VsCodeInstallLocation>{ VsCodeInstallLocation( fileSystem.path.join('/Applications', 'Visual Studio Code.app', 'Contents'), '.vscode', ), if (homeDirPath != null) VsCodeInstallLocation( fileSystem.path.join( homeDirPath, 'Applications', 'Visual Studio Code.app', 'Contents', ), '.vscode', ), VsCodeInstallLocation( fileSystem.path.join('/Applications', 'Visual Studio Code - Insiders.app', 'Contents'), '.vscode-insiders', ), if (homeDirPath != null) VsCodeInstallLocation( fileSystem.path.join( homeDirPath, 'Applications', 'Visual Studio Code - Insiders.app', 'Contents', ), '.vscode-insiders', ), for (final String vsCodePath in LineSplitter.split(vsCodeSpotlightResult)) VsCodeInstallLocation( fileSystem.path.join(vsCodePath, 'Contents'), '.vscode', ), for (final String vsCodeInsidersPath in LineSplitter.split(vsCodeInsiderSpotlightResult)) VsCodeInstallLocation( fileSystem.path.join(vsCodeInsidersPath, 'Contents'), '.vscode-insiders', ), }, fileSystem, platform); } // Windows: // $programfiles(x86)\Microsoft VS Code // $programfiles(x86)\Microsoft VS Code Insiders // User install: // $localappdata\Programs\Microsoft VS Code // $localappdata\Programs\Microsoft VS Code Insiders // TODO(dantup): Confirm these are correct for 64bit // $programfiles\Microsoft VS Code // $programfiles\Microsoft VS Code Insiders // Windows Extensions: // $HOME/.vscode/extensions // $HOME/.vscode-insiders/extensions static List<VsCode> _installedWindows( FileSystem fileSystem, Platform platform, ) { final String? progFiles86 = platform.environment['programfiles(x86)']; final String? progFiles = platform.environment['programfiles']; final String? localAppData = platform.environment['localappdata']; final List<VsCodeInstallLocation> searchLocations = <VsCodeInstallLocation>[ if (localAppData != null) VsCodeInstallLocation( fileSystem.path.join(localAppData, r'Programs\Microsoft VS Code'), '.vscode', ), if (progFiles86 != null) ...<VsCodeInstallLocation>[ VsCodeInstallLocation( fileSystem.path.join(progFiles86, 'Microsoft VS Code'), '.vscode', edition: '32-bit edition', ), VsCodeInstallLocation( fileSystem.path.join(progFiles86, 'Microsoft VS Code Insiders'), '.vscode-insiders', edition: '32-bit edition', ), ], if (progFiles != null) ...<VsCodeInstallLocation>[ VsCodeInstallLocation( fileSystem.path.join(progFiles, 'Microsoft VS Code'), '.vscode', edition: '64-bit edition', ), VsCodeInstallLocation( fileSystem.path.join(progFiles, 'Microsoft VS Code Insiders'), '.vscode-insiders', edition: '64-bit edition', ), ], if (localAppData != null) VsCodeInstallLocation( fileSystem.path.join(localAppData, r'Programs\Microsoft VS Code Insiders'), '.vscode-insiders', ), ]; return _findInstalled(searchLocations, fileSystem, platform); } // Linux: // Deb: // /usr/share/code/bin/code // /usr/share/code-insiders/bin/code-insiders // Snap: // /snap/code/current/usr/share/code // Flatpak: // /var/lib/flatpak/app/com.visualstudio.code/x86_64/stable/active/files/extra/vscode // /var/lib/flatpak/app/com.visualstudio.code.insiders/x86_64/beta/active/files/extra/vscode-insiders // Linux Extensions: // Deb: // $HOME/.vscode/extensions // Snap: // $HOME/.vscode/extensions // Flatpak: // $HOME/.var/app/com.visualstudio.code/data/vscode/extensions // $HOME/.var/app/com.visualstudio.code.insiders/data/vscode-insiders/extensions static List<VsCode> _installedLinux(FileSystem fileSystem, Platform platform) { return _findInstalled(<VsCodeInstallLocation>[ const VsCodeInstallLocation('/usr/share/code', '.vscode'), const VsCodeInstallLocation('/snap/code/current/usr/share/code', '.vscode'), const VsCodeInstallLocation( '/var/lib/flatpak/app/com.visualstudio.code/x86_64/stable/active/files/extra/vscode', '.var/app/com.visualstudio.code/data/vscode', ), const VsCodeInstallLocation( '/usr/share/code-insiders', '.vscode-insiders', ), const VsCodeInstallLocation( '/snap/code-insiders/current/usr/share/code-insiders', '.vscode-insiders', ), const VsCodeInstallLocation( '/var/lib/flatpak/app/com.visualstudio.code.insiders/x86_64/beta/active/files/extra/vscode-insiders', '.var/app/com.visualstudio.code.insiders/data/vscode-insiders', ), ], fileSystem, platform); } static List<VsCode> _findInstalled( Iterable<VsCodeInstallLocation> allLocations, FileSystem fileSystem, Platform platform, ) { final List<VsCode> results = <VsCode>[]; for (final VsCodeInstallLocation searchLocation in allLocations) { final String? homeDirPath = FileSystemUtils(fileSystem: fileSystem, platform: platform).homeDirPath; if (homeDirPath != null && fileSystem.isDirectorySync(searchLocation.installPath)) { final String extensionDirectory = fileSystem.path.join( homeDirPath, searchLocation.extensionsFolder, 'extensions', ); results.add(VsCode.fromDirectory( searchLocation.installPath, extensionDirectory, edition: searchLocation.edition, fileSystem: fileSystem, )); } } return results; } @override String toString() => 'VS Code ($version)${_extensionVersion != null ? ', Flutter ($_extensionVersion)' : ''}'; static String? _getVersionFromPackageJson(String packageJsonPath, FileSystem fileSystem) { if (!fileSystem.isFileSync(packageJsonPath)) { return null; } final String jsonString = fileSystem.file(packageJsonPath).readAsStringSync(); try { final Map<String, dynamic>? jsonObject = castStringKeyedMap(json.decode(jsonString)); if (jsonObject?.containsKey('version') ?? false) { return jsonObject!['version'] as String; } } on FormatException { return null; } return null; } } @immutable @visibleForTesting class VsCodeInstallLocation { const VsCodeInstallLocation( this.installPath, this.extensionsFolder, { this.edition, }); final String installPath; final String extensionsFolder; final String? edition; @override bool operator ==(Object other) { return other is VsCodeInstallLocation && other.installPath == installPath && other.extensionsFolder == extensionsFolder && other.edition == edition; } @override // Lowest bit is for isInsiders boolean. int get hashCode => Object.hash(installPath, extensionsFolder, edition); }
flutter/packages/flutter_tools/lib/src/vscode/vscode.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/vscode/vscode.dart", "repo_id": "flutter", "token_count": 4676 }
373
// Copyright 2014 The Flutter 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:html/dom.dart'; import 'package:html/parser.dart'; import 'base/common.dart'; import 'base/file_system.dart'; /// Placeholder for base href const String kBaseHrefPlaceholder = r'$FLUTTER_BASE_HREF'; class WebTemplateWarning { WebTemplateWarning( this.warningText, this.lineNumber, ); final String warningText; final int lineNumber; } /// Utility class for parsing and performing operations on the contents of the /// index.html file. /// /// For example, to parse the base href from the index.html file: /// /// ```dart /// String parseBaseHref(File indexHtmlFile) { /// final IndexHtml indexHtml = IndexHtml(indexHtmlFile.readAsStringSync()); /// return indexHtml.getBaseHref(); /// } /// ``` class WebTemplate { WebTemplate(this._content); String get content => _content; String _content; Document _getDocument() => parse(_content); /// Parses the base href from the index.html file. String getBaseHref() { final Element? baseElement = _getDocument().querySelector('base'); final String? baseHref = baseElement?.attributes == null ? null : baseElement!.attributes['href']; if (baseHref == null || baseHref == kBaseHrefPlaceholder) { return ''; } if (!baseHref.startsWith('/')) { throw ToolExit( 'Error: The base href in "web/index.html" must be absolute (i.e. start ' 'with a "/"), but found: `${baseElement!.outerHtml}`.\n' '$_kBasePathExample', ); } if (!baseHref.endsWith('/')) { throw ToolExit( 'Error: The base href in "web/index.html" must end with a "/", but found: `${baseElement!.outerHtml}`.\n' '$_kBasePathExample', ); } return stripLeadingSlash(stripTrailingSlash(baseHref)); } List<WebTemplateWarning> getWarnings() { return <WebTemplateWarning>[ ..._getWarningsForPattern( RegExp('(const|var) serviceWorkerVersion = null'), 'Local variable for "serviceWorkerVersion" is deprecated. Use "{{flutter_service_worker_version}}" template token instead.', ), ..._getWarningsForPattern( "navigator.serviceWorker.register('flutter_service_worker.js')", 'Manual service worker registration deprecated. Use flutter.js service worker bootstrapping instead.', ), ..._getWarningsForPattern( '_flutter.loader.loadEntrypoint(', '"FlutterLoader.loadEntrypoint" is deprecated. Use "FlutterLoader.load" instead.', ), ]; } List<WebTemplateWarning> _getWarningsForPattern(Pattern pattern, String warningText) { return <WebTemplateWarning>[ for (final Match match in pattern.allMatches(_content)) _getWarningForMatch(match, warningText) ]; } WebTemplateWarning _getWarningForMatch(Match match, String warningText) { final int lineCount = RegExp(r'(\r\n|\r|\n)').allMatches(_content.substring(0, match.start)).length; return WebTemplateWarning(warningText, lineCount + 1); } /// Applies substitutions to the content of the index.html file. void applySubstitutions({ required String baseHref, required String? serviceWorkerVersion, required File flutterJsFile, String? buildConfig, String? flutterBootstrapJs, }) { if (_content.contains(kBaseHrefPlaceholder)) { _content = _content.replaceAll(kBaseHrefPlaceholder, baseHref); } if (serviceWorkerVersion != null) { _content = _content .replaceFirst( // Support older `var` syntax as well as new `const` syntax RegExp('(const|var) serviceWorkerVersion = null'), 'const serviceWorkerVersion = "$serviceWorkerVersion"', ) // This is for legacy index.html that still uses the old service // worker loading mechanism. .replaceFirst( "navigator.serviceWorker.register('flutter_service_worker.js')", "navigator.serviceWorker.register('flutter_service_worker.js?v=$serviceWorkerVersion')", ); } _content = _content.replaceAll( '{{flutter_service_worker_version}}', serviceWorkerVersion != null ? '"$serviceWorkerVersion"' : 'null', ); if (buildConfig != null) { _content = _content.replaceAll( '{{flutter_build_config}}', buildConfig, ); } if (_content.contains('{{flutter_js}}')) { _content = _content.replaceAll( '{{flutter_js}}', flutterJsFile.readAsStringSync(), ); } if (flutterBootstrapJs != null) { _content = _content.replaceAll( '{{flutter_bootstrap_js}}', flutterBootstrapJs, ); } } } /// Strips the leading slash from a path. String stripLeadingSlash(String path) { while (path.startsWith('/')) { path = path.substring(1); } return path; } /// Strips the trailing slash from a path. String stripTrailingSlash(String path) { while (path.endsWith('/')) { path = path.substring(0, path.length - 1); } return path; } const String _kBasePathExample = ''' For example, to serve from the root use: <base href="/"> To serve from a subpath "foo" (i.e. http://localhost:8080/foo/ instead of http://localhost:8080/) use: <base href="/foo/"> For more information, see: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base ''';
flutter/packages/flutter_tools/lib/src/web_template.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/web_template.dart", "repo_id": "flutter", "token_count": 2057 }
374
<!DOCTYPE HTML> <!-- Copyright 2014 The Flutter Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. --> <html> <head> <title>Flutter Test Browser Host</title> <style> /* Configure so that the test application takes up the whole screen */ body { margin: 0; padding: 0; position: fixed; top: 0px; left: 0px; overflow: hidden; } iframe { border: none; width: 2400px; height: 1800px; position: fixed; top: 0px; left: 0px; overflow: hidden; } </style> </head> <body> <div id="dark"></div> <script src="host.dart.js"></script> </body> </html>
flutter/packages/flutter_tools/static/index.html/0
{ "file_path": "flutter/packages/flutter_tools/static/index.html", "repo_id": "flutter", "token_count": 299 }
375
import Cocoa import FlutterMacOS @main class AppDelegate: FlutterAppDelegate { override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { return true } }
flutter/packages/flutter_tools/templates/app_shared/macos.tmpl/Runner/AppDelegate.swift/0
{ "file_path": "flutter/packages/flutter_tools/templates/app_shared/macos.tmpl/Runner/AppDelegate.swift", "repo_id": "flutter", "token_count": 61 }
376
<manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:dist="http://schemas.android.com/apk/distribution" package="{{androidIdentifier}}.{{componentName}}"> <dist:module dist:instant="false" dist:title="@string/{{componentName}}Name"> <dist:delivery> <dist:on-demand /> </dist:delivery> <dist:fusing dist:include="true" /> </dist:module> </manifest>
flutter/packages/flutter_tools/templates/module/android/deferred_component/src/main/AndroidManifest.xml.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/templates/module/android/deferred_component/src/main/AndroidManifest.xml.tmpl", "repo_id": "flutter", "token_count": 193 }
377
def scriptFile = getClass().protectionDomain.codeSource.location.toURI() def flutterProjectRoot = new File(scriptFile).parentFile.parentFile gradle.include ":flutter" gradle.project(":flutter").projectDir = new File(flutterProjectRoot, ".android/Flutter") def localPropertiesFile = new File(flutterProjectRoot, ".android/local.properties") def properties = new Properties() assert localPropertiesFile.exists(), "❗️The Flutter module doesn't have a `$localPropertiesFile` file." + "\nYou must run `flutter pub get` in `$flutterProjectRoot`." localPropertiesFile.withReader("UTF-8") { reader -> properties.load(reader) } def flutterSdkPath = properties.getProperty("flutter.sdk") assert flutterSdkPath != null, "flutter.sdk not set in local.properties" gradle.apply from: "$flutterSdkPath/packages/flutter_tools/gradle/module_plugin_loader.gradle"
flutter/packages/flutter_tools/templates/module/android/library_new_embedding/include_flutter.groovy.copy.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/templates/module/android/library_new_embedding/include_flutter.groovy.copy.tmpl", "repo_id": "flutter", "token_count": 294 }
378
#include "Flutter.xcconfig"
flutter/packages/flutter_tools/templates/module/ios/host_app_ephemeral/Config.tmpl/Release.xcconfig/0
{ "file_path": "flutter/packages/flutter_tools/templates/module/ios/host_app_ephemeral/Config.tmpl/Release.xcconfig", "repo_id": "flutter", "token_count": 12 }
379
## 0.0.1 * TODO: Describe initial release.
flutter/packages/flutter_tools/templates/package/CHANGELOG.md.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/templates/package/CHANGELOG.md.tmpl", "repo_id": "flutter", "token_count": 18 }
380
import 'dart:async'; import 'dart:isolate'; import '{{projectName}}_bindings_generated.dart' as bindings; /// A very short-lived native function. /// /// For very short-lived functions, it is fine to call them on the main isolate. /// They will block the Dart execution while running the native function, so /// only do this for native functions which are guaranteed to be short-lived. int sum(int a, int b) => bindings.sum(a, b); /// A longer lived native function, which occupies the thread calling it. /// /// Do not call these kind of native functions in the main isolate. They will /// block Dart execution. This will cause dropped frames in Flutter applications. /// Instead, call these native functions on a separate isolate. /// /// Modify this to suit your own use case. Example use cases: /// /// 1. Reuse a single isolate for various different kinds of requests. /// 2. Use multiple helper isolates for parallel execution. Future<int> sumAsync(int a, int b) async { final SendPort helperIsolateSendPort = await _helperIsolateSendPort; final int requestId = _nextSumRequestId++; final _SumRequest request = _SumRequest(requestId, a, b); final Completer<int> completer = Completer<int>(); _sumRequests[requestId] = completer; helperIsolateSendPort.send(request); return completer.future; } /// A request to compute `sum`. /// /// Typically sent from one isolate to another. class _SumRequest { final int id; final int a; final int b; const _SumRequest(this.id, this.a, this.b); } /// A response with the result of `sum`. /// /// Typically sent from one isolate to another. class _SumResponse { final int id; final int result; const _SumResponse(this.id, this.result); } /// Counter to identify [_SumRequest]s and [_SumResponse]s. int _nextSumRequestId = 0; /// Mapping from [_SumRequest] `id`s to the completers corresponding to the correct future of the pending request. final Map<int, Completer<int>> _sumRequests = <int, Completer<int>>{}; /// The SendPort belonging to the helper isolate. Future<SendPort> _helperIsolateSendPort = () async { // The helper isolate is going to send us back a SendPort, which we want to // wait for. final Completer<SendPort> completer = Completer<SendPort>(); // Receive port on the main isolate to receive messages from the helper. // We receive two types of messages: // 1. A port to send messages on. // 2. Responses to requests we sent. final ReceivePort receivePort = ReceivePort() ..listen((dynamic data) { if (data is SendPort) { // The helper isolate sent us the port on which we can sent it requests. completer.complete(data); return; } if (data is _SumResponse) { // The helper isolate sent us a response to a request we sent. final Completer<int> completer = _sumRequests[data.id]!; _sumRequests.remove(data.id); completer.complete(data.result); return; } throw UnsupportedError('Unsupported message type: ${data.runtimeType}'); }); // Start the helper isolate. await Isolate.spawn((SendPort sendPort) async { final ReceivePort helperReceivePort = ReceivePort() ..listen((dynamic data) { // On the helper isolate listen to requests and respond to them. if (data is _SumRequest) { final int result = bindings.sum_long_running(data.a, data.b); final _SumResponse response = _SumResponse(data.id, result); sendPort.send(response); return; } throw UnsupportedError('Unsupported message type: ${data.runtimeType}'); }); // Send the port to the main isolate on which we can receive requests. sendPort.send(helperReceivePort.sendPort); }, receivePort.sendPort); // Wait until the helper isolate has sent us back the SendPort on which we // can start sending requests. return completer.future; }();
flutter/packages/flutter_tools/templates/package_ffi/lib/projectName.dart.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/templates/package_ffi/lib/projectName.dart.tmpl", "repo_id": "flutter", "token_count": 1243 }
381
rootProject.name = '{{projectName}}'
flutter/packages/flutter_tools/templates/plugin/android.tmpl/settings.gradle.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/templates/plugin/android.tmpl/settings.gradle.tmpl", "repo_id": "flutter", "token_count": 12 }
382
# The Flutter tooling requires that developers have a version of Visual Studio # installed that includes CMake 3.14 or later. You should not increase this # version, as doing so will cause the plugin to fail to compile for some # customers of the plugin. cmake_minimum_required(VERSION 3.14) # Project-level configuration. set(PROJECT_NAME "{{projectName}}") project(${PROJECT_NAME} LANGUAGES CXX) # Explicitly opt in to modern CMake behaviors to avoid warnings with recent # versions of CMake. cmake_policy(VERSION 3.14...3.25) # This value is used when generating builds using this plugin, so it must # not be changed set(PLUGIN_NAME "{{projectName}}_plugin") # Any new source files that you add to the plugin should be added here. list(APPEND PLUGIN_SOURCES "{{pluginClassSnakeCase}}.cpp" "{{pluginClassSnakeCase}}.h" ) # Define the plugin library target. Its name must not be changed (see comment # on PLUGIN_NAME above). add_library(${PLUGIN_NAME} SHARED "include/{{projectName}}/{{pluginClassSnakeCase}}_c_api.h" "{{pluginClassSnakeCase}}_c_api.cpp" ${PLUGIN_SOURCES} ) # Apply a standard set of build settings that are configured in the # application-level CMakeLists.txt. This can be removed for plugins that want # full control over build settings. apply_standard_settings(${PLUGIN_NAME}) # Symbols are hidden by default to reduce the chance of accidental conflicts # between plugins. This should not be removed; any symbols that should be # exported should be explicitly exported with the FLUTTER_PLUGIN_EXPORT macro. set_target_properties(${PLUGIN_NAME} PROPERTIES CXX_VISIBILITY_PRESET hidden) target_compile_definitions(${PLUGIN_NAME} PRIVATE FLUTTER_PLUGIN_IMPL) # Source include directories and library dependencies. Add any plugin-specific # dependencies here. target_include_directories(${PLUGIN_NAME} INTERFACE "${CMAKE_CURRENT_SOURCE_DIR}/include") target_link_libraries(${PLUGIN_NAME} PRIVATE flutter flutter_wrapper_plugin) # List of absolute paths to libraries that should be bundled with the plugin. # This list could contain prebuilt libraries, or libraries created by an # external build triggered from this build file. set({{projectName}}_bundled_libraries "" PARENT_SCOPE ) # === Tests === # These unit tests can be run from a terminal after building the example, or # from Visual Studio after opening the generated solution file. # Only enable test builds when building the example (which sets this variable) # so that plugin clients aren't building the tests. if (${include_${PROJECT_NAME}_tests}) set(TEST_RUNNER "${PROJECT_NAME}_test") enable_testing() # Add the Google Test dependency. include(FetchContent) FetchContent_Declare( googletest URL https://github.com/google/googletest/archive/release-1.11.0.zip ) # Prevent overriding the parent project's compiler/linker settings set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) # Disable install commands for gtest so it doesn't end up in the bundle. set(INSTALL_GTEST OFF CACHE BOOL "Disable installation of googletest" FORCE) FetchContent_MakeAvailable(googletest) # The plugin's C API is not very useful for unit testing, so build the sources # directly into the test binary rather than using the DLL. add_executable(${TEST_RUNNER} test/{{pluginClassSnakeCase}}_test.cpp ${PLUGIN_SOURCES} ) apply_standard_settings(${TEST_RUNNER}) target_include_directories(${TEST_RUNNER} PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}") target_link_libraries(${TEST_RUNNER} PRIVATE flutter_wrapper_plugin) target_link_libraries(${TEST_RUNNER} PRIVATE gtest_main gmock) # flutter_wrapper_plugin has link dependencies on the Flutter DLL. add_custom_command(TARGET ${TEST_RUNNER} POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different "${FLUTTER_LIBRARY}" $<TARGET_FILE_DIR:${TEST_RUNNER}> ) # Enable automatic test discovery. include(GoogleTest) gtest_discover_tests(${TEST_RUNNER}) endif()
flutter/packages/flutter_tools/templates/plugin/windows.tmpl/CMakeLists.txt.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/templates/plugin/windows.tmpl/CMakeLists.txt.tmpl", "repo_id": "flutter", "token_count": 1215 }
383
// Relative import to be able to reuse the C sources. // See the comment in ../{{projectName}}.podspec for more information. #include "../../src/{{projectName}}.c"
flutter/packages/flutter_tools/templates/plugin_ffi/ios.tmpl/Classes/projectName.c.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/templates/plugin_ffi/ios.tmpl/Classes/projectName.c.tmpl", "repo_id": "flutter", "token_count": 47 }
384
rootProject.name = '{{projectName}}'
flutter/packages/flutter_tools/templates/plugin_shared/android.tmpl/settings.gradle.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/templates/plugin_shared/android.tmpl/settings.gradle.tmpl", "repo_id": "flutter", "token_count": 12 }
385
// This is an example Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility in the flutter_test package. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. // // Visit https://flutter.dev/docs/cookbook/testing/widget/introduction for // more information about Widget testing. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { group('MyWidget', () { testWidgets('should display a string of text', (WidgetTester tester) async { // Define a Widget const myWidget = MaterialApp( home: Scaffold( body: Text('Hello'), ), ); // Build myWidget and trigger a frame. await tester.pumpWidget(myWidget); // Verify myWidget shows some text expect(find.byType(Text), findsOneWidget); }); }); }
flutter/packages/flutter_tools/templates/skeleton/test/widget_test.dart.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/templates/skeleton/test/widget_test.dart.tmpl", "repo_id": "flutter", "token_count": 339 }
386
// Copyright 2014 The Flutter 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:args/command_runner.dart'; import 'package:file/memory.dart'; import 'package:flutter_tools/src/artifacts.dart'; import 'package:flutter_tools/src/base/file_system.dart'; import 'package:flutter_tools/src/base/logger.dart'; import 'package:flutter_tools/src/base/platform.dart'; import 'package:flutter_tools/src/base/terminal.dart'; import 'package:flutter_tools/src/commands/analyze.dart'; import 'package:flutter_tools/src/project.dart'; import 'package:flutter_tools/src/project_validator.dart'; import 'package:flutter_tools/src/project_validator_result.dart'; import '../../src/common.dart'; import '../../src/context.dart'; import '../../src/test_flutter_command_runner.dart'; class ProjectValidatorDummy extends ProjectValidator { @override Future<List<ProjectValidatorResult>> start(FlutterProject project, {Logger? logger, FileSystem? fileSystem}) async { return <ProjectValidatorResult>[ const ProjectValidatorResult(name: 'pass', value: 'value', status: StatusProjectValidator.success), const ProjectValidatorResult(name: 'fail', value: 'my error', status: StatusProjectValidator.error), const ProjectValidatorResult(name: 'pass two', value: 'pass', warning: 'my warning', status: StatusProjectValidator.warning), ]; } @override bool supportsProject(FlutterProject project) { return true; } @override String get title => 'First Dummy'; } class ProjectValidatorSecondDummy extends ProjectValidator { @override Future<List<ProjectValidatorResult>> start(FlutterProject project, {Logger? logger, FileSystem? fileSystem}) async { return <ProjectValidatorResult>[ const ProjectValidatorResult(name: 'second', value: 'pass', status: StatusProjectValidator.success), const ProjectValidatorResult(name: 'other fail', value: 'second fail', status: StatusProjectValidator.error), ]; } @override bool supportsProject(FlutterProject project) { return true; } @override String get title => 'Second Dummy'; } class ProjectValidatorCrash extends ProjectValidator { @override Future<List<ProjectValidatorResult>> start(FlutterProject project, {Logger? logger, FileSystem? fileSystem}) async { throw Exception('my exception'); } @override bool supportsProject(FlutterProject project) { return true; } @override String get title => 'Crash'; } void main() { late FileSystem fileSystem; late Terminal terminal; late ProcessManager processManager; late Platform platform; group('analyze --suggestions command', () { setUp(() { fileSystem = MemoryFileSystem.test(); terminal = Terminal.test(); processManager = FakeProcessManager.empty(); platform = FakePlatform(); }); testUsingContext('success, error and warning', () async { final BufferLogger loggerTest = BufferLogger.test(); final AnalyzeCommand command = AnalyzeCommand( artifacts: Artifacts.test(), fileSystem: fileSystem, logger: loggerTest, platform: platform, terminal: terminal, processManager: processManager, allProjectValidators: <ProjectValidator>[ ProjectValidatorDummy(), ProjectValidatorSecondDummy() ], suppressAnalytics: true, ); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['analyze', '--suggestions', './']); const String expected = '\n' '┌──────────────────────────────────────────┐\n' '│ First Dummy │\n' '│ [✓] pass: value │\n' '│ [✗] fail: my error │\n' '│ [!] pass two: pass (warning: my warning) │\n' '│ Second Dummy │\n' '│ [✓] second: pass │\n' '│ [✗] other fail: second fail │\n' '└──────────────────────────────────────────┘\n'; expect(loggerTest.statusText, contains(expected)); }); testUsingContext('crash', () async { final BufferLogger loggerTest = BufferLogger.test(); final AnalyzeCommand command = AnalyzeCommand( artifacts: Artifacts.test(), fileSystem: fileSystem, logger: loggerTest, platform: platform, terminal: terminal, processManager: processManager, allProjectValidators: <ProjectValidator>[ ProjectValidatorCrash(), ], suppressAnalytics: true, ); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['analyze', '--suggestions', './']); const String expected = '[☠] Exception: my exception: #0 ProjectValidatorCrash.start'; expect(loggerTest.statusText, contains(expected)); }); testUsingContext('--watch and --suggestions not compatible together', () async { final BufferLogger loggerTest = BufferLogger.test(); final AnalyzeCommand command = AnalyzeCommand( artifacts: Artifacts.test(), fileSystem: fileSystem, logger: loggerTest, platform: platform, terminal: terminal, processManager: processManager, allProjectValidators: <ProjectValidator>[], suppressAnalytics: true, ); final CommandRunner<void> runner = createTestCommandRunner(command); Future<void> result () => runner.run(<String>['analyze', '--suggestions', '--watch']); expect(result, throwsToolExit(message: 'flag --watch is not compatible with --suggestions')); }); }); }
flutter/packages/flutter_tools/test/commands.shard/hermetic/analyze_suggestion_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/commands.shard/hermetic/analyze_suggestion_test.dart", "repo_id": "flutter", "token_count": 2145 }
387
// Copyright 2014 The Flutter 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:args/command_runner.dart'; import 'package:flutter_tools/src/android/java.dart'; import 'package:flutter_tools/src/base/file_system.dart'; import 'package:flutter_tools/src/cache.dart'; import 'package:flutter_tools/src/commands/create.dart'; import 'package:flutter_tools/src/convert.dart'; import 'package:flutter_tools/src/dart/pub.dart'; import 'package:flutter_tools/src/doctor.dart'; import 'package:flutter_tools/src/doctor_validator.dart'; import 'package:flutter_tools/src/features.dart'; import 'package:flutter_tools/src/globals.dart' as globals; import 'package:flutter_tools/src/project.dart'; import 'package:test/fake.dart'; import '../../src/common.dart'; import '../../src/context.dart'; import '../../src/fakes.dart'; import '../../src/test_flutter_command_runner.dart'; import '../../src/testbed.dart'; class FakePub extends Fake implements Pub { int calledGetOffline = 0; int calledOnline = 0; @override Future<void> get({ PubContext? context, required FlutterProject project, bool upgrade = false, bool offline = false, bool generateSyntheticPackage = false, bool generateSyntheticPackageForExample = false, String? flutterRootOverride, bool checkUpToDate = false, bool shouldSkipThirdPartyGenerator = true, PubOutputMode outputMode = PubOutputMode.all, }) async { project.directory.childFile('.packages').createSync(); if (offline) { calledGetOffline += 1; } else { calledOnline += 1; } } } void main() { group('usageValues', () { late Testbed testbed; late FakePub fakePub; setUpAll(() { Cache.disableLocking(); Cache.flutterRoot = 'flutter'; }); setUp(() { testbed = Testbed(setup: () { fakePub = FakePub(); Cache.flutterRoot = 'flutter'; final List<String> filePaths = <String>[ globals.fs.path.join('flutter', 'packages', 'flutter', 'pubspec.yaml'), globals.fs.path.join('flutter', 'packages', 'flutter_driver', 'pubspec.yaml'), globals.fs.path.join('flutter', 'packages', 'flutter_test', 'pubspec.yaml'), globals.fs.path.join('flutter', 'bin', 'cache', 'artifacts', 'gradle_wrapper', 'wrapper'), globals.fs.path.join('usr', 'local', 'bin', 'adb'), globals.fs.path.join('Android', 'platform-tools', 'adb.exe'), ]; for (final String filePath in filePaths) { globals.fs.file(filePath).createSync(recursive: true); } final List<String> templatePaths = <String>[ globals.fs.path.join('flutter', 'packages', 'flutter_tools', 'templates', 'app'), globals.fs.path.join('flutter', 'packages', 'flutter_tools', 'templates', 'app_integration_test'), globals.fs.path.join('flutter', 'packages', 'flutter_tools', 'templates', 'app_shared'), globals.fs.path.join('flutter', 'packages', 'flutter_tools', 'templates', 'app_test_widget'), globals.fs.path.join('flutter', 'packages', 'flutter_tools', 'templates', 'cocoapods'), globals.fs.path.join('flutter', 'packages', 'flutter_tools', 'templates', 'skeleton'), globals.fs.path.join('flutter', 'packages', 'flutter_tools', 'templates', 'module', 'common'), globals.fs.path.join('flutter', 'packages', 'flutter_tools', 'templates', 'package'), globals.fs.path.join('flutter', 'packages', 'flutter_tools', 'templates', 'package_ffi'), globals.fs.path.join('flutter', 'packages', 'flutter_tools', 'templates', 'plugin'), globals.fs.path.join('flutter', 'packages', 'flutter_tools', 'templates', 'plugin_ffi'), globals.fs.path.join('flutter', 'packages', 'flutter_tools', 'templates', 'plugin_shared'), globals.fs.path.join('flutter', 'packages', 'flutter_tools', 'templates', 'plugin_cocoapods'), ]; for (final String templatePath in templatePaths) { globals.fs.directory(templatePath).createSync(recursive: true); } // Set up enough of the packages to satisfy the templating code. final File packagesFile = globals.fs.file( globals.fs.path.join('flutter', 'packages', 'flutter_tools', '.dart_tool', 'package_config.json')); final File flutterManifest = globals.fs.file( globals.fs.path.join('flutter', 'packages', 'flutter_tools', 'templates', 'template_manifest.json')) ..createSync(recursive: true); final Directory templateImagesDirectory = globals.fs.directory('flutter_template_images'); templateImagesDirectory.createSync(recursive: true); packagesFile.createSync(recursive: true); packagesFile.writeAsStringSync(json.encode(<String, Object>{ 'configVersion': 2, 'packages': <Object>[ <String, Object>{ 'name': 'flutter_template_images', 'languageVersion': '2.8', 'rootUri': templateImagesDirectory.uri.toString(), 'packageUri': 'lib/', }, ], })); flutterManifest.writeAsStringSync('{"files":[]}'); }, overrides: <Type, Generator>{ DoctorValidatorsProvider: () => FakeDoctorValidatorsProvider(), FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true), }); }); testUsingContext('set template type as usage value', () => testbed.run(() async { final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--template=module', 'testy']); expect((await command.usageValues).commandCreateProjectType, 'module'); await runner.run(<String>['create', '--no-pub', '--template=app', 'testy1']); expect((await command.usageValues).commandCreateProjectType, 'app'); await runner.run(<String>['create', '--no-pub', '--template=skeleton', 'testy2']); expect((await command.usageValues).commandCreateProjectType, 'skeleton'); await runner.run(<String>['create', '--no-pub', '--template=package', 'testy3']); expect((await command.usageValues).commandCreateProjectType, 'package'); await runner.run(<String>['create', '--no-pub', '--template=plugin', 'testy4']); expect((await command.usageValues).commandCreateProjectType, 'plugin'); await runner.run(<String>['create', '--no-pub', '--template=plugin_ffi', 'testy5']); expect((await command.usageValues).commandCreateProjectType, 'plugin_ffi'); await runner.run(<String>['create', '--no-pub', '--template=package_ffi', 'testy6']); expect((await command.usageValues).commandCreateProjectType, 'package_ffi'); }), overrides: <Type, Generator>{ Java: () => FakeJava(), }); testUsingContext('set iOS host language type as usage value', () => testbed.run(() async { final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>[ 'create', '--no-pub', '--template=app', 'testy', ]); expect((await command.usageValues).commandCreateIosLanguage, 'swift'); await runner.run(<String>[ 'create', '--no-pub', '--template=app', '--ios-language=objc', 'testy', ]); expect((await command.usageValues).commandCreateIosLanguage, 'objc'); }), overrides: <Type, Generator>{ Java: () => FakeJava(), }); testUsingContext('set Android host language type as usage value', () => testbed.run(() async { final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--template=app', 'testy']); expect((await command.usageValues).commandCreateAndroidLanguage, 'kotlin'); await runner.run(<String>[ 'create', '--no-pub', '--template=app', '--android-language=java', 'testy', ]); expect((await command.usageValues).commandCreateAndroidLanguage, 'java'); }), overrides: <Type, Generator>{ Java: () => FakeJava(), }); testUsingContext('create --offline', () => testbed.run(() async { final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', 'testy', '--offline']); expect(fakePub.calledOnline, 0); expect(fakePub.calledGetOffline, 1); expect(command.argParser.options.containsKey('offline'), true); expect(command.shouldUpdateCache, true); }, overrides: <Type, Generator>{ Java: () => null, Pub: () => fakePub, })); testUsingContext('package_ffi template not enabled', () async { final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); expect( runner.run( <String>[ 'create', '--no-pub', '--template=package_ffi', 'my_ffi_package', ], ), throwsUsageException( message: '"package_ffi" is not an allowed value for option "template"', ), ); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags( isNativeAssetsEnabled: false, // ignore: avoid_redundant_argument_values, If we graduate the feature to true by default, don't break this test. ), }); }); } class FakeDoctorValidatorsProvider implements DoctorValidatorsProvider { @override List<DoctorValidator> get validators => <DoctorValidator>[]; @override List<Workflow> get workflows => <Workflow>[]; }
flutter/packages/flutter_tools/test/commands.shard/hermetic/create_usage_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/commands.shard/hermetic/create_usage_test.dart", "repo_id": "flutter", "token_count": 3836 }
388
// Copyright 2014 The Flutter 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:io' as io; import 'dart:typed_data'; import 'package:flutter_tools/src/base/io.dart'; import 'package:flutter_tools/src/base/platform.dart'; import 'package:flutter_tools/src/doctor_validator.dart'; import 'package:flutter_tools/src/proxy_validator.dart'; import '../../src/common.dart'; void main() { setUp(() { setNetworkInterfaceLister( ({ bool includeLoopback = true, bool includeLinkLocal = true, InternetAddressType type = InternetAddressType.any, }) async { final List<FakeNetworkInterface> interfaces = <FakeNetworkInterface>[ FakeNetworkInterface(<FakeInternetAddress>[ const FakeInternetAddress('127.0.0.1'), ]), FakeNetworkInterface(<FakeInternetAddress>[ const FakeInternetAddress('::1'), ]), ]; return Future<List<NetworkInterface>>.value(interfaces); }); }); tearDown(() { resetNetworkInterfaceLister(); }); testWithoutContext('ProxyValidator does not show if HTTP_PROXY is not set', () { final Platform platform = FakePlatform(environment: <String, String>{}); expect(ProxyValidator(platform: platform).shouldShow, isFalse); }); testWithoutContext('ProxyValidator does not show if HTTP_PROXY is only whitespace', () { final Platform platform = FakePlatform(environment: <String, String>{'HTTP_PROXY': ' '}); expect(ProxyValidator(platform: platform).shouldShow, isFalse); }); testWithoutContext('ProxyValidator shows when HTTP_PROXY is set', () { final Platform platform = FakePlatform(environment: <String, String>{'HTTP_PROXY': 'fakeproxy.local'}); expect(ProxyValidator(platform: platform).shouldShow, isTrue); }); testWithoutContext('ProxyValidator shows when http_proxy is set', () { final Platform platform = FakePlatform(environment: <String, String>{'http_proxy': 'fakeproxy.local'}); expect(ProxyValidator(platform: platform).shouldShow, isTrue); }); testWithoutContext('ProxyValidator reports success when NO_PROXY is configured correctly', () async { final Platform platform = FakePlatform( environment: <String, String>{ 'HTTP_PROXY': 'fakeproxy.local', 'NO_PROXY': 'localhost,127.0.0.1,::1', }, ); final ValidationResult results = await ProxyValidator(platform: platform).validate(); expect(results.messages, const <ValidationMessage>[ ValidationMessage('HTTP_PROXY is set'), ValidationMessage('NO_PROXY is localhost,127.0.0.1,::1'), ValidationMessage('NO_PROXY contains localhost'), ValidationMessage('NO_PROXY contains 127.0.0.1'), ValidationMessage('NO_PROXY contains ::1'), ]); }); testWithoutContext('ProxyValidator reports success when no_proxy is configured correctly', () async { final Platform platform = FakePlatform( environment: <String, String>{ 'http_proxy': 'fakeproxy.local', 'no_proxy': 'localhost,127.0.0.1,::1', }, ); final ValidationResult results = await ProxyValidator(platform: platform).validate(); expect(results.messages, const <ValidationMessage>[ ValidationMessage('HTTP_PROXY is set'), ValidationMessage('NO_PROXY is localhost,127.0.0.1,::1'), ValidationMessage('NO_PROXY contains localhost'), ValidationMessage('NO_PROXY contains 127.0.0.1'), ValidationMessage('NO_PROXY contains ::1'), ]); }); testWithoutContext('ProxyValidator reports issues when NO_PROXY is missing localhost', () async { final Platform platform = FakePlatform( environment: <String, String>{ 'HTTP_PROXY': 'fakeproxy.local', 'NO_PROXY': '127.0.0.1,::1', }, ); final ValidationResult results = await ProxyValidator(platform: platform).validate(); expect(results.messages, const <ValidationMessage>[ ValidationMessage('HTTP_PROXY is set'), ValidationMessage('NO_PROXY is 127.0.0.1,::1'), ValidationMessage.hint('NO_PROXY does not contain localhost'), ValidationMessage('NO_PROXY contains 127.0.0.1'), ValidationMessage('NO_PROXY contains ::1'), ]); }); testWithoutContext('ProxyValidator reports issues when NO_PROXY is missing 127.0.0.1', () async { final Platform platform = FakePlatform(environment: <String, String>{ 'HTTP_PROXY': 'fakeproxy.local', 'NO_PROXY': 'localhost,::1', }); final ValidationResult results = await ProxyValidator(platform: platform).validate(); expect(results.messages, const <ValidationMessage>[ ValidationMessage('HTTP_PROXY is set'), ValidationMessage('NO_PROXY is localhost,::1'), ValidationMessage('NO_PROXY contains localhost'), ValidationMessage.hint('NO_PROXY does not contain 127.0.0.1'), ValidationMessage('NO_PROXY contains ::1'), ]); }); testWithoutContext('ProxyValidator reports issues when NO_PROXY is missing ::1', () async { final Platform platform = FakePlatform(environment: <String, String>{ 'HTTP_PROXY': 'fakeproxy.local', 'NO_PROXY': 'localhost,127.0.0.1', }); final ValidationResult results = await ProxyValidator(platform: platform).validate(); expect(results.messages, const <ValidationMessage>[ ValidationMessage('HTTP_PROXY is set'), ValidationMessage('NO_PROXY is localhost,127.0.0.1'), ValidationMessage('NO_PROXY contains localhost'), ValidationMessage('NO_PROXY contains 127.0.0.1'), ValidationMessage.hint('NO_PROXY does not contain ::1'), ]); }); testWithoutContext('ProxyValidator reports issues when NO_PROXY is missing localhost, 127.0.0.1', () async { final Platform platform = FakePlatform( environment: <String, String>{ 'HTTP_PROXY': 'fakeproxy.local', 'NO_PROXY': '::1', }, ); final ValidationResult results = await ProxyValidator(platform: platform).validate(); expect(results.messages, const <ValidationMessage>[ ValidationMessage('HTTP_PROXY is set'), ValidationMessage('NO_PROXY is ::1'), ValidationMessage.hint('NO_PROXY does not contain localhost'), ValidationMessage.hint('NO_PROXY does not contain 127.0.0.1'), ValidationMessage('NO_PROXY contains ::1'), ]); }); testWithoutContext('ProxyValidator reports issues when NO_PROXY is missing localhost, ::1', () async { final Platform platform = FakePlatform( environment: <String, String>{ 'HTTP_PROXY': 'fakeproxy.local', 'NO_PROXY': '127.0.0.1', }, ); final ValidationResult results = await ProxyValidator(platform: platform).validate(); expect(results.messages, const <ValidationMessage>[ ValidationMessage('HTTP_PROXY is set'), ValidationMessage('NO_PROXY is 127.0.0.1'), ValidationMessage.hint('NO_PROXY does not contain localhost'), ValidationMessage('NO_PROXY contains 127.0.0.1'), ValidationMessage.hint('NO_PROXY does not contain ::1'), ]); }); testWithoutContext('ProxyValidator reports issues when NO_PROXY is missing 127.0.0.1, ::1', () async { final Platform platform = FakePlatform( environment: <String, String>{ 'HTTP_PROXY': 'fakeproxy.local', 'NO_PROXY': 'localhost', }, ); final ValidationResult results = await ProxyValidator(platform: platform).validate(); expect(results.messages, const <ValidationMessage>[ ValidationMessage('HTTP_PROXY is set'), ValidationMessage('NO_PROXY is localhost'), ValidationMessage('NO_PROXY contains localhost'), ValidationMessage.hint('NO_PROXY does not contain 127.0.0.1'), ValidationMessage.hint('NO_PROXY does not contain ::1'), ]); }); } class FakeNetworkInterface extends NetworkInterface { FakeNetworkInterface(List<FakeInternetAddress> addresses): super(FakeNetworkInterfaceDelegate(addresses)); @override String get name => 'FakeNetworkInterface$index'; } class FakeNetworkInterfaceDelegate implements io.NetworkInterface { FakeNetworkInterfaceDelegate(this._fakeAddresses); final List<FakeInternetAddress> _fakeAddresses; @override List<io.InternetAddress> get addresses => _fakeAddresses; @override int get index => addresses.length; @override String get name => 'FakeNetworkInterfaceDelegate$index'; } class FakeInternetAddress implements io.InternetAddress { const FakeInternetAddress(this._fakeAddress); final String _fakeAddress; @override String get address => _fakeAddress; @override String get host => throw UnimplementedError(); @override bool get isLinkLocal => throw UnimplementedError(); @override bool get isLoopback => true; @override bool get isMulticast => throw UnimplementedError(); @override Uint8List get rawAddress => throw UnimplementedError(); @override Future<io.InternetAddress> reverse() => throw UnimplementedError(); @override io.InternetAddressType get type => throw UnimplementedError(); }
flutter/packages/flutter_tools/test/commands.shard/hermetic/proxy_validator_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/commands.shard/hermetic/proxy_validator_test.dart", "repo_id": "flutter", "token_count": 3129 }
389
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // TODO(gspencergoog): Remove this tag once this test's state leaks/test // dependencies have been fixed. // https://github.com/flutter/flutter/issues/85160 // Fails with "flutter test --test-randomize-ordering-seed=1000" @Tags(<String>['no-shuffle']) library; import 'dart:async'; import 'dart:convert'; import 'package:args/command_runner.dart'; import 'package:file/memory.dart'; import 'package:flutter_tools/src/base/bot_detector.dart'; import 'package:flutter_tools/src/base/error_handling_io.dart'; import 'package:flutter_tools/src/base/file_system.dart' hide IOSink; import 'package:flutter_tools/src/base/io.dart'; import 'package:flutter_tools/src/base/platform.dart'; import 'package:flutter_tools/src/cache.dart'; import 'package:flutter_tools/src/commands/packages.dart'; import 'package:flutter_tools/src/dart/pub.dart'; import 'package:flutter_tools/src/globals.dart' as globals; import 'package:unified_analytics/unified_analytics.dart'; import '../../src/common.dart'; import '../../src/context.dart'; import '../../src/fake_process_manager.dart'; import '../../src/fakes.dart'; import '../../src/test_flutter_command_runner.dart'; void main() { late FakeStdio mockStdio; setUp(() { mockStdio = FakeStdio()..stdout.terminalColumns = 80; }); Cache.disableLocking(); group('packages get/upgrade', () { late Directory tempDir; late FakeAnalytics fakeAnalytics; setUp(() { tempDir = globals.fs.systemTempDirectory.createTempSync('flutter_tools_packages_test.'); fakeAnalytics = getInitializedFakeAnalyticsInstance( fs: MemoryFileSystem.test(), fakeFlutterVersion: FakeFlutterVersion(), ); }); tearDown(() { tryToDelete(tempDir); }); Future<String> createProjectWithPlugin(String plugin, { List<String>? arguments }) async { final String projectPath = await createProject(tempDir, arguments: arguments); final File pubspec = globals.fs.file(globals.fs.path.join(projectPath, 'pubspec.yaml')); String content = await pubspec.readAsString(); final List<String> contentLines = LineSplitter.split(content).toList(); final int depsIndex = contentLines.indexOf('dependencies:'); expect(depsIndex, isNot(-1)); contentLines.replaceRange(depsIndex, depsIndex + 1, <String>[ 'dependencies:', ' $plugin:', ]); content = contentLines.join('\n'); await pubspec.writeAsString(content, flush: true); return projectPath; } Future<PackagesCommand> runCommandIn(String projectPath, String verb, { List<String>? args }) async { final PackagesCommand command = PackagesCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>[ 'packages', verb, ...?args, '--directory', projectPath, ]); return command; } void expectExists(String projectPath, String relPath) { expect( globals.fs.isFileSync(globals.fs.path.join(projectPath, relPath)), true, reason: '$projectPath/$relPath should exist, but does not', ); } void expectContains(String projectPath, String relPath, String substring) { expectExists(projectPath, relPath); expect( globals.fs.file(globals.fs.path.join(projectPath, relPath)).readAsStringSync(), contains(substring), reason: '$projectPath/$relPath has unexpected content', ); } void expectNotExists(String projectPath, String relPath) { expect( globals.fs.isFileSync(globals.fs.path.join(projectPath, relPath)), false, reason: '$projectPath/$relPath should not exist, but does', ); } void expectNotContains(String projectPath, String relPath, String substring) { expectExists(projectPath, relPath); expect( globals.fs.file(globals.fs.path.join(projectPath, relPath)).readAsStringSync(), isNot(contains(substring)), reason: '$projectPath/$relPath has unexpected content', ); } final List<String> pubOutput = <String>[ globals.fs.path.join('.dart_tool', 'package_config.json'), 'pubspec.lock', ]; const List<String> pluginRegistrants = <String>[ 'ios/Runner/GeneratedPluginRegistrant.h', 'ios/Runner/GeneratedPluginRegistrant.m', 'android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java', ]; const List<String> modulePluginRegistrants = <String>[ '.ios/Flutter/FlutterPluginRegistrant/Classes/GeneratedPluginRegistrant.h', '.ios/Flutter/FlutterPluginRegistrant/Classes/GeneratedPluginRegistrant.m', '.android/Flutter/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java', ]; const List<String> pluginWitnesses = <String>[ '.flutter-plugins', 'ios/Podfile', ]; const List<String> modulePluginWitnesses = <String>[ '.flutter-plugins', '.ios/Podfile', ]; const Map<String, String> pluginContentWitnesses = <String, String>{ 'ios/Flutter/Debug.xcconfig': '#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"', 'ios/Flutter/Release.xcconfig': '#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"', }; const Map<String, String> modulePluginContentWitnesses = <String, String>{ '.ios/Config/Debug.xcconfig': '#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"', '.ios/Config/Release.xcconfig': '#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"', }; void expectDependenciesResolved(String projectPath) { for (final String output in pubOutput) { expectExists(projectPath, output); } } void expectZeroPluginsInjected(String projectPath) { for (final String registrant in modulePluginRegistrants) { expectExists(projectPath, registrant); } for (final String witness in pluginWitnesses) { expectNotExists(projectPath, witness); } modulePluginContentWitnesses.forEach((String witness, String content) { expectNotContains(projectPath, witness, content); }); } void expectPluginInjected(String projectPath) { for (final String registrant in pluginRegistrants) { expectExists(projectPath, registrant); } for (final String witness in pluginWitnesses) { expectExists(projectPath, witness); } pluginContentWitnesses.forEach((String witness, String content) { expectContains(projectPath, witness, content); }); } void expectModulePluginInjected(String projectPath) { for (final String registrant in modulePluginRegistrants) { expectExists(projectPath, registrant); } for (final String witness in modulePluginWitnesses) { expectExists(projectPath, witness); } modulePluginContentWitnesses.forEach((String witness, String content) { expectContains(projectPath, witness, content); }); } void removeGeneratedFiles(String projectPath) { final Iterable<String> allFiles = <List<String>>[ pubOutput, modulePluginRegistrants, pluginWitnesses, ].expand<String>((List<String> list) => list); for (final String path in allFiles) { final File file = globals.fs.file(globals.fs.path.join(projectPath, path)); ErrorHandlingFileSystem.deleteIfExists(file); } } testUsingContext('get fetches packages and has output from pub', () async { final String projectPath = await createProject(tempDir, arguments: <String>['--no-pub', '--template=module']); removeGeneratedFiles(projectPath); await runCommandIn(projectPath, 'get'); expect(mockStdio.stdout.writes.map(utf8.decode), allOf( // The output of pub changed, adding backticks around the directory name. // These regexes are tolerant of the backticks being present or absent. contains(matches(RegExp(r'Resolving dependencies in .+flutter_project`?\.\.\.'))), contains(matches(RegExp(r'\+ flutter 0\.0\.0 from sdk flutter'))), contains(matches(RegExp(r'Changed \d+ dependencies in .+flutter_project`?!'))), ), ); expectDependenciesResolved(projectPath); expectZeroPluginsInjected(projectPath); expect( analyticsTimingEventExists( sentEvents: fakeAnalytics.sentEvents, workflow: 'pub', variableName: 'get', label: 'success', ), true, ); }, overrides: <Type, Generator>{ Stdio: () => mockStdio, Pub: () => Pub.test( fileSystem: globals.fs, logger: globals.logger, processManager: globals.processManager, usage: globals.flutterUsage, botDetector: globals.botDetector, platform: globals.platform, stdio: mockStdio, ), Analytics: () => fakeAnalytics, }); testUsingContext('get --offline fetches packages', () async { final String projectPath = await createProject(tempDir, arguments: <String>['--no-pub', '--template=module']); removeGeneratedFiles(projectPath); await runCommandIn(projectPath, 'get', args: <String>['--offline']); expectDependenciesResolved(projectPath); expectZeroPluginsInjected(projectPath); }, overrides: <Type, Generator>{ Stdio: () => mockStdio, Pub: () => Pub.test( fileSystem: globals.fs, logger: globals.logger, processManager: globals.processManager, usage: globals.flutterUsage, botDetector: globals.botDetector, platform: globals.platform, stdio: mockStdio, ), }); testUsingContext('get generates synthetic package when l10n.yaml has synthetic-package: true', () async { final String projectPath = await createProject(tempDir, arguments: <String>['--no-pub', '--template=module']); final Directory projectDir = globals.fs.directory(projectPath); projectDir .childDirectory('lib') .childDirectory('l10n') .childFile('app_en.arb') ..createSync(recursive: true) ..writeAsStringSync('{ "hello": "Hello world!" }'); String pubspecFileContent = projectDir.childFile('pubspec.yaml').readAsStringSync(); pubspecFileContent = pubspecFileContent.replaceFirst(RegExp(r'\nflutter\:'), ''' flutter: generate: true '''); projectDir .childFile('pubspec.yaml') .writeAsStringSync(pubspecFileContent); projectDir .childFile('l10n.yaml') .writeAsStringSync('synthetic-package: true'); await runCommandIn(projectPath, 'get'); expect( projectDir .childDirectory('.dart_tool') .childDirectory('flutter_gen') .childDirectory('gen_l10n') .childFile('app_localizations.dart') .existsSync(), true ); }, overrides: <Type, Generator>{ Pub: () => Pub( fileSystem: globals.fs, logger: globals.logger, processManager: globals.processManager, usage: globals.flutterUsage, botDetector: globals.botDetector, platform: globals.platform, ), }); testUsingContext('get generates normal files when l10n.yaml has synthetic-package: false', () async { final String projectPath = await createProject(tempDir, arguments: <String>['--no-pub', '--template=module']); final Directory projectDir = globals.fs.directory(projectPath); projectDir .childDirectory('lib') .childDirectory('l10n') .childFile('app_en.arb') ..createSync(recursive: true) ..writeAsStringSync('{ "hello": "Hello world!" }'); projectDir .childFile('l10n.yaml') .writeAsStringSync('synthetic-package: false'); await runCommandIn(projectPath, 'get'); expect( projectDir .childDirectory('lib') .childDirectory('l10n') .childFile('app_localizations.dart') .existsSync(), true ); }, overrides: <Type, Generator>{ Pub: () => Pub( fileSystem: globals.fs, logger: globals.logger, processManager: globals.processManager, usage: globals.flutterUsage, botDetector: globals.botDetector, platform: globals.platform, ), }); testUsingContext('set no plugins as usage value', () async { final String projectPath = await createProject(tempDir, arguments: <String>['--no-pub', '--template=module']); removeGeneratedFiles(projectPath); final PackagesCommand command = await runCommandIn(projectPath, 'get'); final PackagesGetCommand getCommand = command.subcommands['get']! as PackagesGetCommand; expect((await getCommand.usageValues).commandPackagesNumberPlugins, 0); expect( (await getCommand.unifiedAnalyticsUsageValues('pub/get')) .eventData['packagesNumberPlugins'], 0, ); }, overrides: <Type, Generator>{ Stdio: () => mockStdio, Pub: () => Pub.test( fileSystem: globals.fs, logger: globals.logger, processManager: globals.processManager, usage: globals.flutterUsage, botDetector: globals.botDetector, platform: globals.platform, stdio: mockStdio, ), }); testUsingContext('set the number of plugins as usage value', () async { final String projectPath = await createProject( tempDir, arguments: <String>['--template=plugin', '--no-pub', '--platforms=ios,android,macos,windows'], ); final String exampleProjectPath = globals.fs.path.join(projectPath, 'example'); final PackagesCommand command = await runCommandIn(exampleProjectPath, 'get'); final PackagesGetCommand getCommand = command.subcommands['get']! as PackagesGetCommand; // A plugin example depends on the plugin itself, and integration_test. expect((await getCommand.usageValues).commandPackagesNumberPlugins, 2); expect( (await getCommand.unifiedAnalyticsUsageValues('pub/get')) .eventData['packagesNumberPlugins'], 2, ); }, overrides: <Type, Generator>{ Stdio: () => mockStdio, Pub: () => Pub.test( fileSystem: globals.fs, logger: globals.logger, processManager: globals.processManager, usage: globals.flutterUsage, botDetector: globals.botDetector, platform: globals.platform, stdio: mockStdio, ), }); testUsingContext('indicate that the project is not a module in usage value', () async { final String projectPath = await createProject(tempDir, arguments: <String>['--no-pub']); removeGeneratedFiles(projectPath); final PackagesCommand command = await runCommandIn(projectPath, 'get'); final PackagesGetCommand getCommand = command.subcommands['get']! as PackagesGetCommand; expect((await getCommand.usageValues).commandPackagesProjectModule, false); expect( (await getCommand.unifiedAnalyticsUsageValues('pub/get')) .eventData['packagesProjectModule'], false, ); }, overrides: <Type, Generator>{ Stdio: () => mockStdio, Pub: () => Pub.test( fileSystem: globals.fs, logger: globals.logger, processManager: globals.processManager, usage: globals.flutterUsage, botDetector: globals.botDetector, platform: globals.platform, stdio: mockStdio, ), }); testUsingContext('indicate that the project is a module in usage value', () async { final String projectPath = await createProject(tempDir, arguments: <String>['--no-pub', '--template=module']); removeGeneratedFiles(projectPath); final PackagesCommand command = await runCommandIn(projectPath, 'get'); final PackagesGetCommand getCommand = command.subcommands['get']! as PackagesGetCommand; expect((await getCommand.usageValues).commandPackagesProjectModule, true); expect( (await getCommand.unifiedAnalyticsUsageValues('pub/get')) .eventData['packagesProjectModule'], true, ); }, overrides: <Type, Generator>{ Stdio: () => mockStdio, Pub: () => Pub.test( fileSystem: globals.fs, logger: globals.logger, processManager: globals.processManager, usage: globals.flutterUsage, botDetector: globals.botDetector, platform: globals.platform, stdio: mockStdio, ), }); testUsingContext('indicate that Android project reports v2 in usage value', () async { final String projectPath = await createProject(tempDir, arguments: <String>['--no-pub']); removeGeneratedFiles(projectPath); final PackagesCommand command = await runCommandIn(projectPath, 'get'); final PackagesGetCommand getCommand = command.subcommands['get']! as PackagesGetCommand; expect((await getCommand.usageValues).commandPackagesAndroidEmbeddingVersion, 'v2'); expect( (await getCommand.unifiedAnalyticsUsageValues('pub/get')) .eventData['packagesAndroidEmbeddingVersion'], 'v2', ); }, overrides: <Type, Generator>{ Stdio: () => mockStdio, Pub: () => Pub.test( fileSystem: globals.fs, logger: globals.logger, processManager: globals.processManager, usage: globals.flutterUsage, botDetector: globals.botDetector, platform: globals.platform, stdio: mockStdio, ), }); testUsingContext('upgrade fetches packages', () async { final String projectPath = await createProject(tempDir, arguments: <String>['--no-pub', '--template=module']); removeGeneratedFiles(projectPath); await runCommandIn(projectPath, 'upgrade'); expectDependenciesResolved(projectPath); expectZeroPluginsInjected(projectPath); }, overrides: <Type, Generator>{ Stdio: () => mockStdio, Pub: () => Pub.test( fileSystem: globals.fs, logger: globals.logger, processManager: globals.processManager, usage: globals.flutterUsage, botDetector: globals.botDetector, platform: globals.platform, stdio: mockStdio, ), }); testUsingContext('get fetches packages and injects plugin', () async { final String projectPath = await createProjectWithPlugin('path_provider', arguments: <String>['--no-pub', '--template=module']); removeGeneratedFiles(projectPath); await runCommandIn(projectPath, 'get'); expectDependenciesResolved(projectPath); expectModulePluginInjected(projectPath); }, overrides: <Type, Generator>{ Stdio: () => mockStdio, Pub: () => Pub.test( fileSystem: globals.fs, logger: globals.logger, processManager: globals.processManager, usage: globals.flutterUsage, botDetector: globals.botDetector, platform: globals.platform, stdio: mockStdio, ), }); testUsingContext('get fetches packages and injects plugin in plugin project', () async { final String projectPath = await createProject( tempDir, arguments: <String>['--template=plugin', '--no-pub', '--platforms=ios,android'], ); final String exampleProjectPath = globals.fs.path.join(projectPath, 'example'); removeGeneratedFiles(projectPath); removeGeneratedFiles(exampleProjectPath); await runCommandIn(projectPath, 'get'); expectDependenciesResolved(projectPath); await runCommandIn(exampleProjectPath, 'get'); expectDependenciesResolved(exampleProjectPath); expectPluginInjected(exampleProjectPath); }, overrides: <Type, Generator>{ Stdio: () => mockStdio, Pub: () => Pub.test( fileSystem: globals.fs, logger: globals.logger, processManager: globals.processManager, usage: globals.flutterUsage, botDetector: globals.botDetector, platform: globals.platform, stdio: mockStdio, ), }); }); group('packages test/pub', () { late FakeProcessManager processManager; late FakeStdio mockStdio; setUp(() { processManager = FakeProcessManager.empty(); mockStdio = FakeStdio()..stdout.terminalColumns = 80; }); testUsingContext('test without bot', () async { Cache.flutterRoot = ''; globals.fs.directory('/packages/flutter_tools').createSync(recursive: true); globals.fs.file('pubspec.yaml').createSync(); processManager.addCommand( const FakeCommand(command: <String>['/bin/cache/dart-sdk/bin/dart', 'pub', '--suppress-analytics', 'run', 'test']), ); await createTestCommandRunner(PackagesCommand()).run(<String>['packages', 'test']); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ FileSystem: () => MemoryFileSystem.test(), Platform: () => FakePlatform(environment: <String, String>{}), ProcessManager: () => processManager, Stdio: () => mockStdio, BotDetector: () => const FakeBotDetector(false), Pub: () => Pub.test( fileSystem: globals.fs, logger: globals.logger, processManager: globals.processManager, usage: globals.flutterUsage, botDetector: globals.botDetector, platform: globals.platform, stdio: mockStdio, ), }); testUsingContext('test with bot', () async { Cache.flutterRoot = ''; globals.fs.file('pubspec.yaml').createSync(); processManager.addCommand( const FakeCommand(command: <String>['/bin/cache/dart-sdk/bin/dart', 'pub', '--suppress-analytics', '--trace', 'run', 'test']), ); await createTestCommandRunner(PackagesCommand()).run(<String>['packages', 'test']); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ FileSystem: () => MemoryFileSystem.test(), Platform: () => FakePlatform(environment: <String, String>{}), ProcessManager: () => processManager, Stdio: () => mockStdio, BotDetector: () => const FakeBotDetector(true), Pub: () => Pub.test( fileSystem: globals.fs, logger: globals.logger, processManager: globals.processManager, usage: globals.flutterUsage, botDetector: globals.botDetector, platform: globals.platform, stdio: mockStdio, ), }); testUsingContext('run pass arguments through to pub', () async { Cache.flutterRoot = ''; globals.fs.file('pubspec.yaml').createSync(); final IOSink stdin = IOSink(StreamController<List<int>>().sink); processManager.addCommand( FakeCommand( command: const <String>[ '/bin/cache/dart-sdk/bin/dart', 'pub', '--suppress-analytics', 'run', '--foo', 'bar', ], stdin: stdin, ), ); await createTestCommandRunner(PackagesCommand()).run(<String>['packages', '--verbose', 'pub', 'run', '--foo', 'bar']); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ FileSystem: () => MemoryFileSystem.test(), Platform: () => FakePlatform(environment: <String, String>{}), ProcessManager: () => processManager, Stdio: () => mockStdio, Pub: () => Pub.test( fileSystem: globals.fs, logger: globals.logger, processManager: globals.processManager, usage: globals.flutterUsage, botDetector: globals.botDetector, platform: globals.platform, stdio: mockStdio, ), }); testUsingContext('token pass arguments through to pub', () async { Cache.flutterRoot = ''; globals.fs.file('pubspec.yaml').createSync(); final IOSink stdin = IOSink(StreamController<List<int>>().sink); processManager.addCommand( FakeCommand( command: const <String>[ '/bin/cache/dart-sdk/bin/dart', 'pub', '--suppress-analytics', 'token', 'list', ], stdin: stdin, ), ); await createTestCommandRunner(PackagesCommand()).run(<String>['packages', '--verbose', 'pub', 'token', 'list']); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ FileSystem: () => MemoryFileSystem.test(), Platform: () => FakePlatform(environment: <String, String>{}), ProcessManager: () => processManager, Stdio: () => mockStdio, Pub: () => Pub.test( fileSystem: globals.fs, logger: globals.logger, processManager: globals.processManager, usage: globals.flutterUsage, botDetector: globals.botDetector, platform: globals.platform, stdio: mockStdio, ), }); testUsingContext('upgrade does not check for pubspec.yaml if -h/--help is passed', () async { Cache.flutterRoot = ''; processManager.addCommand( FakeCommand( command: const <String>[ '/bin/cache/dart-sdk/bin/dart', 'pub', '--suppress-analytics', 'upgrade', '-h', ], stdin: IOSink(StreamController<List<int>>().sink), ), ); await createTestCommandRunner(PackagesCommand()).run(<String>['pub', 'upgrade', '-h']); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ FileSystem: () => MemoryFileSystem.test(), Platform: () => FakePlatform(environment: <String, String>{}), ProcessManager: () => processManager, Stdio: () => mockStdio, Pub: () => Pub.test( fileSystem: globals.fs, logger: globals.logger, processManager: globals.processManager, usage: globals.flutterUsage, botDetector: globals.botDetector, platform: globals.platform, stdio: mockStdio, ), }); }); }
flutter/packages/flutter_tools/test/commands.shard/permeable/packages_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/commands.shard/permeable/packages_test.dart", "repo_id": "flutter", "token_count": 10524 }
390
// Copyright 2014 The Flutter 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:file/file.dart'; import 'package:file/memory.dart'; import 'package:flutter_tools/src/android/android_studio.dart'; import 'package:flutter_tools/src/android/gradle_utils.dart'; import 'package:flutter_tools/src/android/migrations/android_studio_java_gradle_conflict_migration.dart'; import 'package:flutter_tools/src/android/migrations/min_sdk_version_migration.dart'; import 'package:flutter_tools/src/android/migrations/multidex_removal_migration.dart'; import 'package:flutter_tools/src/android/migrations/top_level_gradle_build_file_migration.dart'; import 'package:flutter_tools/src/base/logger.dart'; import 'package:flutter_tools/src/base/version.dart'; import 'package:flutter_tools/src/project.dart'; import 'package:test/fake.dart'; import '../../src/common.dart'; import '../../src/context.dart'; import '../../src/fakes.dart'; const String otherGradleVersionWrapper = r''' distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-6.6-all.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists '''; const String gradleWrapperToMigrate = r''' distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-6.7-all.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists '''; const String gradleWrapperToMigrateTo = r''' distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.1-all.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists '''; String sampleModuleGradleBuildFile(String minSdkVersionString) { return r''' plugins { id "com.android.application" id "kotlin-android" id "dev.flutter.flutter-gradle-plugin" } def localProperties = new Properties() def localPropertiesFile = rootProject.file('local.properties') if (localPropertiesFile.exists()) { localPropertiesFile.withReader('UTF-8') { reader -> localProperties.load(reader) } } def flutterVersionCode = localProperties.getProperty('flutter.versionCode') if (flutterVersionCode == null) { flutterVersionCode = '1' } def flutterVersionName = localProperties.getProperty('flutter.versionName') if (flutterVersionName == null) { flutterVersionName = '1.0' } android { namespace "com.example.asset_sample" compileSdk flutter.compileSdkVersion ndkVersion flutter.ndkVersion compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = '1.8' } sourceSets { main.java.srcDirs += 'src/main/kotlin' } defaultConfig { // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). applicationId "com.example.asset_sample" // You can update the following values to match your application needs. // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-gradle-build-configuration. ''' + minSdkVersionString + r''' targetSdkVersion flutter.targetSdkVersion versionCode flutterVersionCode.toInteger() versionName flutterVersionName } buildTypes { release { // TODO: Add your own signing config for the release build. // Signing with the debug keys for now, so `flutter run --release` works. signingConfig signingConfigs.debug } } } flutter { source '../..' } dependencies {} '''; } final Version androidStudioDolphin = Version(2021, 3, 1); const Version _javaVersion17 = Version.withText(17, 0, 2, 'openjdk 17.0.2'); const Version _javaVersion16 = Version.withText(16, 0, 2, 'openjdk 16.0.2'); void main() { group('Android migration', () { group('migrate the Gradle "clean" task to lazy declaration', () { late MemoryFileSystem memoryFileSystem; late BufferLogger bufferLogger; late FakeAndroidProject project; late File topLevelGradleBuildFile; setUp(() { memoryFileSystem = MemoryFileSystem.test(); bufferLogger = BufferLogger.test(); project = FakeAndroidProject( root: memoryFileSystem.currentDirectory.childDirectory('android')..createSync(), ); topLevelGradleBuildFile = project.hostAppGradleRoot.childFile('build.gradle'); }); testUsingContext('skipped if files are missing', () async { final TopLevelGradleBuildFileMigration androidProjectMigration = TopLevelGradleBuildFileMigration( project, bufferLogger, ); await androidProjectMigration.migrate(); expect(topLevelGradleBuildFile.existsSync(), isFalse); expect(bufferLogger.traceText, contains('Top-level Gradle build file not found, skipping migration of task "clean".')); }); testUsingContext('skipped if nothing to upgrade', () async { topLevelGradleBuildFile.writeAsStringSync(''' tasks.register("clean", Delete) { delete rootProject.buildDir } '''); final TopLevelGradleBuildFileMigration androidProjectMigration = TopLevelGradleBuildFileMigration( project, bufferLogger, ); final DateTime previousLastModified = topLevelGradleBuildFile.lastModifiedSync(); await androidProjectMigration.migrate(); expect(topLevelGradleBuildFile.lastModifiedSync(), previousLastModified); }); testUsingContext('top-level build.gradle is migrated', () async { topLevelGradleBuildFile.writeAsStringSync(''' task clean(type: Delete) { delete rootProject.buildDir } '''); final TopLevelGradleBuildFileMigration androidProjectMigration = TopLevelGradleBuildFileMigration( project, bufferLogger, ); await androidProjectMigration.migrate(); expect(bufferLogger.traceText, contains('Migrating "clean" Gradle task to lazy declaration style.')); expect(topLevelGradleBuildFile.readAsStringSync(), equals(''' tasks.register("clean", Delete) { delete rootProject.buildDir } ''')); }); }); group('migrate the gradle version to one that does not conflict with the ' 'Android Studio-provided java version', () { late MemoryFileSystem memoryFileSystem; late BufferLogger bufferLogger; late FakeAndroidProject project; late File gradleWrapperPropertiesFile; setUp(() { memoryFileSystem = MemoryFileSystem.test(); bufferLogger = BufferLogger.test(); project = FakeAndroidProject( root: memoryFileSystem.currentDirectory.childDirectory('android')..createSync(), ); project.hostAppGradleRoot.childDirectory(gradleDirectoryName) .childDirectory(gradleWrapperDirectoryName) .createSync(recursive: true); gradleWrapperPropertiesFile = project.hostAppGradleRoot .childDirectory(gradleDirectoryName) .childDirectory(gradleWrapperDirectoryName) .childFile(gradleWrapperPropertiesFilename); }); testWithoutContext('skipped if files are missing', () async { final AndroidStudioJavaGradleConflictMigration migration = AndroidStudioJavaGradleConflictMigration( java: FakeJava(version: _javaVersion17), bufferLogger, project: project, androidStudio: FakeAndroidStudio(version: androidStudioDolphin), ); await migration.migrate(); expect(gradleWrapperPropertiesFile.existsSync(), isFalse); expect(bufferLogger.traceText, contains(gradleWrapperNotFound)); }); testWithoutContext('skipped if android studio is null', () async { final AndroidStudioJavaGradleConflictMigration migration = AndroidStudioJavaGradleConflictMigration( java: FakeJava(version: _javaVersion17), bufferLogger, project: project, ); gradleWrapperPropertiesFile.writeAsStringSync(gradleWrapperToMigrate); await migration.migrate(); expect(bufferLogger.traceText, contains(androidStudioNotFound)); expect(gradleWrapperPropertiesFile.readAsStringSync(), gradleWrapperToMigrate); }); testWithoutContext('skipped if android studio version is null', () async { final AndroidStudioJavaGradleConflictMigration migration = AndroidStudioJavaGradleConflictMigration( java: FakeJava(version: _javaVersion17), bufferLogger, project: project, androidStudio: FakeAndroidStudio(version: null), ); gradleWrapperPropertiesFile.writeAsStringSync(gradleWrapperToMigrate); await migration.migrate(); expect(bufferLogger.traceText, contains(androidStudioNotFound)); expect(gradleWrapperPropertiesFile.readAsStringSync(), gradleWrapperToMigrate); }); testWithoutContext('skipped if error is encountered in migrate()', () async { final AndroidStudioJavaGradleConflictMigration migration = AndroidStudioJavaGradleConflictMigration( java: FakeErroringJava(), bufferLogger, project: project, androidStudio: FakeAndroidStudio(version: androidStudioFlamingo), ); gradleWrapperPropertiesFile.writeAsStringSync(gradleWrapperToMigrate); await migration.migrate(); expect(bufferLogger.traceText, contains(errorWhileMigrating)); expect(gradleWrapperPropertiesFile.readAsStringSync(), gradleWrapperToMigrate); }); testWithoutContext('skipped if android studio version is less than flamingo', () async { final AndroidStudioJavaGradleConflictMigration migration = AndroidStudioJavaGradleConflictMigration( java: FakeJava(), bufferLogger, project: project, androidStudio: FakeAndroidStudio(version: androidStudioDolphin), ); gradleWrapperPropertiesFile.writeAsStringSync(gradleWrapperToMigrate); await migration.migrate(); expect(gradleWrapperPropertiesFile.readAsStringSync(), gradleWrapperToMigrate); expect(bufferLogger.traceText, contains(androidStudioVersionBelowFlamingo)); }); testWithoutContext('skipped if bundled java version is less than 17', () async { final AndroidStudioJavaGradleConflictMigration migration = AndroidStudioJavaGradleConflictMigration( java: FakeJava(version: _javaVersion16), bufferLogger, project: project, androidStudio: FakeAndroidStudio(version: androidStudioFlamingo), ); gradleWrapperPropertiesFile.writeAsStringSync(gradleWrapperToMigrate); await migration.migrate(); expect(gradleWrapperPropertiesFile.readAsStringSync(), gradleWrapperToMigrate); expect(bufferLogger.traceText, contains(javaVersionNot17)); }); testWithoutContext('nothing is changed if gradle version not one that was ' 'used by flutter create', () async { final AndroidStudioJavaGradleConflictMigration migration = AndroidStudioJavaGradleConflictMigration( java: FakeJava(version: _javaVersion17), bufferLogger, project: project, androidStudio: FakeAndroidStudio(version: androidStudioFlamingo), ); gradleWrapperPropertiesFile.writeAsStringSync(otherGradleVersionWrapper); await migration.migrate(); expect(gradleWrapperPropertiesFile.readAsStringSync(), otherGradleVersionWrapper); expect(bufferLogger.traceText, isEmpty); }); testWithoutContext('change is made with one of the specific gradle versions' ' we migrate for', () async { final AndroidStudioJavaGradleConflictMigration migration = AndroidStudioJavaGradleConflictMigration( java: FakeJava(version: _javaVersion17), bufferLogger, project: project, androidStudio: FakeAndroidStudio(version: androidStudioFlamingo), ); gradleWrapperPropertiesFile.writeAsStringSync(gradleWrapperToMigrate); await migration.migrate(); expect(gradleWrapperPropertiesFile.readAsStringSync(), gradleWrapperToMigrateTo); expect(bufferLogger.statusText, contains('Conflict detected between ' 'Android Studio Java version and Gradle version, upgrading Gradle ' 'version from 6.7 to $gradleVersion7_6_1.')); }); testWithoutContext('change is not made when opt out flag is set', () async { final AndroidStudioJavaGradleConflictMigration migration = AndroidStudioJavaGradleConflictMigration( java: FakeJava(version: _javaVersion17), bufferLogger, project: project, androidStudio: FakeAndroidStudio(version: androidStudioFlamingo), ); gradleWrapperPropertiesFile.writeAsStringSync(gradleWrapperToMigrate + optOutFlag); await migration.migrate(); expect(gradleWrapperPropertiesFile.readAsStringSync(), gradleWrapperToMigrate + optOutFlag); expect(bufferLogger.traceText, contains(optOutFlagEnabled)); }); }); group('migrate min sdk versions less than 21 to flutter.minSdkVersion ' 'when in a FlutterProject that is an app', () { late MemoryFileSystem memoryFileSystem; late BufferLogger bufferLogger; late FakeAndroidProject project; late MinSdkVersionMigration migration; setUp(() { memoryFileSystem = MemoryFileSystem.test(); memoryFileSystem.currentDirectory.childDirectory('android').createSync(); bufferLogger = BufferLogger.test(); project = FakeAndroidProject( root: memoryFileSystem.currentDirectory.childDirectory('android'), ); project.appGradleFile.parent.createSync(recursive: true); migration = MinSdkVersionMigration( project, bufferLogger ); }); testWithoutContext('do nothing when files missing', () async { await migration.migrate(); expect(bufferLogger.traceText, contains(appGradleNotFoundWarning)); }); testWithoutContext('replace when api 19', () async { const String minSdkVersion19 = 'minSdkVersion 19'; project.appGradleFile.writeAsStringSync(sampleModuleGradleBuildFile(minSdkVersion19)); await migration.migrate(); expect(project.appGradleFile.readAsStringSync(), sampleModuleGradleBuildFile(replacementMinSdkText)); }); testWithoutContext('replace when api 20', () async { const String minSdkVersion20 = 'minSdkVersion 20'; project.appGradleFile.writeAsStringSync(sampleModuleGradleBuildFile(minSdkVersion20)); await migration.migrate(); expect(project.appGradleFile.readAsStringSync(), sampleModuleGradleBuildFile(replacementMinSdkText)); }); testWithoutContext('do nothing when >=api 21', () async { const String minSdkVersion21 = 'minSdkVersion 21'; project.appGradleFile.writeAsStringSync(sampleModuleGradleBuildFile(minSdkVersion21)); await migration.migrate(); expect(project.appGradleFile.readAsStringSync(), sampleModuleGradleBuildFile(minSdkVersion21)); }); testWithoutContext('do nothing when already using ' 'flutter.minSdkVersion', () async { project.appGradleFile.writeAsStringSync(sampleModuleGradleBuildFile(replacementMinSdkText)); await migration.migrate(); expect(project.appGradleFile.readAsStringSync(), sampleModuleGradleBuildFile(replacementMinSdkText)); }); testWithoutContext('avoid rewriting comments', () async { const String code = '// minSdkVersion 19 // old default\n' ' minSdkVersion 23 // new version'; project.appGradleFile.writeAsStringSync(sampleModuleGradleBuildFile(code)); await migration.migrate(); expect(project.appGradleFile.readAsStringSync(), sampleModuleGradleBuildFile(code)); }); testWithoutContext('do nothing when project is a module', () async { project = FakeAndroidProject( root: memoryFileSystem.currentDirectory.childDirectory('android'), module: true, ); migration = MinSdkVersionMigration( project, bufferLogger ); const String minSdkVersion19 = 'minSdkVersion 19'; project.appGradleFile.writeAsStringSync(sampleModuleGradleBuildFile(minSdkVersion19)); await migration.migrate(); expect(project.appGradleFile.readAsStringSync(), sampleModuleGradleBuildFile(minSdkVersion19)); }); testWithoutContext('do nothing when minSdkVersion is set ' 'to a constant', () async { const String minSdkVersionConstant = 'minSdkVersion kMinSdkversion'; project.appGradleFile.writeAsStringSync(sampleModuleGradleBuildFile(minSdkVersionConstant)); await migration.migrate(); expect(project.appGradleFile.readAsStringSync(), sampleModuleGradleBuildFile(minSdkVersionConstant)); }); testWithoutContext('do nothing when minSdkVersion is set ' 'using = syntax', () async { const String equalsSyntaxMinSdkVersion19 = 'minSdkVersion = 19'; project.appGradleFile.writeAsStringSync(sampleModuleGradleBuildFile(equalsSyntaxMinSdkVersion19)); await migration.migrate(); expect(project.appGradleFile.readAsStringSync(), sampleModuleGradleBuildFile(equalsSyntaxMinSdkVersion19)); }); }); group('delete FlutterMultiDexApplication.java, if it exists', () { late MemoryFileSystem memoryFileSystem; late BufferLogger bufferLogger; late FakeAndroidProject project; late MultidexRemovalMigration migration; setUp(() { memoryFileSystem = MemoryFileSystem.test(); memoryFileSystem.currentDirectory.childDirectory('android').createSync(); bufferLogger = BufferLogger.test(); project = FakeAndroidProject( root: memoryFileSystem.currentDirectory.childDirectory('android'), ); project.appGradleFile.parent.createSync(recursive: true); migration = MultidexRemovalMigration( project, bufferLogger ); }); testWithoutContext('do nothing when FlutterMultiDexApplication.java is not present', () async { await migration.migrate(); expect(bufferLogger.traceText, isEmpty); }); testWithoutContext('delete and note when FlutterMultiDexApplication.java is present', () async { // Write a blank string to the FlutterMultiDexApplication.java file. final File flutterMultiDexApplication = project.hostAppGradleRoot .childDirectory('src') .childDirectory('main') .childDirectory('java') .childDirectory('io') .childDirectory('flutter') .childDirectory('app') .childFile('FlutterMultiDexApplication.java') ..createSync(recursive: true); flutterMultiDexApplication.writeAsStringSync(''); await migration.migrate(); expect(bufferLogger.traceText, contains(MultidexRemovalMigration.deletionMessage)); expect(flutterMultiDexApplication.existsSync(), false); }); }); }); } class FakeAndroidProject extends Fake implements AndroidProject { FakeAndroidProject({required Directory root, this.module, this.plugin}) : hostAppGradleRoot = root; @override Directory hostAppGradleRoot; final bool? module; final bool? plugin; @override bool get isPlugin => plugin ?? false; @override bool get isModule => module ?? false; @override File get appGradleFile => hostAppGradleRoot.childDirectory('app').childFile('build.gradle'); } class FakeAndroidStudio extends Fake implements AndroidStudio { FakeAndroidStudio({required Version? version}) { _version = version; } late Version? _version; @override Version? get version => _version; } class FakeErroringJava extends FakeJava { @override Version get version { throw Exception('How did this happen?'); } }
flutter/packages/flutter_tools/test/general.shard/android/android_project_migration_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/general.shard/android/android_project_migration_test.dart", "repo_id": "flutter", "token_count": 7467 }
391
// Copyright 2014 The Flutter 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:args/args.dart'; import 'package:args/command_runner.dart'; import 'package:flutter_tools/executable.dart' as executable; import 'package:flutter_tools/src/cache.dart'; import 'package:flutter_tools/src/commands/analyze.dart'; import 'package:flutter_tools/src/runner/flutter_command.dart'; import 'package:flutter_tools/src/runner/flutter_command_runner.dart'; import '../src/common.dart'; import '../src/context.dart'; import '../src/testbed.dart'; import 'runner/utils.dart'; void main() { setUpAll(() { Cache.disableLocking(); }); tearDownAll(() { Cache.enableLocking(); }); test('Help for command line arguments is consistently styled and complete', () => Testbed().run(() { final FlutterCommandRunner runner = FlutterCommandRunner(verboseHelp: true); executable.generateCommands( verboseHelp: true, verbose: true, ).forEach(runner.addCommand); verifyCommandRunner(runner); for (final Command<void> command in runner.commands.values) { if (command.name == 'analyze') { final AnalyzeCommand analyze = command as AnalyzeCommand; expect(analyze.allProjectValidators().length, 2); } } })); testUsingContext('Global arg results are available in FlutterCommands', () async { final DummyFlutterCommand command = DummyFlutterCommand( commandFunction: () async { return const FlutterCommandResult(ExitStatus.success); }, ); final FlutterCommandRunner runner = FlutterCommandRunner(verboseHelp: true); runner.addCommand(command); await runner.run(<String>['dummy', '--${FlutterGlobalOptions.kContinuousIntegrationFlag}']); expect(command.globalResults, isNotNull); expect(command.boolArg(FlutterGlobalOptions.kContinuousIntegrationFlag, global: true), true); }); testUsingContext('Global arg results are available in FlutterCommands sub commands', () async { final DummyFlutterCommand command = DummyFlutterCommand( commandFunction: () async { return const FlutterCommandResult(ExitStatus.success); }, ); final DummyFlutterCommand subcommand = DummyFlutterCommand( name: 'sub', commandFunction: () async { return const FlutterCommandResult(ExitStatus.success); }, ); command.addSubcommand(subcommand); final FlutterCommandRunner runner = FlutterCommandRunner(verboseHelp: true); runner.addCommand(command); runner.addCommand(subcommand); await runner.run(<String>['dummy', 'sub', '--${FlutterGlobalOptions.kContinuousIntegrationFlag}']); expect(subcommand.globalResults, isNotNull); expect(subcommand.boolArg(FlutterGlobalOptions.kContinuousIntegrationFlag, global: true), true); }); testUsingContext('bool? safe argResults', () async { final DummyFlutterCommand command = DummyFlutterCommand( commandFunction: () async { return const FlutterCommandResult(ExitStatus.success); }, ); final FlutterCommandRunner runner = FlutterCommandRunner(verboseHelp: true); command.argParser.addFlag('key'); command.argParser.addFlag('key-false'); // argResults will be null at this point, if attempt to read them is made, // exception `Null check operator used on a null value` would be thrown. expect(() => command.boolArg('key'), throwsA(const TypeMatcher<TypeError>())); runner.addCommand(command); await runner.run(<String>['dummy', '--key']); expect(command.boolArg('key'), true); expect(() => command.boolArg('non-existent'), throwsArgumentError); expect(command.boolArg('key'), true); expect(() => command.boolArg('non-existent'), throwsA(const TypeMatcher<ArgumentError>())); expect(command.boolArg('key-false'), false); expect(command.boolArg('key-false'), false); }); testUsingContext('String? safe argResults', () async { final DummyFlutterCommand command = DummyFlutterCommand( commandFunction: () async { return const FlutterCommandResult(ExitStatus.success); }, ); final FlutterCommandRunner runner = FlutterCommandRunner(verboseHelp: true); command.argParser.addOption('key'); // argResults will be null at this point, if attempt to read them is made, // exception `Null check operator used on a null value` would be thrown expect(() => command.stringArg('key'), throwsA(const TypeMatcher<TypeError>())); runner.addCommand(command); await runner.run(<String>['dummy', '--key=value']); expect(command.stringArg('key'), 'value'); expect(() => command.stringArg('non-existent'), throwsArgumentError); expect(command.stringArg('key'), 'value'); expect(() => command.stringArg('non-existent'), throwsA(const TypeMatcher<ArgumentError>())); }); testUsingContext('List<String> safe argResults', () async { final DummyFlutterCommand command = DummyFlutterCommand( commandFunction: () async { return const FlutterCommandResult(ExitStatus.success); }, ); final FlutterCommandRunner runner = FlutterCommandRunner(verboseHelp: true); command.argParser.addMultiOption( 'key', allowed: <String>['a', 'b', 'c'], ); // argResults will be null at this point, if attempt to read them is made, // exception `Null check operator used on a null value` would be thrown. expect(() => command.stringsArg('key'), throwsA(const TypeMatcher<TypeError>())); runner.addCommand(command); await runner.run(<String>['dummy', '--key', 'a']); // throws error when trying to parse non-existent key. expect(() => command.stringsArg('non-existent'), throwsA(const TypeMatcher<ArgumentError>())); expect(command.stringsArg('key'), <String>['a']); await runner.run(<String>['dummy', '--key', 'a', '--key', 'b']); expect(command.stringsArg('key'), <String>['a', 'b']); await runner.run(<String>['dummy']); expect(command.stringsArg('key'), <String>[]); }); } void verifyCommandRunner(CommandRunner<Object?> runner) { expect(runner.argParser, isNotNull, reason: '${runner.runtimeType} has no argParser'); expect(runner.argParser.allowsAnything, isFalse, reason: '${runner.runtimeType} allows anything'); expect(runner.argParser.allowTrailingOptions, isFalse, reason: '${runner.runtimeType} allows trailing options'); verifyOptions(null, runner.argParser.options.values); runner.commands.values.forEach(verifyCommand); } void verifyCommand(Command<Object?> runner) { expect(runner.argParser, isNotNull, reason: 'command ${runner.name} has no argParser'); verifyOptions(runner.name, runner.argParser.options.values); final String firstDescriptionLine = runner.description.split('\n').first; expect(firstDescriptionLine, matches(_allowedTrailingPatterns), reason: "command ${runner.name}'s description does not end with the expected single period that a full sentence should end with"); if (!runner.hidden && runner.parent == null) { expect( runner.category, anyOf( FlutterCommandCategory.sdk, FlutterCommandCategory.project, FlutterCommandCategory.tools, ), reason: "top-level command ${runner.name} doesn't have a valid category", ); } runner.subcommands.values.forEach(verifyCommand); } // Patterns for arguments names. final RegExp _allowedArgumentNamePattern = RegExp(r'^([-a-z0-9]+)$'); final RegExp _allowedArgumentNamePatternForPrecache = RegExp(r'^([-a-z0-9_]+)$'); final RegExp _bannedArgumentNamePattern = RegExp(r'-uri$'); // Patterns for help messages. final RegExp _bannedLeadingPatterns = RegExp(r'^[-a-z]', multiLine: true); final RegExp _allowedTrailingPatterns = RegExp(r'([^ ]([^.^!^:][.!:])\)?|: https?://[^ ]+[^.]|^)$'); final RegExp _bannedQuotePatterns = RegExp(r" '|' |'\.|\('|'\)|`"); final RegExp _bannedArgumentReferencePatterns = RegExp(r'[^"=]--[^ ]'); final RegExp _questionablePatterns = RegExp(r'[a-z]\.[A-Z]'); final RegExp _bannedUri = RegExp(r'\b[Uu][Rr][Ii]\b'); final RegExp _nonSecureFlutterDartUrl = RegExp(r'http://([a-z0-9-]+\.)*(flutter|dart)\.dev', caseSensitive: false); const String _needHelp = "Every option must have help explaining what it does, even if it's " 'for testing purposes, because this is the bare minimum of ' 'documentation we can add just for ourselves. If it is not intended ' 'for developers, then use "hide: !verboseHelp" to only show the ' 'help when people run with "--help --verbose".'; const String _header = ' Comment: '; void verifyOptions(String? command, Iterable<Option> options) { String target; if (command == null) { target = 'the global argument "'; } else { target = '"flutter $command '; } assert(target.contains('"')); for (final Option option in options) { // If you think you need to add an exception here, please ask Hixie (but he'll say no). if (command == 'precache') { expect(option.name, matches(_allowedArgumentNamePatternForPrecache), reason: '$_header$target--${option.name}" is not a valid name for a command line argument. (Is it all lowercase?)'); } else { expect(option.name, matches(_allowedArgumentNamePattern), reason: '$_header$target--${option.name}" is not a valid name for a command line argument. (Is it all lowercase? Does it use hyphens rather than underscores?)'); } expect(option.name, isNot(matches(_bannedArgumentNamePattern)), reason: '$_header$target--${option.name}" is not a valid name for a command line argument. (We use "--foo-url", not "--foo-uri", for example.)'); // The flag --sound-null-safety is deprecated if (option.name != FlutterOptions.kNullSafety && option.name != FlutterOptions.kNullAssertions) { expect(option.hide, isFalse, reason: '${_header}Help for $target--${option.name}" is always hidden. $_needHelp'); } expect(option.help, isNotNull, reason: '${_header}Help for $target--${option.name}" has null help. $_needHelp'); expect(option.help, isNotEmpty, reason: '${_header}Help for $target--${option.name}" has empty help. $_needHelp'); expect(option.help, isNot(matches(_bannedLeadingPatterns)), reason: '${_header}A line in the help for $target--${option.name}" starts with a lowercase letter. For stylistic consistency, all help messages must start with a capital letter.'); expect(option.help, isNot(startsWith('(Deprecated')), reason: '${_header}Help for $target--${option.name}" should start with lowercase "(deprecated)" for consistency with other deprecated commands.'); expect(option.help, isNot(startsWith('(Required')), reason: '${_header}Help for $target--${option.name}" should start with lowercase "(required)" for consistency with other deprecated commands.'); expect(option.help, isNot(contains('?')), reason: '${_header}Help for $target--${option.name}" has a question mark. Generally we prefer the passive voice for help messages.'); expect(option.help, isNot(contains('Note:')), reason: '${_header}Help for $target--${option.name}" uses "Note:". See our style guide entry about "empty prose".'); expect(option.help, isNot(contains('Note that')), reason: '${_header}Help for $target--${option.name}" uses "Note that". See our style guide entry about "empty prose".'); expect(option.help, isNot(matches(_bannedQuotePatterns)), reason: '${_header}Help for $target--${option.name}" uses single quotes or backticks instead of double quotes in the help message. For consistency we use double quotes throughout.'); expect(option.help, isNot(matches(_questionablePatterns)), reason: '${_header}Help for $target--${option.name}" may have a typo. (If it does not you may have to update args_test.dart, sorry. Search for "_questionablePatterns")'); if (option.defaultsTo != null) { expect(option.help, isNot(contains('Default')), reason: '${_header}Help for $target--${option.name}" mentions the default value but that is redundant with the defaultsTo option which is also specified (and preferred).'); final Map<String, String>? allowedHelp = option.allowedHelp; if (allowedHelp != null) { for (final String allowedValue in allowedHelp.keys) { expect( allowedHelp[allowedValue], isNot(anyOf(contains('default'), contains('Default'))), reason: '${_header}Help for $target--${option.name} $allowedValue" mentions the default value but that is redundant with the defaultsTo option which is also specified (and preferred).', ); } } } expect(option.help, isNot(matches(_bannedArgumentReferencePatterns)), reason: '${_header}Help for $target--${option.name}" contains the string "--" in an unexpected way. If it\'s trying to mention another argument, it should be quoted, as in "--foo".'); for (final String line in option.help!.split('\n')) { if (!line.startsWith(' ')) { expect(line, isNot(contains(' ')), reason: '${_header}Help for $target--${option.name}" has excessive whitespace (check e.g. for double spaces after periods or round line breaks in the source).'); expect(line, matches(_allowedTrailingPatterns), reason: '${_header}A line in the help for $target--${option.name}" does not end with the expected period that a full sentence should end with. (If the help ends with a URL, place it after a colon, don\'t leave a trailing period; if it\'s sample code, prefix the line with four spaces.)'); } } expect(option.help, isNot(endsWith(':')), reason: '${_header}Help for $target--${option.name}" ends with a colon, which seems unlikely to be correct.'); expect(option.help, isNot(contains(_bannedUri)), reason: '${_header}Help for $target--${option.name}" uses the term "URI" rather than "URL".'); expect(option.help, isNot(contains(_nonSecureFlutterDartUrl)), reason: '${_header}Help for $target--${option.name}" links to a non-secure ("http") version of a Flutter or Dart site.'); // TODO(ianh): add some checking for embedded URLs to make sure we're consistent on how we format those. // TODO(ianh): arguably we should ban help text that starts with "Whether to..." since by definition a flag is to enable a feature, so the "whether to" is redundant. } }
flutter/packages/flutter_tools/test/general.shard/args_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/general.shard/args_test.dart", "repo_id": "flutter", "token_count": 4732 }
392
// Copyright 2014 The Flutter 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:file/memory.dart'; import 'package:flutter_tools/src/base/deferred_component.dart'; import 'package:flutter_tools/src/base/file_system.dart'; import 'package:flutter_tools/src/base/logger.dart'; import 'package:flutter_tools/src/flutter_manifest.dart'; import '../../src/common.dart'; void main() { group('DeferredComponent basics', () { testWithoutContext('constructor sets values', () { final DeferredComponent component = DeferredComponent( name: 'bestcomponent', libraries: <String>['lib1', 'lib2'], assets: <AssetsEntry>[ AssetsEntry(uri: Uri.file('asset1')), AssetsEntry(uri: Uri.file('asset2')), ], ); expect(component.name, 'bestcomponent'); expect(component.libraries, <String>['lib1', 'lib2']); expect(component.assets, <AssetsEntry>[ AssetsEntry(uri: Uri.file('asset1')), AssetsEntry(uri: Uri.file('asset2')), ]); }); testWithoutContext('assignLoadingUnits selects the needed loading units and sets assigned', () { final DeferredComponent component = DeferredComponent( name: 'bestcomponent', libraries: <String>['lib1', 'lib2'], assets: <AssetsEntry>[ AssetsEntry(uri: Uri.file('asset1')), AssetsEntry(uri: Uri.file('asset2')), ], ); expect(component.libraries, <String>['lib1', 'lib2']); expect(component.assigned, false); expect(component.loadingUnits, null); final List<LoadingUnit> loadingUnits1 = <LoadingUnit>[ LoadingUnit( id: 2, path: 'path/to/so.so', libraries: <String>['lib1', 'lib4'], ), LoadingUnit( id: 3, path: 'path/to/so.so', libraries: <String>['lib2', 'lib5'], ), LoadingUnit( id: 4, path: 'path/to/so.so', libraries: <String>['lib6', 'lib7'], ), ]; component.assignLoadingUnits(loadingUnits1); expect(component.assigned, true); expect(component.loadingUnits, hasLength(2)); expect(component.loadingUnits, contains(loadingUnits1[0])); expect(component.loadingUnits, contains(loadingUnits1[1])); expect(component.loadingUnits, isNot(contains(loadingUnits1[2]))); final List<LoadingUnit> loadingUnits2 = <LoadingUnit>[ LoadingUnit( id: 2, path: 'path/to/so.so', libraries: <String>['lib1', 'lib2'], ), LoadingUnit( id: 3, path: 'path/to/so.so', libraries: <String>['lib5', 'lib6'], ), LoadingUnit( id: 4, path: 'path/to/so.so', libraries: <String>['lib7', 'lib8'], ), ]; // Can reassign loading units. component.assignLoadingUnits(loadingUnits2); expect(component.assigned, true); expect(component.loadingUnits, hasLength(1)); expect(component.loadingUnits, contains(loadingUnits2[0])); expect(component.loadingUnits, isNot(contains(loadingUnits2[1]))); expect(component.loadingUnits, isNot(contains(loadingUnits2[2]))); component.assignLoadingUnits(<LoadingUnit>[]); expect(component.assigned, true); expect(component.loadingUnits, hasLength(0)); }); testWithoutContext('toString produces correct string for unassigned component', () { final DeferredComponent component = DeferredComponent( name: 'bestcomponent', libraries: <String>['lib1', 'lib2'], assets: <AssetsEntry>[ AssetsEntry(uri: Uri.file('asset1')), AssetsEntry(uri: Uri.file('asset2')), ], ); expect(component.toString(), '\nDeferredComponent: bestcomponent\n Libraries:\n - lib1\n - lib2\n Assets:\n - asset1\n - asset2'); }); testWithoutContext('toString produces correct string for assigned component', () { final DeferredComponent component = DeferredComponent( name: 'bestcomponent', libraries: <String>['lib1', 'lib2'], assets: <AssetsEntry>[ AssetsEntry(uri: Uri.file('asset1')), AssetsEntry(uri: Uri.file('asset2')), ], ); component.assignLoadingUnits(<LoadingUnit>[LoadingUnit(id: 2, libraries: <String>['lib1'])]); expect(component.toString(), '\nDeferredComponent: bestcomponent\n Libraries:\n - lib1\n - lib2\n LoadingUnits:\n - 2\n Assets:\n - asset1\n - asset2'); }); }); group('LoadingUnit basics', () { testWithoutContext('constructor sets values', () { final LoadingUnit unit = LoadingUnit( id: 2, path: 'path/to/so.so', libraries: <String>['lib1', 'lib4'], ); expect(unit.id, 2); expect(unit.path, 'path/to/so.so'); expect(unit.libraries, <String>['lib1', 'lib4']); }); testWithoutContext('toString produces correct string', () { final LoadingUnit unit = LoadingUnit( id: 2, path: 'path/to/so.so', libraries: <String>['lib1', 'lib4'], ); expect(unit.toString(),'\nLoadingUnit 2\n Libraries:\n - lib1\n - lib4'); }); testWithoutContext('equalsIgnoringPath works for various input', () { final LoadingUnit unit1 = LoadingUnit( id: 2, path: 'path/to/so.so', libraries: <String>['lib1', 'lib4'], ); final LoadingUnit unit2 = LoadingUnit( id: 2, path: 'path/to/other/so.so', libraries: <String>['lib1', 'lib4'], ); final LoadingUnit unit3 = LoadingUnit( id: 1, path: 'path/to/other/so.so', libraries: <String>['lib1', 'lib4'], ); final LoadingUnit unit4 = LoadingUnit( id: 1, path: 'path/to/other/so.so', libraries: <String>['lib1'], ); final LoadingUnit unit5 = LoadingUnit( id: 1, path: 'path/to/other/so.so', libraries: <String>['lib2'], ); final LoadingUnit unit6 = LoadingUnit( id: 1, path: 'path/to/other/so.so', libraries: <String>['lib1', 'lib5'], ); expect(unit1.equalsIgnoringPath(unit2), true); expect(unit2.equalsIgnoringPath(unit3), false); expect(unit3.equalsIgnoringPath(unit4), false); expect(unit4.equalsIgnoringPath(unit5), false); expect(unit5.equalsIgnoringPath(unit6), false); }); testWithoutContext('parseLoadingUnitManifest parses single manifest file', () { final FileSystem fileSystem = MemoryFileSystem.test(); final File manifest = fileSystem.file('/manifest.json'); manifest.createSync(recursive: true); manifest.writeAsStringSync(r''' { "loadingUnits": [ { "id": 1, "path": "\/arm64-v8a\/app.so", "libraries": [ "dart:core"]} , { "id": 2, "path": "\/arm64-v8a\/app.so-2.part.so", "libraries": [ "lib2"]} , { "id": 3, "path": "\/arm64-v8a\/app.so-3.part.so", "libraries": [ "lib3", "lib4"]} ] } ''', flush: true); final List<LoadingUnit> loadingUnits = LoadingUnit.parseLoadingUnitManifest(manifest, BufferLogger.test()); expect(loadingUnits.length, 2); // base module (id 1) is not parsed. expect(loadingUnits[0].id, 2); expect(loadingUnits[0].path, '/arm64-v8a/app.so-2.part.so'); expect(loadingUnits[0].libraries.length, 1); expect(loadingUnits[0].libraries[0], 'lib2'); expect(loadingUnits[1].id, 3); expect(loadingUnits[1].path, '/arm64-v8a/app.so-3.part.so'); expect(loadingUnits[1].libraries.length, 2); expect(loadingUnits[1].libraries[0], 'lib3'); expect(loadingUnits[1].libraries[1], 'lib4'); }); testWithoutContext('parseLoadingUnitManifest returns empty when manifest is invalid JSON', () { final FileSystem fileSystem = MemoryFileSystem.test(); final File manifest = fileSystem.file('/manifest.json'); manifest.createSync(recursive: true); // invalid due to missing closing brace `}` manifest.writeAsStringSync(r''' { "loadingUnits": [ { "id": 1, "path": "\/arm64-v8a\/app.so", "libraries": [ "dart:core"]} , { "id": 2, "path": "\/arm64-v8a\/app.so-2.part.so", "libraries": [ "lib2"]} , { "id": 3, "path": "\/arm64-v8a\/app.so-3.part.so", "libraries": [ "lib3", "lib4"]} ] ''', flush: true); final List<LoadingUnit> loadingUnits = LoadingUnit.parseLoadingUnitManifest(manifest, BufferLogger.test()); expect(loadingUnits.length, 0); expect(loadingUnits.isEmpty, true); }); testWithoutContext('parseLoadingUnitManifest does not exist', () { final FileSystem fileSystem = MemoryFileSystem.test(); final File manifest = fileSystem.file('/manifest.json'); if (manifest.existsSync()) { manifest.deleteSync(recursive: true); } final List<LoadingUnit> loadingUnits = LoadingUnit.parseLoadingUnitManifest(manifest, BufferLogger.test()); expect(loadingUnits.length, 0); expect(loadingUnits.isEmpty, true); }); testWithoutContext('parseGeneratedLoadingUnits parses all abis if no abis provided', () { final FileSystem fileSystem = MemoryFileSystem.test(); final File manifest1 = fileSystem.file('/test-abi1/manifest.json'); manifest1.createSync(recursive: true); manifest1.writeAsStringSync(r''' { "loadingUnits": [ { "id": 1, "path": "\/test-abi1\/app.so", "libraries": [ "dart:core"]} , { "id": 2, "path": "\/test-abi1\/app.so-2.part.so", "libraries": [ "lib2"]} , { "id": 3, "path": "\/test-abi1\/app.so-3.part.so", "libraries": [ "lib3", "lib4"]} ] } ''', flush: true); final File manifest2 = fileSystem.file('/test-abi2/manifest.json'); manifest2.createSync(recursive: true); manifest2.writeAsStringSync(r''' { "loadingUnits": [ { "id": 1, "path": "\/test-abi2\/app.so", "libraries": [ "dart:core"]} , { "id": 2, "path": "\/test-abi2\/app.so-2.part.so", "libraries": [ "lib2"]} , { "id": 3, "path": "\/test-abi2\/app.so-3.part.so", "libraries": [ "lib3", "lib4"]} ] } ''', flush: true); final List<LoadingUnit> loadingUnits = LoadingUnit.parseGeneratedLoadingUnits(fileSystem.directory('/'), BufferLogger.test()); expect(loadingUnits.length, 4); // base module (id 1) is not parsed. expect(loadingUnits[0].id, 2); expect(loadingUnits[0].path, '/test-abi2/app.so-2.part.so'); expect(loadingUnits[0].libraries.length, 1); expect(loadingUnits[0].libraries[0], 'lib2'); expect(loadingUnits[1].id, 3); expect(loadingUnits[1].path, '/test-abi2/app.so-3.part.so'); expect(loadingUnits[1].libraries.length, 2); expect(loadingUnits[1].libraries[0], 'lib3'); expect(loadingUnits[1].libraries[1], 'lib4'); expect(loadingUnits[2].id, 2); expect(loadingUnits[2].path, '/test-abi1/app.so-2.part.so'); expect(loadingUnits[2].libraries.length, 1); expect(loadingUnits[2].libraries[0], 'lib2'); expect(loadingUnits[3].id, 3); expect(loadingUnits[3].path, '/test-abi1/app.so-3.part.so'); expect(loadingUnits[3].libraries.length, 2); expect(loadingUnits[3].libraries[0], 'lib3'); expect(loadingUnits[3].libraries[1], 'lib4'); }); testWithoutContext('parseGeneratedLoadingUnits only parses provided abis', () { final FileSystem fileSystem = MemoryFileSystem.test(); final File manifest1 = fileSystem.file('/test-abi1/manifest.json'); manifest1.createSync(recursive: true); manifest1.writeAsStringSync(r''' { "loadingUnits": [ { "id": 1, "path": "\/test-abi1\/app.so", "libraries": [ "dart:core"]} , { "id": 2, "path": "\/test-abi1\/app.so-2.part.so", "libraries": [ "lib2"]} , { "id": 3, "path": "\/test-abi1\/app.so-3.part.so", "libraries": [ "lib3", "lib4"]} ] } ''', flush: true); final File manifest2 = fileSystem.file('/test-abi2/manifest.json'); manifest2.createSync(recursive: true); manifest2.writeAsStringSync(r''' { "loadingUnits": [ { "id": 1, "path": "\/test-abi2\/app.so", "libraries": [ "dart:core"]} , { "id": 2, "path": "\/test-abi2\/app.so-2.part.so", "libraries": [ "lib2"]} , { "id": 3, "path": "\/test-abi2\/app.so-3.part.so", "libraries": [ "lib3", "lib4"]} ] } ''', flush: true); final List<LoadingUnit> loadingUnits = LoadingUnit.parseGeneratedLoadingUnits(fileSystem.directory('/'), BufferLogger.test(), abis: <String>['test-abi2']); expect(loadingUnits.length, 2); // base module (id 1) is not parsed. expect(loadingUnits[0].id, 2); expect(loadingUnits[0].path, '/test-abi2/app.so-2.part.so'); expect(loadingUnits[0].libraries.length, 1); expect(loadingUnits[0].libraries[0], 'lib2'); expect(loadingUnits[1].id, 3); expect(loadingUnits[1].path, '/test-abi2/app.so-3.part.so'); expect(loadingUnits[1].libraries.length, 2); expect(loadingUnits[1].libraries[0], 'lib3'); expect(loadingUnits[1].libraries[1], 'lib4'); }); testWithoutContext('parseGeneratedLoadingUnits returns empty when no manifest files exist', () { final FileSystem fileSystem = MemoryFileSystem.test(); final List<LoadingUnit> loadingUnits = LoadingUnit.parseGeneratedLoadingUnits(fileSystem.directory('/'), BufferLogger.test()); expect(loadingUnits.isEmpty, true); expect(loadingUnits.length, 0); }); }); }
flutter/packages/flutter_tools/test/general.shard/base/deferred_component_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/general.shard/base/deferred_component_test.dart", "repo_id": "flutter", "token_count": 5714 }
393
// Copyright 2014 The Flutter 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:flutter_tools/src/base/utils.dart'; import '../src/common.dart'; void main() { group('ItemListNotifier', () { test('sends notifications', () async { final ItemListNotifier<String> list = ItemListNotifier<String>(); expect(list.items, isEmpty); final Future<List<String>> addedStreamItems = list.onAdded.toList(); final Future<List<String>> removedStreamItems = list.onRemoved.toList(); list.updateWithNewList(<String>['aaa']); list.removeItem('bogus'); list.updateWithNewList(<String>['aaa', 'bbb', 'ccc']); list.updateWithNewList(<String>['bbb', 'ccc']); list.removeItem('bbb'); expect(list.items, <String>['ccc']); list.dispose(); final List<String> addedItems = await addedStreamItems; final List<String> removedItems = await removedStreamItems; expect(addedItems.length, 3); expect(addedItems.first, 'aaa'); expect(addedItems[1], 'bbb'); expect(addedItems[2], 'ccc'); expect(removedItems.length, 2); expect(removedItems.first, 'aaa'); expect(removedItems[1], 'bbb'); }); test('becomes populated when item is added', () async { final ItemListNotifier<String> list = ItemListNotifier<String>(); expect(list.isPopulated, false); expect(list.items, isEmpty); // Becomes populated when a new list is added. list.updateWithNewList(<String>['a']); expect(list.isPopulated, true); expect(list.items, <String>['a']); // Remain populated even when the last item is removed. list.removeItem('a'); expect(list.isPopulated, true); expect(list.items, isEmpty); }); test('is populated by default if initialized with list of items', () async { final ItemListNotifier<String> list = ItemListNotifier<String>.from(<String>['a']); expect(list.isPopulated, true); expect(list.items, <String>['a']); }); }); }
flutter/packages/flutter_tools/test/general.shard/base_utils_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/general.shard/base_utils_test.dart", "repo_id": "flutter", "token_count": 791 }
394
// Copyright 2014 The Flutter 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:file/memory.dart'; import 'package:flutter_tools/src/artifacts.dart'; import 'package:flutter_tools/src/base/file_system.dart'; import 'package:flutter_tools/src/base/logger.dart'; import 'package:flutter_tools/src/build_info.dart'; import 'package:flutter_tools/src/build_system/build_system.dart'; import 'package:flutter_tools/src/build_system/targets/icon_tree_shaker.dart'; import 'package:flutter_tools/src/devfs.dart'; import '../../../src/common.dart'; import '../../../src/fake_process_manager.dart'; import '../../../src/fakes.dart'; const List<int> _kTtfHeaderBytes = <int>[0, 1, 0, 0, 0, 15, 0, 128, 0, 3, 0, 112]; const String inputPath = '/input/fonts/MaterialIcons-Regular.otf'; const String outputPath = '/output/fonts/MaterialIcons-Regular.otf'; const String relativePath = 'fonts/MaterialIcons-Regular.otf'; final RegExp whitespace = RegExp(r'\s+'); void main() { late BufferLogger logger; late MemoryFileSystem fileSystem; late FakeProcessManager processManager; late Artifacts artifacts; late DevFSStringContent fontManifestContent; late String dartPath; late String constFinderPath; late String fontSubsetPath; late List<String> fontSubsetArgs; List<String> getConstFinderArgs(String appDillPath) => <String>[ dartPath, '--disable-dart-dev', constFinderPath, '--kernel-file', appDillPath, '--class-library-uri', 'package:flutter/src/widgets/icon_data.dart', '--class-name', 'IconData', '--annotation-class-name', '_StaticIconProvider', '--annotation-class-library-uri', 'package:flutter/src/widgets/icon_data.dart', ]; void addConstFinderInvocation( String appDillPath, { int exitCode = 0, String stdout = '', String stderr = '', }) { processManager.addCommand(FakeCommand( command: getConstFinderArgs(appDillPath), exitCode: exitCode, stdout: stdout, stderr: stderr, )); } void resetFontSubsetInvocation({ int exitCode = 0, String stdout = '', String stderr = '', required CompleterIOSink stdinSink, }) { stdinSink.clear(); processManager.addCommand(FakeCommand( command: fontSubsetArgs, exitCode: exitCode, stdout: stdout, stderr: stderr, stdin: stdinSink, )); } setUp(() { processManager = FakeProcessManager.empty(); fontManifestContent = DevFSStringContent(validFontManifestJson); artifacts = Artifacts.test(); fileSystem = MemoryFileSystem.test(); logger = BufferLogger.test(); dartPath = artifacts.getArtifactPath(Artifact.engineDartBinary); constFinderPath = artifacts.getArtifactPath(Artifact.constFinder); fontSubsetPath = artifacts.getArtifactPath(Artifact.fontSubset); fontSubsetArgs = <String>[ fontSubsetPath, outputPath, inputPath, ]; fileSystem.file(constFinderPath).createSync(recursive: true); fileSystem.file(dartPath).createSync(recursive: true); fileSystem.file(fontSubsetPath).createSync(recursive: true); fileSystem.file(inputPath) ..createSync(recursive: true) ..writeAsBytesSync(_kTtfHeaderBytes); }); Environment createEnvironment(Map<String, String> defines) { return Environment.test( fileSystem.directory('/icon_test')..createSync(recursive: true), defines: defines, artifacts: artifacts, processManager: FakeProcessManager.any(), fileSystem: fileSystem, logger: BufferLogger.test(), ); } testWithoutContext('Prints error in debug mode environment', () async { final Environment environment = createEnvironment(<String, String>{ kIconTreeShakerFlag: 'true', kBuildMode: 'debug', }); final IconTreeShaker iconTreeShaker = IconTreeShaker( environment, fontManifestContent, logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: artifacts, targetPlatform: TargetPlatform.android, ); expect( logger.errorText, 'Font subsetting is not supported in debug mode. The --tree-shake-icons' ' flag will be ignored.\n', ); expect(iconTreeShaker.enabled, false); final bool subsets = await iconTreeShaker.subsetFont( input: fileSystem.file(inputPath), outputPath: outputPath, relativePath: relativePath, ); expect(subsets, false); expect(processManager, hasNoRemainingExpectations); }); testWithoutContext('Does not get enabled without font manifest', () { final Environment environment = createEnvironment(<String, String>{ kIconTreeShakerFlag: 'true', kBuildMode: 'release', }); final IconTreeShaker iconTreeShaker = IconTreeShaker( environment, null, logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: artifacts, targetPlatform: TargetPlatform.android, ); expect( logger.errorText, isEmpty, ); expect(iconTreeShaker.enabled, false); expect(processManager, hasNoRemainingExpectations); }); testWithoutContext('Gets enabled', () { final Environment environment = createEnvironment(<String, String>{ kIconTreeShakerFlag: 'true', kBuildMode: 'release', }); final IconTreeShaker iconTreeShaker = IconTreeShaker( environment, fontManifestContent, logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: artifacts, targetPlatform: TargetPlatform.android, ); expect( logger.errorText, isEmpty, ); expect(iconTreeShaker.enabled, true); expect(processManager, hasNoRemainingExpectations); }); test('No app.dill throws exception', () async { final Environment environment = createEnvironment(<String, String>{ kIconTreeShakerFlag: 'true', kBuildMode: 'release', }); final IconTreeShaker iconTreeShaker = IconTreeShaker( environment, fontManifestContent, logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: artifacts, targetPlatform: TargetPlatform.android, ); expect( () async => iconTreeShaker.subsetFont( input: fileSystem.file(inputPath), outputPath: outputPath, relativePath: relativePath, ), throwsA(isA<IconTreeShakerException>()), ); expect(processManager, hasNoRemainingExpectations); }); testWithoutContext('Can subset a font', () async { final Environment environment = createEnvironment(<String, String>{ kIconTreeShakerFlag: 'true', kBuildMode: 'release', }); final File appDill = environment.buildDir.childFile('app.dill') ..createSync(recursive: true); final IconTreeShaker iconTreeShaker = IconTreeShaker( environment, fontManifestContent, logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: artifacts, targetPlatform: TargetPlatform.android, ); final CompleterIOSink stdinSink = CompleterIOSink(); addConstFinderInvocation(appDill.path, stdout: validConstFinderResult); resetFontSubsetInvocation(stdinSink: stdinSink); // Font starts out 2500 bytes long final File inputFont = fileSystem.file(inputPath) ..writeAsBytesSync(List<int>.filled(2500, 0)); // after subsetting, font is 1200 bytes long fileSystem.file(outputPath) ..createSync(recursive: true) ..writeAsBytesSync(List<int>.filled(1200, 0)); bool subsetted = await iconTreeShaker.subsetFont( input: inputFont, outputPath: outputPath, relativePath: relativePath, ); expect(stdinSink.getAndClear(), '59470\n'); resetFontSubsetInvocation(stdinSink: stdinSink); expect(subsetted, true); subsetted = await iconTreeShaker.subsetFont( input: fileSystem.file(inputPath), outputPath: outputPath, relativePath: relativePath, ); expect(subsetted, true); expect(stdinSink.getAndClear(), '59470\n'); expect(processManager, hasNoRemainingExpectations); expect( logger.statusText, contains('Font asset "MaterialIcons-Regular.otf" was tree-shaken, reducing it from 2500 to 1200 bytes (52.0% reduction). Tree-shaking can be disabled by providing the --no-tree-shake-icons flag when building your app.'), ); }); testWithoutContext('Does not subset a non-supported font', () async { final Environment environment = createEnvironment(<String, String>{ kIconTreeShakerFlag: 'true', kBuildMode: 'release', }); final File appDill = environment.buildDir.childFile('app.dill') ..createSync(recursive: true); final IconTreeShaker iconTreeShaker = IconTreeShaker( environment, fontManifestContent, logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: artifacts, targetPlatform: TargetPlatform.android, ); final CompleterIOSink stdinSink = CompleterIOSink(); addConstFinderInvocation(appDill.path, stdout: validConstFinderResult); resetFontSubsetInvocation(stdinSink: stdinSink); final File notAFont = fileSystem.file('input/foo/bar.txt') ..createSync(recursive: true) ..writeAsStringSync('I could not think of a better string'); final bool subsetted = await iconTreeShaker.subsetFont( input: notAFont, outputPath: outputPath, relativePath: relativePath, ); expect(subsetted, false); }); testWithoutContext('Does not subset an invalid ttf font', () async { final Environment environment = createEnvironment(<String, String>{ kIconTreeShakerFlag: 'true', kBuildMode: 'release', }); final File appDill = environment.buildDir.childFile('app.dill') ..createSync(recursive: true); final IconTreeShaker iconTreeShaker = IconTreeShaker( environment, fontManifestContent, logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: artifacts, targetPlatform: TargetPlatform.android, ); final CompleterIOSink stdinSink = CompleterIOSink(); addConstFinderInvocation(appDill.path, stdout: validConstFinderResult); resetFontSubsetInvocation(stdinSink: stdinSink); final File notAFont = fileSystem.file(inputPath) ..writeAsBytesSync(<int>[0, 1, 2]); final bool subsetted = await iconTreeShaker.subsetFont( input: notAFont, outputPath: outputPath, relativePath: relativePath, ); expect(subsetted, false); }); for (final TargetPlatform platform in <TargetPlatform>[TargetPlatform.android_arm, TargetPlatform.web_javascript]) { testWithoutContext('Non-constant instances $platform', () async { final Environment environment = createEnvironment(<String, String>{ kIconTreeShakerFlag: 'true', kBuildMode: 'release', }); final File appDill = environment.buildDir.childFile('app.dill') ..createSync(recursive: true); final IconTreeShaker iconTreeShaker = IconTreeShaker( environment, fontManifestContent, logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: artifacts, targetPlatform: platform, ); addConstFinderInvocation(appDill.path, stdout: constFinderResultWithInvalid); await expectLater( () => iconTreeShaker.subsetFont( input: fileSystem.file(inputPath), outputPath: outputPath, relativePath: relativePath, ), throwsToolExit( message: 'Avoid non-constant invocations of IconData or try to build' ' again with --no-tree-shake-icons.', ), ); expect(processManager, hasNoRemainingExpectations); }); } testWithoutContext('Does not add 0x32 for non-web builds', () async { final Environment environment = createEnvironment(<String, String>{ kIconTreeShakerFlag: 'true', kBuildMode: 'release', }); final File appDill = environment.buildDir.childFile('app.dill') ..createSync(recursive: true); final IconTreeShaker iconTreeShaker = IconTreeShaker( environment, fontManifestContent, logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: artifacts, targetPlatform: TargetPlatform.android_arm64, ); addConstFinderInvocation( appDill.path, // Does not contain space char stdout: validConstFinderResult, ); final CompleterIOSink stdinSink = CompleterIOSink(); resetFontSubsetInvocation(stdinSink: stdinSink); expect(processManager.hasRemainingExpectations, isTrue); final File inputFont = fileSystem.file(inputPath) ..writeAsBytesSync(List<int>.filled(2500, 0)); fileSystem.file(outputPath) ..createSync(recursive: true) ..writeAsBytesSync(List<int>.filled(1200, 0)); final bool result = await iconTreeShaker.subsetFont( input: inputFont, outputPath: outputPath, relativePath: relativePath, ); expect(result, isTrue); final List<String> codePoints = stdinSink.getAndClear().trim().split(whitespace); expect(codePoints, isNot(contains('optional:32'))); expect(processManager, hasNoRemainingExpectations); }); testWithoutContext('Ensures 0x32 is included for web builds', () async { final Environment environment = createEnvironment(<String, String>{ kIconTreeShakerFlag: 'true', kBuildMode: 'release', }); final File appDill = environment.buildDir.childFile('app.dill') ..createSync(recursive: true); final IconTreeShaker iconTreeShaker = IconTreeShaker( environment, fontManifestContent, logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: artifacts, targetPlatform: TargetPlatform.web_javascript, ); addConstFinderInvocation( appDill.path, // Does not contain space char stdout: validConstFinderResult, ); final CompleterIOSink stdinSink = CompleterIOSink(); resetFontSubsetInvocation(stdinSink: stdinSink); expect(processManager.hasRemainingExpectations, isTrue); final File inputFont = fileSystem.file(inputPath) ..writeAsBytesSync(List<int>.filled(2500, 0)); fileSystem.file(outputPath) ..createSync(recursive: true) ..writeAsBytesSync(List<int>.filled(1200, 0)); final bool result = await iconTreeShaker.subsetFont( input: inputFont, outputPath: outputPath, relativePath: relativePath, ); expect(result, isTrue); final List<String> codePoints = stdinSink.getAndClear().trim().split(whitespace); expect(codePoints, containsAllInOrder(const <String>['59470', 'optional:32'])); expect(processManager, hasNoRemainingExpectations); }); testWithoutContext('Non-zero font-subset exit code', () async { final Environment environment = createEnvironment(<String, String>{ kIconTreeShakerFlag: 'true', kBuildMode: 'release', }); final File appDill = environment.buildDir.childFile('app.dill') ..createSync(recursive: true); fileSystem.file(inputPath).createSync(recursive: true); final IconTreeShaker iconTreeShaker = IconTreeShaker( environment, fontManifestContent, logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: artifacts, targetPlatform: TargetPlatform.android, ); final CompleterIOSink stdinSink = CompleterIOSink(); addConstFinderInvocation(appDill.path, stdout: validConstFinderResult); resetFontSubsetInvocation(exitCode: -1, stdinSink: stdinSink); await expectLater( () => iconTreeShaker.subsetFont( input: fileSystem.file(inputPath), outputPath: outputPath, relativePath: relativePath, ), throwsA(isA<IconTreeShakerException>()), ); expect(processManager, hasNoRemainingExpectations); }); testWithoutContext('font-subset throws on write to sdtin', () async { final Environment environment = createEnvironment(<String, String>{ kIconTreeShakerFlag: 'true', kBuildMode: 'release', }); final File appDill = environment.buildDir.childFile('app.dill') ..createSync(recursive: true); final IconTreeShaker iconTreeShaker = IconTreeShaker( environment, fontManifestContent, logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: artifacts, targetPlatform: TargetPlatform.android, ); final CompleterIOSink stdinSink = CompleterIOSink(throwOnAdd: true); addConstFinderInvocation(appDill.path, stdout: validConstFinderResult); resetFontSubsetInvocation(exitCode: -1, stdinSink: stdinSink); await expectLater( () => iconTreeShaker.subsetFont( input: fileSystem.file(inputPath), outputPath: outputPath, relativePath: relativePath, ), throwsA(isA<IconTreeShakerException>()), ); expect(processManager, hasNoRemainingExpectations); }); testWithoutContext('Invalid font manifest', () async { final Environment environment = createEnvironment(<String, String>{ kIconTreeShakerFlag: 'true', kBuildMode: 'release', }); final File appDill = environment.buildDir.childFile('app.dill') ..createSync(recursive: true); fontManifestContent = DevFSStringContent(invalidFontManifestJson); final IconTreeShaker iconTreeShaker = IconTreeShaker( environment, fontManifestContent, logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: artifacts, targetPlatform: TargetPlatform.android, ); addConstFinderInvocation(appDill.path, stdout: validConstFinderResult); await expectLater( () => iconTreeShaker.subsetFont( input: fileSystem.file(inputPath), outputPath: outputPath, relativePath: relativePath, ), throwsA(isA<IconTreeShakerException>()), ); expect(processManager, hasNoRemainingExpectations); }); testWithoutContext('Allow system font fallback when fontFamily is null', () async { final Environment environment = createEnvironment(<String, String>{ kIconTreeShakerFlag: 'true', kBuildMode: 'release', }); final File appDill = environment.buildDir.childFile('app.dill') ..createSync(recursive: true); // Valid manifest, just not using it. fontManifestContent = DevFSStringContent(validFontManifestJson); final IconTreeShaker iconTreeShaker = IconTreeShaker( environment, fontManifestContent, logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: artifacts, targetPlatform: TargetPlatform.android, ); addConstFinderInvocation(appDill.path, stdout: emptyConstFinderResult); // Does not throw await iconTreeShaker.subsetFont( input: fileSystem.file(inputPath), outputPath: outputPath, relativePath: relativePath, ); expect( logger.traceText, contains( 'Expected to find fontFamily for constant IconData with codepoint: ' '59470, but found fontFamily: null. This usually means ' 'you are relying on the system font. Alternatively, font families in ' 'an IconData class can be provided in the assets section of your ' 'pubspec.yaml, or you are missing "uses-material-design: true".\n' ), ); expect(processManager, hasNoRemainingExpectations); }); testWithoutContext('Allow system font fallback when fontFamily is null and manifest is empty', () async { final Environment environment = createEnvironment(<String, String>{ kIconTreeShakerFlag: 'true', kBuildMode: 'release', }); final File appDill = environment.buildDir.childFile('app.dill') ..createSync(recursive: true); // Nothing in font manifest fontManifestContent = DevFSStringContent(emptyFontManifestJson); final IconTreeShaker iconTreeShaker = IconTreeShaker( environment, fontManifestContent, logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: artifacts, targetPlatform: TargetPlatform.android, ); addConstFinderInvocation(appDill.path, stdout: emptyConstFinderResult); // Does not throw await iconTreeShaker.subsetFont( input: fileSystem.file(inputPath), outputPath: outputPath, relativePath: relativePath, ); expect( logger.traceText, contains( 'Expected to find fontFamily for constant IconData with codepoint: ' '59470, but found fontFamily: null. This usually means ' 'you are relying on the system font. Alternatively, font families in ' 'an IconData class can be provided in the assets section of your ' 'pubspec.yaml, or you are missing "uses-material-design: true".\n' ), ); expect(processManager, hasNoRemainingExpectations); }); testWithoutContext('ConstFinder non-zero exit', () async { final Environment environment = createEnvironment(<String, String>{ kIconTreeShakerFlag: 'true', kBuildMode: 'release', }); final File appDill = environment.buildDir.childFile('app.dill') ..createSync(recursive: true); fontManifestContent = DevFSStringContent(invalidFontManifestJson); final IconTreeShaker iconTreeShaker = IconTreeShaker( environment, fontManifestContent, logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: artifacts, targetPlatform: TargetPlatform.android, ); addConstFinderInvocation(appDill.path, exitCode: -1); await expectLater( () async => iconTreeShaker.subsetFont( input: fileSystem.file(inputPath), outputPath: outputPath, relativePath: relativePath, ), throwsA(isA<IconTreeShakerException>()), ); expect(processManager, hasNoRemainingExpectations); }); } const String validConstFinderResult = ''' { "constantInstances": [ { "codePoint": 59470, "fontFamily": "MaterialIcons", "fontPackage": null, "matchTextDirection": false } ], "nonConstantLocations": [] } '''; const String emptyConstFinderResult = ''' { "constantInstances": [ { "codePoint": 59470, "fontFamily": null, "fontPackage": null, "matchTextDirection": false } ], "nonConstantLocations": [] } '''; const String constFinderResultWithInvalid = ''' { "constantInstances": [ { "codePoint": 59470, "fontFamily": "MaterialIcons", "fontPackage": null, "matchTextDirection": false } ], "nonConstantLocations": [ { "file": "file:///Path/to/hello_world/lib/file.dart", "line": 19, "column": 11 } ] } '''; const String validFontManifestJson = ''' [ { "family": "MaterialIcons", "fonts": [ { "asset": "fonts/MaterialIcons-Regular.otf" } ] }, { "family": "GalleryIcons", "fonts": [ { "asset": "packages/flutter_gallery_assets/fonts/private/gallery_icons/GalleryIcons.ttf" } ] }, { "family": "packages/cupertino_icons/CupertinoIcons", "fonts": [ { "asset": "packages/cupertino_icons/assets/CupertinoIcons.ttf" } ] } ] '''; const String invalidFontManifestJson = ''' { "famly": "MaterialIcons", "fonts": [ { "asset": "fonts/MaterialIcons-Regular.otf" } ] } '''; const String emptyFontManifestJson = '[]';
flutter/packages/flutter_tools/test/general.shard/build_system/targets/icon_tree_shaker_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/general.shard/build_system/targets/icon_tree_shaker_test.dart", "repo_id": "flutter", "token_count": 8939 }
395
// Copyright 2014 The Flutter 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:flutter_tools/src/base/io.dart'; import 'package:flutter_tools/src/base/logger.dart'; import 'package:flutter_tools/src/commands/daemon.dart'; import 'package:test/fake.dart'; import '../../src/common.dart'; void main() { testWithoutContext('binds on ipv4 normally', () async { final FakeServerSocket socket = FakeServerSocket(); final BufferLogger logger = BufferLogger.test(); int bindCalledTimes = 0; final List<Object?> bindAddresses = <Object?>[]; final List<int> bindPorts = <int>[]; final DaemonServer server = DaemonServer( port: 123, logger: logger, bind: (Object? address, int port) async { bindCalledTimes++; bindAddresses.add(address); bindPorts.add(port); return socket; }, ); await server.run(); expect(bindCalledTimes, 1); expect(bindAddresses, <Object?>[InternetAddress.loopbackIPv4]); expect(bindPorts, <int>[123]); }); testWithoutContext('binds on ipv6 if ipv4 failed normally', () async { final FakeServerSocket socket = FakeServerSocket(); final BufferLogger logger = BufferLogger.test(); int bindCalledTimes = 0; final List<Object?> bindAddresses = <Object?>[]; final List<int> bindPorts = <int>[]; final DaemonServer server = DaemonServer( port: 123, logger: logger, bind: (Object? address, int port) async { bindCalledTimes++; bindAddresses.add(address); bindPorts.add(port); if (address == InternetAddress.loopbackIPv4) { throw const SocketException('fail'); } return socket; }, ); await server.run(); expect(bindCalledTimes, 2); expect(bindAddresses, <Object?>[InternetAddress.loopbackIPv4, InternetAddress.loopbackIPv6]); expect(bindPorts, <int>[123, 123]); }); } class FakeServerSocket extends Fake implements ServerSocket { FakeServerSocket(); @override int get port => 1; bool closeCalled = false; final StreamController<Socket> controller = StreamController<Socket>(); @override StreamSubscription<Socket> listen( void Function(Socket event)? onData, { Function? onError, void Function()? onDone, bool? cancelOnError, }) { // Close the controller immediately for testing purpose. scheduleMicrotask(() { controller.close(); }); return controller.stream.listen(onData, onError: onError, onDone: onDone, cancelOnError: cancelOnError); } @override Future<ServerSocket> close() async { closeCalled = true; return this; } }
flutter/packages/flutter_tools/test/general.shard/commands/daemon_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/general.shard/commands/daemon_test.dart", "repo_id": "flutter", "token_count": 1006 }
396
// Copyright 2014 The Flutter 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:dds/dap.dart'; import 'package:file/memory.dart'; import 'package:flutter_tools/src/base/file_system.dart'; import 'package:flutter_tools/src/base/platform.dart'; import 'package:flutter_tools/src/cache.dart'; import 'package:flutter_tools/src/debug_adapters/flutter_adapter.dart'; import 'package:flutter_tools/src/debug_adapters/flutter_adapter_args.dart'; import 'package:flutter_tools/src/globals.dart' as globals show fs, platform; import 'package:test/fake.dart'; import 'package:test/test.dart'; import 'package:vm_service/vm_service.dart'; import 'mocks.dart'; void main() { // Use the real platform as a base so that Windows bots test paths. final FakePlatform platform = FakePlatform.fromPlatform(globals.platform); final FileSystemStyle fsStyle = platform.isWindows ? FileSystemStyle.windows : FileSystemStyle.posix; final String flutterRoot = platform.isWindows ? r'C:\fake\flutter' : '/fake/flutter'; group('flutter adapter', () { final String expectedFlutterExecutable = platform.isWindows ? r'C:\fake\flutter\bin\flutter.bat' : '/fake/flutter/bin/flutter'; setUpAll(() { Cache.flutterRoot = flutterRoot; }); group('launchRequest', () { test('runs "flutter run" with --machine', () async { final MockFlutterDebugAdapter adapter = MockFlutterDebugAdapter( fileSystem: MemoryFileSystem.test(style: fsStyle), platform: platform, ); final Completer<void> responseCompleter = Completer<void>(); final FlutterLaunchRequestArguments args = FlutterLaunchRequestArguments( cwd: '.', program: 'foo.dart', ); await adapter.configurationDoneRequest(MockRequest(), null, () {}); await adapter.launchRequest(MockRequest(), args, responseCompleter.complete); await responseCompleter.future; expect(adapter.processArgs, containsAllInOrder(<String>['run', '--machine'])); }); test('includes env variables', () async { final MockFlutterDebugAdapter adapter = MockFlutterDebugAdapter( fileSystem: MemoryFileSystem.test(style: fsStyle), platform: platform, ); final Completer<void> responseCompleter = Completer<void>(); final FlutterLaunchRequestArguments args = FlutterLaunchRequestArguments( cwd: '.', program: 'foo.dart', env: <String, String>{ 'MY_TEST_ENV': 'MY_TEST_VALUE', }, ); await adapter.configurationDoneRequest(MockRequest(), null, () {}); await adapter.launchRequest(MockRequest(), args, responseCompleter.complete); await responseCompleter.future; expect(adapter.env!['MY_TEST_ENV'], 'MY_TEST_VALUE'); }); test('does not record the VMs PID for terminating', () async { final MockFlutterDebugAdapter adapter = MockFlutterDebugAdapter( fileSystem: MemoryFileSystem.test(style: fsStyle), platform: platform, ); final Completer<void> responseCompleter = Completer<void>(); final FlutterLaunchRequestArguments args = FlutterLaunchRequestArguments( cwd: '.', program: 'foo.dart', ); await adapter.configurationDoneRequest(MockRequest(), null, () {}); await adapter.launchRequest(MockRequest(), args, responseCompleter.complete); await responseCompleter.future; // Trigger a fake debuggerConnected with a pid that we expect the // adapter _not_ to record, because it may be on another device. await adapter.debuggerConnected(_FakeVm(pid: 123)); // Ensure the VM's pid was not recorded. expect(adapter.pidsToTerminate, isNot(contains(123))); }); group('supportsRestartRequest', () { void testRestartSupport(bool supportsRestart) { test('notifies client for supportsRestart: $supportsRestart', () async { final MockFlutterDebugAdapter adapter = MockFlutterDebugAdapter( fileSystem: MemoryFileSystem.test(style: fsStyle), platform: platform, supportsRestart: supportsRestart, ); final FlutterLaunchRequestArguments args = FlutterLaunchRequestArguments( cwd: '.', program: 'foo.dart', ); // Listen for a Capabilities event that modifies 'supportsRestartRequest'. final Future<CapabilitiesEventBody> capabilitiesUpdate = adapter .dapToClientMessages .where((Map<String, Object?> message) => message['event'] == 'capabilities') .map((Map<String, Object?> message) => message['body'] as Map<String, Object?>?) .where((Map<String, Object?>? body) => body != null).cast<Map<String, Object?>>() .map(CapabilitiesEventBody.fromJson) .firstWhere((CapabilitiesEventBody body) => body.capabilities.supportsRestartRequest != null); await adapter.configurationDoneRequest(MockRequest(), null, () {}); final Completer<void> launchCompleter = Completer<void>(); await adapter.launchRequest(MockRequest(), args, launchCompleter.complete); await launchCompleter.future; // Ensure the Capabilities update has the expected value. expect((await capabilitiesUpdate).capabilities.supportsRestartRequest, supportsRestart); }); } testRestartSupport(true); testRestartSupport(false); }); test('calls "app.stop" on terminateRequest', () async { final MockFlutterDebugAdapter adapter = MockFlutterDebugAdapter( fileSystem: MemoryFileSystem.test(style: fsStyle), platform: platform, ); final FlutterLaunchRequestArguments args = FlutterLaunchRequestArguments( cwd: '.', program: 'foo.dart', ); await adapter.configurationDoneRequest(MockRequest(), null, () {}); final Completer<void> launchCompleter = Completer<void>(); await adapter.launchRequest(MockRequest(), args, launchCompleter.complete); await launchCompleter.future; final Completer<void> terminateCompleter = Completer<void>(); await adapter.terminateRequest(MockRequest(), TerminateArguments(restart: false), terminateCompleter.complete); await terminateCompleter.future; expect(adapter.dapToFlutterRequests, contains('app.stop')); }); test('does not call "app.stop" on terminateRequest if app was not started', () async { final MockFlutterDebugAdapter adapter = MockFlutterDebugAdapter( fileSystem: MemoryFileSystem.test(style: fsStyle), platform: platform, simulateAppStarted: false, ); final FlutterLaunchRequestArguments args = FlutterLaunchRequestArguments( cwd: '.', program: 'foo.dart', ); await adapter.configurationDoneRequest(MockRequest(), null, () {}); final Completer<void> launchCompleter = Completer<void>(); await adapter.launchRequest(MockRequest(), args, launchCompleter.complete); await launchCompleter.future; final Completer<void> terminateCompleter = Completer<void>(); await adapter.terminateRequest(MockRequest(), TerminateArguments(restart: false), terminateCompleter.complete); await terminateCompleter.future; expect(adapter.dapToFlutterRequests, isNot(contains('app.stop'))); }); test('does not call "app.restart" before app has been started', () async { final MockFlutterDebugAdapter adapter = MockFlutterDebugAdapter( fileSystem: MemoryFileSystem.test(style: fsStyle), platform: platform, simulateAppStarted: false, ); final Completer<void> launchCompleter = Completer<void>(); final FlutterLaunchRequestArguments launchArgs = FlutterLaunchRequestArguments( cwd: '.', program: 'foo.dart', ); final Completer<void> restartCompleter = Completer<void>(); final RestartArguments restartArgs = RestartArguments(); await adapter.configurationDoneRequest(MockRequest(), null, () {}); await adapter.launchRequest(MockRequest(), launchArgs, launchCompleter.complete); await launchCompleter.future; await adapter.restartRequest(MockRequest(), restartArgs, restartCompleter.complete); await restartCompleter.future; expect(adapter.dapToFlutterRequests, isNot(contains('app.restart'))); }); test('includes build progress updates', () async { final MockFlutterDebugAdapter adapter = MockFlutterDebugAdapter( fileSystem: MemoryFileSystem.test(style: fsStyle), platform: platform, ); final Completer<void> responseCompleter = Completer<void>(); final FlutterLaunchRequestArguments args = FlutterLaunchRequestArguments( cwd: '.', program: 'foo.dart', ); // Begin listening for progress events up until `progressEnd` (but don't await yet). final Future<List<List<Object?>>> progressEventsFuture = adapter.dapToClientProgressEvents .takeWhile((Map<String, Object?> message) => message['event'] != 'progressEnd') .map((Map<String, Object?> message) => <Object?>[message['event'], (message['body']! as Map<String, Object?>)['message']]) .toList(); // Initialize with progress support. await adapter.initializeRequest( MockRequest(), DartInitializeRequestArguments(adapterID: 'test', supportsProgressReporting: true, ), (_) {}, ); await adapter.configurationDoneRequest(MockRequest(), null, () {}); await adapter.launchRequest(MockRequest(), args, responseCompleter.complete); await responseCompleter.future; // Ensure we got the expected events prior to the progressEnd. final List<List<Object?>> progressEvents = await progressEventsFuture; expect(progressEvents, containsAllInOrder(<List<String?>>[ <String?>['progressStart', 'Launching…'], <String?>['progressUpdate', 'Step 1…'], <String?>['progressUpdate', 'Step 2…'], // progressEnd isn't included because we used takeWhile to stop when it arrived above. ])); }); test('includes Dart Debug extension progress update', () async { final MockFlutterDebugAdapter adapter = MockFlutterDebugAdapter( fileSystem: MemoryFileSystem.test(style: fsStyle), platform: platform, preAppStart: (MockFlutterDebugAdapter adapter) { adapter.simulateRawStdout('Waiting for connection from Dart debug extension…'); } ); final Completer<void> responseCompleter = Completer<void>(); final FlutterLaunchRequestArguments args = FlutterLaunchRequestArguments( cwd: '.', program: 'foo.dart', ); // Begin listening for progress events up until `progressEnd` (but don't await yet). final Future<List<List<Object?>>> progressEventsFuture = adapter.dapToClientProgressEvents .takeWhile((Map<String, Object?> message) => message['event'] != 'progressEnd') .map((Map<String, Object?> message) => <Object?>[message['event'], (message['body']! as Map<String, Object?>)['message']]) .toList(); // Initialize with progress support. await adapter.initializeRequest( MockRequest(), DartInitializeRequestArguments(adapterID: 'test', supportsProgressReporting: true, ), (_) {}, ); await adapter.configurationDoneRequest(MockRequest(), null, () {}); await adapter.launchRequest(MockRequest(), args, responseCompleter.complete); await responseCompleter.future; // Ensure we got the expected events prior to the progressEnd. final List<List<Object?>> progressEvents = await progressEventsFuture; expect(progressEvents, containsAllInOrder(<List<String>>[ <String>['progressStart', 'Launching…'], <String>['progressUpdate', 'Please click the Dart Debug extension button in the spawned browser window'], // progressEnd isn't included because we used takeWhile to stop when it arrived above. ])); }); }); group('attachRequest', () { test('runs "flutter attach" with --machine', () async { final MockFlutterDebugAdapter adapter = MockFlutterDebugAdapter( fileSystem: MemoryFileSystem.test(style: fsStyle), platform: platform, ); final Completer<void> responseCompleter = Completer<void>(); final FlutterAttachRequestArguments args = FlutterAttachRequestArguments( cwd: '.', ); await adapter.configurationDoneRequest(MockRequest(), null, () {}); await adapter.attachRequest(MockRequest(), args, responseCompleter.complete); await responseCompleter.future; expect(adapter.processArgs, containsAllInOrder(<String>['attach', '--machine'])); }); test('runs "flutter attach" with program if passed in', () async { final MockFlutterDebugAdapter adapter = MockFlutterDebugAdapter( fileSystem: MemoryFileSystem.test(style: fsStyle), platform: platform, ); final Completer<void> responseCompleter = Completer<void>(); final FlutterAttachRequestArguments args = FlutterAttachRequestArguments( cwd: '.', program: 'program/main.dart', ); await adapter.configurationDoneRequest(MockRequest(), null, () {}); await adapter.attachRequest( MockRequest(), args, responseCompleter.complete); await responseCompleter.future; expect( adapter.processArgs, containsAllInOrder(<String>[ 'attach', '--machine', '--target', 'program/main.dart' ])); }); test('runs "flutter attach" with --debug-uri if vmServiceUri is passed', () async { final MockFlutterDebugAdapter adapter = MockFlutterDebugAdapter( fileSystem: MemoryFileSystem.test(style: fsStyle), platform: platform, ); final Completer<void> responseCompleter = Completer<void>(); final FlutterAttachRequestArguments args = FlutterAttachRequestArguments( cwd: '.', program: 'program/main.dart', vmServiceUri: 'ws://1.2.3.4/ws' ); await adapter.configurationDoneRequest(MockRequest(), null, () {}); await adapter.attachRequest( MockRequest(), args, responseCompleter.complete); await responseCompleter.future; expect( adapter.processArgs, containsAllInOrder(<String>[ 'attach', '--machine', '--debug-uri', 'ws://1.2.3.4/ws', '--target', 'program/main.dart', ])); }); test('runs "flutter attach" with --debug-uri if vmServiceInfoFile exists', () async { final MockFlutterDebugAdapter adapter = MockFlutterDebugAdapter( fileSystem: MemoryFileSystem.test(style: fsStyle), platform: platform, ); final Completer<void> responseCompleter = Completer<void>(); final File serviceInfoFile = globals.fs.systemTempDirectory.createTempSync('dap_flutter_attach_vmServiceInfoFile').childFile('vmServiceInfo.json'); final FlutterAttachRequestArguments args = FlutterAttachRequestArguments( cwd: '.', program: 'program/main.dart', vmServiceInfoFile: serviceInfoFile.path, ); // Write the service info file before trying to attach: serviceInfoFile.writeAsStringSync('{ "uri": "ws://1.2.3.4/ws" }'); await adapter.configurationDoneRequest(MockRequest(), null, () {}); await adapter.attachRequest(MockRequest(), args, responseCompleter.complete); await responseCompleter.future; expect( adapter.processArgs, containsAllInOrder(<String>[ 'attach', '--machine', '--debug-uri', 'ws://1.2.3.4/ws', '--target', 'program/main.dart', ])); }); test('runs "flutter attach" with --debug-uri if vmServiceInfoFile is created later', () async { final MockFlutterDebugAdapter adapter = MockFlutterDebugAdapter( fileSystem: MemoryFileSystem.test(style: fsStyle), platform: platform, ); final Completer<void> responseCompleter = Completer<void>(); final File serviceInfoFile = globals.fs.systemTempDirectory.createTempSync('dap_flutter_attach_vmServiceInfoFile').childFile('vmServiceInfo.json'); final FlutterAttachRequestArguments args = FlutterAttachRequestArguments( cwd: '.', program: 'program/main.dart', vmServiceInfoFile: serviceInfoFile.path, ); await adapter.configurationDoneRequest(MockRequest(), null, () {}); final Future<void> attachResponseFuture = adapter.attachRequest(MockRequest(), args, responseCompleter.complete); // Write the service info file a little later to ensure we detect it: await pumpEventQueue(times:5000); serviceInfoFile.writeAsStringSync('{ "uri": "ws://1.2.3.4/ws" }'); await attachResponseFuture; await responseCompleter.future; expect( adapter.processArgs, containsAllInOrder(<String>[ 'attach', '--machine', '--debug-uri', 'ws://1.2.3.4/ws', '--target', 'program/main.dart', ])); }); test('does not record the VMs PID for terminating', () async { final MockFlutterDebugAdapter adapter = MockFlutterDebugAdapter( fileSystem: MemoryFileSystem.test(style: fsStyle), platform: platform, ); final Completer<void> responseCompleter = Completer<void>(); final FlutterAttachRequestArguments args = FlutterAttachRequestArguments( cwd: '.', ); await adapter.configurationDoneRequest(MockRequest(), null, () {}); await adapter.attachRequest(MockRequest(), args, responseCompleter.complete); await responseCompleter.future; // Trigger a fake debuggerConnected with a pid that we expect the // adapter _not_ to record, because it may be on another device. await adapter.debuggerConnected(_FakeVm(pid: 123)); // Ensure the VM's pid was not recorded. expect(adapter.pidsToTerminate, isNot(contains(123))); }); test('calls "app.detach" on terminateRequest', () async { final MockFlutterDebugAdapter adapter = MockFlutterDebugAdapter( fileSystem: MemoryFileSystem.test(style: fsStyle), platform: platform, ); final FlutterAttachRequestArguments args = FlutterAttachRequestArguments( cwd: '.', ); await adapter.configurationDoneRequest(MockRequest(), null, () {}); final Completer<void> attachCompleter = Completer<void>(); await adapter.attachRequest(MockRequest(), args, attachCompleter.complete); await attachCompleter.future; final Completer<void> terminateCompleter = Completer<void>(); await adapter.terminateRequest(MockRequest(), TerminateArguments(restart: false), terminateCompleter.complete); await terminateCompleter.future; expect(adapter.dapToFlutterRequests, contains('app.detach')); }); }); group('forwards events', () { test('app.webLaunchUrl', () async { final MockFlutterDebugAdapter adapter = MockFlutterDebugAdapter( fileSystem: MemoryFileSystem.test(style: fsStyle), platform: platform, ); // Start listening for the forwarded event (don't await it yet, it won't // be triggered until the call below). final Future<Map<String, Object?>> forwardedEvent = adapter.dapToClientMessages .firstWhere((Map<String, Object?> data) => data['event'] == 'flutter.forwardedEvent'); // Simulate Flutter asking for a URL to be launched. adapter.simulateStdoutMessage(<String, Object?>{ 'event': 'app.webLaunchUrl', 'params': <String, Object?>{ 'url': 'http://localhost:123/', 'launched': false, } }); // Wait for the forwarded event. final Map<String, Object?> message = await forwardedEvent; // Ensure the body of the event matches the original event sent by Flutter. expect(message['body'], <String, Object?>{ 'event': 'app.webLaunchUrl', 'params': <String, Object?>{ 'url': 'http://localhost:123/', 'launched': false, } }); }); }); group('handles reverse requests', () { test('app.exposeUrl', () async { final MockFlutterDebugAdapter adapter = MockFlutterDebugAdapter( fileSystem: MemoryFileSystem.test(style: fsStyle), platform: platform, ); // Pretend to be the client, handling any reverse-requests for exposeUrl // and mapping the host to 'mapped-host'. adapter.exposeUrlHandler = (String url) => Uri.parse(url).replace(host: 'mapped-host').toString(); // Simulate Flutter asking for a URL to be exposed. const int requestId = 12345; adapter.simulateStdoutMessage(<String, Object?>{ 'id': requestId, 'method': 'app.exposeUrl', 'params': <String, Object?>{ 'url': 'http://localhost:123/', } }); // Allow the handler to be processed. await pumpEventQueue(times: 5000); final Map<String, Object?> message = adapter.dapToFlutterMessages.singleWhere((Map<String, Object?> data) => data['id'] == requestId); expect(message['result'], 'http://mapped-host:123/'); }); }); group('--start-paused', () { test('is passed for debug mode', () async { final MockFlutterDebugAdapter adapter = MockFlutterDebugAdapter( fileSystem: MemoryFileSystem.test(style: fsStyle), platform: platform, ); final Completer<void> responseCompleter = Completer<void>(); final FlutterLaunchRequestArguments args = FlutterLaunchRequestArguments( cwd: '.', program: 'foo.dart', ); await adapter.configurationDoneRequest(MockRequest(), null, () {}); await adapter.launchRequest(MockRequest(), args, responseCompleter.complete); await responseCompleter.future; expect(adapter.processArgs, contains('--start-paused')); }); test('is not passed for noDebug mode', () async { final MockFlutterDebugAdapter adapter = MockFlutterDebugAdapter( fileSystem: MemoryFileSystem.test(style: fsStyle), platform: platform, ); final Completer<void> responseCompleter = Completer<void>(); final FlutterLaunchRequestArguments args = FlutterLaunchRequestArguments( cwd: '.', program: 'foo.dart', noDebug: true, ); await adapter.configurationDoneRequest(MockRequest(), null, () {}); await adapter.launchRequest(MockRequest(), args, responseCompleter.complete); await responseCompleter.future; expect(adapter.processArgs, isNot(contains('--start-paused'))); }); test('is not passed if toolArgs contains --profile', () async { final MockFlutterDebugAdapter adapter = MockFlutterDebugAdapter( fileSystem: MemoryFileSystem.test(style: fsStyle), platform: platform, ); final Completer<void> responseCompleter = Completer<void>(); final FlutterLaunchRequestArguments args = FlutterLaunchRequestArguments( cwd: '.', program: 'foo.dart', toolArgs: <String>['--profile'], ); await adapter.configurationDoneRequest(MockRequest(), null, () {}); await adapter.launchRequest(MockRequest(), args, responseCompleter.complete); await responseCompleter.future; expect(adapter.processArgs, isNot(contains('--start-paused'))); }); test('is not passed if toolArgs contains --release', () async { final MockFlutterDebugAdapter adapter = MockFlutterDebugAdapter( fileSystem: MemoryFileSystem.test(style: fsStyle), platform: platform, ); final Completer<void> responseCompleter = Completer<void>(); final FlutterLaunchRequestArguments args = FlutterLaunchRequestArguments( cwd: '.', program: 'foo.dart', toolArgs: <String>['--release'], ); await adapter.configurationDoneRequest(MockRequest(), null, () {}); await adapter.launchRequest(MockRequest(), args, responseCompleter.complete); await responseCompleter.future; expect(adapter.processArgs, isNot(contains('--start-paused'))); }); }); test('includes toolArgs', () async { final MockFlutterDebugAdapter adapter = MockFlutterDebugAdapter( fileSystem: MemoryFileSystem.test(style: fsStyle), platform: platform, ); final Completer<void> responseCompleter = Completer<void>(); final FlutterLaunchRequestArguments args = FlutterLaunchRequestArguments( cwd: '.', program: 'foo.dart', toolArgs: <String>['tool_arg'], noDebug: true, ); await adapter.configurationDoneRequest(MockRequest(), null, () {}); await adapter.launchRequest(MockRequest(), args, responseCompleter.complete); await responseCompleter.future; expect(adapter.executable, equals(expectedFlutterExecutable)); expect(adapter.processArgs, contains('tool_arg')); }); group('maps org-dartlang-sdk paths', () { late FileSystem fs; late FlutterDebugAdapter adapter; setUp(() { fs = MemoryFileSystem.test(style: fsStyle); adapter = MockFlutterDebugAdapter( fileSystem: fs, platform: platform, ); }); test('dart:ui URI to file path', () async { expect( adapter.convertOrgDartlangSdkToPath(Uri.parse('org-dartlang-sdk:///flutter/lib/ui/ui.dart')), Uri.file(fs.path.join(flutterRoot, 'bin', 'cache', 'pkg', 'sky_engine', 'lib', 'ui', 'ui.dart')), ); }); test('dart:ui file path to URI', () async { expect( adapter.convertUriToOrgDartlangSdk(Uri.file(fs.path.join(flutterRoot, 'bin', 'cache', 'pkg', 'sky_engine', 'lib', 'ui', 'ui.dart'))), Uri.parse('org-dartlang-sdk:///flutter/lib/ui/ui.dart'), ); }); test('dart:core URI to file path', () async { expect( adapter.convertOrgDartlangSdkToPath(Uri.parse('org-dartlang-sdk:///third_party/dart/sdk/lib/core/core.dart')), Uri.file(fs.path.join(flutterRoot, 'bin', 'cache', 'pkg', 'sky_engine', 'lib', 'core', 'core.dart')), ); }); test('dart:core file path to URI', () async { expect( adapter.convertUriToOrgDartlangSdk(Uri.file(fs.path.join(flutterRoot, 'bin', 'cache', 'pkg', 'sky_engine', 'lib', 'core', 'core.dart'))), Uri.parse('org-dartlang-sdk:///third_party/dart/sdk/lib/core/core.dart'), ); }); }); group('includes customTool', () { test('with no args replaced', () async { final MockFlutterDebugAdapter adapter = MockFlutterDebugAdapter( fileSystem: MemoryFileSystem.test(style: fsStyle), platform: platform, ); final FlutterLaunchRequestArguments args = FlutterLaunchRequestArguments( cwd: '.', program: 'foo.dart', customTool: '/custom/flutter', noDebug: true, ); await adapter.configurationDoneRequest(MockRequest(), null, () {}); final Completer<void> responseCompleter = Completer<void>(); await adapter.launchRequest(MockRequest(), args, responseCompleter.complete); await responseCompleter.future; expect(adapter.executable, equals('/custom/flutter')); // args should be in-tact expect(adapter.processArgs, contains('--machine')); }); test('with all args replaced', () async { final MockFlutterDebugAdapter adapter = MockFlutterDebugAdapter( fileSystem: MemoryFileSystem.test(style: fsStyle), platform: platform, ); final FlutterLaunchRequestArguments args = FlutterLaunchRequestArguments( cwd: '.', program: 'foo.dart', customTool: '/custom/flutter', customToolReplacesArgs: 9999, // replaces all built-in args noDebug: true, toolArgs: <String>['tool_args'], // should still be in args ); await adapter.configurationDoneRequest(MockRequest(), null, () {}); final Completer<void> responseCompleter = Completer<void>(); await adapter.launchRequest(MockRequest(), args, responseCompleter.complete); await responseCompleter.future; expect(adapter.executable, equals('/custom/flutter')); // normal built-in args are replaced by customToolReplacesArgs, but // user-provided toolArgs are not. expect(adapter.processArgs, isNot(contains('--machine'))); expect(adapter.processArgs, contains('tool_args')); }); }); }); } class _FakeVm extends Fake implements VM { _FakeVm({this.pid = 1}); @override final int pid; }
flutter/packages/flutter_tools/test/general.shard/dap/flutter_adapter_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/general.shard/dap/flutter_adapter_test.dart", "repo_id": "flutter", "token_count": 12245 }
397
// Copyright 2014 The Flutter 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:fake_async/fake_async.dart'; import 'package:flutter_tools/src/base/io.dart'; import 'package:flutter_tools/src/convert.dart' show utf8; import '../src/common.dart'; import '../src/fake_process_manager.dart'; void main() { group(FakeProcess, () { testWithoutContext('exits with specified exit code', () async { final FakeProcess process = FakeProcess(exitCode: 42); expect(await process.exitCode, 42); }); testWithoutContext('exits with specified stderr, stdout', () async { final FakeProcess process = FakeProcess( stderr: 'stderr\u{FFFD}'.codeUnits, stdout: 'stdout\u{FFFD}'.codeUnits, ); await process.exitCode; // Verify that no encoding changes have been applied to output. // // In the past, we had hardcoded UTF-8 encoding for these streams in // FakeProcess. When a specific encoding is desired, it can be specified // on FakeCommand or in the encoding parameter of FakeProcessManager.run // or FakeProcessManager.runAsync. expect((await process.stderr.toList()).expand((List<int> x) => x), 'stderr\u{FFFD}'.codeUnits); expect((await process.stdout.toList()).expand((List<int> x) => x), 'stdout\u{FFFD}'.codeUnits); }); testWithoutContext('exits after specified delay (if no completer specified)', () { final bool done = FakeAsync().run<bool>((FakeAsync time) { final FakeProcess process = FakeProcess( duration: const Duration(seconds: 30), ); bool hasExited = false; unawaited(process.exitCode.then((int _) { hasExited = true; })); // Verify process hasn't exited before specified delay. time.elapse(const Duration(seconds: 15)); expect(hasExited, isFalse); // Verify process has exited after specified delay. time.elapse(const Duration(seconds: 20)); expect(hasExited, isTrue); return true; }); expect(done, isTrue); }); testWithoutContext('exits when completer completes (if no duration specified)', () { final bool done = FakeAsync().run<bool>((FakeAsync time) { final Completer<void> completer = Completer<void>(); final FakeProcess process = FakeProcess( completer: completer, ); bool hasExited = false; unawaited(process.exitCode.then((int _) { hasExited = true; })); // Verify process hasn't exited when all async tasks flushed. time.elapse(Duration.zero); expect(hasExited, isFalse); // Verify process has exited after completer completes. completer.complete(); time.flushMicrotasks(); expect(hasExited, isTrue); return true; }); expect(done, isTrue); }); testWithoutContext('when completer and duration are specified, does not exit until completer is completed', () { final bool done = FakeAsync().run<bool>((FakeAsync time) { final Completer<void> completer = Completer<void>(); final FakeProcess process = FakeProcess( duration: const Duration(seconds: 30), completer: completer, ); bool hasExited = false; unawaited(process.exitCode.then((int _) { hasExited = true; })); // Verify process hasn't exited before specified delay. time.elapse(const Duration(seconds: 15)); expect(hasExited, isFalse); // Verify process hasn't exited until the completer completes. time.elapse(const Duration(seconds: 20)); expect(hasExited, isFalse); // Verify process exits after the completer completes. completer.complete(); time.flushMicrotasks(); expect(hasExited, isTrue); return true; }); expect(done, isTrue); }); testWithoutContext('when completer and duration are specified, does not exit until duration has elapsed', () { final bool done = FakeAsync().run<bool>((FakeAsync time) { final Completer<void> completer = Completer<void>(); final FakeProcess process = FakeProcess( duration: const Duration(seconds: 30), completer: completer, ); bool hasExited = false; unawaited(process.exitCode.then((int _) { hasExited = true; })); // Verify process hasn't exited before specified delay. time.elapse(const Duration(seconds: 15)); expect(hasExited, isFalse); // Verify process does not exit until duration has elapsed. completer.complete(); expect(hasExited, isFalse); // Verify process exits after the duration elapses. time.elapse(const Duration(seconds: 20)); expect(hasExited, isTrue); return true; }); expect(done, isTrue); }); testWithoutContext('process exit is asynchronous', () async { final FakeProcess process = FakeProcess(); bool hasExited = false; unawaited(process.exitCode.then((int _) { hasExited = true; })); // Verify process hasn't completed. expect(hasExited, isFalse); // Flush async tasks. Verify process completes. await Future<void>.delayed(Duration.zero); expect(hasExited, isTrue); }); testWithoutContext('stderr, stdout stream data after exit when outputFollowsExit is true', () async { final FakeProcess process = FakeProcess( stderr: 'stderr'.codeUnits, stdout: 'stdout'.codeUnits, outputFollowsExit: true, ); final List<int> stderr = <int>[]; final List<int> stdout = <int>[]; process.stderr.listen(stderr.addAll); process.stdout.listen(stdout.addAll); // Ensure that no bytes have been received at process exit. await process.exitCode; expect(stderr, isEmpty); expect(stdout, isEmpty); // Flush all remaining async work. Ensure stderr, stdout is received. await Future<void>.delayed(Duration.zero); expect(stderr, 'stderr'.codeUnits); expect(stdout, 'stdout'.codeUnits); }); }); group(FakeProcessManager, () { late FakeProcessManager manager; setUp(() { manager = FakeProcessManager.empty(); }); group('start', () { testWithoutContext('can run a fake command', () async { manager.addCommand(const FakeCommand(command: <String>['faketool'])); final Process process = await manager.start(<String>['faketool']); expect(await process.exitCode, 0); expect(await utf8.decodeStream(process.stdout), isEmpty); expect(await utf8.decodeStream(process.stderr), isEmpty); }); testWithoutContext('outputFollowsExit delays stderr, stdout until after process exit', () async { manager.addCommand(const FakeCommand( command: <String>['faketool'], stderr: 'hello', stdout: 'world', outputFollowsExit: true, )); final List<int> stderrBytes = <int>[]; final List<int> stdoutBytes = <int>[]; // Start the process. final Process process = await manager.start(<String>['faketool']); final StreamSubscription<List<int>> stderrSubscription = process.stderr.listen((List<int> chunk) { stderrBytes.addAll(chunk); }); final StreamSubscription<List<int>> stdoutSubscription = process.stdout.listen((List<int> chunk) { stdoutBytes.addAll(chunk); }); // Immediately after exit, no output is emitted. await process.exitCode; expect(utf8.decode(stderrBytes), isEmpty); expect(utf8.decode(stdoutBytes), isEmpty); // Output is emitted asynchronously after process exit. await Future.wait(<Future<void>>[ stderrSubscription.asFuture(), stdoutSubscription.asFuture(), ]); expect(utf8.decode(stderrBytes), 'hello'); expect(utf8.decode(stdoutBytes), 'world'); // Clean up stream subscriptions. await stderrSubscription.cancel(); await stdoutSubscription.cancel(); }); }); group('run', () { testWithoutContext('can run a fake command', () async { manager.addCommand(const FakeCommand(command: <String>['faketool'])); final ProcessResult result = await manager.run(<String>['faketool']); expect(result.exitCode, 0); expect(result.stdout, isEmpty); expect(result.stderr, isEmpty); }); testWithoutContext('stderr, stdout are String if encoding is unspecified', () async { manager.addCommand(const FakeCommand(command: <String>['faketool'])); final ProcessResult result = await manager.run(<String>['faketool']); expect(result.exitCode, 0); expect(result.stdout, isA<String>()); expect(result.stderr, isA<String>()); }); testWithoutContext('stderr, stdout are List<int> if encoding is null', () async { manager.addCommand(const FakeCommand(command: <String>['faketool'])); final ProcessResult result = await manager.run( <String>['faketool'], stderrEncoding: null, stdoutEncoding: null, ); expect(result.exitCode, 0); expect(result.stdout, isA<List<int>>()); expect(result.stderr, isA<List<int>>()); }); testWithoutContext('stderr, stdout are String if encoding is specified', () async { manager.addCommand(const FakeCommand(command: <String>['faketool'])); final ProcessResult result = await manager.run( <String>['faketool'], stderrEncoding: utf8, stdoutEncoding: utf8, ); expect(result.exitCode, 0); expect(result.stdout, isA<String>()); expect(result.stderr, isA<String>()); }); }); group('runSync', () { testWithoutContext('can run a fake command', () { manager.addCommand(const FakeCommand(command: <String>['faketool'])); final ProcessResult result = manager.runSync(<String>['faketool']); expect(result.exitCode, 0); expect(result.stdout, isEmpty); expect(result.stderr, isEmpty); }); testWithoutContext('stderr, stdout are String if encoding is unspecified', () { manager.addCommand(const FakeCommand(command: <String>['faketool'])); final ProcessResult result = manager.runSync(<String>['faketool']); expect(result.exitCode, 0); expect(result.stdout, isA<String>()); expect(result.stderr, isA<String>()); }); testWithoutContext('stderr, stdout are List<int> if encoding is null', () { manager.addCommand(const FakeCommand(command: <String>['faketool'])); final ProcessResult result = manager.runSync( <String>['faketool'], stderrEncoding: null, stdoutEncoding: null, ); expect(result.exitCode, 0); expect(result.stdout, isA<List<int>>()); expect(result.stderr, isA<List<int>>()); }); testWithoutContext('stderr, stdout are String if encoding is specified', () { manager.addCommand(const FakeCommand(command: <String>['faketool'])); final ProcessResult result = manager.runSync( <String>['faketool'], stderrEncoding: utf8, stdoutEncoding: utf8, ); expect(result.exitCode, 0); expect(result.stdout, isA<String>()); expect(result.stderr, isA<String>()); }); }); }); }
flutter/packages/flutter_tools/test/general.shard/fake_process_manager_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/general.shard/fake_process_manager_test.dart", "repo_id": "flutter", "token_count": 4613 }
398
// Copyright 2014 The Flutter 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:file/file.dart'; import 'package:file/memory.dart'; import 'package:flutter_tools/src/base/io.dart'; import 'package:flutter_tools/src/base/logger.dart'; import 'package:flutter_tools/src/devfs.dart'; import 'package:flutter_tools/src/project.dart'; import 'package:flutter_tools/src/reporting/github_template.dart'; import '../src/common.dart'; import '../src/context.dart'; void main() { late BufferLogger logger; late FileSystem fs; setUp(() { logger = BufferLogger.test(); fs = MemoryFileSystem.test(); }); group('GitHub template creator', () { testWithoutContext('similar issues URL', () { expect( GitHubTemplateCreator.toolCrashSimilarIssuesURL('this is a 100% error'), 'https://github.com/flutter/flutter/issues?q=is%3Aissue+this+is+a+100%25+error', ); }); group('sanitized error message', () { testWithoutContext('ProcessException', () { expect( GitHubTemplateCreator.sanitizedCrashException( const ProcessException('cd', <String>['path/to/something']) ), 'ProcessException: Command: cd, OS error code: 0', ); expect( GitHubTemplateCreator.sanitizedCrashException( const ProcessException('cd', <String>['path/to/something'], 'message') ), 'ProcessException: message Command: cd, OS error code: 0', ); expect( GitHubTemplateCreator.sanitizedCrashException( const ProcessException('cd', <String>['path/to/something'], 'message', -19) ), 'ProcessException: message Command: cd, OS error code: -19', ); }); testWithoutContext('FileSystemException', () { expect( GitHubTemplateCreator.sanitizedCrashException( const FileSystemException('delete failed', 'path/to/something') ), 'FileSystemException: delete failed, null', ); expect( GitHubTemplateCreator.sanitizedCrashException( const FileSystemException('delete failed', 'path/to/something', OSError('message', -19)) ), 'FileSystemException: delete failed, OS Error: message, errno = -19', ); }); testWithoutContext('SocketException', () { expect( GitHubTemplateCreator.sanitizedCrashException( SocketException( 'message', osError: const OSError('message', -19), address: InternetAddress.anyIPv6, port: 2000 ) ), 'SocketException: message, OS Error: message, errno = -19', ); }); testWithoutContext('DevFSException', () { final StackTrace stackTrace = StackTrace.fromString(''' #0 _File.open.<anonymous closure> (dart:io/file_impl.dart:366:9) #1 _rootRunUnary (dart:async/zone.dart:1141:38)'''); expect( GitHubTemplateCreator.sanitizedCrashException( DevFSException('message', ArgumentError('argument error message'), stackTrace) ), 'DevFSException: message', ); }); testWithoutContext('ArgumentError', () { expect( GitHubTemplateCreator.sanitizedCrashException( ArgumentError('argument error message') ), 'ArgumentError: Invalid argument(s): argument error message', ); }); testWithoutContext('Error', () { expect( GitHubTemplateCreator.sanitizedCrashException( FakeError() ), 'FakeError: (#0 _File.open.<anonymous closure> (dart:io/file_impl.dart:366:9))', ); }); testWithoutContext('String', () { expect( GitHubTemplateCreator.sanitizedCrashException( 'May have non-tool-internal info, very long string, 0b8abb4724aa590dd0f429683339b' // ignore: missing_whitespace_between_adjacent_strings '24aa590dd0f429683339b1e045a1594d0b8abb4724aa590dd0f429683339b1e045a1594d0b8abb' '24aa590dd0f429683339b1e045a1594d0b8abb4724aa590dd0f429683339b1e045a1594d0b8abb' '24aa590dd0f429683339b1e045a1594d0b8abb4724aa590dd0f429683339b1e045a1594d0b8abb' '24aa590dd0f429683339b1e045a1594d0b8abb4724aa590dd0f429683339b1e045a1594d0b8abb' '24aa590dd0f429683339b1e045a1594d0b8abb4724aa590dd0f429683339b1e045a1594d0b8abb' '24aa590dd0f429683339b1e045a1594d0b8abb4724aa590dd0f429683339b1e045a1594d0b8abb' '24aa590dd0f429683339b1e045a1594d0b8abb4724aa590dd0f429683339b1e045a1594d0b8abb' '24aa590dd0f429683339b1e045a1594d0b8abb4724aa590dd0f429683339b1e045a1594d0b8abb' '24aa590dd0f429683339b1e045a1594d0b8abb4724aa590dd0f429683339b1e045a1594d0b8abb' '24aa590dd0f429683339b1e045a1594d0b8abb4724aa590dd0f429683339b1e045a1594d0b8abb' '24aa590dd0f429683339b1e045a1594d0b8abb4724aa590dd0f429683339b1e045a1594d0b8abb' '24aa590dd0f429683339b1e045a1594d0b8abb4724aa590dd0f429683339b1e045a1594d0b8abb' ), 'String: <1,016 characters>', ); }); testWithoutContext('Exception', () { expect( GitHubTemplateCreator.sanitizedCrashException( Exception('May have non-tool-internal info') ), '_Exception', ); }); }); group('new issue template URL', () { late StackTrace stackTrace; late Error error; const String command = 'flutter test'; const String doctorText = ' [✓] Flutter (Channel report'; setUp(() async { stackTrace = StackTrace.fromString('trace'); error = ArgumentError('argument error message'); }); testUsingContext('shows GitHub issue URL', () async { final GitHubTemplateCreator creator = GitHubTemplateCreator( fileSystem: fs, logger: logger, flutterProjectFactory: FlutterProjectFactory( fileSystem: fs, logger: logger, ), ); expect( await creator.toolCrashIssueTemplateGitHubURL(command, error, stackTrace, doctorText), 'https://github.com/flutter/flutter/issues/new?title=%5Btool_crash%5D+ArgumentError%3A+' 'Invalid+argument%28s%29%3A+argument+error+message&body=%23%23+Command%0A%60%60%60sh%0A' 'flutter+test%0A%60%60%60%0A%0A%23%23+Steps+to+Reproduce%0A1.+...%0A2.+...%0A3.+...%0' 'A%0A%23%23+Logs%0AArgumentError%3A+Invalid+argument%28s%29%3A+argument+error+message' '%0A%60%60%60console%0Atrace%0A%60%60%60%0A%60%60%60console%0A+%5B%E2%9C%93%5D+Flutter+%28Channel+r' 'eport%0A%60%60%60%0A%0A%23%23+Flutter+Application+Metadata%0ANo+pubspec+in+working+d' 'irectory.%0A&labels=tool%2Csevere%3A+crash' ); }, overrides: <Type, Generator>{ FileSystem: () => MemoryFileSystem.test(), ProcessManager: () => FakeProcessManager.any(), }); testUsingContext('app metadata', () async { final GitHubTemplateCreator creator = GitHubTemplateCreator( fileSystem: fs, logger: logger, flutterProjectFactory: FlutterProjectFactory( fileSystem: fs, logger: logger, ), ); final Directory projectDirectory = fs.currentDirectory; projectDirectory .childFile('pubspec.yaml') .writeAsStringSync(''' name: failing_app version: 2.0.1+100 flutter: uses-material-design: true module: androidX: true androidPackage: com.example.failing.android iosBundleIdentifier: com.example.failing.ios '''); final File pluginsFile = projectDirectory.childFile('.flutter-plugins'); pluginsFile .writeAsStringSync(''' camera=/fake/pub.dartlang.org/camera-0.5.7+2/ device_info=/fake/pub.dartlang.org/pub.dartlang.org/device_info-0.4.1+4/ '''); final File metadataFile = projectDirectory.childFile('.metadata'); metadataFile .writeAsStringSync(''' version: revision: 0b8abb4724aa590dd0f429683339b1e045a1594d channel: stable project_type: app '''); final String actualURL = await creator.toolCrashIssueTemplateGitHubURL(command, error, stackTrace, doctorText); final String? actualBody = Uri.parse(actualURL).queryParameters['body']; const String expectedBody = ''' ## Command ```sh flutter test ``` ## Steps to Reproduce 1. ... 2. ... 3. ... ## Logs ArgumentError: Invalid argument(s): argument error message ```console trace ``` ```console [✓] Flutter (Channel report ``` ## Flutter Application Metadata **Type**: app **Version**: 2.0.1+100 **Material**: true **Android X**: true **Module**: true **Plugin**: false **Android package**: com.example.failing.android **iOS bundle identifier**: com.example.failing.ios **Creation channel**: stable **Creation framework version**: 0b8abb4724aa590dd0f429683339b1e045a1594d ### Plugins camera-0.5.7+2 device_info-0.4.1+4 '''; expect(actualBody, expectedBody); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), }); }); }); } class FakeError extends Error { @override StackTrace get stackTrace => StackTrace.fromString(''' #0 _File.open.<anonymous closure> (dart:io/file_impl.dart:366:9) #1 _rootRunUnary (dart:async/zone.dart:1141:38)'''); @override String toString() => 'PII to ignore'; }
flutter/packages/flutter_tools/test/general.shard/github_template_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/general.shard/github_template_test.dart", "repo_id": "flutter", "token_count": 4381 }
399