text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
// 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/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; const String tooltipText = 'TIP'; void main() { testWidgets('Tooltip does not build MouseRegion when mouse is detected and in TooltipVisibility with visibility = false', (WidgetTester tester) async { final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); addTearDown(() async { return gesture.removePointer(); }); await gesture.addPointer(); await gesture.moveTo(const Offset(1.0, 1.0)); await tester.pump(); await gesture.moveTo(Offset.zero); await tester.pumpWidget( const MaterialApp( home: TooltipVisibility( visible: false, child: Tooltip( message: tooltipText, child: SizedBox( width: 100.0, height: 100.0, ), ), ), ), ); expect(find.descendant(of: find.byType(Tooltip), matching: find.byType(MouseRegion)), findsNothing); }); testWidgets('Tooltip does not show when hovered when in TooltipVisibility with visible = false', (WidgetTester tester) async { const Duration waitDuration = Duration.zero; final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); addTearDown(() async { return gesture.removePointer(); }); await gesture.addPointer(); await gesture.moveTo(const Offset(1.0, 1.0)); await tester.pump(); await gesture.moveTo(Offset.zero); await tester.pumpWidget( const MaterialApp( home: Center( child: TooltipVisibility( visible: false, child: Tooltip( message: tooltipText, waitDuration: waitDuration, child: SizedBox( width: 100.0, height: 100.0, ), ), ), ), ), ); final Finder tooltip = find.byType(Tooltip); await gesture.moveTo(Offset.zero); await tester.pump(); await gesture.moveTo(tester.getCenter(tooltip)); await tester.pump(); // Wait for it to appear. await tester.pump(waitDuration); expect(find.text(tooltipText), findsNothing); }); testWidgets('Tooltip shows when hovered when in TooltipVisibility with visible = true', (WidgetTester tester) async { const Duration waitDuration = Duration.zero; TestGesture? gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); addTearDown(() async { if (gesture != null) { return gesture.removePointer(); } }); await gesture.addPointer(); await gesture.moveTo(const Offset(1.0, 1.0)); await tester.pump(); await gesture.moveTo(Offset.zero); await tester.pumpWidget( const MaterialApp( home: Center( child: TooltipVisibility( visible: true, child: Tooltip( message: tooltipText, waitDuration: waitDuration, child: SizedBox( width: 100.0, height: 100.0, ), ), ), ), ), ); final Finder tooltip = find.byType(Tooltip); await gesture.moveTo(Offset.zero); await tester.pump(); await gesture.moveTo(tester.getCenter(tooltip)); await tester.pump(); // Wait for it to appear. await tester.pump(waitDuration); expect(find.text(tooltipText), findsOneWidget); // Wait for it to disappear. await gesture.moveTo(Offset.zero); await tester.pumpAndSettle(); await gesture.removePointer(); gesture = null; expect(find.text(tooltipText), findsNothing); }); testWidgets('Tooltip does not build GestureDetector when in TooltipVisibility with visibility = false', (WidgetTester tester) async { await setWidgetForTooltipMode(tester, TooltipTriggerMode.tap, false); expect(find.byType(GestureDetector), findsNothing); }); testWidgets('Tooltip triggers on tap when trigger mode is tap and in TooltipVisibility with visible = true', (WidgetTester tester) async { await setWidgetForTooltipMode(tester, TooltipTriggerMode.tap, true); final Finder tooltip = find.byType(Tooltip); expect(find.text(tooltipText), findsNothing); await testGestureTap(tester, tooltip); expect(find.text(tooltipText), findsOneWidget); }); testWidgets('Tooltip does not trigger manually when in TooltipVisibility with visible = false', (WidgetTester tester) async { final GlobalKey<TooltipState> tooltipKey = GlobalKey<TooltipState>(); await tester.pumpWidget( MaterialApp( home: TooltipVisibility( visible: false, child: Tooltip( key: tooltipKey, message: tooltipText, child: const SizedBox(width: 100.0, height: 100.0), ), ), ), ); tooltipKey.currentState?.ensureTooltipVisible(); await tester.pump(); expect(find.text(tooltipText), findsNothing); }); testWidgets('Tooltip triggers manually when in TooltipVisibility with visible = true', (WidgetTester tester) async { final GlobalKey<TooltipState> tooltipKey = GlobalKey<TooltipState>(); await tester.pumpWidget( MaterialApp( home: TooltipVisibility( visible: true, child: Tooltip( key: tooltipKey, message: tooltipText, child: const SizedBox(width: 100.0, height: 100.0), ), ), ), ); tooltipKey.currentState?.ensureTooltipVisible(); await tester.pump(); expect(find.text(tooltipText), findsOneWidget); }); } Future<void> setWidgetForTooltipMode(WidgetTester tester, TooltipTriggerMode triggerMode, bool visibility) async { await tester.pumpWidget( MaterialApp( home: TooltipVisibility( visible: visibility, child: Tooltip( message: tooltipText, triggerMode: triggerMode, child: const SizedBox(width: 100.0, height: 100.0), ), ), ), ); } Future<void> testGestureTap(WidgetTester tester, Finder tooltip) async { await tester.tap(tooltip); await tester.pump(const Duration(milliseconds: 10)); }
flutter/packages/flutter/test/material/tooltip_visibility_test.dart/0
{ "file_path": "flutter/packages/flutter/test/material/tooltip_visibility_test.dart", "repo_id": "flutter", "token_count": 2619 }
679
// 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/painting.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { test('applyBoxFit', () { FittedSizes result; result = applyBoxFit(BoxFit.scaleDown, const Size(100.0, 1000.0), const Size(200.0, 2000.0)); expect(result.source, equals(const Size(100.0, 1000.0))); expect(result.destination, equals(const Size(100.0, 1000.0))); result = applyBoxFit(BoxFit.scaleDown, const Size(300.0, 3000.0), const Size(200.0, 2000.0)); expect(result.source, equals(const Size(300.0, 3000.0))); expect(result.destination, equals(const Size(200.0, 2000.0))); result = applyBoxFit(BoxFit.fitWidth, const Size(2000.0, 400.0), const Size(1000.0, 100.0)); expect(result.source, equals(const Size(2000.0, 200.0))); expect(result.destination, equals(const Size(1000.0, 100.0))); result = applyBoxFit(BoxFit.fitWidth, const Size(2000.0, 400.0), const Size(1000.0, 300.0)); expect(result.source, equals(const Size(2000.0, 400.0))); expect(result.destination, equals(const Size(1000.0, 200.0))); result = applyBoxFit(BoxFit.fitHeight, const Size(400.0, 2000.0), const Size(100.0, 1000.0)); expect(result.source, equals(const Size(200.0, 2000.0))); expect(result.destination, equals(const Size(100.0, 1000.0))); result = applyBoxFit(BoxFit.fitHeight, const Size(400.0, 2000.0), const Size(300.0, 1000.0)); expect(result.source, equals(const Size(400.0, 2000.0))); expect(result.destination, equals(const Size(200.0, 1000.0))); _testZeroAndNegativeSizes(BoxFit.fill); _testZeroAndNegativeSizes(BoxFit.contain); _testZeroAndNegativeSizes(BoxFit.cover); _testZeroAndNegativeSizes(BoxFit.fitWidth); _testZeroAndNegativeSizes(BoxFit.fitHeight); _testZeroAndNegativeSizes(BoxFit.none); _testZeroAndNegativeSizes(BoxFit.scaleDown); }); } void _testZeroAndNegativeSizes(BoxFit fit) { FittedSizes result; result = applyBoxFit(fit, const Size(-400.0, 2000.0), const Size(100.0, 1000.0)); expect(result.source, equals(Size.zero)); expect(result.destination, equals(Size.zero)); result = applyBoxFit(fit, const Size(400.0, -2000.0), const Size(100.0, 1000.0)); expect(result.source, equals(Size.zero)); expect(result.destination, equals(Size.zero)); result = applyBoxFit(fit, const Size(400.0, 2000.0), const Size(-100.0, 1000.0)); expect(result.source, equals(Size.zero)); expect(result.destination, equals(Size.zero)); result = applyBoxFit(fit, const Size(400.0, 2000.0), const Size(100.0, -1000.0)); expect(result.source, equals(Size.zero)); expect(result.destination, equals(Size.zero)); result = applyBoxFit(fit, const Size(0.0, 2000.0), const Size(100.0, 1000.0)); expect(result.source, equals(Size.zero)); expect(result.destination, equals(Size.zero)); result = applyBoxFit(fit, const Size(400.0, 0.0), const Size(100.0, 1000.0)); expect(result.source, equals(Size.zero)); expect(result.destination, equals(Size.zero)); result = applyBoxFit(fit, const Size(400.0, 2000.0), const Size(0.0, 1000.0)); expect(result.source, equals(Size.zero)); expect(result.destination, equals(Size.zero)); result = applyBoxFit(fit, const Size(400.0, 2000.0), const Size(100.0, 0.0)); expect(result.source, equals(Size.zero)); expect(result.destination, equals(Size.zero)); }
flutter/packages/flutter/test/painting/box_fit_test.dart/0
{ "file_path": "flutter/packages/flutter/test/painting/box_fit_test.dart", "repo_id": "flutter", "token_count": 1274 }
680
// 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:flutter/painting.dart'; import 'package:flutter_test/flutter_test.dart'; import '../image_data.dart'; import '../rendering/rendering_tester.dart'; void main() { TestRenderingFlutterBinding.ensureInitialized(); test("Clearing images while they're pending does not crash", () async { final Uint8List bytes = Uint8List.fromList(kTransparentImage); final MemoryImage memoryImage = MemoryImage(bytes); final ImageStream stream = memoryImage.resolve(ImageConfiguration.empty); final Completer<void> completer = Completer<void>(); FlutterError.onError = (FlutterErrorDetails error) { completer.completeError(error.exception, error.stack); }; stream.addListener(ImageStreamListener( (ImageInfo image, bool synchronousCall) { completer.complete(); }, )); imageCache.clearLiveImages(); await completer.future; }); }
flutter/packages/flutter/test/painting/image_cache_clearing_test.dart/0
{ "file_path": "flutter/packages/flutter/test/painting/image_cache_clearing_test.dart", "repo_id": "flutter", "token_count": 358 }
681
// 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 'package:flutter/painting.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { group('CircularNotchedRectangle', () { test("guest and host don't overlap", () { const CircularNotchedRectangle shape = CircularNotchedRectangle(); const Rect host = Rect.fromLTRB(0.0, 100.0, 300.0, 300.0); const Rect guest = Rect.fromLTWH(50.0, 50.0, 10.0, 10.0); final Path actualPath = shape.getOuterPath(host, guest); final Path expectedPath = Path()..addRect(host); expect( actualPath, coversSameAreaAs( expectedPath, areaToCompare: host.inflate(5.0), sampleSize: 40, ), ); }); test('guest center above host', () { const CircularNotchedRectangle shape = CircularNotchedRectangle(); const Rect host = Rect.fromLTRB(0.0, 100.0, 300.0, 300.0); const Rect guest = Rect.fromLTRB(190.0, 85.0, 210.0, 105.0); final Path actualPath = shape.getOuterPath(host, guest); expect(pathDoesNotContainCircle(actualPath, guest), isTrue); }); test('guest center below host', () { const CircularNotchedRectangle shape = CircularNotchedRectangle(); const Rect host = Rect.fromLTRB(0.0, 100.0, 300.0, 300.0); const Rect guest = Rect.fromLTRB(190.0, 95.0, 210.0, 115.0); final Path actualPath = shape.getOuterPath(host, guest); expect(pathDoesNotContainCircle(actualPath, guest), isTrue); }); test('no guest is ok', () { const Rect host = Rect.fromLTRB(0.0, 100.0, 300.0, 300.0); expect( const CircularNotchedRectangle().getOuterPath(host, null), coversSameAreaAs( Path()..addRect(host), areaToCompare: host.inflate(800.0), sampleSize: 100, ), ); }); test('AutomaticNotchedShape - with guest', () { expect( const AutomaticNotchedShape( RoundedRectangleBorder(), RoundedRectangleBorder(), ).getOuterPath( const Rect.fromLTWH(-200.0, -100.0, 50.0, 100.0), const Rect.fromLTWH(-175.0, -110.0, 100.0, 100.0), ), coversSameAreaAs( Path() ..moveTo(-200.0, -100.0) ..lineTo(-150.0, -100.0) ..lineTo(-150.0, -10.0) ..lineTo(-175.0, -10.0) ..lineTo(-175.0, 0.0) ..lineTo(-200.0, 0.0) ..close(), areaToCompare: const Rect.fromLTWH(-300.0, -300.0, 600.0, 600.0), sampleSize: 100, ), ); }, skip: isBrowser); // https://github.com/flutter/flutter/issues/44572 test('AutomaticNotchedShape - no guest', () { expect( const AutomaticNotchedShape( RoundedRectangleBorder(), RoundedRectangleBorder(), ).getOuterPath( const Rect.fromLTWH(-200.0, -100.0, 50.0, 100.0), null, ), coversSameAreaAs( Path() ..moveTo(-200.0, -100.0) ..lineTo(-150.0, -100.0) ..lineTo(-150.0, 0.0) ..lineTo(-200.0, 0.0) ..close(), areaToCompare: const Rect.fromLTWH(-300.0, -300.0, 600.0, 600.0), sampleSize: 100, ), ); }); }); } bool pathDoesNotContainCircle(Path path, Rect circleBounds) { assert(circleBounds.width == circleBounds.height); final double radius = circleBounds.width / 2.0; for (double theta = 0.0; theta <= 2.0 * math.pi; theta += math.pi / 20.0) { for (double i = 0.0; i < 1; i += 0.01) { final double x = i * radius * math.cos(theta); final double y = i * radius * math.sin(theta); if (path.contains(Offset(x,y) + circleBounds.center)) { return false; } } } return true; }
flutter/packages/flutter/test/painting/notched_shapes_test.dart/0
{ "file_path": "flutter/packages/flutter/test/painting/notched_shapes_test.dart", "repo_id": "flutter", "token_count": 1846 }
682
// 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 show FontFeature, FontVariation, ParagraphStyle, Shadow, TextStyle; import 'package:flutter/painting.dart'; import 'package:flutter_test/flutter_test.dart'; // This matcher verifies ui.TextStyle.toString (from dart:ui) reports a superset // of the given TextStyle's (from painting.dart) properties. class _DartUiTextStyleToStringMatcher extends Matcher { _DartUiTextStyleToStringMatcher(this.textStyle); final TextStyle textStyle; late final List<String> propertiesInOrder = <String>[ _propertyToString('color', textStyle.color), _propertyToString('decoration', textStyle.decoration), _propertyToString('decorationColor', textStyle.decorationColor), _propertyToString('decorationStyle', textStyle.decorationStyle), _propertyToString('decorationThickness', textStyle.decorationThickness), _propertyToString('fontWeight', textStyle.fontWeight), _propertyToString('fontStyle', textStyle.fontStyle), _propertyToString('textBaseline', textStyle.textBaseline), _propertyToString('fontFamily', textStyle.fontFamily), _propertyToString('fontFamilyFallback', textStyle.fontFamilyFallback), _propertyToString('fontSize', textStyle.fontSize), _propertyToString('letterSpacing', textStyle.letterSpacing), _propertyToString('wordSpacing', textStyle.wordSpacing), _propertyToString('height', textStyle.height), _propertyToString('leadingDistribution', textStyle.leadingDistribution), _propertyToString('locale', textStyle.locale), _propertyToString('background', textStyle.background), _propertyToString('foreground', textStyle.foreground), _propertyToString('shadows', textStyle.shadows), _propertyToString('fontFeatures', textStyle.fontFeatures), _propertyToString('fontVariations', textStyle.fontVariations), ]; static String _propertyToString(String name, Object? property) => '$name: ${property ?? 'unspecified'}'; @override Description describe(Description description) => description.add('is a superset of $textStyle.'); @override bool matches(dynamic item, Map<dynamic, dynamic> matchState) { final String description = item.toString(); const String prefix = 'TextStyle('; const String suffix = ')'; if (!description.startsWith(prefix) || !description.endsWith(suffix)) { return false; } final String propertyDescription = description.substring( prefix.length, description.length - suffix.length, ); int startIndex = 0; for (final String property in propertiesInOrder) { startIndex = propertyDescription.indexOf(property, startIndex); if (startIndex < 0) { matchState['missingProperty'] = property; return false; } startIndex += property.length; } return true; } @override Description describeMismatch(dynamic item, Description mismatchDescription, Map<dynamic, dynamic> matchState, bool verbose) { final Description description = super.describeMismatch(item, mismatchDescription, matchState, verbose); final String itemAsString = item.toString(); final String? property = matchState['missingProperty'] as String?; if (property != null) { description.add("expect property: '$property'"); final int propertyIndex = propertiesInOrder.indexOf(property); if (propertyIndex > 0) { final String lastProperty = propertiesInOrder[propertyIndex - 1]; description.add(" after: '$lastProperty'\n"); description.add('but found: ${itemAsString.substring(itemAsString.indexOf(lastProperty))}'); } description.add('\n'); } return description; } } Matcher matchesToStringOf(TextStyle textStyle) => _DartUiTextStyleToStringMatcher(textStyle); void main() { test('TextStyle control test', () { expect( const TextStyle(inherit: false).toString(), equals('TextStyle(inherit: false, <no style specified>)'), ); expect( const TextStyle().toString(), equals('TextStyle(<all styles inherited>)'), ); const TextStyle s1 = TextStyle( fontSize: 10.0, fontWeight: FontWeight.w800, height: 123.0, ); expect(s1.fontFamily, isNull); expect(s1.fontSize, 10.0); expect(s1.fontWeight, FontWeight.w800); expect(s1.height, 123.0); expect(s1, equals(s1)); expect( s1.toString(), equals('TextStyle(inherit: true, size: 10.0, weight: 800, height: 123.0x)'), ); // Check that the inherit flag can be set with copyWith(). expect( s1.copyWith(inherit: false).toString(), equals('TextStyle(inherit: false, size: 10.0, weight: 800, height: 123.0x)'), ); final TextStyle s2 = s1.copyWith( color: const Color(0xFF00FF00), height: 100.0, leadingDistribution: TextLeadingDistribution.even, ); expect(s1.fontFamily, isNull); expect(s1.fontSize, 10.0); expect(s1.fontWeight, FontWeight.w800); expect(s1.height, 123.0); expect(s1.color, isNull); expect(s2.fontFamily, isNull); expect(s2.fontSize, 10.0); expect(s2.fontWeight, FontWeight.w800); expect(s2.height, 100.0); expect(s2.color, const Color(0xFF00FF00)); expect(s2.leadingDistribution, TextLeadingDistribution.even); expect(s2, isNot(equals(s1))); expect( s2.toString(), equals( 'TextStyle(inherit: true, color: Color(0xff00ff00), size: 10.0, weight: 800, height: 100.0x, leadingDistribution: even)', ), ); final TextStyle s3 = s1.apply(fontSizeFactor: 2.0, fontSizeDelta: -2.0, fontWeightDelta: -4); expect(s1.fontFamily, isNull); expect(s1.fontSize, 10.0); expect(s1.fontWeight, FontWeight.w800); expect(s1.height, 123.0); expect(s1.color, isNull); expect(s3.fontFamily, isNull); expect(s3.fontSize, 18.0); expect(s3.fontWeight, FontWeight.w400); expect(s3.height, 123.0); expect(s3.color, isNull); expect(s3, isNot(equals(s1))); expect(s1.apply(fontWeightDelta: -10).fontWeight, FontWeight.w100); expect(s1.apply(fontWeightDelta: 2).fontWeight, FontWeight.w900); expect(s1.merge(null), equals(s1)); final TextStyle s4 = s2.merge(s1); expect(s1.fontFamily, isNull); expect(s1.fontSize, 10.0); expect(s1.fontWeight, FontWeight.w800); expect(s1.height, 123.0); expect(s1.color, isNull); expect(s2.fontFamily, isNull); expect(s2.fontSize, 10.0); expect(s2.fontWeight, FontWeight.w800); expect(s2.height, 100.0); expect(s2.color, const Color(0xFF00FF00)); expect(s2.leadingDistribution, TextLeadingDistribution.even); expect(s2, isNot(equals(s1))); expect(s2, isNot(equals(s4))); expect(s4.fontFamily, isNull); expect(s4.fontSize, 10.0); expect(s4.fontWeight, FontWeight.w800); expect(s4.height, 123.0); expect(s4.color, const Color(0xFF00FF00)); expect(s4.leadingDistribution, TextLeadingDistribution.even); final TextStyle s5 = TextStyle.lerp(s1, s3, 0.25)!; expect(s1.fontFamily, isNull); expect(s1.fontSize, 10.0); expect(s1.fontWeight, FontWeight.w800); expect(s1.height, 123.0); expect(s1.color, isNull); expect(s3.fontFamily, isNull); expect(s3.fontSize, 18.0); expect(s3.fontWeight, FontWeight.w400); expect(s3.height, 123.0); expect(s3.color, isNull); expect(s3, isNot(equals(s1))); expect(s3, isNot(equals(s5))); expect(s5.fontFamily, isNull); expect(s5.fontSize, 12.0); expect(s5.fontWeight, FontWeight.w700); expect(s5.height, 123.0); expect(s5.color, isNull); expect(TextStyle.lerp(null, null, 0.5), isNull); final TextStyle s6 = TextStyle.lerp(null, s3, 0.25)!; expect(s3.fontFamily, isNull); expect(s3.fontSize, 18.0); expect(s3.fontWeight, FontWeight.w400); expect(s3.height, 123.0); expect(s3.color, isNull); expect(s3, isNot(equals(s6))); expect(s6.fontFamily, isNull); expect(s6.fontSize, isNull); expect(s6.fontWeight, FontWeight.w400); expect(s6.height, isNull); expect(s6.color, isNull); final TextStyle s7 = TextStyle.lerp(null, s3, 0.75)!; expect(s3.fontFamily, isNull); expect(s3.fontSize, 18.0); expect(s3.fontWeight, FontWeight.w400); expect(s3.height, 123.0); expect(s3.color, isNull); expect(s3, equals(s7)); expect(s7.fontFamily, isNull); expect(s7.fontSize, 18.0); expect(s7.fontWeight, FontWeight.w400); expect(s7.height, 123.0); expect(s7.color, isNull); final TextStyle s8 = TextStyle.lerp(s3, null, 0.25)!; expect(s3.fontFamily, isNull); expect(s3.fontSize, 18.0); expect(s3.fontWeight, FontWeight.w400); expect(s3.height, 123.0); expect(s3.color, isNull); expect(s3, equals(s8)); expect(s8.fontFamily, isNull); expect(s8.fontSize, 18.0); expect(s8.fontWeight, FontWeight.w400); expect(s8.height, 123.0); expect(s8.color, isNull); final TextStyle s9 = TextStyle.lerp(s3, null, 0.75)!; expect(s3.fontFamily, isNull); expect(s3.fontSize, 18.0); expect(s3.fontWeight, FontWeight.w400); expect(s3.height, 123.0); expect(s3.color, isNull); expect(s3, isNot(equals(s9))); expect(s9.fontFamily, isNull); expect(s9.fontSize, isNull); expect(s9.fontWeight, FontWeight.w400); expect(s9.height, isNull); expect(s9.color, isNull); final ui.TextStyle ts5 = s5.getTextStyle(); expect(ts5, equals(ui.TextStyle(fontWeight: FontWeight.w700, fontSize: 12.0, height: 123.0))); expect(ts5, matchesToStringOf(s5)); final ui.TextStyle ts2 = s2.getTextStyle(); expect(ts2, equals(ui.TextStyle(color: const Color(0xFF00FF00), fontWeight: FontWeight.w800, fontSize: 10.0, height: 100.0, leadingDistribution: TextLeadingDistribution.even))); expect(ts2, matchesToStringOf(s2)); final ui.ParagraphStyle ps2 = s2.getParagraphStyle(textAlign: TextAlign.center); expect( ps2, equals(ui.ParagraphStyle(textAlign: TextAlign.center, fontWeight: FontWeight.w800, fontSize: 10.0, height: 100.0, textHeightBehavior: const TextHeightBehavior(leadingDistribution: TextLeadingDistribution.even))), ); final ui.ParagraphStyle ps5 = s5.getParagraphStyle(); expect( ps5, equals(ui.ParagraphStyle(fontWeight: FontWeight.w700, fontSize: 12.0, height: 123.0)), ); }); test('TextStyle with text direction', () { final ui.ParagraphStyle ps6 = const TextStyle().getParagraphStyle(textDirection: TextDirection.ltr); expect(ps6, equals(ui.ParagraphStyle(textDirection: TextDirection.ltr, fontSize: 14.0))); final ui.ParagraphStyle ps7 = const TextStyle().getParagraphStyle(textDirection: TextDirection.rtl); expect(ps7, equals(ui.ParagraphStyle(textDirection: TextDirection.rtl, fontSize: 14.0))); }); test('TextStyle using package font', () { const TextStyle s6 = TextStyle(fontFamily: 'test'); expect(s6.fontFamily, 'test'); expect(s6.getTextStyle(), matchesToStringOf(s6)); const TextStyle s7 = TextStyle(fontFamily: 'test', package: 'p'); expect(s7.fontFamily, 'packages/p/test'); expect(s7.getTextStyle(), matchesToStringOf(s7)); const TextStyle s8 = TextStyle(fontFamilyFallback: <String>['test', 'test2'], package: 'p'); expect(s8.fontFamilyFallback![0], 'packages/p/test'); expect(s8.fontFamilyFallback![1], 'packages/p/test2'); expect(s8.fontFamilyFallback!.length, 2); const TextStyle s9 = TextStyle(package: 'p'); expect(s9.fontFamilyFallback, null); const TextStyle s10 = TextStyle(fontFamilyFallback: <String>[], package: 'p'); expect(s10.fontFamilyFallback, <String>[]); // Ensure that package prefix is not duplicated after copying. final TextStyle s11 = s8.copyWith(); expect(s11.fontFamilyFallback![0], 'packages/p/test'); expect(s11.fontFamilyFallback![1], 'packages/p/test2'); expect(s11.fontFamilyFallback!.length, 2); expect(s8, s11); // Ensure that package prefix is not duplicated after applying. final TextStyle s12 = s8.apply(); expect(s12.fontFamilyFallback![0], 'packages/p/test'); expect(s12.fontFamilyFallback![1], 'packages/p/test2'); expect(s12.fontFamilyFallback!.length, 2); expect(s8, s12); }); test('TextStyle package font merge', () { const TextStyle s1 = TextStyle(package: 'p', fontFamily: 'font1', fontFamilyFallback: <String>['fallback1']); const TextStyle s2 = TextStyle(package: 'p', fontFamily: 'font2', fontFamilyFallback: <String>['fallback2']); final TextStyle emptyMerge = const TextStyle().merge(s1); expect(emptyMerge.fontFamily, 'packages/p/font1'); expect(emptyMerge.fontFamilyFallback, <String>['packages/p/fallback1']); final TextStyle lerp1 = TextStyle.lerp(s1, s2, 0)!; expect(lerp1.fontFamily, 'packages/p/font1'); expect(lerp1.fontFamilyFallback, <String>['packages/p/fallback1']); final TextStyle lerp2 = TextStyle.lerp(s1, s2, 1.0)!; expect(lerp2.fontFamily, 'packages/p/font2'); expect(lerp2.fontFamilyFallback, <String>['packages/p/fallback2']); }); test('TextStyle font family fallback', () { const TextStyle s1 = TextStyle(fontFamilyFallback: <String>['Roboto', 'test']); expect(s1.fontFamilyFallback![0], 'Roboto'); expect(s1.fontFamilyFallback![1], 'test'); expect(s1.fontFamilyFallback!.length, 2); const TextStyle s2 = TextStyle(fontFamily: 'foo', fontFamilyFallback: <String>['Roboto', 'test']); expect(s2.fontFamilyFallback![0], 'Roboto'); expect(s2.fontFamilyFallback![1], 'test'); expect(s2.fontFamily, 'foo'); expect(s2.fontFamilyFallback!.length, 2); const TextStyle s3 = TextStyle(fontFamily: 'foo'); expect(s3.fontFamily, 'foo'); expect(s3.fontFamilyFallback, null); const TextStyle s4 = TextStyle(fontFamily: 'foo', fontFamilyFallback: <String>[]); expect(s4.fontFamily, 'foo'); expect(s4.fontFamilyFallback, <String>[]); expect(s4.fontFamilyFallback!.isEmpty, true); final ui.TextStyle uis1 = s2.getTextStyle(); expect(uis1, matchesToStringOf(s2)); expect(s2.apply().fontFamily, 'foo'); expect(s2.apply().fontFamilyFallback, const <String>['Roboto', 'test']); expect(s2.apply(fontFamily: 'bar').fontFamily, 'bar'); expect(s2.apply(fontFamilyFallback: const <String>['Banana']).fontFamilyFallback, const <String>['Banana']); }); test('TextStyle.debugLabel', () { const TextStyle unknown = TextStyle(); const TextStyle foo = TextStyle(debugLabel: 'foo', fontSize: 1.0); const TextStyle bar = TextStyle(debugLabel: 'bar', fontSize: 2.0); const TextStyle baz = TextStyle(debugLabel: 'baz', fontSize: 3.0); expect(unknown.debugLabel, null); expect(unknown.toString(), 'TextStyle(<all styles inherited>)'); expect(unknown.copyWith().debugLabel, null); expect(unknown.copyWith(debugLabel: '123').debugLabel, '123'); expect(unknown.apply().debugLabel, null); expect(foo.debugLabel, 'foo'); expect(foo.toString(), 'TextStyle(debugLabel: foo, inherit: true, size: 1.0)'); expect(foo.merge(bar).debugLabel, '(foo).merge(bar)'); expect(foo.merge(bar).merge(baz).debugLabel, '((foo).merge(bar)).merge(baz)'); expect(foo.copyWith().debugLabel, '(foo).copyWith'); expect(foo.apply().debugLabel, '(foo).apply'); expect(TextStyle.lerp(foo, bar, 0.5)!.debugLabel, 'lerp(foo ⎯0.5→ bar)'); expect(TextStyle.lerp(foo.merge(bar), baz, 0.51)!.copyWith().debugLabel, '(lerp((foo).merge(bar) ⎯0.5→ baz)).copyWith'); }); test('TextStyle.hashCode', () { const TextStyle a = TextStyle( fontFamilyFallback: <String>['Roboto'], shadows: <ui.Shadow>[ui.Shadow()], fontFeatures: <ui.FontFeature>[ui.FontFeature('abcd')], fontVariations: <ui.FontVariation>[ui.FontVariation('wght', 123.0)], ); const TextStyle b = TextStyle( fontFamilyFallback: <String>['Noto'], shadows: <ui.Shadow>[ui.Shadow()], fontFeatures: <ui.FontFeature>[ui.FontFeature('abcd')], fontVariations: <ui.FontVariation>[ui.FontVariation('wght', 123.0)], ); expect(a.hashCode, a.hashCode); expect(a.hashCode, isNot(equals(b.hashCode))); const TextStyle c = TextStyle(leadingDistribution: TextLeadingDistribution.even); const TextStyle d = TextStyle(leadingDistribution: TextLeadingDistribution.proportional); expect(c.hashCode, c.hashCode); expect(c.hashCode, isNot(d.hashCode)); }); test('TextStyle foreground and color combos', () { const Color red = Color.fromARGB(255, 255, 0, 0); const Color blue = Color.fromARGB(255, 0, 0, 255); const TextStyle redTextStyle = TextStyle(color: red); const TextStyle blueTextStyle = TextStyle(color: blue); final TextStyle redPaintTextStyle = TextStyle(foreground: Paint()..color = red); final TextStyle bluePaintTextStyle = TextStyle(foreground: Paint()..color = blue); // merge/copyWith final TextStyle redBlueBothForegroundMerged = redTextStyle.merge(blueTextStyle); expect(redBlueBothForegroundMerged.color, blue); expect(redBlueBothForegroundMerged.foreground, isNull); final TextStyle redBlueBothPaintMerged = redPaintTextStyle.merge(bluePaintTextStyle); expect(redBlueBothPaintMerged.color, null); expect(redBlueBothPaintMerged.foreground, bluePaintTextStyle.foreground); final TextStyle redPaintBlueColorMerged = redPaintTextStyle.merge(blueTextStyle); expect(redPaintBlueColorMerged.color, null); expect(redPaintBlueColorMerged.foreground, redPaintTextStyle.foreground); final TextStyle blueColorRedPaintMerged = blueTextStyle.merge(redPaintTextStyle); expect(blueColorRedPaintMerged.color, null); expect(blueColorRedPaintMerged.foreground, redPaintTextStyle.foreground); // apply expect(redPaintTextStyle.apply(color: blue).color, isNull); expect(redPaintTextStyle.apply(color: blue).foreground!.color, red); expect(redTextStyle.apply(color: blue).color, blue); // lerp expect(TextStyle.lerp(redTextStyle, blueTextStyle, .25)!.color, Color.lerp(red, blue, .25)); expect(TextStyle.lerp(redTextStyle, bluePaintTextStyle, .25)!.color, isNull); expect(TextStyle.lerp(redTextStyle, bluePaintTextStyle, .25)!.foreground!.color, red); expect(TextStyle.lerp(redTextStyle, bluePaintTextStyle, .75)!.foreground!.color, blue); expect(TextStyle.lerp(redPaintTextStyle, bluePaintTextStyle, .25)!.color, isNull); expect(TextStyle.lerp(redPaintTextStyle, bluePaintTextStyle, .25)!.foreground!.color, red); expect(TextStyle.lerp(redPaintTextStyle, bluePaintTextStyle, .75)!.foreground!.color, blue); }); test('backgroundColor', () { const TextStyle s1 = TextStyle(); expect(s1.backgroundColor, isNull); expect(s1.toString(), 'TextStyle(<all styles inherited>)'); const TextStyle s2 = TextStyle(backgroundColor: Color(0xFF00FF00)); expect(s2.backgroundColor, const Color(0xFF00FF00)); expect(s2.toString(), 'TextStyle(inherit: true, backgroundColor: Color(0xff00ff00))'); final ui.TextStyle ts2 = s2.getTextStyle(); // TODO(matanlurey): Remove when https://github.com/flutter/flutter/issues/112498 is resolved. // The web implementation never includes "dither: ..." as a property, and after #112498 neither // does non-web (as there will no longer be a user-visible "dither" property). So, relax the // test to just check for the color by using a regular expression. expect( ts2.toString(), matches(RegExp(r'background: Paint\(Color\(0xff00ff00\).*\)')), ); }); test('TextStyle background and backgroundColor combos', () { const Color red = Color.fromARGB(255, 255, 0, 0); const Color blue = Color.fromARGB(255, 0, 0, 255); const TextStyle redTextStyle = TextStyle(backgroundColor: red); const TextStyle blueTextStyle = TextStyle(backgroundColor: blue); final TextStyle redPaintTextStyle = TextStyle(background: Paint()..color = red); final TextStyle bluePaintTextStyle = TextStyle(background: Paint()..color = blue); // merge/copyWith final TextStyle redBlueBothForegroundMerged = redTextStyle.merge(blueTextStyle); expect(redBlueBothForegroundMerged.backgroundColor, blue); expect(redBlueBothForegroundMerged.foreground, isNull); final TextStyle redBlueBothPaintMerged = redPaintTextStyle.merge(bluePaintTextStyle); expect(redBlueBothPaintMerged.backgroundColor, null); expect(redBlueBothPaintMerged.background, bluePaintTextStyle.background); final TextStyle redPaintBlueColorMerged = redPaintTextStyle.merge(blueTextStyle); expect(redPaintBlueColorMerged.backgroundColor, null); expect(redPaintBlueColorMerged.background, redPaintTextStyle.background); final TextStyle blueColorRedPaintMerged = blueTextStyle.merge(redPaintTextStyle); expect(blueColorRedPaintMerged.backgroundColor, null); expect(blueColorRedPaintMerged.background, redPaintTextStyle.background); // apply expect(redPaintTextStyle.apply(backgroundColor: blue).backgroundColor, isNull); expect(redPaintTextStyle.apply(backgroundColor: blue).background!.color, red); expect(redTextStyle.apply(backgroundColor: blue).backgroundColor, blue); // lerp expect(TextStyle.lerp(redTextStyle, blueTextStyle, .25)!.backgroundColor, Color.lerp(red, blue, .25)); expect(TextStyle.lerp(redTextStyle, bluePaintTextStyle, .25)!.backgroundColor, isNull); expect(TextStyle.lerp(redTextStyle, bluePaintTextStyle, .25)!.background!.color, red); expect(TextStyle.lerp(redTextStyle, bluePaintTextStyle, .75)!.background!.color, blue); expect(TextStyle.lerp(redPaintTextStyle, bluePaintTextStyle, .25)!.backgroundColor, isNull); expect(TextStyle.lerp(redPaintTextStyle, bluePaintTextStyle, .25)!.background!.color, red); expect(TextStyle.lerp(redPaintTextStyle, bluePaintTextStyle, .75)!.background!.color, blue); }); test('TextStyle strut textScaler', () { const TextStyle style0 = TextStyle(fontSize: 10); final ui.ParagraphStyle paragraphStyle0 = style0.getParagraphStyle(textScaler: const TextScaler.linear(2.5)); const TextStyle style1 = TextStyle(fontSize: 25); final ui.ParagraphStyle paragraphStyle1 = style1.getParagraphStyle(); expect(paragraphStyle0 == paragraphStyle1, true); }); test('TextStyle apply', () { const TextStyle style = TextStyle( fontSize: 10, shadows: <ui.Shadow>[], fontStyle: FontStyle.normal, fontFeatures: <ui.FontFeature>[], fontVariations: <ui.FontVariation>[], textBaseline: TextBaseline.alphabetic, leadingDistribution: TextLeadingDistribution.even, ); expect(style.apply().shadows, const <ui.Shadow>[]); expect(style.apply(shadows: const <ui.Shadow>[ui.Shadow(blurRadius: 2.0)]).shadows, const <ui.Shadow>[ui.Shadow(blurRadius: 2.0)]); expect(style.apply().fontStyle, FontStyle.normal); expect(style.apply(fontStyle: FontStyle.italic).fontStyle, FontStyle.italic); expect(style.apply().locale, isNull); expect(style.apply(locale: const Locale.fromSubtags(languageCode: 'es')).locale, const Locale.fromSubtags(languageCode: 'es')); expect(style.apply().fontFeatures, const <ui.FontFeature>[]); expect(style.apply(fontFeatures: const <ui.FontFeature>[ui.FontFeature.enable('test')]).fontFeatures, const <ui.FontFeature>[ui.FontFeature.enable('test')]); expect(style.apply().fontVariations, const <ui.FontVariation>[]); expect(style.apply(fontVariations: const <ui.FontVariation>[ui.FontVariation('test', 100.0)]).fontVariations, const <ui.FontVariation>[ui.FontVariation('test', 100.0)]); expect(style.apply().textBaseline, TextBaseline.alphabetic); expect(style.apply(textBaseline: TextBaseline.ideographic).textBaseline, TextBaseline.ideographic); expect(style.apply().leadingDistribution, TextLeadingDistribution.even); expect( style.apply(leadingDistribution: TextLeadingDistribution.proportional).leadingDistribution, TextLeadingDistribution.proportional, ); }); test('TextStyle fontFamily and package', () { expect(const TextStyle(fontFamily: 'fontFamily', package: 'foo') != const TextStyle(fontFamily: 'fontFamily', package: 'bar'), true); expect(const TextStyle(fontFamily: 'fontFamily', package: 'foo').hashCode != const TextStyle(package: 'bar', fontFamily: 'fontFamily').hashCode, true); expect(const TextStyle(fontFamily: 'fontFamily').fontFamily, 'fontFamily'); expect(const TextStyle(fontFamily: 'fontFamily').fontFamily, 'fontFamily'); expect(const TextStyle(fontFamily: 'fontFamily').copyWith(package: 'bar').fontFamily, 'packages/bar/fontFamily'); expect(const TextStyle(fontFamily: 'fontFamily', package: 'foo').fontFamily, 'packages/foo/fontFamily'); expect(const TextStyle(fontFamily: 'fontFamily', package: 'foo').copyWith(package: 'bar').fontFamily, 'packages/bar/fontFamily'); expect(const TextStyle().merge(const TextStyle(fontFamily: 'fontFamily', package: 'bar')).fontFamily, 'packages/bar/fontFamily'); expect(const TextStyle().apply(fontFamily: 'fontFamily', package: 'foo').fontFamily, 'packages/foo/fontFamily'); expect(const TextStyle(fontFamily: 'fontFamily', package: 'foo').apply(fontFamily: 'fontFamily', package: 'bar').fontFamily, 'packages/bar/fontFamily'); }); test('TextStyle.lerp identical a,b', () { expect(TextStyle.lerp(null, null, 0), null); const TextStyle style = TextStyle(); expect(identical(TextStyle.lerp(style, style, 0.5), style), true); }); test('Throws when lerping between inherit:true and inherit:false with unspecified fields', () { const TextStyle fromStyle = TextStyle(); const TextStyle toStyle = TextStyle(inherit: false); expect( () => TextStyle.lerp(fromStyle, toStyle, 0.5), throwsFlutterError, ); expect(TextStyle.lerp(fromStyle, fromStyle, 0.5), fromStyle); }); test('Does not throw when lerping between inherit:true and inherit:false but fully specified styles', () { const TextStyle fromStyle = TextStyle(); const TextStyle toStyle = TextStyle( inherit: false, color: Color(0x87654321), backgroundColor: Color(0x12345678), fontSize: 20, letterSpacing: 1, wordSpacing: 1, height: 20, decorationColor: Color(0x11111111), decorationThickness: 5, ); expect(TextStyle.lerp(fromStyle, toStyle, 1), toStyle); }); test('lerpFontVariations', () { // nil cases expect(lerpFontVariations(const <FontVariation>[], const <FontVariation>[], 0.0), const <FontVariation>[]); expect(lerpFontVariations(const <FontVariation>[], const <FontVariation>[], 0.5), const <FontVariation>[]); expect(lerpFontVariations(const <FontVariation>[], const <FontVariation>[], 1.0), const <FontVariation>[]); expect(lerpFontVariations(null, const <FontVariation>[], 0.0), null); expect(lerpFontVariations(const <FontVariation>[], null, 0.0), const <FontVariation>[]); expect(lerpFontVariations(null, null, 0.0), null); expect(lerpFontVariations(null, const <FontVariation>[], 0.5), const <FontVariation>[]); expect(lerpFontVariations(const <FontVariation>[], null, 0.5), null); expect(lerpFontVariations(null, null, 0.5), null); expect(lerpFontVariations(null, const <FontVariation>[], 1.0), const <FontVariation>[]); expect(lerpFontVariations(const <FontVariation>[], null, 1.0), null); expect(lerpFontVariations(null, null, 1.0), null); const FontVariation w100 = FontVariation.weight(100.0); const FontVariation w120 = FontVariation.weight(120.0); const FontVariation w150 = FontVariation.weight(150.0); const FontVariation w200 = FontVariation.weight(200.0); const FontVariation w300 = FontVariation.weight(300.0); const FontVariation w1000 = FontVariation.weight(1000.0); // one axis expect(lerpFontVariations(const <FontVariation>[w100], const <FontVariation>[w200], 0.0), const <FontVariation>[w100]); expect(lerpFontVariations(const <FontVariation>[w100], const <FontVariation>[w200], 0.2), const <FontVariation>[w120]); expect(lerpFontVariations(const <FontVariation>[w100], const <FontVariation>[w200], 0.5), const <FontVariation>[w150]); expect(lerpFontVariations(const <FontVariation>[w100], const <FontVariation>[w200], 2.0), const <FontVariation>[w300]); // weird one axis cases expect(lerpFontVariations(const <FontVariation>[w100, w1000], const <FontVariation>[w300], 0.0), const <FontVariation>[w100, w1000]); expect(lerpFontVariations(const <FontVariation>[w100, w1000], const <FontVariation>[w300], 0.5), const <FontVariation>[w200]); expect(lerpFontVariations(const <FontVariation>[w100, w1000], const <FontVariation>[w300], 1.0), const <FontVariation>[w300]); expect(lerpFontVariations(const <FontVariation>[w100, w1000], const <FontVariation>[], 0.5), const <FontVariation>[]); const FontVariation sn80 = FontVariation.slant(-80.0); const FontVariation sn40 = FontVariation.slant(-40.0); const FontVariation s0 = FontVariation.slant(0.0); const FontVariation sp40 = FontVariation.slant(40.0); const FontVariation sp80 = FontVariation.slant(80.0); // two axis matched order expect(lerpFontVariations(const <FontVariation>[w100, sn80], const <FontVariation>[w300, sp80], 0.5), const <FontVariation>[w200, s0]); // two axis unmatched order expect(lerpFontVariations(const <FontVariation>[sn80, w100], const <FontVariation>[w300, sp80], 0.0), const <FontVariation>[sn80, w100]); expect(lerpFontVariations(const <FontVariation>[sn80, w100], const <FontVariation>[w300, sp80], 0.5), unorderedMatches(const <FontVariation>[s0, w200])); expect(lerpFontVariations(const <FontVariation>[sn80, w100], const <FontVariation>[w300, sp80], 1.0), const <FontVariation>[w300, sp80]); // two axis with duplicates expect(lerpFontVariations(const <FontVariation>[sn80, w100, sp80], const <FontVariation>[w300, sp80], 0.5), unorderedMatches(const <FontVariation>[sp80, w200])); // mixed axis counts expect(lerpFontVariations(const <FontVariation>[sn80, w100], const <FontVariation>[w300], 0.5), const <FontVariation>[w200]); expect(lerpFontVariations(const <FontVariation>[sn80], const <FontVariation>[w300], 0.0), const <FontVariation>[sn80]); expect(lerpFontVariations(const <FontVariation>[sn80], const <FontVariation>[w300], 0.1), const <FontVariation>[sn80]); expect(lerpFontVariations(const <FontVariation>[sn80], const <FontVariation>[w300], 0.9), const <FontVariation>[w300]); expect(lerpFontVariations(const <FontVariation>[sn80], const <FontVariation>[w300], 1.0), const <FontVariation>[w300]); expect(lerpFontVariations(const <FontVariation>[sn40, s0, w100], const <FontVariation>[sp40, w300, sp80], 0.5), anyOf(equals(const <FontVariation>[s0, w200, sp40]), equals(const <FontVariation>[s0, sp40, w200]))); }); }
flutter/packages/flutter/test/painting/text_style_test.dart/0
{ "file_path": "flutter/packages/flutter/test/painting/text_style_test.dart", "repo_id": "flutter", "token_count": 11404 }
683
// 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_test/flutter_test.dart'; import 'rendering_tester.dart'; class MissingPerformLayoutRenderBox extends RenderBox { void triggerExceptionSettingSizeOutsideOfLayout() { size = const Size(200, 200); } // performLayout is left unimplemented to test the error reported if it is // missing. } class FakeMissingSizeRenderBox extends RenderBox { @override void performLayout() { size = constraints.biggest; } @override bool get hasSize => !fakeMissingSize && super.hasSize; bool fakeMissingSize = false; } class MissingSetSizeRenderBox extends RenderBox { @override void performLayout() { } } class BadBaselineRenderBox extends RenderBox { @override void performLayout() { size = constraints.biggest; } @override double? computeDistanceToActualBaseline(TextBaseline baseline) { throw Exception(); } } void main() { TestRenderingFlutterBinding.ensureInitialized(); test('should size to render view', () { final RenderBox root = RenderDecoratedBox( decoration: BoxDecoration( color: const Color(0xFF00FF00), gradient: RadialGradient( center: Alignment.topLeft, radius: 1.8, colors: <Color>[Colors.yellow[500]!, Colors.blue[500]!], ), boxShadow: kElevationToShadow[3], ), ); layout(root); expect(root.size.width, equals(800.0)); expect(root.size.height, equals(600.0)); }); test('performLayout error message', () { late FlutterError result; try { MissingPerformLayoutRenderBox().performLayout(); } on FlutterError catch (e) { result = e; } expect(result, isNotNull); expect( result.toStringDeep(), equalsIgnoringHashCodes( 'FlutterError\n' ' MissingPerformLayoutRenderBox did not implement performLayout().\n' ' RenderBox subclasses need to either override performLayout() to\n' ' set a size and lay out any children, or, set sizedByParent to\n' ' true so that performResize() sizes the render object.\n', ), ); expect( result.diagnostics.singleWhere((DiagnosticsNode node) => node.level == DiagnosticLevel.hint).toString(), 'RenderBox subclasses need to either override performLayout() to set a ' 'size and lay out any children, or, set sizedByParent to true so that ' 'performResize() sizes the render object.', ); }); test('applyPaintTransform error message', () { final RenderBox paddingBox = RenderPadding( padding: const EdgeInsets.all(10.0), ); final RenderBox root = RenderPadding( padding: const EdgeInsets.all(10.0), child: paddingBox, ); layout(root); // Trigger the error by overriding the parentData with data that isn't a // BoxParentData. paddingBox.parentData = ParentData(); late FlutterError result; try { root.applyPaintTransform(paddingBox, Matrix4.identity()); } on FlutterError catch (e) { result = e; } expect(result, isNotNull); expect( result.toStringDeep(), equalsIgnoringHashCodes( 'FlutterError\n' ' RenderPadding does not implement applyPaintTransform.\n' ' The following RenderPadding object: RenderPadding#00000 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE:\n' ' parentData: <none>\n' ' constraints: BoxConstraints(w=800.0, h=600.0)\n' ' size: Size(800.0, 600.0)\n' ' padding: EdgeInsets.all(10.0)\n' ' ...did not use a BoxParentData class for the parentData field of the following child:\n' ' RenderPadding#00000 NEEDS-PAINT:\n' ' parentData: <none> (can use size)\n' ' constraints: BoxConstraints(w=780.0, h=580.0)\n' ' size: Size(780.0, 580.0)\n' ' padding: EdgeInsets.all(10.0)\n' ' The RenderPadding class inherits from RenderBox.\n' ' The default applyPaintTransform implementation provided by\n' ' RenderBox assumes that the children all use BoxParentData objects\n' ' for their parentData field. Since RenderPadding does not in fact\n' ' use that ParentData class for its children, it must provide an\n' ' implementation of applyPaintTransform that supports the specific\n' ' ParentData subclass used by its children (which apparently is\n' ' ParentData).\n', ), ); expect( result.diagnostics.singleWhere((DiagnosticsNode node) => node.level == DiagnosticLevel.hint).toString(), 'The default applyPaintTransform implementation provided by RenderBox ' 'assumes that the children all use BoxParentData objects for their ' 'parentData field. Since RenderPadding does not in fact use that ' 'ParentData class for its children, it must provide an implementation ' 'of applyPaintTransform that supports the specific ParentData subclass ' 'used by its children (which apparently is ParentData).', ); }); test('Set size error messages', () { final RenderBox root = RenderDecoratedBox( decoration: const BoxDecoration( color: Color(0xFF00FF00), ), ); layout(root); final MissingPerformLayoutRenderBox testBox = MissingPerformLayoutRenderBox(); { late FlutterError result; try { testBox.triggerExceptionSettingSizeOutsideOfLayout(); } on FlutterError catch (e) { result = e; } expect(result, isNotNull); expect( result.toStringDeep(), equalsIgnoringHashCodes( 'FlutterError\n' ' RenderBox size setter called incorrectly.\n' ' The size setter was called from outside layout (neither\n' ' performResize() nor performLayout() were being run for this\n' ' object).\n' ' Because this RenderBox has sizedByParent set to false, it must\n' ' set its size in performLayout().\n', ), ); expect(result.diagnostics.where((DiagnosticsNode node) => node.level == DiagnosticLevel.hint), isEmpty); } { late FlutterError result; try { testBox.debugAdoptSize(root.size); } on FlutterError catch (e) { result = e; } expect(result, isNotNull); expect( result.toStringDeep(), equalsIgnoringHashCodes( 'FlutterError\n' ' The size property was assigned a size inappropriately.\n' ' The following render object: MissingPerformLayoutRenderBox#00000 NEEDS-LAYOUT NEEDS-PAINT DETACHED:\n' ' parentData: MISSING\n' ' constraints: MISSING\n' ' size: MISSING\n' ' ...was assigned a size obtained from: RenderDecoratedBox#00000 NEEDS-PAINT:\n' ' parentData: <none>\n' ' constraints: BoxConstraints(w=800.0, h=600.0)\n' ' size: Size(800.0, 600.0)\n' ' decoration: BoxDecoration:\n' ' color: Color(0xff00ff00)\n' ' configuration: ImageConfiguration()\n' ' However, this second render object is not, or is no longer, a\n' ' child of the first, and it is therefore a violation of the\n' ' RenderBox layout protocol to use that size in the layout of the\n' ' first render object.\n' ' If the size was obtained at a time where it was valid to read the\n' ' size (because the second render object above was a child of the\n' ' first at the time), then it should be adopted using\n' ' debugAdoptSize at that time.\n' ' If the size comes from a grandchild or a render object from an\n' ' entirely different part of the render tree, then there is no way\n' ' to be notified when the size changes and therefore attempts to\n' ' read that size are almost certainly a source of bugs. A different\n' ' approach should be used.\n', ), ); expect(result.diagnostics.where((DiagnosticsNode node) => node.level == DiagnosticLevel.hint).length, 2); } }); test('Flex and padding', () { final RenderBox size = RenderConstrainedBox( additionalConstraints: const BoxConstraints().tighten(height: 100.0), ); final RenderBox inner = RenderDecoratedBox( decoration: const BoxDecoration( color: Color(0xFF00FF00), ), child: size, ); final RenderBox padding = RenderPadding( padding: const EdgeInsets.all(50.0), child: inner, ); final RenderBox flex = RenderFlex( children: <RenderBox>[padding], direction: Axis.vertical, crossAxisAlignment: CrossAxisAlignment.stretch, ); final RenderBox outer = RenderDecoratedBox( decoration: const BoxDecoration( color: Color(0xFF0000FF), ), child: flex, ); layout(outer); expect(size.size.width, equals(700.0)); expect(size.size.height, equals(100.0)); expect(inner.size.width, equals(700.0)); expect(inner.size.height, equals(100.0)); expect(padding.size.width, equals(800.0)); expect(padding.size.height, equals(200.0)); expect(flex.size.width, equals(800.0)); expect(flex.size.height, equals(600.0)); expect(outer.size.width, equals(800.0)); expect(outer.size.height, equals(600.0)); }); test('should not have a 0 sized colored Box', () { final RenderBox coloredBox = RenderDecoratedBox( decoration: const BoxDecoration(), ); expect(coloredBox, hasAGoodToStringDeep); expect( coloredBox.toStringDeep(minLevel: DiagnosticLevel.info), equalsIgnoringHashCodes( 'RenderDecoratedBox#00000 NEEDS-LAYOUT NEEDS-PAINT DETACHED\n' ' parentData: MISSING\n' ' constraints: MISSING\n' ' size: MISSING\n' ' decoration: BoxDecoration:\n' ' <no decorations specified>\n' ' configuration: ImageConfiguration()\n', ), ); final RenderBox paddingBox = RenderPadding( padding: const EdgeInsets.all(10.0), child: coloredBox, ); final RenderBox root = RenderDecoratedBox( decoration: const BoxDecoration(), child: paddingBox, ); layout(root); expect(coloredBox.size.width, equals(780.0)); expect(coloredBox.size.height, equals(580.0)); expect(coloredBox, hasAGoodToStringDeep); expect( coloredBox.toStringDeep(minLevel: DiagnosticLevel.info), equalsIgnoringHashCodes( 'RenderDecoratedBox#00000 NEEDS-PAINT\n' ' parentData: offset=Offset(10.0, 10.0) (can use size)\n' ' constraints: BoxConstraints(w=780.0, h=580.0)\n' ' size: Size(780.0, 580.0)\n' ' decoration: BoxDecoration:\n' ' <no decorations specified>\n' ' configuration: ImageConfiguration()\n', ), ); }); test('reparenting should clear position', () { final RenderDecoratedBox coloredBox = RenderDecoratedBox( decoration: const BoxDecoration(), ); final RenderPadding paddedBox = RenderPadding( child: coloredBox, padding: const EdgeInsets.all(10.0), ); layout(paddedBox); final BoxParentData parentData = coloredBox.parentData! as BoxParentData; expect(parentData.offset.dx, isNot(equals(0.0))); paddedBox.child = null; final RenderConstrainedBox constrainedBox = RenderConstrainedBox( child: coloredBox, additionalConstraints: const BoxConstraints(), ); layout(constrainedBox); expect(coloredBox.parentData?.runtimeType, ParentData); }); test('UnconstrainedBox expands to fit children', () { final RenderConstraintsTransformBox unconstrained = RenderConstraintsTransformBox( constraintsTransform: ConstraintsTransformBox.widthUnconstrained, textDirection: TextDirection.ltr, child: RenderConstrainedBox( additionalConstraints: const BoxConstraints.tightFor(width: 200.0, height: 200.0), ), alignment: Alignment.center, ); layout( unconstrained, constraints: const BoxConstraints( minWidth: 200.0, maxWidth: 200.0, minHeight: 200.0, maxHeight: 200.0, ), ); // Check that we can update the constrained axis to null. unconstrained.constraintsTransform = ConstraintsTransformBox.unconstrained; TestRenderingFlutterBinding.instance.reassembleApplication(); expect(unconstrained.size.width, equals(200.0), reason: 'unconstrained width'); expect(unconstrained.size.height, equals(200.0), reason: 'unconstrained height'); }); test('UnconstrainedBox handles vertical overflow', () { final RenderConstraintsTransformBox unconstrained = RenderConstraintsTransformBox( constraintsTransform: ConstraintsTransformBox.unconstrained, textDirection: TextDirection.ltr, child: RenderConstrainedBox( additionalConstraints: const BoxConstraints.tightFor(height: 200.0), ), alignment: Alignment.center, ); const BoxConstraints viewport = BoxConstraints(maxHeight: 100.0, maxWidth: 100.0); layout(unconstrained, constraints: viewport); expect(unconstrained.getMinIntrinsicHeight(100.0), equals(200.0)); expect(unconstrained.getMaxIntrinsicHeight(100.0), equals(200.0)); expect(unconstrained.getMinIntrinsicWidth(100.0), equals(0.0)); expect(unconstrained.getMaxIntrinsicWidth(100.0), equals(0.0)); }); test('UnconstrainedBox handles horizontal overflow', () { final RenderConstraintsTransformBox unconstrained = RenderConstraintsTransformBox( constraintsTransform: ConstraintsTransformBox.unconstrained, textDirection: TextDirection.ltr, child: RenderConstrainedBox( additionalConstraints: const BoxConstraints.tightFor(width: 200.0), ), alignment: Alignment.center, ); const BoxConstraints viewport = BoxConstraints(maxHeight: 100.0, maxWidth: 100.0); layout(unconstrained, constraints: viewport); expect(unconstrained.getMinIntrinsicHeight(100.0), equals(0.0)); expect(unconstrained.getMaxIntrinsicHeight(100.0), equals(0.0)); expect(unconstrained.getMinIntrinsicWidth(100.0), equals(200.0)); expect(unconstrained.getMaxIntrinsicWidth(100.0), equals(200.0)); }); group('ConstraintsTransformBox', () { FlutterErrorDetails? firstErrorDetails; void exhaustErrors() { FlutterErrorDetails? next; do { next = TestRenderingFlutterBinding.instance.takeFlutterErrorDetails(); firstErrorDetails ??= next; } while (next != null); } tearDown(() { firstErrorDetails = null; RenderObject.debugCheckingIntrinsics = false; }); test('throws if the resulting constraints are not normalized', () { final RenderConstrainedBox child = RenderConstrainedBox(additionalConstraints: const BoxConstraints.tightFor(height: 0)); final RenderConstraintsTransformBox box = RenderConstraintsTransformBox( alignment: Alignment.center, textDirection: TextDirection.ltr, constraintsTransform: (BoxConstraints constraints) => const BoxConstraints(maxHeight: -1, minHeight: 200), child: child, ); layout(box, constraints: const BoxConstraints(), onErrors: exhaustErrors); expect(firstErrorDetails?.toString(), contains('is not normalized')); }); test('overflow is reported when insufficient size is given and clipBehavior is Clip.none', () { bool hadErrors = false; void expectOverflowedErrors() { absorbOverflowedErrors(); hadErrors = true; } final TestClipPaintingContext context = TestClipPaintingContext(); for (final Clip? clip in <Clip?>[null, ...Clip.values]) { final RenderConstraintsTransformBox box; switch (clip) { case Clip.none: case Clip.hardEdge: case Clip.antiAlias: case Clip.antiAliasWithSaveLayer: box = RenderConstraintsTransformBox( alignment: Alignment.center, textDirection: TextDirection.ltr, constraintsTransform: (BoxConstraints constraints) => constraints.copyWith(maxWidth: double.infinity), clipBehavior: clip!, child: RenderConstrainedBox( additionalConstraints: const BoxConstraints.tightFor( width: double.maxFinite, height: double.maxFinite, ), ), ); case null: box = RenderConstraintsTransformBox( alignment: Alignment.center, textDirection: TextDirection.ltr, constraintsTransform: (BoxConstraints constraints) => constraints.copyWith(maxWidth: double.infinity), child: RenderConstrainedBox( additionalConstraints: const BoxConstraints.tightFor( width: double.maxFinite, height: double.maxFinite, ), ), ); } layout(box, constraints: const BoxConstraints(), phase: EnginePhase.composite, onErrors: expectOverflowedErrors); context.paintChild(box, Offset.zero); // By default, clipBehavior should be Clip.none expect(context.clipBehavior, equals(clip ?? Clip.none)); switch (clip) { case null: case Clip.none: expect(hadErrors, isTrue, reason: 'Should have had overflow errors for $clip'); case Clip.hardEdge: case Clip.antiAlias: case Clip.antiAliasWithSaveLayer: expect(hadErrors, isFalse, reason: 'Should not have had overflow errors for $clip'); } hadErrors = false; } }); test('handles flow layout', () { final RenderParagraph child = RenderParagraph( TextSpan(text: 'a' * 100), textDirection: TextDirection.ltr, ); final RenderConstraintsTransformBox box = RenderConstraintsTransformBox( alignment: Alignment.center, textDirection: TextDirection.ltr, constraintsTransform: (BoxConstraints constraints) => constraints.copyWith(maxWidth: double.infinity), child: child, ); // With a width of 30, the RenderParagraph would have wrapped, but the // RenderConstraintsTransformBox allows the paragraph to expand regardless // of the width constraint: // unconstrainedHeight * numberOfLines = constrainedHeight. final double constrainedHeight = child.getMinIntrinsicHeight(30); final double unconstrainedHeight = box.getMinIntrinsicHeight(30); // At least 2 lines. expect(constrainedHeight, greaterThanOrEqualTo(2 * unconstrainedHeight)); }); }); test ('getMinIntrinsicWidth error handling', () { final RenderConstraintsTransformBox unconstrained = RenderConstraintsTransformBox( constraintsTransform: ConstraintsTransformBox.unconstrained, textDirection: TextDirection.ltr, child: RenderConstrainedBox( additionalConstraints: const BoxConstraints.tightFor(width: 200.0), ), alignment: Alignment.center, ); const BoxConstraints viewport = BoxConstraints(maxHeight: 100.0, maxWidth: 100.0); layout(unconstrained, constraints: viewport); { late FlutterError result; try { unconstrained.getMinIntrinsicWidth(-1); } on FlutterError catch (e) { result = e; } expect(result, isNotNull); expect( result.toStringDeep(), equalsIgnoringHashCodes( 'FlutterError\n' ' The height argument to getMinIntrinsicWidth was negative.\n' ' The argument to getMinIntrinsicWidth must not be negative or\n' ' null.\n' ' If you perform computations on another height before passing it\n' ' to getMinIntrinsicWidth, consider using math.max() or\n' ' double.clamp() to force the value into the valid range.\n', ), ); expect( result.diagnostics.singleWhere((DiagnosticsNode node) => node.level == DiagnosticLevel.hint).toString(), 'If you perform computations on another height before passing it to ' 'getMinIntrinsicWidth, consider using math.max() or double.clamp() ' 'to force the value into the valid range.', ); } { late FlutterError result; try { unconstrained.getMinIntrinsicHeight(-1); } on FlutterError catch (e) { result = e; } expect(result, isNotNull); expect( result.toStringDeep(), equalsIgnoringHashCodes( 'FlutterError\n' ' The width argument to getMinIntrinsicHeight was negative.\n' ' The argument to getMinIntrinsicHeight must not be negative or\n' ' null.\n' ' If you perform computations on another width before passing it to\n' ' getMinIntrinsicHeight, consider using math.max() or\n' ' double.clamp() to force the value into the valid range.\n', ), ); expect( result.diagnostics.singleWhere((DiagnosticsNode node) => node.level == DiagnosticLevel.hint).toString(), 'If you perform computations on another width before passing it to ' 'getMinIntrinsicHeight, consider using math.max() or double.clamp() ' 'to force the value into the valid range.', ); } { late FlutterError result; try { unconstrained.getMaxIntrinsicWidth(-1); } on FlutterError catch (e) { result = e; } expect(result, isNotNull); expect( result.toStringDeep(), equalsIgnoringHashCodes( 'FlutterError\n' ' The height argument to getMaxIntrinsicWidth was negative.\n' ' The argument to getMaxIntrinsicWidth must not be negative or\n' ' null.\n' ' If you perform computations on another height before passing it\n' ' to getMaxIntrinsicWidth, consider using math.max() or\n' ' double.clamp() to force the value into the valid range.\n', ), ); expect( result.diagnostics.singleWhere((DiagnosticsNode node) => node.level == DiagnosticLevel.hint).toString(), 'If you perform computations on another height before passing it to ' 'getMaxIntrinsicWidth, consider using math.max() or double.clamp() ' 'to force the value into the valid range.', ); } { late FlutterError result; try { unconstrained.getMaxIntrinsicHeight(-1); } on FlutterError catch (e) { result = e; } expect(result, isNotNull); expect( result.toStringDeep(), equalsIgnoringHashCodes( 'FlutterError\n' ' The width argument to getMaxIntrinsicHeight was negative.\n' ' The argument to getMaxIntrinsicHeight must not be negative or\n' ' null.\n' ' If you perform computations on another width before passing it to\n' ' getMaxIntrinsicHeight, consider using math.max() or\n' ' double.clamp() to force the value into the valid range.\n', ), ); expect( result.diagnostics.singleWhere((DiagnosticsNode node) => node.level == DiagnosticLevel.hint).toString(), 'If you perform computations on another width before passing it to ' 'getMaxIntrinsicHeight, consider using math.max() or double.clamp() ' 'to force the value into the valid range.', ); } }); test('UnconstrainedBox.toStringDeep returns useful information', () { final RenderConstraintsTransformBox unconstrained = RenderConstraintsTransformBox( constraintsTransform: ConstraintsTransformBox.unconstrained, textDirection: TextDirection.ltr, alignment: Alignment.center, ); expect(unconstrained.alignment, Alignment.center); expect(unconstrained.textDirection, TextDirection.ltr); expect(unconstrained, hasAGoodToStringDeep); expect( unconstrained.toStringDeep(minLevel: DiagnosticLevel.info), equalsIgnoringHashCodes( 'RenderConstraintsTransformBox#00000 NEEDS-LAYOUT NEEDS-PAINT DETACHED\n' ' parentData: MISSING\n' ' constraints: MISSING\n' ' size: MISSING\n' ' alignment: Alignment.center\n' ' textDirection: ltr\n', ), ); }); test('UnconstrainedBox honors constrainedAxis=Axis.horizontal', () { final RenderConstrainedBox flexible = RenderConstrainedBox(additionalConstraints: const BoxConstraints.expand(height: 200.0)); final RenderConstraintsTransformBox unconstrained = RenderConstraintsTransformBox( constraintsTransform: ConstraintsTransformBox.heightUnconstrained, textDirection: TextDirection.ltr, child: RenderFlex( textDirection: TextDirection.ltr, children: <RenderBox>[flexible], ), alignment: Alignment.center, ); final FlexParentData flexParentData = flexible.parentData! as FlexParentData; flexParentData.flex = 1; flexParentData.fit = FlexFit.tight; const BoxConstraints viewport = BoxConstraints(maxWidth: 100.0); layout(unconstrained, constraints: viewport); expect(unconstrained.size.width, equals(100.0), reason: 'constrained width'); expect(unconstrained.size.height, equals(200.0), reason: 'unconstrained height'); }); test('UnconstrainedBox honors constrainedAxis=Axis.vertical', () { final RenderConstrainedBox flexible = RenderConstrainedBox(additionalConstraints: const BoxConstraints.expand(width: 200.0)); final RenderConstraintsTransformBox unconstrained = RenderConstraintsTransformBox( constraintsTransform: ConstraintsTransformBox.widthUnconstrained, textDirection: TextDirection.ltr, child: RenderFlex( direction: Axis.vertical, textDirection: TextDirection.ltr, children: <RenderBox>[flexible], ), alignment: Alignment.center, ); final FlexParentData flexParentData = flexible.parentData! as FlexParentData; flexParentData.flex = 1; flexParentData.fit = FlexFit.tight; const BoxConstraints viewport = BoxConstraints(maxHeight: 100.0); layout(unconstrained, constraints: viewport); expect(unconstrained.size.width, equals(200.0), reason: 'unconstrained width'); expect(unconstrained.size.height, equals(100.0), reason: 'constrained height'); }); test('clipBehavior is respected', () { const BoxConstraints viewport = BoxConstraints(maxHeight: 100.0, maxWidth: 100.0); final TestClipPaintingContext context = TestClipPaintingContext(); bool hadErrors = false; void expectOverflowedErrors() { absorbOverflowedErrors(); hadErrors = true; } for (final Clip? clip in <Clip?>[null, ...Clip.values]) { final RenderConstraintsTransformBox box; switch (clip) { case Clip.none: case Clip.hardEdge: case Clip.antiAlias: case Clip.antiAliasWithSaveLayer: box = RenderConstraintsTransformBox( constraintsTransform: ConstraintsTransformBox.unconstrained, alignment: Alignment.center, textDirection: TextDirection.ltr, child: box200x200, clipBehavior: clip!, ); case null: box = RenderConstraintsTransformBox( constraintsTransform: ConstraintsTransformBox.unconstrained, alignment: Alignment.center, textDirection: TextDirection.ltr, child: box200x200, ); } layout(box, constraints: viewport, phase: EnginePhase.composite, onErrors: expectOverflowedErrors); switch (clip) { case null: case Clip.none: expect(hadErrors, isTrue, reason: 'Should have had overflow errors for $clip'); case Clip.hardEdge: case Clip.antiAlias: case Clip.antiAliasWithSaveLayer: expect(hadErrors, isFalse, reason: 'Should not have had overflow errors for $clip'); } hadErrors = false; context.paintChild(box, Offset.zero); // By default, clipBehavior should be Clip.none expect(context.clipBehavior, equals(clip ?? Clip.none), reason: 'for $clip'); } }); group('hit testing', () { test('BoxHitTestResult wrapping HitTestResult', () { final HitTestEntry entry1 = HitTestEntry(_DummyHitTestTarget()); final HitTestEntry entry2 = HitTestEntry(_DummyHitTestTarget()); final HitTestEntry entry3 = HitTestEntry(_DummyHitTestTarget()); final Matrix4 transform = Matrix4.translationValues(40.0, 150.0, 0.0); final HitTestResult wrapped = MyHitTestResult() ..publicPushTransform(transform); wrapped.add(entry1); expect(wrapped.path, equals(<HitTestEntry>[entry1])); expect(entry1.transform, transform); final BoxHitTestResult wrapping = BoxHitTestResult.wrap(wrapped); expect(wrapping.path, equals(<HitTestEntry>[entry1])); expect(wrapping.path, same(wrapped.path)); wrapping.add(entry2); expect(wrapping.path, equals(<HitTestEntry>[entry1, entry2])); expect(wrapped.path, equals(<HitTestEntry>[entry1, entry2])); expect(entry2.transform, transform); wrapped.add(entry3); expect(wrapping.path, equals(<HitTestEntry>[entry1, entry2, entry3])); expect(wrapped.path, equals(<HitTestEntry>[entry1, entry2, entry3])); expect(entry3.transform, transform); }); test('addWithPaintTransform', () { final BoxHitTestResult result = BoxHitTestResult(); final List<Offset> positions = <Offset>[]; bool isHit = result.addWithPaintTransform( transform: null, position: Offset.zero, hitTest: (BoxHitTestResult result, Offset position) { expect(result, isNotNull); positions.add(position); return true; }, ); expect(isHit, isTrue); expect(positions.single, Offset.zero); positions.clear(); isHit = result.addWithPaintTransform( transform: Matrix4.translationValues(20, 30, 0), position: Offset.zero, hitTest: (BoxHitTestResult result, Offset position) { expect(result, isNotNull); positions.add(position); return true; }, ); expect(isHit, isTrue); expect(positions.single, const Offset(-20.0, -30.0)); positions.clear(); const Offset position = Offset(3, 4); isHit = result.addWithPaintTransform( transform: null, position: position, hitTest: (BoxHitTestResult result, Offset position) { expect(result, isNotNull); positions.add(position); return false; }, ); expect(isHit, isFalse); expect(positions.single, position); positions.clear(); isHit = result.addWithPaintTransform( transform: Matrix4.identity(), position: position, hitTest: (BoxHitTestResult result, Offset position) { expect(result, isNotNull); positions.add(position); return true; }, ); expect(isHit, isTrue); expect(positions.single, position); positions.clear(); isHit = result.addWithPaintTransform( transform: Matrix4.translationValues(20, 30, 0), position: position, hitTest: (BoxHitTestResult result, Offset position) { expect(result, isNotNull); positions.add(position); return true; }, ); expect(isHit, isTrue); expect(positions.single, position - const Offset(20, 30)); positions.clear(); isHit = result.addWithPaintTransform( transform: MatrixUtils.forceToPoint(position), // cannot be inverted position: position, hitTest: (BoxHitTestResult result, Offset position) { expect(result, isNotNull); positions.add(position); return true; }, ); expect(isHit, isFalse); expect(positions, isEmpty); positions.clear(); }); test('addWithPaintOffset', () { final BoxHitTestResult result = BoxHitTestResult(); final List<Offset> positions = <Offset>[]; bool isHit = result.addWithPaintOffset( offset: null, position: Offset.zero, hitTest: (BoxHitTestResult result, Offset position) { expect(result, isNotNull); positions.add(position); return true; }, ); expect(isHit, isTrue); expect(positions.single, Offset.zero); positions.clear(); isHit = result.addWithPaintOffset( offset: const Offset(55, 32), position: Offset.zero, hitTest: (BoxHitTestResult result, Offset position) { expect(result, isNotNull); positions.add(position); return true; }, ); expect(isHit, isTrue); expect(positions.single, const Offset(-55.0, -32.0)); positions.clear(); const Offset position = Offset(3, 4); isHit = result.addWithPaintOffset( offset: null, position: position, hitTest: (BoxHitTestResult result, Offset position) { expect(result, isNotNull); positions.add(position); return false; }, ); expect(isHit, isFalse); expect(positions.single, position); positions.clear(); isHit = result.addWithPaintOffset( offset: Offset.zero, position: position, hitTest: (BoxHitTestResult result, Offset position) { expect(result, isNotNull); positions.add(position); return true; }, ); expect(isHit, isTrue); expect(positions.single, position); positions.clear(); isHit = result.addWithPaintOffset( offset: const Offset(20, 30), position: position, hitTest: (BoxHitTestResult result, Offset position) { expect(result, isNotNull); positions.add(position); return true; }, ); expect(isHit, isTrue); expect(positions.single, position - const Offset(20, 30)); positions.clear(); }); test('addWithRawTransform', () { final BoxHitTestResult result = BoxHitTestResult(); final List<Offset> positions = <Offset>[]; bool isHit = result.addWithRawTransform( transform: null, position: Offset.zero, hitTest: (BoxHitTestResult result, Offset position) { expect(result, isNotNull); positions.add(position); return true; }, ); expect(isHit, isTrue); expect(positions.single, Offset.zero); positions.clear(); isHit = result.addWithRawTransform( transform: Matrix4.translationValues(20, 30, 0), position: Offset.zero, hitTest: (BoxHitTestResult result, Offset position) { expect(result, isNotNull); positions.add(position); return true; }, ); expect(isHit, isTrue); expect(positions.single, const Offset(20.0, 30.0)); positions.clear(); const Offset position = Offset(3, 4); isHit = result.addWithRawTransform( transform: null, position: position, hitTest: (BoxHitTestResult result, Offset position) { expect(result, isNotNull); positions.add(position); return false; }, ); expect(isHit, isFalse); expect(positions.single, position); positions.clear(); isHit = result.addWithRawTransform( transform: Matrix4.identity(), position: position, hitTest: (BoxHitTestResult result, Offset position) { expect(result, isNotNull); positions.add(position); return true; }, ); expect(isHit, isTrue); expect(positions.single, position); positions.clear(); isHit = result.addWithRawTransform( transform: Matrix4.translationValues(20, 30, 0), position: position, hitTest: (BoxHitTestResult result, Offset position) { expect(result, isNotNull); positions.add(position); return true; }, ); expect(isHit, isTrue); expect(positions.single, position + const Offset(20, 30)); positions.clear(); }); test('addWithOutOfBandPosition', () { final BoxHitTestResult result = BoxHitTestResult(); bool ran = false; bool isHit = result.addWithOutOfBandPosition( paintOffset: const Offset(20, 30), hitTest: (BoxHitTestResult result) { expect(result, isNotNull); ran = true; return true; }, ); expect(isHit, isTrue); expect(ran, isTrue); ran = false; isHit = result.addWithOutOfBandPosition( paintTransform: Matrix4.translationValues(20, 30, 0), hitTest: (BoxHitTestResult result) { expect(result, isNotNull); ran = true; return true; }, ); expect(isHit, isTrue); expect(ran, isTrue); ran = false; isHit = result.addWithOutOfBandPosition( rawTransform: Matrix4.translationValues(20, 30, 0), hitTest: (BoxHitTestResult result) { expect(result, isNotNull); ran = true; return true; }, ); expect(isHit, isTrue); expect(ran, isTrue); ran = false; isHit = result.addWithOutOfBandPosition( rawTransform: MatrixUtils.forceToPoint(Offset.zero), // cannot be inverted hitTest: (BoxHitTestResult result) { expect(result, isNotNull); ran = true; return true; }, ); expect(isHit, isTrue); expect(ran, isTrue); isHit = false; ran = false; expect( () { isHit = result.addWithOutOfBandPosition( paintTransform: MatrixUtils.forceToPoint(Offset.zero), // cannot be inverted hitTest: (BoxHitTestResult result) { fail('non-invertible transform should be caught'); }, ); }, throwsA(isAssertionError.having( (AssertionError error) => error.message, 'message', 'paintTransform must be invertible.', )), ); expect(isHit, isFalse); expect( () { isHit = result.addWithOutOfBandPosition( hitTest: (BoxHitTestResult result) { fail('addWithOutOfBandPosition should need some transformation of some sort'); }, ); }, throwsA(isAssertionError.having( (AssertionError error) => error.message, 'message', 'Exactly one transform or offset argument must be provided.', )), ); expect(isHit, isFalse); }); test('error message', () { { final RenderBox renderObject = RenderConstrainedBox( additionalConstraints: const BoxConstraints().tighten(height: 100.0), ); late FlutterError result; try { final BoxHitTestResult result = BoxHitTestResult(); renderObject.hitTest(result, position: Offset.zero); } on FlutterError catch (e) { result = e; } expect(result, isNotNull); expect( result.toStringDeep(), equalsIgnoringHashCodes( 'FlutterError\n' ' Cannot hit test a render box that has never been laid out.\n' ' The hitTest() method was called on this RenderBox: RenderConstrainedBox#00000 NEEDS-LAYOUT NEEDS-PAINT DETACHED:\n' ' parentData: MISSING\n' ' constraints: MISSING\n' ' size: MISSING\n' ' additionalConstraints: BoxConstraints(0.0<=w<=Infinity, h=100.0)\n' " Unfortunately, this object's geometry is not known at this time,\n" ' probably because it has never been laid out. This means it cannot\n' ' be accurately hit-tested.\n' ' If you are trying to perform a hit test during the layout phase\n' ' itself, make sure you only hit test nodes that have completed\n' " layout (e.g. the node's children, after their layout() method has\n" ' been called).\n', ), ); expect( result.diagnostics.singleWhere((DiagnosticsNode node) => node.level == DiagnosticLevel.hint).toString(), 'If you are trying to perform a hit test during the layout phase ' 'itself, make sure you only hit test nodes that have completed ' "layout (e.g. the node's children, after their layout() method has " 'been called).', ); } { late FlutterError result; final FakeMissingSizeRenderBox renderObject = FakeMissingSizeRenderBox(); layout(renderObject); renderObject.fakeMissingSize = true; try { final BoxHitTestResult result = BoxHitTestResult(); renderObject.hitTest(result, position: Offset.zero); } on FlutterError catch (e) { result = e; } expect(result, isNotNull); expect( result.toStringDeep(), equalsIgnoringHashCodes( 'FlutterError\n' ' Cannot hit test a render box with no size.\n' ' The hitTest() method was called on this RenderBox: FakeMissingSizeRenderBox#00000 NEEDS-PAINT:\n' ' parentData: <none>\n' ' constraints: BoxConstraints(w=800.0, h=600.0)\n' ' size: Size(800.0, 600.0)\n' ' Although this node is not marked as needing layout, its size is\n' ' not set.\n' ' A RenderBox object must have an explicit size before it can be\n' ' hit-tested. Make sure that the RenderBox in question sets its\n' ' size during layout.\n', ), ); expect( result.diagnostics.singleWhere((DiagnosticsNode node) => node.level == DiagnosticLevel.hint).toString(), 'A RenderBox object must have an explicit size before it can be ' 'hit-tested. Make sure that the RenderBox in question sets its ' 'size during layout.', ); } }); test('localToGlobal with ancestor', () { final RenderConstrainedBox innerConstrained = RenderConstrainedBox(additionalConstraints: const BoxConstraints.tightFor(width: 50, height: 50)); final RenderPositionedBox innerCenter = RenderPositionedBox(child: innerConstrained); final RenderConstrainedBox outerConstrained = RenderConstrainedBox(additionalConstraints: const BoxConstraints.tightFor(width: 100, height: 100), child: innerCenter); final RenderPositionedBox outerCentered = RenderPositionedBox(child: outerConstrained); layout(outerCentered); expect(innerConstrained.localToGlobal(Offset.zero, ancestor: outerConstrained).dy, 25.0); }); }); test('Error message when size has not been set in RenderBox performLayout should be well versed', () { late FlutterErrorDetails errorDetails; final FlutterExceptionHandler? oldHandler = FlutterError.onError; FlutterError.onError = (FlutterErrorDetails details) { errorDetails = details; }; try { MissingSetSizeRenderBox().layout(const BoxConstraints()); } finally { FlutterError.onError = oldHandler; } expect(errorDetails, isNotNull); // Check the ErrorDetails without the stack trace. final List<String> lines = errorDetails.toString().split('\n'); expect( lines.take(5).join('\n'), equalsIgnoringHashCodes( '══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞══════════════════════\n' 'The following assertion was thrown during performLayout():\n' 'RenderBox did not set its size during layout.\n' 'Because this RenderBox has sizedByParent set to false, it must\n' 'set its size in performLayout().', ), ); }); test('debugDoingBaseline flag is cleared after exception', () { final BadBaselineRenderBox badChild = BadBaselineRenderBox(); final RenderBox badRoot = RenderBaseline( child: badChild, baseline: 0.0, baselineType: TextBaseline.alphabetic, ); final List<dynamic> exceptions = <dynamic>[]; layout(badRoot, onErrors: () { exceptions.addAll(TestRenderingFlutterBinding.instance.takeAllFlutterExceptions()); }); expect(exceptions, isNotEmpty); final RenderBox goodRoot = RenderBaseline( child: RenderDecoratedBox(decoration: const BoxDecoration()), baseline: 0.0, baselineType: TextBaseline.alphabetic, ); layout(goodRoot, onErrors: () { assert(false); }); }); group('BaselineOffset', () { test('minOf', () { expect(BaselineOffset.noBaseline.minOf(BaselineOffset.noBaseline), BaselineOffset.noBaseline); expect(BaselineOffset.noBaseline.minOf(const BaselineOffset(1)), const BaselineOffset(1)); expect(const BaselineOffset(1).minOf(BaselineOffset.noBaseline), const BaselineOffset(1)); expect(const BaselineOffset(2).minOf(const BaselineOffset(1)), const BaselineOffset(1)); expect(const BaselineOffset(1).minOf(const BaselineOffset(2)), const BaselineOffset(1)); }); test('+', () { expect(BaselineOffset.noBaseline + 2, BaselineOffset.noBaseline); expect(const BaselineOffset(1) + 2, const BaselineOffset(3)); }); }); } class _DummyHitTestTarget implements HitTestTarget { @override void handleEvent(PointerEvent event, HitTestEntry entry) { // Nothing to do. } } class MyHitTestResult extends HitTestResult { void publicPushTransform(Matrix4 transform) => pushTransform(transform); }
flutter/packages/flutter/test/rendering/box_test.dart/0
{ "file_path": "flutter/packages/flutter/test/rendering/box_test.dart", "repo_id": "flutter", "token_count": 18846 }
684
// 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/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:vector_math/vector_math_64.dart'; void main() { test('ContainerLayer.findAllAnnotations returns all results from its children', () { final Layer root = _Layers( ContainerLayer(), children: <Object>[ _TestAnnotatedLayer(1, opaque: false), _TestAnnotatedLayer(2, opaque: false), _TestAnnotatedLayer(3, opaque: false), ], ).build(); expect( root.findAllAnnotations<int>(Offset.zero).entries.toList(), _equalToAnnotationResult<int>(<AnnotationEntry<int>>[ const AnnotationEntry<int>(annotation: 3, localPosition: Offset.zero), const AnnotationEntry<int>(annotation: 2, localPosition: Offset.zero), const AnnotationEntry<int>(annotation: 1, localPosition: Offset.zero), ]), ); }); test('ContainerLayer.find returns the first result from its children', () { final Layer root = _Layers( ContainerLayer(), children: <Object>[ _TestAnnotatedLayer(1, opaque: false), _TestAnnotatedLayer(2, opaque: false), _TestAnnotatedLayer(3, opaque: false), ], ).build(); final int result = root.find<int>(Offset.zero)!; expect(result, 3); }); test('ContainerLayer.findAllAnnotations returns empty result when finding nothing', () { final Layer root = _Layers( ContainerLayer(), children: <Object>[ _TestAnnotatedLayer(1, opaque: false), _TestAnnotatedLayer(2, opaque: false), _TestAnnotatedLayer(3, opaque: false), ], ).build(); expect(root.findAllAnnotations<double>(Offset.zero).entries.isEmpty, isTrue); }); test('ContainerLayer.find returns null when finding nothing', () { final Layer root = _Layers( ContainerLayer(), children: <Object>[ _TestAnnotatedLayer(1, opaque: false), _TestAnnotatedLayer(2, opaque: false), _TestAnnotatedLayer(3, opaque: false), ], ).build(); expect(root.find<double>(Offset.zero), isNull); }); test('ContainerLayer.findAllAnnotations stops at the first opaque child', () { final Layer root = _Layers( ContainerLayer(), children: <Object>[ _TestAnnotatedLayer(1, opaque: false), _TestAnnotatedLayer(2, opaque: true), _TestAnnotatedLayer(3, opaque: false), ], ).build(); expect( root.findAllAnnotations<int>(Offset.zero).entries.toList(), _equalToAnnotationResult<int>(<AnnotationEntry<int>>[ const AnnotationEntry<int>(annotation: 3, localPosition: Offset.zero), const AnnotationEntry<int>(annotation: 2, localPosition: Offset.zero), ]), ); }); test("ContainerLayer.findAllAnnotations returns children's opacity (true)", () { final Layer root = _withBackgroundAnnotation( 1000, _Layers( ContainerLayer(), children: <Object>[ _TestAnnotatedLayer(2, opaque: true), ], ).build(), ); expect( root.findAllAnnotations<int>(Offset.zero).entries.toList(), _equalToAnnotationResult<int>(<AnnotationEntry<int>>[ const AnnotationEntry<int>(annotation: 2, localPosition: Offset.zero), ]), ); }); test("ContainerLayer.findAllAnnotations returns children's opacity (false)", () { final Layer root = _withBackgroundAnnotation( 1000, _Layers( ContainerLayer(), children: <Object>[ _TestAnnotatedLayer(2, opaque: false), ], ).build(), ); expect( root.findAllAnnotations<int>(Offset.zero).entries.toList(), _equalToAnnotationResult<int>(<AnnotationEntry<int>>[ const AnnotationEntry<int>(annotation: 2, localPosition: Offset.zero), const AnnotationEntry<int>(annotation: 1000, localPosition: Offset.zero), ]), ); }); test('ContainerLayer.findAllAnnotations returns false as opacity when finding nothing', () { final Layer root = _withBackgroundAnnotation( 1000, _Layers( ContainerLayer(), children: <Object>[ _TestAnnotatedLayer(2, opaque: false, size: Size.zero), ], ).build(), ); expect( root.findAllAnnotations<int>(Offset.zero).entries.toList(), _equalToAnnotationResult<int>(<AnnotationEntry<int>>[ const AnnotationEntry<int>(annotation: 1000, localPosition: Offset.zero), ]), ); }); test('OffsetLayer.findAllAnnotations respects offset', () { const Offset insidePosition = Offset(-5, 5); const Offset outsidePosition = Offset(5, 5); final Layer root = _withBackgroundAnnotation( 1000, _Layers( OffsetLayer(offset: const Offset(-10, 0)), children: <Object>[ _TestAnnotatedLayer(1, opaque: true, size: const Size(10, 10)), ], ).build(), ); expect( root.findAllAnnotations<int>(insidePosition).entries.toList(), _equalToAnnotationResult<int>(<AnnotationEntry<int>>[ const AnnotationEntry<int>(annotation: 1, localPosition: Offset(5, 5)), ]), ); expect( root.findAllAnnotations<int>(outsidePosition).entries.toList(), _equalToAnnotationResult<int>(<AnnotationEntry<int>>[ const AnnotationEntry<int>(annotation: 1000, localPosition: Offset(5, 5)), ]), ); }); test('ClipRectLayer.findAllAnnotations respects clipRect', () { const Offset insidePosition = Offset(11, 11); const Offset outsidePosition = Offset(19, 19); final Layer root = _withBackgroundAnnotation( 1000, _Layers( ClipRectLayer(clipRect: const Offset(10, 10) & const Size(5, 5)), children: <Object>[ _TestAnnotatedLayer( 1, opaque: true, size: const Size(10, 10), offset: const Offset(10, 10), ), ], ).build(), ); expect( root.findAllAnnotations<int>(insidePosition).entries.toList(), _equalToAnnotationResult<int>(<AnnotationEntry<int>>[ const AnnotationEntry<int>(annotation: 1, localPosition: insidePosition), ]), ); expect( root.findAllAnnotations<int>(outsidePosition).entries.toList(), _equalToAnnotationResult<int>(<AnnotationEntry<int>>[ const AnnotationEntry<int>(annotation: 1000, localPosition: outsidePosition), ]), ); }); test('ClipRRectLayer.findAllAnnotations respects clipRRect', () { // For a curve of radius 4 centered at (4, 4), // location (1, 1) is outside, while (2, 2) is inside. // Here we shift this RRect by (10, 10). final RRect rrect = RRect.fromRectAndRadius( const Offset(10, 10) & const Size(10, 10), const Radius.circular(4), ); const Offset insidePosition = Offset(12, 12); const Offset outsidePosition = Offset(11, 11); final Layer root = _withBackgroundAnnotation( 1000, _Layers( ClipRRectLayer(clipRRect: rrect), children: <Object>[ _TestAnnotatedLayer( 1, opaque: true, size: const Size(10, 10), offset: const Offset(10, 10), ), ], ).build(), ); expect( root.findAllAnnotations<int>(insidePosition).entries.toList(), _equalToAnnotationResult<int>(<AnnotationEntry<int>>[ const AnnotationEntry<int>(annotation: 1, localPosition: insidePosition), ]), ); expect( root.findAllAnnotations<int>(outsidePosition).entries.toList(), _equalToAnnotationResult<int>(<AnnotationEntry<int>>[ const AnnotationEntry<int>(annotation: 1000, localPosition: outsidePosition), ]), ); }); test('ClipPathLayer.findAllAnnotations respects clipPath', () { // For this triangle, location (1, 1) is inside, while (2, 2) is outside. // 2 // ————— // | / // | / // 2 |/ final Path originalPath = Path(); originalPath.lineTo(2, 0); originalPath.lineTo(0, 2); originalPath.close(); // Shift this clip path by (10, 10). final Path path = originalPath.shift(const Offset(10, 10)); const Offset insidePosition = Offset(11, 11); const Offset outsidePosition = Offset(12, 12); final Layer root = _withBackgroundAnnotation( 1000, _Layers( ClipPathLayer(clipPath: path), children: <Object>[ _TestAnnotatedLayer( 1, opaque: true, size: const Size(10, 10), offset: const Offset(10, 10), ), ], ).build(), ); expect( root.findAllAnnotations<int>(insidePosition).entries.toList(), _equalToAnnotationResult<int>(<AnnotationEntry<int>>[ const AnnotationEntry<int>(annotation: 1, localPosition: insidePosition), ]), ); expect( root.findAllAnnotations<int>(outsidePosition).entries.toList(), _equalToAnnotationResult<int>(<AnnotationEntry<int>>[ const AnnotationEntry<int>(annotation: 1000, localPosition: outsidePosition), ]), ); }); test('TransformLayer.findAllAnnotations respects transform', () { // Matrix `transform` enlarges the target by (2x, 4x), then shift it by // (10, 20). final Matrix4 transform = Matrix4.diagonal3Values(2, 4, 1)..setTranslation(Vector3(10, 20, 0)); // The original region is Offset(10, 10) & Size(10, 10) // The transformed region is Offset(30, 60) & Size(20, 40) const Offset insidePosition = Offset(40, 80); const Offset outsidePosition = Offset(20, 40); final Layer root = _withBackgroundAnnotation( 1000, _Layers( TransformLayer(transform: transform), children: <Object>[ _TestAnnotatedLayer( 1, opaque: true, size: const Size(10, 10), offset: const Offset(10, 10), ), ], ).build(), ); expect( root.findAllAnnotations<int>(insidePosition).entries.toList(), _equalToAnnotationResult<int>(<AnnotationEntry<int>>[ const AnnotationEntry<int>(annotation: 1, localPosition: Offset(15, 15)), ]), ); expect( root.findAllAnnotations<int>(outsidePosition).entries.toList(), _equalToAnnotationResult<int>(<AnnotationEntry<int>>[ const AnnotationEntry<int>(annotation: 1000, localPosition: outsidePosition), ]), ); }); test('TransformLayer.findAllAnnotations correctly transforms with perspective', () { // Test the 4 corners of a transformed annotated region. final Matrix4 transform = Matrix4.identity() ..setEntry(3, 2, 0.005) ..rotateX(-0.2) ..rotateY(0.2); final Layer root = _withBackgroundAnnotation( 0, _Layers( TransformLayer(transform: transform), children: <Object>[ _TestAnnotatedLayer( 1, opaque: true, size: const Size(30, 40), offset: const Offset(10, 20), ), ], ).build(), ); void expectOneAnnotation({ required Offset globalPosition, required int value, required Offset localPosition, }) { expect( root.findAllAnnotations<int>(globalPosition).entries.toList(), _equalToAnnotationResult<int>( <AnnotationEntry<int>>[ AnnotationEntry<int>(annotation: value, localPosition: localPosition), ], maxCoordinateRelativeDiff: 0.005, ), ); } expectOneAnnotation( globalPosition: const Offset(10.0, 19.7), value: 0, localPosition: const Offset(10.0, 19.7), ); expectOneAnnotation( globalPosition: const Offset(10.1, 19.8), value: 1, localPosition: const Offset(10.0, 20.0), ); expectOneAnnotation( globalPosition: const Offset(10.5, 62.8), value: 0, localPosition: const Offset(10.5, 62.8), ); expectOneAnnotation( globalPosition: const Offset(10.6, 62.7), value: 1, localPosition: const Offset(10.1, 59.9), ); expectOneAnnotation( globalPosition: const Offset(42.6, 40.8), value: 0, localPosition: const Offset(42.6, 40.8), ); expectOneAnnotation( globalPosition: const Offset(42.5, 40.9), value: 1, localPosition: const Offset(39.9, 40.0), ); expectOneAnnotation( globalPosition: const Offset(43.5, 63.5), value: 0, localPosition: const Offset(43.5, 63.5), ); expectOneAnnotation( globalPosition: const Offset(43.4, 63.4), value: 1, localPosition: const Offset(39.9, 59.9), ); }); test('TransformLayer.findAllAnnotations skips when transform is irreversible', () { final Matrix4 transform = Matrix4.diagonal3Values(1, 0, 1); final Layer root = _withBackgroundAnnotation( 1000, _Layers( TransformLayer(transform: transform), children: <Object>[ _TestAnnotatedLayer(1, opaque: true), ], ).build(), ); expect( root.findAllAnnotations<int>(Offset.zero).entries.toList(), _equalToAnnotationResult<int>(<AnnotationEntry<int>>[ const AnnotationEntry<int>(annotation: 1000, localPosition: Offset.zero), ]), ); }); test('LeaderLayer.findAllAnnotations respects offset', () { const Offset insidePosition = Offset(-5, 5); const Offset outsidePosition = Offset(5, 5); final Layer root = _withBackgroundAnnotation( 1000, _Layers( LeaderLayer( link: LayerLink(), offset: const Offset(-10, 0), ), children: <Object>[ _TestAnnotatedLayer(1, opaque: true, size: const Size(10, 10)), ], ).build(), ); expect( root.findAllAnnotations<int>(insidePosition).entries.toList(), _equalToAnnotationResult<int>(<AnnotationEntry<int>>[ const AnnotationEntry<int>(annotation: 1, localPosition: Offset(5, 5)), ]), ); expect( root.findAllAnnotations<int>(outsidePosition).entries.toList(), _equalToAnnotationResult<int>(<AnnotationEntry<int>>[ const AnnotationEntry<int>(annotation: 1000, localPosition: outsidePosition), ]), ); }); test( 'AnnotatedRegionLayer.findAllAnnotations should append to the list ' 'and return the given opacity (false) during a successful hit', () { const Offset position = Offset(5, 5); final Layer root = _withBackgroundAnnotation( 1000, _Layers( AnnotatedRegionLayer<int>(1), children: <Object>[ _TestAnnotatedLayer(2, opaque: false), ], ).build(), ); expect( root.findAllAnnotations<int>(position).entries.toList(), _equalToAnnotationResult<int>(<AnnotationEntry<int>>[ const AnnotationEntry<int>(annotation: 2, localPosition: position), const AnnotationEntry<int>(annotation: 1, localPosition: position), const AnnotationEntry<int>(annotation: 1000, localPosition: position), ]), ); }, ); test( 'AnnotatedRegionLayer.findAllAnnotations should append to the list ' 'and return the given opacity (true) during a successful hit', () { const Offset position = Offset(5, 5); final Layer root = _withBackgroundAnnotation( 1000, _Layers( AnnotatedRegionLayer<int>(1, opaque: true), children: <Object>[ _TestAnnotatedLayer(2, opaque: false), ], ).build(), ); expect( root.findAllAnnotations<int>(position).entries.toList(), _equalToAnnotationResult<int>(<AnnotationEntry<int>>[ const AnnotationEntry<int>(annotation: 2, localPosition: position), const AnnotationEntry<int>(annotation: 1, localPosition: position), ]), ); }, ); test('AnnotatedRegionLayer.findAllAnnotations has default opacity as false', () { const Offset position = Offset(5, 5); final Layer root = _withBackgroundAnnotation( 1000, _Layers( AnnotatedRegionLayer<int>(1), children: <Object>[ _TestAnnotatedLayer(2, opaque: false), ], ).build(), ); expect( root.findAllAnnotations<int>(position).entries.toList(), _equalToAnnotationResult<int>(<AnnotationEntry<int>>[ const AnnotationEntry<int>(annotation: 2, localPosition: position), const AnnotationEntry<int>(annotation: 1, localPosition: position), const AnnotationEntry<int>(annotation: 1000, localPosition: position), ]), ); }); test( 'AnnotatedRegionLayer.findAllAnnotations should still check children and return ' "children's opacity (false) during a failed hit", () { const Offset position = Offset(5, 5); final Layer root = _withBackgroundAnnotation( 1000, _Layers( AnnotatedRegionLayer<int>(1, opaque: true, size: Size.zero), children: <Object>[ _TestAnnotatedLayer(2, opaque: false), ], ).build(), ); expect( root.findAllAnnotations<int>(position).entries.toList(), _equalToAnnotationResult<int>(<AnnotationEntry<int>>[ const AnnotationEntry<int>(annotation: 2, localPosition: position), const AnnotationEntry<int>(annotation: 1000, localPosition: position), ]), ); }, ); test( 'AnnotatedRegionLayer.findAllAnnotations should still check children and return ' "children's opacity (true) during a failed hit", () { const Offset position = Offset(5, 5); final Layer root = _withBackgroundAnnotation( 1000, _Layers( AnnotatedRegionLayer<int>(1, size: Size.zero), children: <Object>[ _TestAnnotatedLayer(2, opaque: true), ], ).build(), ); expect( root.findAllAnnotations<int>(position).entries.toList(), _equalToAnnotationResult<int>(<AnnotationEntry<int>>[ const AnnotationEntry<int>(annotation: 2, localPosition: position), ]), ); }, ); test( "AnnotatedRegionLayer.findAllAnnotations should not add to children's opacity " 'during a successful hit if it is not opaque', () { const Offset position = Offset(5, 5); final Layer root = _withBackgroundAnnotation( 1000, _Layers( AnnotatedRegionLayer<int>(1), children: <Object>[ _TestAnnotatedLayer(2, opaque: false), ], ).build(), ); expect( root.findAllAnnotations<int>(position).entries.toList(), _equalToAnnotationResult<int>(<AnnotationEntry<int>>[ const AnnotationEntry<int>(annotation: 2, localPosition: position), const AnnotationEntry<int>(annotation: 1, localPosition: position), const AnnotationEntry<int>(annotation: 1000, localPosition: position), ]), ); }, ); test( "AnnotatedRegionLayer.findAllAnnotations should add to children's opacity " 'during a successful hit if it is opaque', () { const Offset position = Offset(5, 5); final Layer root = _withBackgroundAnnotation( 1000, _Layers( AnnotatedRegionLayer<int>(1, opaque: true), children: <Object>[ _TestAnnotatedLayer(2, opaque: false), ], ).build(), ); expect( root.findAllAnnotations<int>(position).entries.toList(), _equalToAnnotationResult<int>(<AnnotationEntry<int>>[ const AnnotationEntry<int>(annotation: 2, localPosition: position), const AnnotationEntry<int>(annotation: 1, localPosition: position), ]), ); }, ); test( 'AnnotatedRegionLayer.findAllAnnotations should clip its annotation ' 'using size and offset (positive)', () { // The target position would have fallen outside if not for the offset. const Offset position = Offset(100, 100); final Layer root = _withBackgroundAnnotation( 1000, _Layers( AnnotatedRegionLayer<int>( 1, size: const Size(20, 20), offset: const Offset(90, 90), ), children: <Object>[ _TestAnnotatedLayer( 2, opaque: false, // Use this offset to make sure AnnotatedRegionLayer's offset // does not affect its children. offset: const Offset(20, 20), size: const Size(110, 110), ), ], ).build(), ); expect( root.findAllAnnotations<int>(position).entries.toList(), _equalToAnnotationResult<int>(<AnnotationEntry<int>>[ const AnnotationEntry<int>(annotation: 2, localPosition: position), const AnnotationEntry<int>(annotation: 1, localPosition: Offset(10, 10)), const AnnotationEntry<int>(annotation: 1000, localPosition: position), ]), ); }, ); test( 'AnnotatedRegionLayer.findAllAnnotations should clip its annotation ' 'using size and offset (negative)', () { // The target position would have fallen inside if not for the offset. const Offset position = Offset(10, 10); final Layer root = _withBackgroundAnnotation( 1000, _Layers( AnnotatedRegionLayer<int>( 1, size: const Size(20, 20), offset: const Offset(90, 90), ), children: <Object>[ _TestAnnotatedLayer(2, opaque: false, size: const Size(110, 110)), ], ).build(), ); expect( root.findAllAnnotations<int>(position).entries.toList(), _equalToAnnotationResult<int>(<AnnotationEntry<int>>[ const AnnotationEntry<int>(annotation: 2, localPosition: position), const AnnotationEntry<int>(annotation: 1000, localPosition: position), ]), ); }, ); } /// A [ContainerLayer] that contains a stack of layers: `layer` in the front, /// and another layer annotated with `value` in the back. /// /// It is a utility function that helps checking the opacity returned by /// [Layer.findAnnotations]. Layer _withBackgroundAnnotation(int value, Layer layer) { return _Layers( ContainerLayer(), children: <Object>[ _TestAnnotatedLayer(value, opaque: false), layer, ], ).build(); } // A utility class that helps building a layer tree. class _Layers { _Layers(this.root, {this.children}); final ContainerLayer root; // Each element must be instance of Layer or _Layers. final List<Object>? children; bool _assigned = false; // Build the layer tree by calling each child's `build`, then append children // to [root]. Returns the root. Layer build() { assert(!_assigned); _assigned = true; if (children != null) { for (final Object child in children!) { late Layer layer; if (child is Layer) { layer = child; } else if (child is _Layers) { layer = child.build(); } else { assert(false, 'Element of _Layers.children must be instance of Layer or _Layers'); } root.append(layer); } } return root; } } // This layer's [findAnnotation] can be controlled by the given arguments. class _TestAnnotatedLayer extends Layer { _TestAnnotatedLayer( this.value, { required this.opaque, this.offset = Offset.zero, this.size, }); // The value added to result in [findAnnotations] during a successful hit. final int value; // The return value of [findAnnotations] during a successful hit. final bool opaque; /// The [offset] is optionally used to translate the clip region for the /// hit-testing of [find] by [offset]. /// /// If not provided, offset defaults to [Offset.zero]. /// /// Ignored if [size] is not set. final Offset offset; /// The [size] is optionally used to clip the hit-testing of [find]. /// /// If not provided, all offsets are considered to be contained within this /// layer, unless an ancestor layer applies a clip. /// /// If [offset] is set, then the offset is applied to the size region before /// hit testing in [find]. final Size? size; @override EngineLayer? addToScene(SceneBuilder builder) { return null; } // This implementation is hit when the type is `int` and position is within // [offset] & [size]. If it is hit, it adds [value] to result and returns // [opaque]; otherwise it directly returns false. @override bool findAnnotations<S extends Object>( AnnotationResult<S> result, Offset localPosition, { required bool onlyFirst, }) { if (S != int) { return false; } if (size != null && !(offset & size!).contains(localPosition)) { return false; } final Object untypedValue = value; final S typedValue = untypedValue as S; result.add(AnnotationEntry<S>(annotation: typedValue, localPosition: localPosition)); return opaque; } } bool _almostEqual(double a, double b, double maxRelativeDiff) { assert(maxRelativeDiff >= 0); assert(maxRelativeDiff < 1); return (a - b).abs() <= a.abs() * maxRelativeDiff; } Matcher _equalToAnnotationResult<T>( List<AnnotationEntry<int>> list, { double maxCoordinateRelativeDiff = 0, }) { return pairwiseCompare<AnnotationEntry<int>, AnnotationEntry<int>>( list, (AnnotationEntry<int> a, AnnotationEntry<int> b) { return a.annotation == b.annotation && _almostEqual(a.localPosition.dx, b.localPosition.dx, maxCoordinateRelativeDiff) && _almostEqual(a.localPosition.dy, b.localPosition.dy, maxCoordinateRelativeDiff); }, 'equal to', ); }
flutter/packages/flutter/test/rendering/layer_annotations_test.dart/0
{ "file_path": "flutter/packages/flutter/test/rendering/layer_annotations_test.dart", "repo_id": "flutter", "token_count": 10556 }
685
// 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'; import 'rendering_tester.dart'; void main() { TestRenderingFlutterBinding.ensureInitialized(); test('PaintingContext.setIsComplexHint', () { final ContainerLayer layer = ContainerLayer(); final PaintingContext context = PaintingContext(layer, Rect.zero); expect(layer.hasChildren, isFalse); context.setIsComplexHint(); expect(layer.hasChildren, isTrue); expect(layer.firstChild, isA<PictureLayer>()); expect((layer.firstChild! as PictureLayer).isComplexHint, isTrue); }); test('PaintingContext.setWillChangeHint', () { final ContainerLayer layer = ContainerLayer(); final PaintingContext context = PaintingContext(layer, Rect.zero); expect(layer.hasChildren, isFalse); context.setWillChangeHint(); expect(layer.hasChildren, isTrue); expect(layer.firstChild, isA<PictureLayer>()); expect((layer.firstChild! as PictureLayer).willChangeHint, isTrue); }); }
flutter/packages/flutter/test/rendering/painting_context_test.dart/0
{ "file_path": "flutter/packages/flutter/test/rendering/painting_context_test.dart", "repo_id": "flutter", "token_count": 373 }
686
// 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'; import 'rendering_tester.dart'; int countSemanticsChildren(RenderObject object) { int count = 0; object.visitChildrenForSemantics((RenderObject child) { count += 1; }); return count; } void main() { TestRenderingFlutterBinding.ensureInitialized(); test('RenderOpacity and children and semantics', () { final RenderOpacity box = RenderOpacity( child: RenderParagraph( const TextSpan(), textDirection: TextDirection.ltr, ), ); expect(countSemanticsChildren(box), 1); box.opacity = 0.5; expect(countSemanticsChildren(box), 1); box.opacity = 0.25; expect(countSemanticsChildren(box), 1); box.opacity = 0.125; expect(countSemanticsChildren(box), 1); box.opacity = 0.0; expect(countSemanticsChildren(box), 0); box.opacity = 0.125; expect(countSemanticsChildren(box), 1); box.opacity = 0.0; expect(countSemanticsChildren(box), 0); }); test('RenderOpacity and children and semantics', () { final AnimationController controller = AnimationController(vsync: const TestVSync()); final RenderAnimatedOpacity box = RenderAnimatedOpacity( opacity: controller, child: RenderParagraph( const TextSpan(), textDirection: TextDirection.ltr, ), ); expect(countSemanticsChildren(box), 0); // controller defaults to 0.0 controller.value = 0.2; // has no effect, box isn't subscribed yet expect(countSemanticsChildren(box), 0); controller.value = 1.0; // ditto expect(countSemanticsChildren(box), 0); // alpha is still 0 layout(box); // this causes the box to attach, which makes it subscribe expect(countSemanticsChildren(box), 1); controller.value = 1.0; expect(countSemanticsChildren(box), 1); controller.value = 0.5; expect(countSemanticsChildren(box), 1); controller.value = 0.25; expect(countSemanticsChildren(box), 1); controller.value = 0.125; expect(countSemanticsChildren(box), 1); controller.value = 0.0; expect(countSemanticsChildren(box), 0); controller.value = 0.125; expect(countSemanticsChildren(box), 1); controller.value = 0.0; expect(countSemanticsChildren(box), 0); }); }
flutter/packages/flutter/test/rendering/semantics_and_children_test.dart/0
{ "file_path": "flutter/packages/flutter/test/rendering/semantics_and_children_test.dart", "repo_id": "flutter", "token_count": 886 }
687
// 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/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Properly constraints the physical size', (WidgetTester tester) async { final FlutterViewSpy view = FlutterViewSpy(view: tester.view) ..physicalConstraints = ViewConstraints.tight(const Size(1008.0, 2198.0)) ..devicePixelRatio = 1.912500023841858; await tester.pumpWidget( wrapWithView: false, View( view: view, child: const SizedBox(), ), ); expect(view.sizes.single, const Size(1008.0, 2198.0)); }); } class FlutterViewSpy extends TestFlutterView { FlutterViewSpy({required TestFlutterView super.view}) : super(platformDispatcher: view.platformDispatcher, display: view.display); List<Size?> sizes = <Size?>[]; @override void render(Scene scene, {Size? size}) { sizes.add(size); } }
flutter/packages/flutter/test/rendering/view_constraints_test.dart/0
{ "file_path": "flutter/packages/flutter/test/rendering/view_constraints_test.dart", "repo_id": "flutter", "token_count": 395 }
688
// 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/semantics.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; void main() { testWidgets('Listeners are called when semantics are turned on with ensureSemantics', (WidgetTester tester) async { expect(SemanticsBinding.instance.semanticsEnabled, isFalse); final List<bool> status = <bool>[]; void listener() { status.add(SemanticsBinding.instance.semanticsEnabled); } SemanticsBinding.instance.addSemanticsEnabledListener(listener); expect(SemanticsBinding.instance.semanticsEnabled, isFalse); final SemanticsHandle handle1 = SemanticsBinding.instance.ensureSemantics(); expect(status.single, isTrue); expect(SemanticsBinding.instance.semanticsEnabled, isTrue); status.clear(); final SemanticsHandle handle2 = SemanticsBinding.instance.ensureSemantics(); expect(status, isEmpty); // Listener didn't fire again. expect(SemanticsBinding.instance.semanticsEnabled, isTrue); expect(tester.binding.platformDispatcher.semanticsEnabled, isFalse); tester.binding.platformDispatcher.semanticsEnabledTestValue = true; expect(tester.binding.platformDispatcher.semanticsEnabled, isTrue); tester.binding.platformDispatcher.clearSemanticsEnabledTestValue(); expect(tester.binding.platformDispatcher.semanticsEnabled, isFalse); expect(status, isEmpty); // Listener didn't fire again. expect(SemanticsBinding.instance.semanticsEnabled, isTrue); handle1.dispose(); expect(status, isEmpty); // Listener didn't fire. expect(SemanticsBinding.instance.semanticsEnabled, isTrue); handle2.dispose(); expect(status.single, isFalse); expect(SemanticsBinding.instance.semanticsEnabled, isFalse); }, semanticsEnabled: false); testWidgets('Listeners are called when semantics are turned on by platform', (WidgetTester tester) async { expect(SemanticsBinding.instance.semanticsEnabled, isFalse); final List<bool> status = <bool>[]; void listener() { status.add(SemanticsBinding.instance.semanticsEnabled); } SemanticsBinding.instance.addSemanticsEnabledListener(listener); expect(SemanticsBinding.instance.semanticsEnabled, isFalse); tester.binding.platformDispatcher.semanticsEnabledTestValue = true; expect(status.single, isTrue); expect(SemanticsBinding.instance.semanticsEnabled, isTrue); status.clear(); final SemanticsHandle handle = SemanticsBinding.instance.ensureSemantics(); handle.dispose(); expect(status, isEmpty); // Listener didn't fire. expect(SemanticsBinding.instance.semanticsEnabled, isTrue); tester.binding.platformDispatcher.clearSemanticsEnabledTestValue(); expect(status.single, isFalse); expect(SemanticsBinding.instance.semanticsEnabled, isFalse); }, semanticsEnabled: false); testWidgets('SemanticsBinding.ensureSemantics triggers creation of semantics owner.', (WidgetTester tester) async { expect(SemanticsBinding.instance.semanticsEnabled, isFalse); expect(tester.binding.pipelineOwner.semanticsOwner, isNull); final SemanticsHandle handle = SemanticsBinding.instance.ensureSemantics(); expect(SemanticsBinding.instance.semanticsEnabled, isTrue); expect(tester.binding.pipelineOwner.semanticsOwner, isNotNull); handle.dispose(); expect(SemanticsBinding.instance.semanticsEnabled, isFalse); expect(tester.binding.pipelineOwner.semanticsOwner, isNull); }, semanticsEnabled: false); test('SemanticsHandle dispatches memory events', () async { await expectLater( await memoryEvents( () => SemanticsBinding.instance.ensureSemantics().dispose(), SemanticsHandle, ), areCreateAndDispose, ); }); }
flutter/packages/flutter/test/semantics/semantics_binding_test.dart/0
{ "file_path": "flutter/packages/flutter/test/semantics/semantics_binding_test.dart", "repo_id": "flutter", "token_count": 1256 }
689
// 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/services.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); test('installDeferredComponent test', () async { final List<MethodCall> log = <MethodCall>[]; TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.deferredComponent, (MethodCall methodCall) async { log.add(methodCall); return null; }); await DeferredComponent.installDeferredComponent(componentName: 'testComponentName'); expect(log, hasLength(1)); expect(log.single, isMethodCall( 'installDeferredComponent', arguments: <String, dynamic>{'loadingUnitId': -1, 'componentName': 'testComponentName'}, )); }); test('uninstallDeferredComponent test', () async { final List<MethodCall> log = <MethodCall>[]; TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.deferredComponent, (MethodCall methodCall) async { log.add(methodCall); return null; }); await DeferredComponent.uninstallDeferredComponent(componentName: 'testComponentName'); expect(log, hasLength(1)); expect(log.single, isMethodCall( 'uninstallDeferredComponent', arguments: <String, dynamic>{'loadingUnitId': -1, 'componentName': 'testComponentName'}, )); }); }
flutter/packages/flutter/test/services/deferred_component_test.dart/0
{ "file_path": "flutter/packages/flutter/test/services/deferred_component_test.dart", "repo_id": "flutter", "token_count": 503 }
690
// 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/services.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); test('ProcessTextService.queryTextActions emits correct method call', () async { final List<MethodCall> log = <MethodCall>[]; TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.processText, (MethodCall methodCall) async { log.add(methodCall); return null; }); final ProcessTextService processTextService = DefaultProcessTextService(); await processTextService.queryTextActions(); expect(log, hasLength(1)); expect(log.single, isMethodCall('ProcessText.queryTextActions', arguments: null)); }); test('ProcessTextService.processTextAction emits correct method call', () async { final List<MethodCall> log = <MethodCall>[]; TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.processText, (MethodCall methodCall) async { log.add(methodCall); return null; }); final ProcessTextService processTextService = DefaultProcessTextService(); const String fakeActionId = 'fakeActivity.fakeAction'; const String textToProcess = 'Flutter'; await processTextService.processTextAction(fakeActionId, textToProcess, false); expect(log, hasLength(1)); expect(log.single, isMethodCall('ProcessText.processTextAction', arguments: <Object>[fakeActionId, textToProcess, false])); }); test('ProcessTextService handles engine answers over the channel', () async { const String action1Id = 'fakeActivity.fakeAction1'; const String action2Id = 'fakeActivity.fakeAction2'; // Fake channel that simulates responses returned from the engine. final MethodChannel fakeChannel = FakeProcessTextChannel((MethodCall call) async { if (call.method == 'ProcessText.queryTextActions') { return <String, String>{ action1Id: 'Action1', action2Id: 'Action2', }; } if (call.method == 'ProcessText.processTextAction') { final List<dynamic> args = call.arguments as List<dynamic>; final String actionId = args[0] as String; final String testToProcess = args[1] as String; if (actionId == action1Id) { // Simulates an action that returns a transformed text. return '$testToProcess!!!'; } // Simulates an action that failed or does not transform text. return null; } }); final DefaultProcessTextService processTextService = DefaultProcessTextService(); processTextService.setChannel(fakeChannel); final List<ProcessTextAction> actions = await processTextService.queryTextActions(); expect(actions, hasLength(2)); const String textToProcess = 'Flutter'; String? processedText; processedText = await processTextService.processTextAction(action1Id, textToProcess, false); expect(processedText, 'Flutter!!!'); processedText = await processTextService.processTextAction(action2Id, textToProcess, false); expect(processedText, null); }); } class FakeProcessTextChannel implements MethodChannel { FakeProcessTextChannel(this.outgoing); Future<dynamic> Function(MethodCall) outgoing; Future<void> Function(MethodCall)? incoming; List<MethodCall> outgoingCalls = <MethodCall>[]; @override BinaryMessenger get binaryMessenger => throw UnimplementedError(); @override MethodCodec get codec => const StandardMethodCodec(); @override Future<List<T>> invokeListMethod<T>(String method, [dynamic arguments]) => throw UnimplementedError(); @override Future<Map<K, V>> invokeMapMethod<K, V>(String method, [dynamic arguments]) => throw UnimplementedError(); @override Future<T> invokeMethod<T>(String method, [dynamic arguments]) async { final MethodCall call = MethodCall(method, arguments); outgoingCalls.add(call); return await outgoing(call) as T; } @override String get name => 'flutter/processtext'; @override void setMethodCallHandler(Future<void> Function(MethodCall call)? handler) => incoming = handler; }
flutter/packages/flutter/test/services/process_text_test.dart/0
{ "file_path": "flutter/packages/flutter/test/services/process_text_test.dart", "repo_id": "flutter", "token_count": 1360 }
691
// 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'; import 'semantics_tester.dart'; void main() { testWidgets('AbsorbPointers do not block siblings', (WidgetTester tester) async { bool tapped = false; await tester.pumpWidget( Column( children: <Widget>[ Expanded( child: GestureDetector( onTap: () => tapped = true, ), ), const Expanded( child: AbsorbPointer(), ), ], ), ); await tester.tap(find.byType(GestureDetector)); expect(tapped, true); }); group('AbsorbPointer semantics', () { testWidgets('does not change semantics when not absorbing', (WidgetTester tester) async { final UniqueKey key = UniqueKey(); await tester.pumpWidget( MaterialApp( home: AbsorbPointer( absorbing: false, child: ElevatedButton( key: key, onPressed: () { }, child: const Text('button'), ), ), ), ); expect( tester.getSemantics(find.byKey(key)), matchesSemantics( label: 'button', hasTapAction: true, isButton: true, isFocusable: true, hasEnabledState: true, isEnabled: true, ), ); }); testWidgets('drops semantics when its ignoreSemantics is true', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final UniqueKey key = UniqueKey(); await tester.pumpWidget( MaterialApp( home: AbsorbPointer( ignoringSemantics: true, child: ElevatedButton( key: key, onPressed: () { }, child: const Text('button'), ), ), ), ); expect(semantics, isNot(includesNodeWith(label: 'button'))); semantics.dispose(); }); testWidgets('ignores user interactions', (WidgetTester tester) async { final UniqueKey key = UniqueKey(); await tester.pumpWidget( MaterialApp( home: AbsorbPointer( child: ElevatedButton( key: key, onPressed: () { }, child: const Text('button'), ), ), ), ); expect( tester.getSemantics(find.byKey(key)), // Tap action is blocked. matchesSemantics( label: 'button', isButton: true, isFocusable: true, hasEnabledState: true, isEnabled: true, ), ); }); }); }
flutter/packages/flutter/test/widgets/absorb_pointer_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/absorb_pointer_test.dart", "repo_id": "flutter", "token_count": 1358 }
692
// 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'; Route<void> generateRoute(RouteSettings settings) => PageRouteBuilder<void>( settings: settings, pageBuilder: (BuildContext context, Animation<double> animation1, Animation<double> animation2) { return const Placeholder(); }, ); void main() { testWidgets('WidgetsApp.navigatorKey', (WidgetTester tester) async { final GlobalKey<NavigatorState> key = GlobalKey<NavigatorState>(); await tester.pumpWidget(WidgetsApp( navigatorKey: key, color: const Color(0xFF112233), onGenerateRoute: generateRoute, )); expect(key.currentState, isA<NavigatorState>()); await tester.pumpWidget(WidgetsApp( color: const Color(0xFF112233), onGenerateRoute: generateRoute, )); expect(key.currentState, isNull); await tester.pumpWidget(WidgetsApp( navigatorKey: key, color: const Color(0xFF112233), onGenerateRoute: generateRoute, )); expect(key.currentState, isA<NavigatorState>()); }); }
flutter/packages/flutter/test/widgets/app_navigator_key_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/app_navigator_key_test.dart", "repo_id": "flutter", "token_count": 432 }
693
// 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/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; const String _actualContent = 'Actual Content'; const String _loading = 'Loading...'; void main() { testWidgets('deferFirstFrame/allowFirstFrame stops sending frames to engine', (WidgetTester tester) async { expect(RendererBinding.instance.sendFramesToEngine, isTrue); final Completer<void> completer = Completer<void>(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: _DeferringWidget( key: UniqueKey(), loader: completer.future, ), ), ); final _DeferringWidgetState state = tester.state<_DeferringWidgetState>(find.byType(_DeferringWidget)); expect(find.text(_loading), findsOneWidget); expect(find.text(_actualContent), findsNothing); expect(RendererBinding.instance.sendFramesToEngine, isFalse); await tester.pump(); expect(find.text(_loading), findsOneWidget); expect(find.text(_actualContent), findsNothing); expect(RendererBinding.instance.sendFramesToEngine, isFalse); expect(state.doneLoading, isFalse); // Complete the future to start sending frames. completer.complete(); await tester.idle(); expect(state.doneLoading, isTrue); expect(RendererBinding.instance.sendFramesToEngine, isTrue); await tester.pump(); expect(find.text(_loading), findsNothing); expect(find.text(_actualContent), findsOneWidget); expect(RendererBinding.instance.sendFramesToEngine, isTrue); }); testWidgets('Two widgets can defer frames', (WidgetTester tester) async { expect(RendererBinding.instance.sendFramesToEngine, isTrue); final Completer<void> completer1 = Completer<void>(); final Completer<void> completer2 = Completer<void>(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Row( children: <Widget>[ _DeferringWidget( key: UniqueKey(), loader: completer1.future, ), _DeferringWidget( key: UniqueKey(), loader: completer2.future, ), ], ), ), ); expect(find.text(_loading), findsNWidgets(2)); expect(find.text(_actualContent), findsNothing); expect(RendererBinding.instance.sendFramesToEngine, isFalse); completer1.complete(); completer2.complete(); await tester.idle(); await tester.pump(); expect(find.text(_loading), findsNothing); expect(find.text(_actualContent), findsNWidgets(2)); expect(RendererBinding.instance.sendFramesToEngine, isTrue); }); } class _DeferringWidget extends StatefulWidget { const _DeferringWidget({required Key key, required this.loader}) : super(key: key); final Future<void> loader; @override State<_DeferringWidget> createState() => _DeferringWidgetState(); } class _DeferringWidgetState extends State<_DeferringWidget> { bool doneLoading = false; @override void initState() { super.initState(); RendererBinding.instance.deferFirstFrame(); widget.loader.then((_) { setState(() { doneLoading = true; RendererBinding.instance.allowFirstFrame(); }); }); } @override Widget build(BuildContext context) { return doneLoading ? const Text(_actualContent) : const Text(_loading); } }
flutter/packages/flutter/test/widgets/binding_deferred_first_frame_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/binding_deferred_first_frame_test.dart", "repo_id": "flutter", "token_count": 1386 }
694
// 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/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { // DOWN (default) testWidgets('Column with one flexible child', (WidgetTester tester) async { const Key columnKey = Key('column'); const Key child0Key = Key('child0'); const Key child1Key = Key('child1'); const Key child2Key = Key('child2'); // Default is MainAxisSize.max so the Column should be as high as the test: 600. // Default is MainAxisAlignment.start so children so the children's // top edges should be at 0, 100, 500, child2's height should be 400. await tester.pumpWidget(const Center( child: Column( key: columnKey, children: <Widget>[ SizedBox(key: child0Key, width: 100.0, height: 100.0), Expanded(child: SizedBox(key: child1Key, width: 100.0, height: 100.0)), SizedBox(key: child2Key, width: 100.0, height: 100.0), ], ), )); RenderBox renderBox; BoxParentData boxParentData; renderBox = tester.renderObject(find.byKey(columnKey)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(600.0)); renderBox = tester.renderObject(find.byKey(child0Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dy, equals(0.0)); renderBox = tester.renderObject(find.byKey(child1Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(400.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dy, equals(100.0)); renderBox = tester.renderObject(find.byKey(child2Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dy, equals(500.0)); }); testWidgets('Column with default main axis parameters', (WidgetTester tester) async { const Key columnKey = Key('column'); const Key child0Key = Key('child0'); const Key child1Key = Key('child1'); const Key child2Key = Key('child2'); // Default is MainAxisSize.max so the Column should be as high as the test: 600. // Default is MainAxisAlignment.start so children so the children's // top edges should be at 0, 100, 200 await tester.pumpWidget(const Center( child: Column( key: columnKey, children: <Widget>[ SizedBox(key: child0Key, width: 100.0, height: 100.0), SizedBox(key: child1Key, width: 100.0, height: 100.0), SizedBox(key: child2Key, width: 100.0, height: 100.0), ], ), )); RenderBox renderBox; BoxParentData boxParentData; renderBox = tester.renderObject(find.byKey(columnKey)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(600.0)); renderBox = tester.renderObject(find.byKey(child0Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dy, equals(0.0)); renderBox = tester.renderObject(find.byKey(child1Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dy, equals(100.0)); renderBox = tester.renderObject(find.byKey(child2Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dy, equals(200.0)); }); testWidgets('Column with MainAxisAlignment.center', (WidgetTester tester) async { const Key columnKey = Key('column'); const Key child0Key = Key('child0'); const Key child1Key = Key('child1'); // Default is MainAxisSize.max so the Column should be as high as the test: 600. // The 100x100 children's top edges should be at 200, 300 await tester.pumpWidget(const Center( child: Column( key: columnKey, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ SizedBox(key: child0Key, width: 100.0, height: 100.0), SizedBox(key: child1Key, width: 100.0, height: 100.0), ], ), )); RenderBox renderBox; BoxParentData boxParentData; renderBox = tester.renderObject(find.byKey(columnKey)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(600.0)); renderBox = tester.renderObject(find.byKey(child0Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dy, equals(200.0)); renderBox = tester.renderObject(find.byKey(child1Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dy, equals(300.0)); }); testWidgets('Column with MainAxisAlignment.end', (WidgetTester tester) async { const Key columnKey = Key('column'); const Key child0Key = Key('child0'); const Key child1Key = Key('child1'); const Key child2Key = Key('child2'); // Default is MainAxisSize.max so the Column should be as high as the test: 600. // The 100x100 children's top edges should be at 300, 400, 500. await tester.pumpWidget(const Center( child: Column( key: columnKey, mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[ SizedBox(key: child0Key, width: 100.0, height: 100.0), SizedBox(key: child1Key, width: 100.0, height: 100.0), SizedBox(key: child2Key, width: 100.0, height: 100.0), ], ), )); RenderBox renderBox; BoxParentData boxParentData; renderBox = tester.renderObject(find.byKey(columnKey)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(600.0)); renderBox = tester.renderObject(find.byKey(child0Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dy, equals(300.0)); renderBox = tester.renderObject(find.byKey(child1Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dy, equals(400.0)); renderBox = tester.renderObject(find.byKey(child2Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dy, equals(500.0)); }); testWidgets('Column with MainAxisAlignment.spaceBetween', (WidgetTester tester) async { const Key columnKey = Key('column'); const Key child0Key = Key('child0'); const Key child1Key = Key('child1'); const Key child2Key = Key('child2'); // Default is MainAxisSize.max so the Column should be as high as the test: 600. // The 100x100 children's top edges should be at 0, 250, 500 await tester.pumpWidget(const Center( child: Column( key: columnKey, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ SizedBox(key: child0Key, width: 100.0, height: 100.0), SizedBox(key: child1Key, width: 100.0, height: 100.0), SizedBox(key: child2Key, width: 100.0, height: 100.0), ], ), )); RenderBox renderBox; BoxParentData boxParentData; renderBox = tester.renderObject(find.byKey(columnKey)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(600.0)); renderBox = tester.renderObject(find.byKey(child0Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dy, equals(0.0)); renderBox = tester.renderObject(find.byKey(child1Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dy, equals(250.0)); renderBox = tester.renderObject(find.byKey(child2Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dy, equals(500.0)); }); testWidgets('Column with MainAxisAlignment.spaceAround', (WidgetTester tester) async { const Key columnKey = Key('column'); const Key child0Key = Key('child0'); const Key child1Key = Key('child1'); const Key child2Key = Key('child2'); const Key child3Key = Key('child3'); // Default is MainAxisSize.max so the Column should be as high as the test: 600. // The 100x100 children's top edges should be at 25, 175, 325, 475 await tester.pumpWidget(const Center( child: Column( key: columnKey, mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ SizedBox(key: child0Key, width: 100.0, height: 100.0), SizedBox(key: child1Key, width: 100.0, height: 100.0), SizedBox(key: child2Key, width: 100.0, height: 100.0), SizedBox(key: child3Key, width: 100.0, height: 100.0), ], ), )); RenderBox renderBox; BoxParentData boxParentData; renderBox = tester.renderObject(find.byKey(columnKey)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(600.0)); renderBox = tester.renderObject(find.byKey(child0Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dy, equals(25.0)); renderBox = tester.renderObject(find.byKey(child1Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dy, equals(175.0)); renderBox = tester.renderObject(find.byKey(child2Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dy, equals(325.0)); renderBox = tester.renderObject(find.byKey(child3Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dy, equals(475.0)); }); testWidgets('Column with MainAxisAlignment.spaceEvenly', (WidgetTester tester) async { const Key columnKey = Key('column'); const Key child0Key = Key('child0'); const Key child1Key = Key('child1'); const Key child2Key = Key('child2'); // Default is MainAxisSize.max so the Column should be as high as the test: 600. // The 100x20 children's top edges should be at 135, 290, 445 await tester.pumpWidget(const Center( child: Column( key: columnKey, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ SizedBox(key: child0Key, width: 100.0, height: 20.0), SizedBox(key: child1Key, width: 100.0, height: 20.0), SizedBox(key: child2Key, width: 100.0, height: 20.0), ], ), )); RenderBox renderBox; BoxParentData boxParentData; renderBox = tester.renderObject(find.byKey(columnKey)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(600.0)); renderBox = tester.renderObject(find.byKey(child0Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(20.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dy, equals(135.0)); renderBox = tester.renderObject(find.byKey(child1Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(20.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dy, equals(290.0)); renderBox = tester.renderObject(find.byKey(child2Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(20.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dy, equals(445.0)); }); testWidgets('Column and MainAxisSize.min', (WidgetTester tester) async { const Key flexKey = Key('flexKey'); // Default is MainAxisSize.max so the Column should be as high as the test: 600. await tester.pumpWidget(const Center( child: Column( key: flexKey, children: <Widget>[ SizedBox(width: 100.0, height: 100.0), SizedBox(width: 100.0, height: 150.0), ], ), )); RenderBox renderBox = tester.renderObject(find.byKey(flexKey)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(600.0)); // Column with MainAxisSize.min without flexible children shrink wraps. await tester.pumpWidget(const Center( child: Column( key: flexKey, mainAxisSize: MainAxisSize.min, children: <Widget>[ SizedBox(width: 100.0, height: 100.0), SizedBox(width: 100.0, height: 150.0), ], ), )); renderBox = tester.renderObject(find.byKey(flexKey)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(250.0)); }); testWidgets('Column MainAxisSize.min layout at zero size', (WidgetTester tester) async { const Key childKey = Key('childKey'); await tester.pumpWidget(const Center( child: SizedBox.shrink( child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ SizedBox( key: childKey, width: 100.0, height: 100.0, ), ], ), ), )); final RenderBox renderBox = tester.renderObject(find.byKey(childKey)); expect(renderBox.size.width, equals(0.0)); expect(renderBox.size.height, equals(100.0)); }); // UP testWidgets('Column with one flexible child', (WidgetTester tester) async { const Key columnKey = Key('column'); const Key child0Key = Key('child0'); const Key child1Key = Key('child1'); const Key child2Key = Key('child2'); // Default is MainAxisSize.max so the Column should be as high as the test: 600. // Default is MainAxisAlignment.start so children so the children's // bottom edges should be at 0, 100, 500 from bottom, child2's height should be 400. await tester.pumpWidget(const Center( child: Column( key: columnKey, verticalDirection: VerticalDirection.up, children: <Widget>[ SizedBox(key: child0Key, width: 100.0, height: 100.0), Expanded(child: SizedBox(key: child1Key, width: 100.0, height: 100.0)), SizedBox(key: child2Key, width: 100.0, height: 100.0), ], ), )); RenderBox renderBox; BoxParentData boxParentData; renderBox = tester.renderObject(find.byKey(columnKey)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(600.0)); renderBox = tester.renderObject(find.byKey(child0Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dy, equals(500.0)); renderBox = tester.renderObject(find.byKey(child1Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(400.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dy, equals(100.0)); renderBox = tester.renderObject(find.byKey(child2Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dy, equals(0.0)); }); testWidgets('Column with default main axis parameters', (WidgetTester tester) async { const Key columnKey = Key('column'); const Key child0Key = Key('child0'); const Key child1Key = Key('child1'); const Key child2Key = Key('child2'); // Default is MainAxisSize.max so the Column should be as high as the test: 600. // Default is MainAxisAlignment.start so children so the children's // bottom edges should be at 0, 100, 200 from bottom await tester.pumpWidget(const Center( child: Column( key: columnKey, verticalDirection: VerticalDirection.up, children: <Widget>[ SizedBox(key: child0Key, width: 100.0, height: 100.0), SizedBox(key: child1Key, width: 100.0, height: 100.0), SizedBox(key: child2Key, width: 100.0, height: 100.0), ], ), )); RenderBox renderBox; BoxParentData boxParentData; renderBox = tester.renderObject(find.byKey(columnKey)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(600.0)); renderBox = tester.renderObject(find.byKey(child0Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dy, equals(500.0)); renderBox = tester.renderObject(find.byKey(child1Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dy, equals(400.0)); renderBox = tester.renderObject(find.byKey(child2Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dy, equals(300.0)); }); testWidgets('Column with MainAxisAlignment.center', (WidgetTester tester) async { const Key columnKey = Key('column'); const Key child0Key = Key('child0'); const Key child1Key = Key('child1'); // Default is MainAxisSize.max so the Column should be as high as the test: 600. // The 100x100 children's bottom edges should be at 200, 300 from bottom await tester.pumpWidget(const Center( child: Column( key: columnKey, mainAxisAlignment: MainAxisAlignment.center, verticalDirection: VerticalDirection.up, children: <Widget>[ SizedBox(key: child0Key, width: 100.0, height: 100.0), SizedBox(key: child1Key, width: 100.0, height: 100.0), ], ), )); RenderBox renderBox; BoxParentData boxParentData; renderBox = tester.renderObject(find.byKey(columnKey)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(600.0)); renderBox = tester.renderObject(find.byKey(child0Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dy, equals(300.0)); renderBox = tester.renderObject(find.byKey(child1Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dy, equals(200.0)); }); testWidgets('Column with MainAxisAlignment.end', (WidgetTester tester) async { const Key columnKey = Key('column'); const Key child0Key = Key('child0'); const Key child1Key = Key('child1'); const Key child2Key = Key('child2'); // Default is MainAxisSize.max so the Column should be as high as the test: 600. // The 100x100 children's bottom edges should be at 300, 400, 500 from bottom. await tester.pumpWidget(const Center( child: Column( key: columnKey, mainAxisAlignment: MainAxisAlignment.end, verticalDirection: VerticalDirection.up, children: <Widget>[ SizedBox(key: child0Key, width: 100.0, height: 100.0), SizedBox(key: child1Key, width: 100.0, height: 100.0), SizedBox(key: child2Key, width: 100.0, height: 100.0), ], ), )); RenderBox renderBox; BoxParentData boxParentData; renderBox = tester.renderObject(find.byKey(columnKey)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(600.0)); renderBox = tester.renderObject(find.byKey(child0Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dy, equals(200.0)); renderBox = tester.renderObject(find.byKey(child1Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dy, equals(100.0)); renderBox = tester.renderObject(find.byKey(child2Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dy, equals(0.0)); }); testWidgets('Column with MainAxisAlignment.spaceBetween', (WidgetTester tester) async { const Key columnKey = Key('column'); const Key child0Key = Key('child0'); const Key child1Key = Key('child1'); const Key child2Key = Key('child2'); // Default is MainAxisSize.max so the Column should be as high as the test: 600. // The 100x100 children's bottom edges should be at 0, 250, 500 from bottom await tester.pumpWidget(const Center( child: Column( key: columnKey, mainAxisAlignment: MainAxisAlignment.spaceBetween, verticalDirection: VerticalDirection.up, children: <Widget>[ SizedBox(key: child0Key, width: 100.0, height: 100.0), SizedBox(key: child1Key, width: 100.0, height: 100.0), SizedBox(key: child2Key, width: 100.0, height: 100.0), ], ), )); RenderBox renderBox; BoxParentData boxParentData; renderBox = tester.renderObject(find.byKey(columnKey)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(600.0)); renderBox = tester.renderObject(find.byKey(child0Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dy, equals(500.0)); renderBox = tester.renderObject(find.byKey(child1Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dy, equals(250.0)); renderBox = tester.renderObject(find.byKey(child2Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dy, equals(0.0)); }); testWidgets('Column with MainAxisAlignment.spaceAround', (WidgetTester tester) async { const Key columnKey = Key('column'); const Key child0Key = Key('child0'); const Key child1Key = Key('child1'); const Key child2Key = Key('child2'); const Key child3Key = Key('child3'); // Default is MainAxisSize.max so the Column should be as high as the test: 600. // The 100x100 children's bottom edges should be at 25, 175, 325, 475 from bottom await tester.pumpWidget(const Center( child: Column( key: columnKey, mainAxisAlignment: MainAxisAlignment.spaceAround, verticalDirection: VerticalDirection.up, children: <Widget>[ SizedBox(key: child0Key, width: 100.0, height: 100.0), SizedBox(key: child1Key, width: 100.0, height: 100.0), SizedBox(key: child2Key, width: 100.0, height: 100.0), SizedBox(key: child3Key, width: 100.0, height: 100.0), ], ), )); RenderBox renderBox; BoxParentData boxParentData; renderBox = tester.renderObject(find.byKey(columnKey)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(600.0)); renderBox = tester.renderObject(find.byKey(child0Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dy, equals(500.0 - 25.0)); renderBox = tester.renderObject(find.byKey(child1Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dy, equals(500.0 - 175.0)); renderBox = tester.renderObject(find.byKey(child2Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dy, equals(500.0 - 325.0)); renderBox = tester.renderObject(find.byKey(child3Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(100.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dy, equals(500.0 - 475.0)); }); testWidgets('Column with MainAxisAlignment.spaceEvenly', (WidgetTester tester) async { const Key columnKey = Key('column'); const Key child0Key = Key('child0'); const Key child1Key = Key('child1'); const Key child2Key = Key('child2'); // Default is MainAxisSize.max so the Column should be as high as the test: 600. // The 100x20 children's bottom edges should be at 135, 290, 445 from bottom await tester.pumpWidget(const Center( child: Column( key: columnKey, mainAxisAlignment: MainAxisAlignment.spaceEvenly, verticalDirection: VerticalDirection.up, children: <Widget>[ SizedBox(key: child0Key, width: 100.0, height: 20.0), SizedBox(key: child1Key, width: 100.0, height: 20.0), SizedBox(key: child2Key, width: 100.0, height: 20.0), ], ), )); RenderBox renderBox; BoxParentData boxParentData; renderBox = tester.renderObject(find.byKey(columnKey)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(600.0)); renderBox = tester.renderObject(find.byKey(child0Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(20.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dy, equals(600.0 - 135.0 - 20.0)); renderBox = tester.renderObject(find.byKey(child1Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(20.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dy, equals(600.0 - 290.0 - 20.0)); renderBox = tester.renderObject(find.byKey(child2Key)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(20.0)); boxParentData = renderBox.parentData! as BoxParentData; expect(boxParentData.offset.dy, equals(600.0 - 445.0 - 20.0)); }); testWidgets('Column and MainAxisSize.min', (WidgetTester tester) async { const Key flexKey = Key('flexKey'); // Default is MainAxisSize.max so the Column should be as high as the test: 600. await tester.pumpWidget(const Center( child: Column( key: flexKey, verticalDirection: VerticalDirection.up, children: <Widget>[ SizedBox(width: 100.0, height: 100.0), SizedBox(width: 100.0, height: 150.0), ], ), )); RenderBox renderBox = tester.renderObject(find.byKey(flexKey)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(600.0)); // Column with MainAxisSize.min without flexible children shrink wraps. await tester.pumpWidget(const Center( child: Column( key: flexKey, mainAxisSize: MainAxisSize.min, verticalDirection: VerticalDirection.up, children: <Widget>[ SizedBox(width: 100.0, height: 100.0), SizedBox(width: 100.0, height: 150.0), ], ), )); renderBox = tester.renderObject(find.byKey(flexKey)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(250.0)); }); testWidgets('Column MainAxisSize.min layout at zero size', (WidgetTester tester) async { const Key childKey = Key('childKey'); await tester.pumpWidget(const Center( child: SizedBox.shrink( child: Column( mainAxisSize: MainAxisSize.min, verticalDirection: VerticalDirection.up, children: <Widget>[ SizedBox( key: childKey, width: 100.0, height: 100.0, ), ], ), ), )); final RenderBox renderBox = tester.renderObject(find.byKey(childKey)); expect(renderBox.size.width, equals(0.0)); expect(renderBox.size.height, equals(100.0)); }); }
flutter/packages/flutter/test/widgets/column_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/column_test.dart", "repo_id": "flutter", "token_count": 11706 }
695
// 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 show TextHeightBehavior; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('DefaultTextStyle changes propagate to Text', (WidgetTester tester) async { const Text textWidget = Text('Hello', textDirection: TextDirection.ltr); const TextStyle s1 = TextStyle( fontSize: 10.0, fontWeight: FontWeight.w800, height: 123.0, ); await tester.pumpWidget(const DefaultTextStyle( style: s1, child: textWidget, )); RichText text = tester.firstWidget(find.byType(RichText)); expect(text, isNotNull); expect(text.text.style, s1); await tester.pumpWidget(const DefaultTextStyle( style: s1, textAlign: TextAlign.justify, softWrap: false, overflow: TextOverflow.fade, maxLines: 3, child: textWidget, )); text = tester.firstWidget(find.byType(RichText)); expect(text, isNotNull); expect(text.text.style, s1); expect(text.textAlign, TextAlign.justify); expect(text.softWrap, false); expect(text.overflow, TextOverflow.fade); expect(text.maxLines, 3); }); testWidgets('AnimatedDefaultTextStyle changes propagate to Text', (WidgetTester tester) async { const Text textWidget = Text('Hello', textDirection: TextDirection.ltr); const TextStyle s1 = TextStyle( fontSize: 10.0, fontWeight: FontWeight.w800, height: 123.0, ); const TextStyle s2 = TextStyle( fontSize: 20.0, fontWeight: FontWeight.w200, height: 1.0, ); await tester.pumpWidget(const AnimatedDefaultTextStyle( style: s1, duration: Duration(milliseconds: 1000), child: textWidget, )); final RichText text1 = tester.firstWidget(find.byType(RichText)); expect(text1, isNotNull); expect(text1.text.style, s1); expect(text1.textAlign, TextAlign.start); expect(text1.softWrap, isTrue); expect(text1.overflow, TextOverflow.clip); expect(text1.maxLines, isNull); expect(text1.textWidthBasis, TextWidthBasis.parent); expect(text1.textHeightBehavior, isNull); await tester.pumpWidget(const AnimatedDefaultTextStyle( style: s2, textAlign: TextAlign.justify, softWrap: false, overflow: TextOverflow.fade, maxLines: 3, textWidthBasis: TextWidthBasis.longestLine, textHeightBehavior: ui.TextHeightBehavior(applyHeightToFirstAscent: false), duration: Duration(milliseconds: 1000), child: textWidget, )); final RichText text2 = tester.firstWidget(find.byType(RichText)); expect(text2, isNotNull); expect(text2.text.style, s1); // animation hasn't started yet expect(text2.textAlign, TextAlign.justify); expect(text2.softWrap, false); expect(text2.overflow, TextOverflow.fade); expect(text2.maxLines, 3); expect(text2.textWidthBasis, TextWidthBasis.longestLine); expect(text2.textHeightBehavior, const ui.TextHeightBehavior(applyHeightToFirstAscent: false)); await tester.pump(const Duration(milliseconds: 1000)); final RichText text3 = tester.firstWidget(find.byType(RichText)); expect(text3, isNotNull); expect(text3.text.style, s2); // animation has now finished expect(text3.textAlign, TextAlign.justify); expect(text3.softWrap, false); expect(text3.overflow, TextOverflow.fade); expect(text3.maxLines, 3); expect(text2.textWidthBasis, TextWidthBasis.longestLine); expect(text2.textHeightBehavior, const ui.TextHeightBehavior(applyHeightToFirstAscent: false)); }); }
flutter/packages/flutter/test/widgets/default_text_style_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/default_text_style_test.dart", "repo_id": "flutter", "token_count": 1454 }
696
// 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 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'two_dimensional_utils.dart'; Finder findKey(int i) => find.byKey(ValueKey<int>(i), skipOffstage: false); Widget buildSingleChildScrollView(Axis scrollDirection, { bool reverse = false }) { return Directionality( textDirection: TextDirection.ltr, child: Center( child: SizedBox( width: 600.0, height: 400.0, child: SingleChildScrollView( scrollDirection: scrollDirection, reverse: reverse, child: ListBody( mainAxis: scrollDirection, children: const <Widget>[ SizedBox(key: ValueKey<int>(0), width: 200.0, height: 200.0), SizedBox(key: ValueKey<int>(1), width: 200.0, height: 200.0), SizedBox(key: ValueKey<int>(2), width: 200.0, height: 200.0), SizedBox(key: ValueKey<int>(3), width: 200.0, height: 200.0), SizedBox(key: ValueKey<int>(4), width: 200.0, height: 200.0), SizedBox(key: ValueKey<int>(5), width: 200.0, height: 200.0), SizedBox(key: ValueKey<int>(6), width: 200.0, height: 200.0), ], ), ), ), ), ); } Widget buildListView(Axis scrollDirection, { bool reverse = false, bool shrinkWrap = false }) { return Directionality( textDirection: TextDirection.ltr, child: Center( child: SizedBox( width: 600.0, height: 400.0, child: ListView( scrollDirection: scrollDirection, reverse: reverse, addSemanticIndexes: false, shrinkWrap: shrinkWrap, children: const <Widget>[ SizedBox(key: ValueKey<int>(0), width: 200.0, height: 200.0), SizedBox(key: ValueKey<int>(1), width: 200.0, height: 200.0), SizedBox(key: ValueKey<int>(2), width: 200.0, height: 200.0), SizedBox(key: ValueKey<int>(3), width: 200.0, height: 200.0), SizedBox(key: ValueKey<int>(4), width: 200.0, height: 200.0), SizedBox(key: ValueKey<int>(5), width: 200.0, height: 200.0), SizedBox(key: ValueKey<int>(6), width: 200.0, height: 200.0), ], ), ), ), ); } void main() { group('SingleChildScrollView', () { testWidgets('SingleChildScrollView ensureVisible Axis.vertical', (WidgetTester tester) async { BuildContext findContext(int i) => tester.element(findKey(i)); await tester.pumpWidget(buildSingleChildScrollView(Axis.vertical)); Scrollable.ensureVisible(findContext(3)); await tester.pump(); expect(tester.getTopLeft(findKey(3)).dy, equals(100.0)); Scrollable.ensureVisible(findContext(6)); await tester.pump(); expect(tester.getTopLeft(findKey(6)).dy, equals(300.0)); Scrollable.ensureVisible(findContext(4), alignment: 1.0); await tester.pump(); expect(tester.getBottomRight(findKey(4)).dy, equals(500.0)); Scrollable.ensureVisible(findContext(0), alignment: 1.0); await tester.pump(); expect(tester.getTopLeft(findKey(0)).dy, equals(100.0)); Scrollable.ensureVisible(findContext(3), duration: const Duration(seconds: 1)); await tester.pump(); await tester.pump(const Duration(milliseconds: 1020)); expect(tester.getTopLeft(findKey(3)).dy, equals(100.0)); }); testWidgets('SingleChildScrollView ensureVisible Axis.horizontal', (WidgetTester tester) async { BuildContext findContext(int i) => tester.element(findKey(i)); await tester.pumpWidget(buildSingleChildScrollView(Axis.horizontal)); Scrollable.ensureVisible(findContext(3)); await tester.pump(); expect(tester.getTopLeft(findKey(3)).dx, equals(100.0)); Scrollable.ensureVisible(findContext(6)); await tester.pump(); expect(tester.getTopLeft(findKey(6)).dx, equals(500.0)); Scrollable.ensureVisible(findContext(4), alignment: 1.0); await tester.pump(); expect(tester.getBottomRight(findKey(4)).dx, equals(700.0)); Scrollable.ensureVisible(findContext(0), alignment: 1.0); await tester.pump(); expect(tester.getTopLeft(findKey(0)).dx, equals(100.0)); Scrollable.ensureVisible(findContext(3), duration: const Duration(seconds: 1)); await tester.pump(); await tester.pump(const Duration(milliseconds: 1020)); expect(tester.getTopLeft(findKey(3)).dx, equals(100.0)); }); testWidgets('SingleChildScrollView ensureVisible Axis.vertical reverse', (WidgetTester tester) async { BuildContext findContext(int i) => tester.element(findKey(i)); await tester.pumpWidget(buildSingleChildScrollView(Axis.vertical, reverse: true)); Scrollable.ensureVisible(findContext(3)); await tester.pump(); expect(tester.getBottomRight(findKey(3)).dy, equals(500.0)); Scrollable.ensureVisible(findContext(0)); await tester.pump(); expect(tester.getBottomRight(findKey(0)).dy, equals(300.0)); Scrollable.ensureVisible(findContext(2), alignment: 1.0); await tester.pump(); expect(tester.getTopLeft(findKey(2)).dy, equals(100.0)); Scrollable.ensureVisible(findContext(6), alignment: 1.0); await tester.pump(); expect(tester.getBottomRight(findKey(6)).dy, equals(500.0)); Scrollable.ensureVisible(findContext(3), duration: const Duration(seconds: 1)); await tester.pump(); await tester.pump(const Duration(milliseconds: 1020)); expect(tester.getBottomRight(findKey(3)).dy, equals(500.0)); // Regression test for https://github.com/flutter/flutter/issues/128749 // Reset to zero position. tester.state<ScrollableState>(find.byType(Scrollable)).position.jumpTo(0.0); await tester.pump(); // 4 is not currently visible as the SingleChildScrollView is contained // within a centered SizedBox. expect(tester.getBottomLeft(findKey(4)).dy, equals(100.0)); expect(tester.getBottomLeft(findKey(6)).dy, equals(500.0)); Scrollable.ensureVisible( findContext(6), alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtStart, ); await tester.pump(); Scrollable.ensureVisible( findContext(5), alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtStart, ); await tester.pump(); // 5 and 6 are already visible beyond the top edge, so no change. expect(tester.getBottomLeft(findKey(4)).dy, equals(100.0)); expect(tester.getBottomLeft(findKey(6)).dy, equals(500.0)); Scrollable.ensureVisible( findContext(4), alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtStart, ); await tester.pump(); // Since it is reversed, 4 should have come into view at the top // edge of the scrollable, matching the alignment expectation. expect(tester.getBottomLeft(findKey(4)).dy, equals(300.0)); expect(tester.getBottomLeft(findKey(6)).dy, equals(700.0)); // Bring 6 back into view at the trailing edge, checking the other // alignment. Scrollable.ensureVisible( findContext(6), alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtEnd, ); await tester.pump(); expect(tester.getBottomLeft(findKey(4)).dy, equals(100.0)); expect(tester.getBottomLeft(findKey(6)).dy, equals(500.0)); }); testWidgets('SingleChildScrollView ensureVisible Axis.horizontal reverse', (WidgetTester tester) async { BuildContext findContext(int i) => tester.element(findKey(i)); await tester.pumpWidget(buildSingleChildScrollView(Axis.horizontal, reverse: true)); Scrollable.ensureVisible(findContext(3)); await tester.pump(); expect(tester.getBottomRight(findKey(3)).dx, equals(700.0)); Scrollable.ensureVisible(findContext(0)); await tester.pump(); expect(tester.getBottomRight(findKey(0)).dx, equals(300.0)); Scrollable.ensureVisible(findContext(2), alignment: 1.0); await tester.pump(); expect(tester.getTopLeft(findKey(2)).dx, equals(100.0)); Scrollable.ensureVisible(findContext(6), alignment: 1.0); await tester.pump(); expect(tester.getBottomRight(findKey(6)).dx, equals(700.0)); Scrollable.ensureVisible(findContext(3), duration: const Duration(seconds: 1)); await tester.pump(); await tester.pump(const Duration(milliseconds: 1020)); expect(tester.getBottomRight(findKey(3)).dx, equals(700.0)); // Regression test for https://github.com/flutter/flutter/issues/128749 // Reset to zero position. tester.state<ScrollableState>(find.byType(Scrollable)).position.jumpTo(0.0); await tester.pump(); // 4 is not currently visible as the SingleChildScrollView is contained // within a centered SizedBox. expect(tester.getBottomLeft(findKey(3)).dx, equals(-100.0)); expect(tester.getBottomLeft(findKey(6)).dx, equals(500.0)); Scrollable.ensureVisible( findContext(6), alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtStart, ); await tester.pump(); Scrollable.ensureVisible( findContext(5), alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtStart, ); await tester.pump(); Scrollable.ensureVisible( findContext(4), alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtStart, ); await tester.pump(); // 4, 5 and 6 are already visible beyond the left edge, so no change. expect(tester.getBottomLeft(findKey(3)).dx, equals(-100.0)); expect(tester.getBottomLeft(findKey(6)).dx, equals(500.0)); Scrollable.ensureVisible( findContext(3), alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtStart, ); await tester.pump(); // Since it is reversed, 3 should have come into view at the leading // edge of the scrollable, matching the alignment expectation. expect(tester.getBottomLeft(findKey(3)).dx, equals(100.0)); expect(tester.getBottomLeft(findKey(6)).dx, equals(700.0)); // Bring 6 back into view at the trailing edge, checking the other // alignment. Scrollable.ensureVisible( findContext(6), alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtEnd, ); await tester.pump(); expect(tester.getBottomLeft(findKey(3)).dx, equals(-100.0)); expect(tester.getBottomLeft(findKey(6)).dx, equals(500.0)); }); testWidgets('SingleChildScrollView ensureVisible rotated child', (WidgetTester tester) async { BuildContext findContext(int i) => tester.element(findKey(i)); await tester.pumpWidget( Center( child: SizedBox( width: 600.0, height: 400.0, child: SingleChildScrollView( child: ListBody( children: <Widget>[ const SizedBox(height: 200.0), const SizedBox(height: 200.0), const SizedBox(height: 200.0), SizedBox( height: 200.0, child: Center( child: Transform( transform: Matrix4.rotationZ(math.pi), child: Container( key: const ValueKey<int>(0), width: 100.0, height: 100.0, color: const Color(0xFFFFFFFF), ), ), ), ), const SizedBox(height: 200.0), const SizedBox(height: 200.0), const SizedBox(height: 200.0), ], ), ), ), ), ); Scrollable.ensureVisible(findContext(0)); await tester.pump(); expect(tester.getBottomRight(findKey(0)).dy, moreOrLessEquals(100.0, epsilon: 0.1)); Scrollable.ensureVisible(findContext(0), alignment: 1.0); await tester.pump(); expect(tester.getTopLeft(findKey(0)).dy, moreOrLessEquals(500.0, epsilon: 0.1)); }); testWidgets('Nested SingleChildScrollView ensureVisible behavior test', (WidgetTester tester) async { // Regressing test for https://github.com/flutter/flutter/issues/65100 Finder findKey(String coordinate) => find.byKey(ValueKey<String>(coordinate)); BuildContext findContext(String coordinate) => tester.element(findKey(coordinate)); final List<Row> rows = List<Row>.generate( 7, (int y) => Row( children: List<SizedBox>.generate( 7, (int x) => SizedBox(key: ValueKey<String>('$x, $y'), width: 200.0, height: 200.0), ), ), ); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Center( child: SizedBox( width: 600.0, height: 400.0, child: SingleChildScrollView( scrollDirection: Axis.horizontal, child: SingleChildScrollView( child: Column( children: rows, ), ), ), ), ), ), ); // Items: 7 * 7 Container(width: 200.0, height: 200.0) // viewport: Size(width: 600.0, height: 400.0) // // 0 600 // +----------------------+ // |0,0 |1,0 |2,0 | // | | | | // +----------------------+ // |0,1 |1,1 |2,1 | // | | | | // 400 +----------------------+ Scrollable.ensureVisible(findContext('0, 0')); await tester.pump(); expect(tester.getTopLeft(findKey('0, 0')), const Offset(100.0, 100.0)); Scrollable.ensureVisible(findContext('3, 0')); await tester.pump(); expect(tester.getTopLeft(findKey('3, 0')), const Offset(100.0, 100.0)); Scrollable.ensureVisible(findContext('3, 0'), alignment: 0.5); await tester.pump(); expect(tester.getTopLeft(findKey('3, 0')), const Offset(300.0, 100.0)); Scrollable.ensureVisible(findContext('6, 0')); await tester.pump(); expect(tester.getTopLeft(findKey('6, 0')), const Offset(500.0, 100.0)); Scrollable.ensureVisible(findContext('0, 2')); await tester.pump(); expect(tester.getTopLeft(findKey('0, 2')), const Offset(100.0, 100.0)); Scrollable.ensureVisible(findContext('3, 2')); await tester.pump(); expect(tester.getTopLeft(findKey('3, 2')), const Offset(100.0, 100.0)); // It should be at the center of the screen. Scrollable.ensureVisible(findContext('3, 2'), alignment: 0.5); await tester.pump(); expect(tester.getTopLeft(findKey('3, 2')), const Offset(300.0, 200.0)); }); }); group('ListView', () { testWidgets('ListView ensureVisible Axis.vertical', (WidgetTester tester) async { BuildContext findContext(int i) => tester.element(findKey(i)); Future<void> prepare(double offset) async { tester.state<ScrollableState>(find.byType(Scrollable)).position.jumpTo(offset); await tester.pump(); } await tester.pumpWidget(buildListView(Axis.vertical)); await prepare(480.0); Scrollable.ensureVisible(findContext(3)); await tester.pump(); expect(tester.getTopLeft(findKey(3)).dy, equals(100.0)); await prepare(1083.0); Scrollable.ensureVisible(findContext(6)); await tester.pump(); expect(tester.getTopLeft(findKey(6)).dy, equals(300.0)); await prepare(735.0); Scrollable.ensureVisible(findContext(4), alignment: 1.0); await tester.pump(); expect(tester.getBottomRight(findKey(4)).dy, equals(500.0)); await prepare(123.0); Scrollable.ensureVisible(findContext(0), alignment: 1.0); await tester.pump(); expect(tester.getTopLeft(findKey(0)).dy, equals(100.0)); await prepare(523.0); Scrollable.ensureVisible(findContext(3), duration: const Duration(seconds: 1)); await tester.pump(); await tester.pump(const Duration(milliseconds: 1020)); expect(tester.getTopLeft(findKey(3)).dy, equals(100.0)); }); testWidgets('ListView ensureVisible Axis.horizontal', (WidgetTester tester) async { BuildContext findContext(int i) => tester.element(findKey(i)); Future<void> prepare(double offset) async { tester.state<ScrollableState>(find.byType(Scrollable)).position.jumpTo(offset); await tester.pump(); } await tester.pumpWidget(buildListView(Axis.horizontal)); await prepare(23.0); Scrollable.ensureVisible(findContext(3)); await tester.pump(); expect(tester.getTopLeft(findKey(3)).dx, equals(100.0)); await prepare(843.0); Scrollable.ensureVisible(findContext(6)); await tester.pump(); expect(tester.getTopLeft(findKey(6)).dx, equals(500.0)); await prepare(415.0); Scrollable.ensureVisible(findContext(4), alignment: 1.0); await tester.pump(); expect(tester.getBottomRight(findKey(4)).dx, equals(700.0)); await prepare(46.0); Scrollable.ensureVisible(findContext(0), alignment: 1.0); await tester.pump(); expect(tester.getTopLeft(findKey(0)).dx, equals(100.0)); await prepare(211.0); Scrollable.ensureVisible(findContext(3), duration: const Duration(seconds: 1)); await tester.pump(); await tester.pump(const Duration(milliseconds: 1020)); expect(tester.getTopLeft(findKey(3)).dx, equals(100.0)); }); testWidgets('ListView ensureVisible Axis.vertical reverse', (WidgetTester tester) async { BuildContext findContext(int i) => tester.element(findKey(i)); Future<void> prepare(double offset) async { tester.state<ScrollableState>(find.byType(Scrollable)).position.jumpTo(offset); await tester.pump(); } await tester.pumpWidget(buildListView(Axis.vertical, reverse: true)); await prepare(211.0); Scrollable.ensureVisible(findContext(3)); await tester.pump(); expect(tester.getBottomRight(findKey(3)).dy, equals(500.0)); await prepare(23.0); Scrollable.ensureVisible(findContext(0)); await tester.pump(); expect(tester.getBottomRight(findKey(0)).dy, equals(500.0)); await prepare(230.0); Scrollable.ensureVisible(findContext(2), alignment: 1.0); await tester.pump(); expect(tester.getTopLeft(findKey(2)).dy, equals(100.0)); await prepare(1083.0); Scrollable.ensureVisible(findContext(6), alignment: 1.0); await tester.pump(); expect(tester.getBottomRight(findKey(6)).dy, equals(300.0)); await prepare(345.0); Scrollable.ensureVisible(findContext(3), duration: const Duration(seconds: 1)); await tester.pump(); await tester.pump(const Duration(milliseconds: 1020)); expect(tester.getBottomRight(findKey(3)).dy, equals(500.0)); // Regression test for https://github.com/flutter/flutter/issues/128749 // Reset to zero position. await prepare(0.0); // 2 is not currently visible as the ListView is contained // within a centered SizedBox. expect(tester.getBottomLeft(findKey(2)).dy, equals(100.0)); expect(tester.getBottomLeft(findKey(0)).dy, equals(500.0)); Scrollable.ensureVisible( findContext(0), alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtStart, ); await tester.pump(); Scrollable.ensureVisible( findContext(1), alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtStart, ); await tester.pump(); // 0 and 1 are already visible beyond the top edge, so no change. expect(tester.getBottomLeft(findKey(2)).dy, equals(100.0)); expect(tester.getBottomLeft(findKey(0)).dy, equals(500.0)); Scrollable.ensureVisible( findContext(2), alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtStart, ); await tester.pump(); // Since it is reversed, 2 should have come into view at the top // edge of the scrollable, matching the alignment expectation. expect(tester.getBottomLeft(findKey(2)).dy, equals(300.0)); expect(tester.getBottomLeft(findKey(0)).dy, equals(700.0)); // Bring 0 back into view at the trailing edge, checking the other // alignment. Scrollable.ensureVisible( findContext(0), alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtEnd, ); await tester.pump(); expect(tester.getBottomLeft(findKey(2)).dy, equals(100.0)); expect(tester.getBottomLeft(findKey(0)).dy, equals(500.0)); }); testWidgets('ListView ensureVisible Axis.horizontal reverse', (WidgetTester tester) async { BuildContext findContext(int i) => tester.element(findKey(i)); Future<void> prepare(double offset) async { tester.state<ScrollableState>(find.byType(Scrollable)).position.jumpTo(offset); await tester.pump(); } await tester.pumpWidget(buildListView(Axis.horizontal, reverse: true)); await prepare(211.0); Scrollable.ensureVisible(findContext(3)); await tester.pump(); expect(tester.getBottomRight(findKey(3)).dx, equals(700.0)); await prepare(23.0); Scrollable.ensureVisible(findContext(0)); await tester.pump(); expect(tester.getBottomRight(findKey(0)).dx, equals(700.0)); await prepare(230.0); Scrollable.ensureVisible(findContext(2), alignment: 1.0); await tester.pump(); expect(tester.getTopLeft(findKey(2)).dx, equals(100.0)); await prepare(1083.0); Scrollable.ensureVisible(findContext(6), alignment: 1.0); await tester.pump(); expect(tester.getBottomRight(findKey(6)).dx, equals(300.0)); await prepare(345.0); Scrollable.ensureVisible(findContext(3), duration: const Duration(seconds: 1)); await tester.pump(); await tester.pump(const Duration(milliseconds: 1020)); expect(tester.getBottomRight(findKey(3)).dx, equals(700.0)); // Regression test for https://github.com/flutter/flutter/issues/128749 // Reset to zero position. await prepare(0.0); // 3 is not currently visible as the ListView is contained // within a centered SizedBox. expect(tester.getBottomLeft(findKey(3)).dx, equals(-100.0)); expect(tester.getBottomLeft(findKey(0)).dx, equals(500.0)); Scrollable.ensureVisible( findContext(0), alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtStart, ); await tester.pump(); Scrollable.ensureVisible( findContext(1), alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtStart, ); await tester.pump(); Scrollable.ensureVisible( findContext(2), alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtStart, ); await tester.pump(); // 0, 1 and 2 are already visible beyond the left edge, so no change. expect(tester.getBottomLeft(findKey(3)).dx, equals(-100.0)); expect(tester.getBottomLeft(findKey(0)).dx, equals(500.0)); Scrollable.ensureVisible( findContext(3), alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtStart, ); await tester.pump(); // Since it is reversed, 3 should have come into view at the leading // edge of the scrollable, matching the alignment expectation. expect(tester.getBottomLeft(findKey(3)).dx, equals(100.0)); expect(tester.getBottomLeft(findKey(0)).dx, equals(700.0)); // Bring 0 back into view at the trailing edge, checking the other // alignment. Scrollable.ensureVisible( findContext(0), alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtEnd, ); await tester.pump(); expect(tester.getBottomLeft(findKey(3)).dx, equals(-100.0)); expect(tester.getBottomLeft(findKey(0)).dx, equals(500.0)); }); testWidgets('ListView ensureVisible negative child', (WidgetTester tester) async { BuildContext findContext(int i) => tester.element(findKey(i)); Future<void> prepare(double offset) async { tester.state<ScrollableState>(find.byType(Scrollable)).position.jumpTo(offset); await tester.pump(); } double getOffset() { return tester.state<ScrollableState>(find.byType(Scrollable)).position.pixels; } Widget buildSliver(int i) { return SliverToBoxAdapter( key: ValueKey<int>(i), child: const SizedBox(width: 200.0, height: 200.0), ); } await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Center( child: SizedBox( width: 600.0, height: 400.0, child: Scrollable( viewportBuilder: (BuildContext context, ViewportOffset offset) { return Viewport( offset: offset, center: const ValueKey<int>(4), slivers: <Widget>[ buildSliver(0), buildSliver(1), buildSliver(2), buildSliver(3), buildSliver(4), buildSliver(5), buildSliver(6), ], ); }, ), ), ), ), ); await prepare(-125.0); Scrollable.ensureVisible(findContext(3)); await tester.pump(); expect(getOffset(), equals(-200.0)); await prepare(-225.0); Scrollable.ensureVisible(findContext(2)); await tester.pump(); expect(getOffset(), equals(-400.0)); }); testWidgets('ListView ensureVisible rotated child', (WidgetTester tester) async { BuildContext findContext(int i) => tester.element(findKey(i)); Future<void> prepare(double offset) async { tester.state<ScrollableState>(find.byType(Scrollable)).position.jumpTo(offset); await tester.pump(); } await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: Center( child: SizedBox( width: 600.0, height: 400.0, child: ListView( children: <Widget>[ const SizedBox(height: 200.0), const SizedBox(height: 200.0), const SizedBox(height: 200.0), SizedBox( height: 200.0, child: Center( child: Transform( transform: Matrix4.rotationZ(math.pi), child: Container( key: const ValueKey<int>(0), width: 100.0, height: 100.0, color: const Color(0xFFFFFFFF), ), ), ), ), const SizedBox(height: 200.0), const SizedBox(height: 200.0), const SizedBox(height: 200.0), ], ), ), ), )); await prepare(321.0); Scrollable.ensureVisible(findContext(0)); await tester.pump(); expect(tester.getBottomRight(findKey(0)).dy, moreOrLessEquals(100.0, epsilon: 0.1)); Scrollable.ensureVisible(findContext(0), alignment: 1.0); await tester.pump(); expect(tester.getTopLeft(findKey(0)).dy, moreOrLessEquals(500.0, epsilon: 0.1)); }); }); group('ListView shrinkWrap', () { testWidgets('ListView ensureVisible Axis.vertical', (WidgetTester tester) async { BuildContext findContext(int i) => tester.element(findKey(i)); Future<void> prepare(double offset) async { tester.state<ScrollableState>(find.byType(Scrollable)).position.jumpTo(offset); await tester.pump(); } await tester.pumpWidget(buildListView(Axis.vertical, shrinkWrap: true)); await prepare(480.0); Scrollable.ensureVisible(findContext(3)); await tester.pump(); expect(tester.getTopLeft(findKey(3)).dy, equals(100.0)); await prepare(1083.0); Scrollable.ensureVisible(findContext(6)); await tester.pump(); expect(tester.getTopLeft(findKey(6)).dy, equals(300.0)); await prepare(735.0); Scrollable.ensureVisible(findContext(4), alignment: 1.0); await tester.pump(); expect(tester.getBottomRight(findKey(4)).dy, equals(500.0)); await prepare(123.0); Scrollable.ensureVisible(findContext(0), alignment: 1.0); await tester.pump(); expect(tester.getTopLeft(findKey(0)).dy, equals(100.0)); await prepare(523.0); Scrollable.ensureVisible(findContext(3), duration: const Duration(seconds: 1)); await tester.pump(); await tester.pump(const Duration(milliseconds: 1020)); expect(tester.getTopLeft(findKey(3)).dy, equals(100.0)); }); testWidgets('ListView ensureVisible Axis.horizontal', (WidgetTester tester) async { BuildContext findContext(int i) => tester.element(findKey(i)); Future<void> prepare(double offset) async { tester.state<ScrollableState>(find.byType(Scrollable)).position.jumpTo(offset); await tester.pump(); } await tester.pumpWidget(buildListView(Axis.horizontal, shrinkWrap: true)); await prepare(23.0); Scrollable.ensureVisible(findContext(3)); await tester.pump(); expect(tester.getTopLeft(findKey(3)).dx, equals(100.0)); await prepare(843.0); Scrollable.ensureVisible(findContext(6)); await tester.pump(); expect(tester.getTopLeft(findKey(6)).dx, equals(500.0)); await prepare(415.0); Scrollable.ensureVisible(findContext(4), alignment: 1.0); await tester.pump(); expect(tester.getBottomRight(findKey(4)).dx, equals(700.0)); await prepare(46.0); Scrollable.ensureVisible(findContext(0), alignment: 1.0); await tester.pump(); expect(tester.getTopLeft(findKey(0)).dx, equals(100.0)); await prepare(211.0); Scrollable.ensureVisible(findContext(3), duration: const Duration(seconds: 1)); await tester.pump(); await tester.pump(const Duration(milliseconds: 1020)); expect(tester.getTopLeft(findKey(3)).dx, equals(100.0)); }); testWidgets('ListView ensureVisible Axis.vertical reverse', (WidgetTester tester) async { BuildContext findContext(int i) => tester.element(findKey(i)); Future<void> prepare(double offset) async { tester.state<ScrollableState>(find.byType(Scrollable)).position.jumpTo(offset); await tester.pump(); } await tester.pumpWidget(buildListView(Axis.vertical, reverse: true, shrinkWrap: true)); await prepare(211.0); Scrollable.ensureVisible(findContext(3)); await tester.pump(); expect(tester.getBottomRight(findKey(3)).dy, equals(500.0)); await prepare(23.0); Scrollable.ensureVisible(findContext(0)); await tester.pump(); expect(tester.getBottomRight(findKey(0)).dy, equals(500.0)); await prepare(230.0); Scrollable.ensureVisible(findContext(2), alignment: 1.0); await tester.pump(); expect(tester.getTopLeft(findKey(2)).dy, equals(100.0)); await prepare(1083.0); Scrollable.ensureVisible(findContext(6), alignment: 1.0); await tester.pump(); expect(tester.getBottomRight(findKey(6)).dy, equals(300.0)); await prepare(345.0); Scrollable.ensureVisible(findContext(3), duration: const Duration(seconds: 1)); await tester.pump(); await tester.pump(const Duration(milliseconds: 1020)); expect(tester.getBottomRight(findKey(3)).dy, equals(500.0)); // Regression test for https://github.com/flutter/flutter/issues/128749 // Reset to zero position. await prepare(0.0); // 2 is not currently visible as the ListView is contained // within a centered SizedBox. expect(tester.getBottomLeft(findKey(2)).dy, equals(100.0)); expect(tester.getBottomLeft(findKey(0)).dy, equals(500.0)); Scrollable.ensureVisible( findContext(0), alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtStart, ); await tester.pump(); Scrollable.ensureVisible( findContext(1), alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtStart, ); await tester.pump(); // 0 and 1 are already visible beyond the top edge, so no change. expect(tester.getBottomLeft(findKey(2)).dy, equals(100.0)); expect(tester.getBottomLeft(findKey(0)).dy, equals(500.0)); Scrollable.ensureVisible( findContext(2), alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtStart, ); await tester.pump(); // Since it is reversed, 2 should have come into view at the top // edge of the scrollable, matching the alignment expectation. expect(tester.getBottomLeft(findKey(2)).dy, equals(300.0)); expect(tester.getBottomLeft(findKey(0)).dy, equals(700.0)); // Bring 0 back into view at the trailing edge, checking the other // alignment. Scrollable.ensureVisible( findContext(0), alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtEnd, ); await tester.pump(); expect(tester.getBottomLeft(findKey(2)).dy, equals(100.0)); expect(tester.getBottomLeft(findKey(0)).dy, equals(500.0)); }); testWidgets('ListView ensureVisible Axis.horizontal reverse', (WidgetTester tester) async { BuildContext findContext(int i) => tester.element(findKey(i)); Future<void> prepare(double offset) async { tester.state<ScrollableState>(find.byType(Scrollable)).position.jumpTo(offset); await tester.pump(); } await tester.pumpWidget(buildListView(Axis.horizontal, reverse: true, shrinkWrap: true)); await prepare(211.0); Scrollable.ensureVisible(findContext(3)); await tester.pump(); expect(tester.getBottomRight(findKey(3)).dx, equals(700.0)); await prepare(23.0); Scrollable.ensureVisible(findContext(0)); await tester.pump(); expect(tester.getBottomRight(findKey(0)).dx, equals(700.0)); await prepare(230.0); Scrollable.ensureVisible(findContext(2), alignment: 1.0); await tester.pump(); expect(tester.getTopLeft(findKey(2)).dx, equals(100.0)); await prepare(1083.0); Scrollable.ensureVisible(findContext(6), alignment: 1.0); await tester.pump(); expect(tester.getBottomRight(findKey(6)).dx, equals(300.0)); await prepare(345.0); Scrollable.ensureVisible(findContext(3), duration: const Duration(seconds: 1)); await tester.pump(); await tester.pump(const Duration(milliseconds: 1020)); expect(tester.getBottomRight(findKey(3)).dx, equals(700.0)); // Regression test for https://github.com/flutter/flutter/issues/128749 // Reset to zero position. await prepare(0.0); // 3 is not currently visible as the ListView is contained // within a centered SizedBox. expect(tester.getBottomLeft(findKey(3)).dx, equals(-100.0)); expect(tester.getBottomLeft(findKey(0)).dx, equals(500.0)); Scrollable.ensureVisible( findContext(0), alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtStart, ); await tester.pump(); Scrollable.ensureVisible( findContext(1), alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtStart, ); await tester.pump(); Scrollable.ensureVisible( findContext(2), alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtStart, ); await tester.pump(); // 0, 1 and 2 are already visible beyond the left edge, so no change. expect(tester.getBottomLeft(findKey(3)).dx, equals(-100.0)); expect(tester.getBottomLeft(findKey(0)).dx, equals(500.0)); Scrollable.ensureVisible( findContext(3), alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtStart, ); await tester.pump(); // Since it is reversed, 3 should have come into view at the leading // edge of the scrollable, matching the alignment expectation. expect(tester.getBottomLeft(findKey(3)).dx, equals(100.0)); expect(tester.getBottomLeft(findKey(0)).dx, equals(700.0)); // Bring 0 back into view at the trailing edge, checking the other // alignment. Scrollable.ensureVisible( findContext(0), alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtEnd, ); await tester.pump(); expect(tester.getBottomLeft(findKey(3)).dx, equals(-100.0)); expect(tester.getBottomLeft(findKey(0)).dx, equals(500.0)); }); }); group('Scrollable with center', () { testWidgets('ensureVisible', (WidgetTester tester) async { BuildContext findContext(int i) => tester.element(findKey(i)); Future<void> prepare(double offset) async { tester.state<ScrollableState>(find.byType(Scrollable)).position.jumpTo(offset); await tester.pump(); } await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Center( child: SizedBox( width: 600.0, height: 400.0, child: Scrollable( viewportBuilder: (BuildContext context, ViewportOffset offset) { return Viewport( offset: offset, center: const ValueKey<String>('center'), slivers: const <Widget>[ SliverToBoxAdapter(child: SizedBox(key: ValueKey<int>(-6), width: 200.0, height: 200.0)), SliverToBoxAdapter(child: SizedBox(key: ValueKey<int>(-5), width: 200.0, height: 200.0)), SliverToBoxAdapter(child: SizedBox(key: ValueKey<int>(-4), width: 200.0, height: 200.0)), SliverToBoxAdapter(child: SizedBox(key: ValueKey<int>(-3), width: 200.0, height: 200.0)), SliverToBoxAdapter(child: SizedBox(key: ValueKey<int>(-2), width: 200.0, height: 200.0)), SliverToBoxAdapter(child: SizedBox(key: ValueKey<int>(-1), width: 200.0, height: 200.0)), SliverToBoxAdapter(key: ValueKey<String>('center'), child: SizedBox(key: ValueKey<int>(0), width: 200.0, height: 200.0)), SliverToBoxAdapter(child: SizedBox(key: ValueKey<int>(1), width: 200.0, height: 200.0)), SliverToBoxAdapter(child: SizedBox(key: ValueKey<int>(2), width: 200.0, height: 200.0)), SliverToBoxAdapter(child: SizedBox(key: ValueKey<int>(3), width: 200.0, height: 200.0)), SliverToBoxAdapter(child: SizedBox(key: ValueKey<int>(4), width: 200.0, height: 200.0)), SliverToBoxAdapter(child: SizedBox(key: ValueKey<int>(5), width: 200.0, height: 200.0)), SliverToBoxAdapter(child: SizedBox(key: ValueKey<int>(6), width: 200.0, height: 200.0)), ], ); }, ), ), ), ), ); await prepare(480.0); Scrollable.ensureVisible(findContext(3)); await tester.pump(); expect(tester.getTopLeft(findKey(3)).dy, equals(100.0)); await prepare(1083.0); Scrollable.ensureVisible(findContext(6)); await tester.pump(); expect(tester.getTopLeft(findKey(6)).dy, equals(300.0)); await prepare(735.0); Scrollable.ensureVisible(findContext(4), alignment: 1.0); await tester.pump(); expect(tester.getBottomRight(findKey(4)).dy, equals(500.0)); await prepare(123.0); Scrollable.ensureVisible(findContext(0), alignment: 1.0); await tester.pump(); expect(tester.getBottomRight(findKey(0)).dy, equals(500.0)); await prepare(523.0); Scrollable.ensureVisible(findContext(3), duration: const Duration(seconds: 1)); await tester.pump(); await tester.pump(const Duration(milliseconds: 1020)); expect(tester.getTopLeft(findKey(3)).dy, equals(100.0)); await prepare(-480.0); Scrollable.ensureVisible(findContext(-3)); await tester.pump(); expect(tester.getTopLeft(findKey(-3)).dy, equals(100.0)); await prepare(-1083.0); Scrollable.ensureVisible(findContext(-6)); await tester.pump(); expect(tester.getTopLeft(findKey(-6)).dy, equals(100.0)); await prepare(-735.0); Scrollable.ensureVisible(findContext(-4), alignment: 1.0); await tester.pump(); expect(tester.getBottomRight(findKey(-4)).dy, equals(500.0)); await prepare(-523.0); Scrollable.ensureVisible(findContext(-3), duration: const Duration(seconds: 1)); await tester.pump(); await tester.pump(const Duration(milliseconds: 1020)); expect(tester.getTopLeft(findKey(-3)).dy, equals(100.0)); }); }); group('TwoDimensionalViewport ensureVisible', () { Finder findKey(ChildVicinity vicinity) { return find.byKey(ValueKey<ChildVicinity>(vicinity)); } BuildContext findContext(WidgetTester tester, ChildVicinity vicinity) { return tester.element(findKey(vicinity)); } testWidgets('Axis.vertical', (WidgetTester tester) async { await tester.pumpWidget(simpleBuilderTest(useCacheExtent: true)); Scrollable.ensureVisible(findContext( tester, const ChildVicinity(xIndex: 0, yIndex: 0)), ); await tester.pump(); expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 0, yIndex: 0))).dy, equals(0.0), ); // (0, 3) is in the cache extent, and will be brought into view next expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 0, yIndex: 3))).dy, equals(600.0), ); Scrollable.ensureVisible(findContext( tester, const ChildVicinity(xIndex: 0, yIndex: 3)), ); await tester.pump(); // Now in view at top edge of viewport expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 0, yIndex: 3))).dy, equals(0.0), ); // If already visible, no change Scrollable.ensureVisible(findContext( tester, const ChildVicinity(xIndex: 0, yIndex: 3)), ); await tester.pump(); expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 0, yIndex: 3))).dy, equals(0.0), ); }); testWidgets('Axis.horizontal', (WidgetTester tester) async { await tester.pumpWidget(simpleBuilderTest(useCacheExtent: true)); Scrollable.ensureVisible(findContext( tester, const ChildVicinity(xIndex: 1, yIndex: 0)), ); await tester.pump(); expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 1, yIndex: 0))).dx, equals(0.0), ); // (5, 0) is now in the cache extent, and will be brought into view next expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 5, yIndex: 0))).dx, equals(800.0), ); Scrollable.ensureVisible(findContext( tester, const ChildVicinity(xIndex: 5, yIndex: 0)), alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtEnd, ); await tester.pump(); // Now in view at trailing edge of viewport expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 5, yIndex: 0))).dx, equals(600.0), ); // If already in position, no change Scrollable.ensureVisible(findContext( tester, const ChildVicinity(xIndex: 5, yIndex: 0)), alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtEnd, ); await tester.pump(); expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 5, yIndex: 0))).dx, equals(600.0), ); }); testWidgets('both axes', (WidgetTester tester) async { await tester.pumpWidget(simpleBuilderTest(useCacheExtent: true)); Scrollable.ensureVisible(findContext( tester, const ChildVicinity(xIndex: 1, yIndex: 1)), ); await tester.pump(); expect( tester.getRect(findKey(const ChildVicinity(xIndex: 1, yIndex: 1))), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), ); // (5, 4) is in the cache extent, and will be brought into view next expect( tester.getRect(findKey(const ChildVicinity(xIndex: 5, yIndex: 4))), const Rect.fromLTRB(800.0, 600.0, 1000.0, 800.0), ); Scrollable.ensureVisible(findContext( tester, const ChildVicinity(xIndex: 5, yIndex: 4)), alignment: 1.0, // Same as ScrollAlignmentPolicy.keepVisibleAtEnd ); await tester.pump(); // Now in view at bottom trailing corner of viewport expect( tester.getRect(findKey(const ChildVicinity(xIndex: 5, yIndex: 4))), const Rect.fromLTRB(600.0, 400.0, 800.0, 600.0), ); // If already visible, no change Scrollable.ensureVisible(findContext( tester, const ChildVicinity(xIndex: 5, yIndex: 4)), alignment: 1.0, ); await tester.pump(); expect( tester.getRect(findKey(const ChildVicinity(xIndex: 5, yIndex: 4))), const Rect.fromLTRB(600.0, 400.0, 800.0, 600.0), ); }); testWidgets('Axis.vertical reverse', (WidgetTester tester) async { await tester.pumpWidget(simpleBuilderTest( verticalDetails: const ScrollableDetails.vertical(reverse: true), useCacheExtent: true, )); expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 0, yIndex: 0))).dy, equals(400.0), ); Scrollable.ensureVisible(findContext( tester, const ChildVicinity(xIndex: 0, yIndex: 0)), ); await tester.pump(); // Already visible so no change. expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 0, yIndex: 0))).dy, equals(400.0), ); // (0, 3) is in the cache extent, and will be brought into view next expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 0, yIndex: 3))).dy, equals(-200.0), ); Scrollable.ensureVisible(findContext( tester, const ChildVicinity(xIndex: 0, yIndex: 3)), ); await tester.pump(); // Now in view at bottom edge of viewport since we are reversed expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 0, yIndex: 3))).dy, equals(400.0), ); // If already visible, no change Scrollable.ensureVisible(findContext( tester, const ChildVicinity(xIndex: 0, yIndex: 3)), ); await tester.pump(); expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 0, yIndex: 3))).dy, equals(400.0), ); }); testWidgets('Axis.horizontal reverse', (WidgetTester tester) async { await tester.pumpWidget(simpleBuilderTest( horizontalDetails: const ScrollableDetails.horizontal(reverse: true), useCacheExtent: true, )); expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 0, yIndex: 0))).dx, equals(600.0), ); Scrollable.ensureVisible(findContext( tester, const ChildVicinity(xIndex: 0, yIndex: 0)), ); await tester.pump(); // Already visible so no change. expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 0, yIndex: 0))).dx, equals(600.0), ); // (4, 0) is in the cache extent, and will be brought into view next expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 4, yIndex: 0))).dx, equals(-200.0), ); Scrollable.ensureVisible(findContext( tester, const ChildVicinity(xIndex: 4, yIndex: 0)), ); await tester.pump(); expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 4, yIndex: 0))).dx, equals(200.0), ); // If already visible, no change Scrollable.ensureVisible(findContext( tester, const ChildVicinity(xIndex: 4, yIndex: 0)), ); await tester.pump(); expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 4, yIndex: 0))).dx, equals(200.0), ); }); testWidgets('both axes reverse', (WidgetTester tester) async { await tester.pumpWidget(simpleBuilderTest( verticalDetails: const ScrollableDetails.vertical(reverse: true), horizontalDetails: const ScrollableDetails.horizontal(reverse: true), useCacheExtent: true, )); Scrollable.ensureVisible(findContext( tester, const ChildVicinity(xIndex: 1, yIndex: 1)), ); await tester.pump(); expect( tester.getRect(findKey(const ChildVicinity(xIndex: 1, yIndex: 1))), const Rect.fromLTRB(600.0, 400.0, 800.0, 600.0), ); // (5, 4) is in the cache extent, and will be brought into view next expect( tester.getRect(findKey(const ChildVicinity(xIndex: 5, yIndex: 4))), const Rect.fromLTRB(-200.0, -200.0, 0.0, 0.0), ); Scrollable.ensureVisible(findContext( tester, const ChildVicinity(xIndex: 5, yIndex: 4)), alignment: 1.0, // Same as ScrollAlignmentPolicy.keepVisibleAtEnd ); await tester.pump(); // Now in view at trailing corner of viewport expect( tester.getRect(findKey(const ChildVicinity(xIndex: 5, yIndex: 4))), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), ); // If already visible, no change Scrollable.ensureVisible(findContext( tester, const ChildVicinity(xIndex: 5, yIndex: 4)), alignment: 1.0, ); await tester.pump(); expect( tester.getRect(findKey(const ChildVicinity(xIndex: 5, yIndex: 4))), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), ); }); }); }
flutter/packages/flutter/test/widgets/ensure_visible_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/ensure_visible_test.dart", "repo_id": "flutter", "token_count": 22420 }
697
// 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('onTap detection with canceled pointer and a drag listener', (WidgetTester tester) async { int detector1TapCount = 0; int detector2TapCount = 0; final Widget widget = GestureDetector( child: Column( children: <Widget>[ GestureDetector( onTap: () { detector1TapCount += 1; }, behavior: HitTestBehavior.opaque, child: const SizedBox(width: 200.0, height: 200.0), ), GestureDetector( onTap: () { detector2TapCount += 1; }, behavior: HitTestBehavior.opaque, child: const SizedBox(width: 200.0, height: 200.0), ), ], ), ); await tester.pumpWidget(widget); // The following pointer event sequence was causing the issue described // in https://github.com/flutter/flutter/issues/12470 by triggering 2 tap // events on the second detector. final TestGesture gesture1 = await tester.startGesture(const Offset(400.0, 10.0)); final TestGesture gesture2 = await tester.startGesture(const Offset(400.0, 210.0)); await gesture1.up(); await gesture2.cancel(); final TestGesture gesture3 = await tester.startGesture(const Offset(400.0, 250.0)); await gesture3.up(); expect(detector1TapCount, 1); expect(detector2TapCount, 1); }); }
flutter/packages/flutter/test/widgets/gesture_disambiguation_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/gesture_disambiguation_test.dart", "repo_id": "flutter", "token_count": 626 }
698
// 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:io'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import '../image_data.dart'; void main() { final MockHttpClient client = MockHttpClient(); testWidgets('Headers', (WidgetTester tester) async { HttpOverrides.runZoned<Future<void>>(() async { await tester.pumpWidget(Image.network( 'https://www.example.com/images/frame.png', headers: const <String, String>{'flutter': 'flutter'}, )); expect(MockHttpHeaders.headers['flutter'], <String>['flutter']); }, createHttpClient: (SecurityContext? _) { return client; }); }, skip: isBrowser); // https://github.com/flutter/flutter/issues/57187 } class MockHttpClient extends Fake implements HttpClient { @override Future<HttpClientRequest> getUrl(Uri url) async { return MockHttpClientRequest(); } @override bool autoUncompress = false; } class MockHttpClientRequest extends Fake implements HttpClientRequest { @override final MockHttpHeaders headers = MockHttpHeaders(); @override Future<HttpClientResponse> close() async { return MockHttpClientResponse(); } } class MockHttpClientResponse extends Fake implements HttpClientResponse { @override int get contentLength => kTransparentImage.length; @override int get statusCode => HttpStatus.ok; @override HttpClientResponseCompressionState get compressionState => HttpClientResponseCompressionState.decompressed; @override StreamSubscription<List<int>> listen(void Function(List<int> event)? onData, {Function? onError, void Function()? onDone, bool? cancelOnError}) { return Stream<List<int>>.fromIterable(<List<int>>[kTransparentImage]).listen( onData, onDone: onDone, onError: onError, cancelOnError: cancelOnError, ); } } class MockHttpHeaders extends Fake implements HttpHeaders { static final Map<String, List<String>> headers = <String, List<String>>{}; @override void add(String key, Object value, { bool preserveHeaderCase = false }) { headers[key] ??= <String>[]; headers[key]!.add(value.toString()); } }
flutter/packages/flutter/test/widgets/image_headers_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/image_headers_test.dart", "repo_id": "flutter", "token_count": 769 }
699
// 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/rendering.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('InvertColors', (WidgetTester tester) async { await tester.pumpWidget(const RepaintBoundary( child: SizedBox( width: 200.0, height: 200.0, child: InvertColorTestWidget( color: Color.fromRGBO(255, 0, 0, 1.0), ), ), )); await expectLater( find.byType(RepaintBoundary), matchesGoldenFile('invert_colors_test.0.png'), ); }); testWidgets('InvertColors and ColorFilter', (WidgetTester tester) async { await tester.pumpWidget(const RepaintBoundary( child: SizedBox( width: 200.0, height: 200.0, child: InvertColorTestWidget( color: Color.fromRGBO(255, 0, 0, 1.0), filter: ColorFilter.mode(Color.fromRGBO(0, 255, 0, 0.5), BlendMode.plus), ), ), )); await expectLater( find.byType(RepaintBoundary), matchesGoldenFile('invert_colors_test.1.png'), ); }); } // Draws a rectangle sized by the parent widget with [color], [colorFilter], // and [invertColors] applied for testing the invert colors. class InvertColorTestWidget extends LeafRenderObjectWidget { const InvertColorTestWidget({ required this.color, this.filter, super.key, }); final Color color; final ColorFilter? filter; @override RenderInvertColorTest createRenderObject(BuildContext context) { return RenderInvertColorTest(color, filter); } @override void updateRenderObject(BuildContext context, covariant RenderInvertColorTest renderObject) { renderObject ..color = color ..filter = filter; } } class RenderInvertColorTest extends RenderProxyBox { RenderInvertColorTest(this._color, this._filter); Color get color => _color; Color _color; set color(Color value) { if (color == value) { return; } _color = value; markNeedsPaint(); } ColorFilter? get filter => _filter; ColorFilter? _filter; set filter(ColorFilter? value) { if (filter == value) { return; } _filter = value; markNeedsPaint(); } @override void paint(PaintingContext context, Offset offset) { final Paint paint = Paint() ..style = PaintingStyle.fill ..color = color ..colorFilter = filter ..invertColors = true; context.canvas.drawRect(offset & size, paint); } }
flutter/packages/flutter/test/widgets/invert_colors_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/invert_colors_test.dart", "repo_id": "flutter", "token_count": 1055 }
700
// 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'; const Key blockKey = Key('test'); void main() { testWidgets('Cannot scroll a non-overflowing block', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListView( key: blockKey, children: const <Widget>[ SizedBox( height: 200.0, // less than 600, the height of the test area child: Text('Hello'), ), ], ), ), ); final Offset middleOfContainer = tester.getCenter(find.text('Hello')); final Offset target = tester.getCenter(find.byKey(blockKey)); final TestGesture gesture = await tester.startGesture(target); await gesture.moveBy(const Offset(0.0, -10.0)); await tester.pump(const Duration(milliseconds: 1)); expect(tester.getCenter(find.text('Hello')) == middleOfContainer, isTrue); await gesture.up(); }); testWidgets('Can scroll an overflowing block', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListView( key: blockKey, children: const <Widget>[ SizedBox( height: 2000.0, // more than 600, the height of the test area child: Text('Hello'), ), ], ), ), ); final Offset middleOfContainer = tester.getCenter(find.text('Hello')); expect(middleOfContainer.dx, equals(400.0)); expect(middleOfContainer.dy, equals(1000.0)); final Offset target = tester.getCenter(find.byKey(blockKey)); final TestGesture gesture = await tester.startGesture(target); await gesture.moveBy(const Offset(0.0, -10.0)); await tester.pump(); // redo layout expect(tester.getCenter(find.text('Hello')), isNot(equals(middleOfContainer))); await gesture.up(); }); testWidgets('ListView reverse', (WidgetTester tester) async { int first = 0; int second = 0; Widget buildBlock({ bool reverse = false }) { return Directionality( textDirection: TextDirection.ltr, child: ListView( key: UniqueKey(), reverse: reverse, children: <Widget>[ GestureDetector( onTap: () { first += 1; }, child: Container( height: 350.0, // more than half the height of the test area color: const Color(0xFF00FF00), ), ), GestureDetector( onTap: () { second += 1; }, child: Container( height: 350.0, // more than half the height of the test area color: const Color(0xFF0000FF), ), ), ], ), ); } await tester.pumpWidget(buildBlock(reverse: true)); const Offset target = Offset(200.0, 200.0); await tester.tapAt(target); expect(first, equals(0)); expect(second, equals(1)); await tester.pumpWidget(buildBlock()); await tester.tapAt(target); expect(first, equals(1)); expect(second, equals(1)); }); testWidgets('ListView controller', (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); Widget buildBlock() { return Directionality( textDirection: TextDirection.ltr, child: ListView( controller: controller, children: const <Widget>[Text('A'), Text('B'), Text('C')], ), ); } await tester.pumpWidget(buildBlock()); expect(controller.offset, equals(0.0)); }); testWidgets('SliverBlockChildListDelegate.estimateMaxScrollOffset hits end', (WidgetTester tester) async { final SliverChildListDelegate delegate = SliverChildListDelegate(<Widget>[ Container(), Container(), Container(), Container(), Container(), ]); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: CustomScrollView( slivers: <Widget>[ SliverList( delegate: delegate, ), ], ), ), ); final SliverMultiBoxAdaptorElement element = tester.element(find.byType(SliverList, skipOffstage: false)); final double maxScrollOffset = element.estimateMaxScrollOffset( null, firstIndex: 3, lastIndex: 4, leadingScrollOffset: 25.0, trailingScrollOffset: 26.0, ); expect(maxScrollOffset, equals(26.0)); }); testWidgets('Resizing a ListView child restores scroll offset', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/9221 final AnimationController controller = AnimationController( vsync: const TestVSync(), duration: const Duration(milliseconds: 200), ); addTearDown(controller.dispose); // The overall height of the frame is (as ever) 600 Widget buildFrame() { return Directionality( textDirection: TextDirection.ltr, child: Column( children: <Widget>[ Flexible( // The overall height of the ListView's contents is 500 child: ListView( children: const <Widget>[ SizedBox( height: 150.0, child: Center( child: Text('top'), ), ), SizedBox( height: 200.0, child: Center( child: Text('middle'), ), ), SizedBox( height: 150.0, child: Center( child: Text('bottom'), ), ), ], ), ), // If this widget's height is > 100 the ListView can scroll. SizeTransition( sizeFactor: controller.view, child: const SizedBox( height: 300.0, child: Text('keyboard'), ), ), ], ), ); } await tester.pumpWidget(buildFrame()); expect(find.text('top'), findsOneWidget); final ScrollPosition position = Scrollable.of(tester.element(find.text('middle'))).position; expect(position.viewportDimension, 600.0); expect(position.pixels, 0.0); // Animate the 'keyboard' height from 0 to 300 controller.forward(); await tester.pumpAndSettle(); expect(position.viewportDimension, 300.0); // Scroll the ListView upwards position.jumpTo(200.0); await tester.pumpAndSettle(); expect(position.pixels, 200.0); expect(find.text('top'), findsNothing); // Animate the 'keyboard' height back to 0. This causes the scroll // offset to return to 0.0 controller.reverse(); await tester.pumpAndSettle(); expect(position.viewportDimension, 600.0); expect(position.pixels, 0.0); expect(find.text('top'), findsOneWidget); }); }
flutter/packages/flutter/test/widgets/list_view_misc_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/list_view_misc_test.dart", "repo_id": "flutter", "token_count": 3299 }
701
// 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'; import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; int _creations = 0; int _disposals = 0; void main() { // LeakTesting is turned off because it adds subscriptions to // [FlutterMemoryAllocations], that may interfere with the tests. LeakTesting.settings = LeakTesting.settings.withIgnoredAll(); final FlutterMemoryAllocations ma = FlutterMemoryAllocations.instance; test('Publishers dispatch events in debug mode', () async { void listener(ObjectEvent event) { if (event is ObjectDisposed) { _disposals++; } if (event is ObjectCreated) { _creations++; } } ma.addListener(listener); final _EventStats actual = await _activateFlutterObjectsAndReturnCountOfEvents(); expect(actual.creations, _creations); expect(actual.disposals, _disposals); ma.removeListener(listener); expect(ma.hasListeners, isFalse); }); testWidgets('State dispatches events in debug mode', (WidgetTester tester) async { bool stateCreated = false; bool stateDisposed = false; expect(ma.hasListeners, false); void listener(ObjectEvent event) { if (event is ObjectCreated && event.object is State) { stateCreated = true; } if (event is ObjectDisposed && event.object is State) { stateDisposed = true; } } ma.addListener(listener); await tester.pumpWidget(const _TestStatefulWidget()); expect(stateCreated, isTrue); expect(stateDisposed, isFalse); await tester.pumpWidget(const SizedBox.shrink()); expect(stateCreated, isTrue); expect(stateDisposed, isTrue); ma.removeListener(listener); expect(ma.hasListeners, false); }); } class _TestLeafRenderObjectWidget extends LeafRenderObjectWidget { @override RenderObject createRenderObject(BuildContext context) { return _TestRenderObject(); } } class _TestElement extends RenderObjectElement with RootElementMixin { _TestElement(): super(_TestLeafRenderObjectWidget()); void makeInactive() { final FocusManager newFocusManager = FocusManager(); assignOwner(BuildOwner(focusManager: newFocusManager)); mount(null, null); deactivate(); } @override void insertRenderObjectChild(covariant RenderObject child, covariant Object? slot) { } @override void moveRenderObjectChild(covariant RenderObject child, covariant Object? oldSlot, covariant Object? newSlot) { } @override void removeRenderObjectChild(covariant RenderObject child, covariant Object? slot) { } } class _TestRenderObject extends RenderObject { @override void debugAssertDoesMeetConstraints() {} @override Rect get paintBounds => throw UnimplementedError(); @override void performLayout() {} @override void performResize() {} @override Rect get semanticBounds => throw UnimplementedError(); } class _TestStatefulWidget extends StatefulWidget { const _TestStatefulWidget(); @override State<_TestStatefulWidget> createState() => _TestStatefulWidgetState(); } class _TestStatefulWidgetState extends State<_TestStatefulWidget> { @override Widget build(BuildContext context) { return Container(); } } class _EventStats { int creations = 0; int disposals = 0; } /// Create and dispose Flutter objects to fire memory allocation events. Future<_EventStats> _activateFlutterObjectsAndReturnCountOfEvents() async { final _EventStats result = _EventStats(); final _TestElement element = _TestElement(); result.creations++; final RenderObject renderObject = _TestRenderObject(); result.creations++; element.makeInactive(); result.creations += 4; // 1 for the new BuildOwner, 1 for the new FocusManager, 1 for the new FocusScopeNode, 1 for the new _HighlightModeManager element.unmount(); result.disposals += 2; // 1 for the old BuildOwner, 1 for the element renderObject.dispose(); result.disposals += 1; return result; }
flutter/packages/flutter/test/widgets/memory_allocations_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/memory_allocations_test.dart", "repo_id": "flutter", "token_count": 1329 }
702
// 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:typed_data'; import 'dart:ui' as ui show Image; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; import '../image_data.dart'; import '../painting/fake_codec.dart'; import '../painting/fake_image_provider.dart'; Future<void> main() async { final FakeCodec fakeCodec = await FakeCodec.fromData(Uint8List.fromList(kAnimatedGif)); final FakeImageProvider fakeImageProvider = FakeImageProvider(fakeCodec); testWidgets('Obscured image does not animate', (WidgetTester tester) async { final GlobalKey imageKey = GlobalKey(); await tester.pumpWidget( MaterialApp( home: Image(image: fakeImageProvider, excludeFromSemantics: true, key: imageKey), routes: <String, WidgetBuilder>{ '/page': (BuildContext context) => Container(), }, ), ); final RenderImage renderImage = tester.renderObject(find.byType(Image)); final ui.Image? image1 = renderImage.image; await tester.pump(const Duration(milliseconds: 100)); final ui.Image? image2 = renderImage.image; expect(image1, isNot(same(image2))); Navigator.pushNamed(imageKey.currentContext!, '/page'); await tester.pump(); // Starts the page animation. await tester.pump(const Duration(seconds: 1)); // Let the page animation complete. // The image is now obscured by another page, it should not be changing // frames. final ui.Image? image3 = renderImage.image; await tester.pump(const Duration(milliseconds: 100)); final ui.Image? image4 = renderImage.image; expect(image3, same(image4)); }); }
flutter/packages/flutter/test/widgets/obscured_animated_image_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/obscured_animated_image_test.dart", "repo_id": "flutter", "token_count": 625 }
703
// 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 'test_widgets.dart'; class TestParentData { TestParentData({ this.top, this.right, this.bottom, this.left }); final double? top; final double? right; final double? bottom; final double? left; } void checkTree(WidgetTester tester, List<TestParentData> expectedParentData) { final MultiChildRenderObjectElement element = tester.element( find.byElementPredicate((Element element) => element is MultiChildRenderObjectElement), ); expect(element, isNotNull); expect(element.renderObject, isA<RenderStack>()); final RenderStack renderObject = element.renderObject as RenderStack; try { RenderObject? child = renderObject.firstChild; for (final TestParentData expected in expectedParentData) { expect(child, isA<RenderDecoratedBox>()); final RenderDecoratedBox decoratedBox = child! as RenderDecoratedBox; expect(decoratedBox.parentData, isA<StackParentData>()); final StackParentData parentData = decoratedBox.parentData! as StackParentData; expect(parentData.top, equals(expected.top)); expect(parentData.right, equals(expected.right)); expect(parentData.bottom, equals(expected.bottom)); expect(parentData.left, equals(expected.left)); final StackParentData? decoratedBoxParentData = decoratedBox.parentData as StackParentData?; child = decoratedBoxParentData?.nextSibling; } expect(child, isNull); } catch (e) { debugPrint(renderObject.toStringDeep()); rethrow; } } final TestParentData kNonPositioned = TestParentData(); void main() { testWidgets('ParentDataWidget control test', (WidgetTester tester) async { await tester.pumpWidget( const Stack( textDirection: TextDirection.ltr, children: <Widget>[ DecoratedBox(decoration: kBoxDecorationA), Positioned( top: 10.0, left: 10.0, child: DecoratedBox(decoration: kBoxDecorationB), ), DecoratedBox(decoration: kBoxDecorationC), ], ), ); checkTree(tester, <TestParentData>[ kNonPositioned, TestParentData(top: 10.0, left: 10.0), kNonPositioned, ]); await tester.pumpWidget( const Stack( textDirection: TextDirection.ltr, children: <Widget>[ Positioned( bottom: 5.0, right: 7.0, child: DecoratedBox(decoration: kBoxDecorationA), ), Positioned( top: 10.0, left: 10.0, child: DecoratedBox(decoration: kBoxDecorationB), ), DecoratedBox(decoration: kBoxDecorationC), ], ), ); checkTree(tester, <TestParentData>[ TestParentData(bottom: 5.0, right: 7.0), TestParentData(top: 10.0, left: 10.0), kNonPositioned, ]); const DecoratedBox kDecoratedBoxA = DecoratedBox(decoration: kBoxDecorationA); const DecoratedBox kDecoratedBoxB = DecoratedBox(decoration: kBoxDecorationB); const DecoratedBox kDecoratedBoxC = DecoratedBox(decoration: kBoxDecorationC); await tester.pumpWidget( const Stack( textDirection: TextDirection.ltr, children: <Widget>[ Positioned( bottom: 5.0, right: 7.0, child: kDecoratedBoxA, ), Positioned( top: 10.0, left: 10.0, child: kDecoratedBoxB, ), kDecoratedBoxC, ], ), ); checkTree(tester, <TestParentData>[ TestParentData(bottom: 5.0, right: 7.0), TestParentData(top: 10.0, left: 10.0), kNonPositioned, ]); await tester.pumpWidget( const Stack( textDirection: TextDirection.ltr, children: <Widget>[ Positioned( bottom: 6.0, right: 8.0, child: kDecoratedBoxA, ), Positioned( left: 10.0, right: 10.0, child: kDecoratedBoxB, ), kDecoratedBoxC, ], ), ); checkTree(tester, <TestParentData>[ TestParentData(bottom: 6.0, right: 8.0), TestParentData(left: 10.0, right: 10.0), kNonPositioned, ]); await tester.pumpWidget( Stack( textDirection: TextDirection.ltr, children: <Widget>[ kDecoratedBoxA, Positioned( left: 11.0, right: 12.0, child: Container(child: kDecoratedBoxB), ), kDecoratedBoxC, ], ), ); checkTree(tester, <TestParentData>[ kNonPositioned, TestParentData(left: 11.0, right: 12.0), kNonPositioned, ]); await tester.pumpWidget( Stack( textDirection: TextDirection.ltr, children: <Widget>[ kDecoratedBoxA, Positioned( right: 10.0, child: Container(child: kDecoratedBoxB), ), const DummyWidget( child: Positioned( top: 8.0, child: kDecoratedBoxC, ), ), ], ), ); checkTree(tester, <TestParentData>[ kNonPositioned, TestParentData(right: 10.0), TestParentData(top: 8.0), ]); await tester.pumpWidget( const Stack( textDirection: TextDirection.ltr, children: <Widget>[ Positioned( right: 10.0, child: FlipWidget(left: kDecoratedBoxA, right: kDecoratedBoxB), ), ], ), ); checkTree(tester, <TestParentData>[ TestParentData(right: 10.0), ]); flipStatefulWidget(tester); await tester.pump(); checkTree(tester, <TestParentData>[ TestParentData(right: 10.0), ]); await tester.pumpWidget( const Stack( textDirection: TextDirection.ltr, children: <Widget>[ Positioned( top: 7.0, child: FlipWidget(left: kDecoratedBoxA, right: kDecoratedBoxB), ), ], ), ); checkTree(tester, <TestParentData>[ TestParentData(top: 7.0), ]); flipStatefulWidget(tester); await tester.pump(); checkTree(tester, <TestParentData>[ TestParentData(top: 7.0), ]); await tester.pumpWidget( const Stack(textDirection: TextDirection.ltr), ); checkTree(tester, <TestParentData>[]); }); testWidgets('ParentData overwrite with custom ParentDataWidget subclasses', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ CustomPositionedWidget( bottom: 8.0, child: Positioned( top: 6.0, left: 7.0, child: DecoratedBox(decoration: kBoxDecorationB), ), ), ], ), ), ); dynamic exception = tester.takeException(); expect(exception, isFlutterError); expect( exception.toString(), startsWith( 'Incorrect use of ParentDataWidget.\n' 'Competing ParentDataWidgets are providing parent data to the same RenderObject:\n' '- Positioned(left: 7.0, top: 6.0), which writes ParentData of type ' 'StackParentData, (typically placed directly inside a Stack widget)\n' '- CustomPositionedWidget, which writes ParentData of type ' 'StackParentData, (typically placed directly inside a Stack widget)\n' 'A RenderObject can receive parent data from multiple ' 'ParentDataWidgets, but the Type of ParentData must be unique to ' 'prevent one overwriting another.\n' 'Usually, this indicates that one or more of the offending ParentDataWidgets listed ' "above isn't placed inside a dedicated compatible ancestor widget that it isn't " 'sharing with another ParentDataWidget of the same type.\n' 'Otherwise, separating aspects of ParentData to prevent conflicts can ' 'be done using mixins, mixing them all in on the full ParentData ' 'Object, such as KeepAlive does with KeepAliveParentDataMixin.\n' 'The ownership chain for the RenderObject that received the parent data was:\n' ' DecoratedBox ← Positioned ← CustomPositionedWidget ← Stack ← Directionality ← ', // End of chain omitted, not relevant for test. ), ); await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ SubclassPositioned( bottom: 8.0, child: Positioned( top: 6.0, left: 7.0, child: DecoratedBox(decoration: kBoxDecorationB), ), ), ], ), ), ); exception = tester.takeException(); expect(exception, isFlutterError); expect( exception.toString(), startsWith( 'Incorrect use of ParentDataWidget.\n' 'Competing ParentDataWidgets are providing parent data to the same RenderObject:\n' '- Positioned(left: 7.0, top: 6.0), which writes ParentData of type ' 'StackParentData, (typically placed directly inside a Stack widget)\n' '- SubclassPositioned(bottom: 8.0), which writes ParentData of type ' 'StackParentData, (typically placed directly inside a Stack widget)\n' 'A RenderObject can receive parent data from multiple ' 'ParentDataWidgets, but the Type of ParentData must be unique to ' 'prevent one overwriting another.\n' 'Usually, this indicates that one or more of the offending ParentDataWidgets listed ' "above isn't placed inside a dedicated compatible ancestor widget that it isn't " 'sharing with another ParentDataWidget of the same type.\n' 'Otherwise, separating aspects of ParentData to prevent conflicts can ' 'be done using mixins, mixing them all in on the full ParentData ' 'Object, such as KeepAlive does with KeepAliveParentDataMixin.\n' 'The ownership chain for the RenderObject that received the parent data was:\n' ' DecoratedBox ← Positioned ← SubclassPositioned ← Stack ← Directionality ← ', // End of chain omitted, not relevant for test. ), ); }); testWidgets('ParentDataWidget conflicting data', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Positioned( top: 5.0, bottom: 8.0, child: Positioned( top: 6.0, left: 7.0, child: DecoratedBox(decoration: kBoxDecorationB), ), ), ], ), ), ); dynamic exception = tester.takeException(); expect(exception, isFlutterError); expect( exception.toString(), startsWith( 'Incorrect use of ParentDataWidget.\n' 'Competing ParentDataWidgets are providing parent data to the same RenderObject:\n' '- Positioned(left: 7.0, top: 6.0), which writes ParentData of type ' 'StackParentData, (typically placed directly inside a Stack widget)\n' '- Positioned(top: 5.0, bottom: 8.0), which writes ParentData of type ' 'StackParentData, (typically placed directly inside a Stack widget)\n' 'A RenderObject can receive parent data from multiple ' 'ParentDataWidgets, but the Type of ParentData must be unique to ' 'prevent one overwriting another.\n' 'Usually, this indicates that one or more of the offending ParentDataWidgets listed ' "above isn't placed inside a dedicated compatible ancestor widget that it isn't " 'sharing with another ParentDataWidget of the same type.\n' 'Otherwise, separating aspects of ParentData to prevent conflicts can ' 'be done using mixins, mixing them all in on the full ParentData ' 'Object, such as KeepAlive does with KeepAliveParentDataMixin.\n' 'The ownership chain for the RenderObject that received the parent data was:\n' ' DecoratedBox ← Positioned ← Positioned ← Stack ← Directionality ← ', // End of chain omitted, not relevant for test. ), ); await tester.pumpWidget(const Stack(textDirection: TextDirection.ltr)); checkTree(tester, <TestParentData>[]); await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: DummyWidget( child: Row( children: <Widget>[ Positioned( top: 6.0, left: 7.0, child: DecoratedBox(decoration: kBoxDecorationB), ), ], ), ), ), ); exception = tester.takeException(); expect(exception, isFlutterError); expect( exception.toString(), startsWith( 'Incorrect use of ParentDataWidget.\n' 'The ParentDataWidget Positioned(left: 7.0, top: 6.0) wants to apply ParentData of type ' 'StackParentData to a RenderObject, which has been set up to accept ParentData of ' 'incompatible type FlexParentData.\n' 'Usually, this means that the Positioned widget has the wrong ancestor RenderObjectWidget. ' 'Typically, Positioned widgets are placed directly inside Stack widgets.\n' 'The offending Positioned is currently placed inside a Row widget.\n' 'The ownership chain for the RenderObject that received the incompatible parent data was:\n' ' DecoratedBox ← Positioned ← Row ← DummyWidget ← Directionality ← ', // End of chain omitted, not relevant for test. ), ); await tester.pumpWidget( const Stack(textDirection: TextDirection.ltr), ); checkTree(tester, <TestParentData>[]); }); testWidgets('ParentDataWidget interacts with global keys', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); await tester.pumpWidget( Stack( textDirection: TextDirection.ltr, children: <Widget>[ Positioned( top: 10.0, left: 10.0, child: DecoratedBox(key: key, decoration: kBoxDecorationA), ), ], ), ); checkTree(tester, <TestParentData>[ TestParentData(top: 10.0, left: 10.0), ]); await tester.pumpWidget( Stack( textDirection: TextDirection.ltr, children: <Widget>[ Positioned( top: 10.0, left: 10.0, child: DecoratedBox( decoration: kBoxDecorationB, child: DecoratedBox(key: key, decoration: kBoxDecorationA), ), ), ], ), ); checkTree(tester, <TestParentData>[ TestParentData(top: 10.0, left: 10.0), ]); await tester.pumpWidget( Stack( textDirection: TextDirection.ltr, children: <Widget>[ Positioned( top: 10.0, left: 10.0, child: DecoratedBox(key: key, decoration: kBoxDecorationA), ), ], ), ); checkTree(tester, <TestParentData>[ TestParentData(top: 10.0, left: 10.0), ]); }); testWidgets('Parent data invalid ancestor', (WidgetTester tester) async { await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: Row( children: <Widget>[ Stack( textDirection: TextDirection.ltr, children: <Widget>[ Expanded( child: Container(), ), ], ), ], ), )); final dynamic exception = tester.takeException(); expect(exception, isFlutterError); expect( exception.toString(), startsWith( 'Incorrect use of ParentDataWidget.\n' 'The ParentDataWidget Expanded(flex: 1) wants to apply ParentData of type ' 'FlexParentData to a RenderObject, which has been set up to accept ParentData of ' 'incompatible type StackParentData.\n' 'Usually, this means that the Expanded widget has the wrong ancestor RenderObjectWidget. ' 'Typically, Expanded widgets are placed directly inside Flex widgets.\n' 'The offending Expanded is currently placed inside a Stack widget.\n' 'The ownership chain for the RenderObject that received the incompatible parent data was:\n' ' LimitedBox ← Container ← Expanded ← Stack ← Row ← Directionality ← ', // Omitted end of debugCreator chain because it's irrelevant for test. ), ); }); testWidgets('ParentDataWidget can be used with different ancestor RenderObjectWidgets', (WidgetTester tester) async { await tester.pumpWidget( OneAncestorWidget( child: Container(), ), ); DummyParentData parentData = tester.renderObject(find.byType(Container)).parentData! as DummyParentData; expect(parentData.string, isNull); await tester.pumpWidget( OneAncestorWidget( child: TestParentDataWidget( string: 'Foo', child: Container(), ), ), ); parentData = tester.renderObject(find.byType(Container)).parentData! as DummyParentData; expect(parentData.string, 'Foo'); await tester.pumpWidget( AnotherAncestorWidget( child: TestParentDataWidget( string: 'Bar', child: Container(), ), ), ); parentData = tester.renderObject(find.byType(Container)).parentData! as DummyParentData; expect(parentData.string, 'Bar'); }); } class SubclassPositioned extends Positioned { const SubclassPositioned({ super.key, super.left, super.top, super.right, super.bottom, super.width, super.height, required super.child, }); @override void applyParentData(RenderObject renderObject) { assert(renderObject.parentData is StackParentData); final StackParentData parentData = renderObject.parentData! as StackParentData; parentData.bottom = bottom; } } class CustomPositionedWidget extends ParentDataWidget<StackParentData> { const CustomPositionedWidget({ super.key, required this.bottom, required super.child, }); final double bottom; @override void applyParentData(RenderObject renderObject) { assert(renderObject.parentData is StackParentData); final StackParentData parentData = renderObject.parentData! as StackParentData; parentData.bottom = bottom; } @override Type get debugTypicalAncestorWidgetClass => Stack; } class TestParentDataWidget extends ParentDataWidget<DummyParentData> { const TestParentDataWidget({ super.key, required this.string, required super.child, }); final String string; @override void applyParentData(RenderObject renderObject) { assert(renderObject.parentData is DummyParentData); final DummyParentData parentData = renderObject.parentData! as DummyParentData; parentData.string = string; } @override Type get debugTypicalAncestorWidgetClass => OneAncestorWidget; } class DummyParentData extends ParentData { String? string; } class OneAncestorWidget extends SingleChildRenderObjectWidget { const OneAncestorWidget({ super.key, required Widget super.child, }); @override RenderOne createRenderObject(BuildContext context) => RenderOne(); } class AnotherAncestorWidget extends SingleChildRenderObjectWidget { const AnotherAncestorWidget({ super.key, required Widget super.child, }); @override RenderAnother createRenderObject(BuildContext context) => RenderAnother(); } class RenderOne extends RenderProxyBox { @override void setupParentData(RenderBox child) { if (child.parentData is! DummyParentData) { child.parentData = DummyParentData(); } } } class RenderAnother extends RenderProxyBox { @override void setupParentData(RenderBox child) { if (child.parentData is! DummyParentData) { child.parentData = DummyParentData(); } } } class DummyWidget extends StatelessWidget { const DummyWidget({ super.key, required this.child }); final Widget child; @override Widget build(BuildContext context) => child; }
flutter/packages/flutter/test/widgets/parent_data_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/parent_data_test.dart", "repo_id": "flutter", "token_count": 8611 }
704
// 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'; class StateMarker extends StatefulWidget { const StateMarker({ super.key, this.child }); final Widget? child; @override StateMarkerState createState() => StateMarkerState(); } class StateMarkerState extends State<StateMarker> { String? marker; @override Widget build(BuildContext context) { return widget.child ?? Container(); } } class DeactivateLogger extends StatefulWidget { const DeactivateLogger({ required Key key, required this.log }) : super(key: key); final List<String> log; @override DeactivateLoggerState createState() => DeactivateLoggerState(); } class DeactivateLoggerState extends State<DeactivateLogger> { @override void deactivate() { widget.log.add('deactivate'); super.deactivate(); } @override Widget build(BuildContext context) { widget.log.add('build'); return Container(); } } void main() { testWidgets('can reparent state', (WidgetTester tester) async { final GlobalKey left = GlobalKey(); final GlobalKey right = GlobalKey(); const StateMarker grandchild = StateMarker(); await tester.pumpWidget( Stack( textDirection: TextDirection.ltr, children: <Widget>[ ColoredBox( color: Colors.green, child: StateMarker(key: left), ), ColoredBox( color: Colors.green, child: StateMarker( key: right, child: grandchild, ), ), ], ), ); final StateMarkerState leftState = left.currentState! as StateMarkerState; leftState.marker = 'left'; final StateMarkerState rightState = right.currentState! as StateMarkerState; rightState.marker = 'right'; final StateMarkerState grandchildState = tester.state(find.byWidget(grandchild)); expect(grandchildState, isNotNull); grandchildState.marker = 'grandchild'; const StateMarker newGrandchild = StateMarker(); await tester.pumpWidget( Stack( textDirection: TextDirection.ltr, children: <Widget>[ ColoredBox( color: Colors.green, child: StateMarker( key: right, child: newGrandchild, ), ), ColoredBox( color: Colors.green, child: StateMarker(key: left), ), ], ), ); expect(left.currentState, equals(leftState)); expect(leftState.marker, equals('left')); expect(right.currentState, equals(rightState)); expect(rightState.marker, equals('right')); final StateMarkerState newGrandchildState = tester.state(find.byWidget(newGrandchild)); expect(newGrandchildState, isNotNull); expect(newGrandchildState, equals(grandchildState)); expect(newGrandchildState.marker, equals('grandchild')); await tester.pumpWidget( Center( child: ColoredBox( color: Colors.green, child: StateMarker( key: left, child: Container(), ), ), ), ); expect(left.currentState, equals(leftState)); expect(leftState.marker, equals('left')); expect(right.currentState, isNull); }); testWidgets('can reparent state with multichild widgets', (WidgetTester tester) async { final GlobalKey left = GlobalKey(); final GlobalKey right = GlobalKey(); const StateMarker grandchild = StateMarker(); await tester.pumpWidget( Stack( textDirection: TextDirection.ltr, children: <Widget>[ StateMarker(key: left), StateMarker( key: right, child: grandchild, ), ], ), ); final StateMarkerState leftState = left.currentState! as StateMarkerState; leftState.marker = 'left'; final StateMarkerState rightState = right.currentState! as StateMarkerState; rightState.marker = 'right'; final StateMarkerState grandchildState = tester.state(find.byWidget(grandchild)); expect(grandchildState, isNotNull); grandchildState.marker = 'grandchild'; const StateMarker newGrandchild = StateMarker(); await tester.pumpWidget( Stack( textDirection: TextDirection.ltr, children: <Widget>[ StateMarker( key: right, child: newGrandchild, ), StateMarker(key: left), ], ), ); expect(left.currentState, equals(leftState)); expect(leftState.marker, equals('left')); expect(right.currentState, equals(rightState)); expect(rightState.marker, equals('right')); final StateMarkerState newGrandchildState = tester.state(find.byWidget(newGrandchild)); expect(newGrandchildState, isNotNull); expect(newGrandchildState, equals(grandchildState)); expect(newGrandchildState.marker, equals('grandchild')); await tester.pumpWidget( Center( child: ColoredBox( color: Colors.green, child: StateMarker( key: left, child: Container(), ), ), ), ); expect(left.currentState, equals(leftState)); expect(leftState.marker, equals('left')); expect(right.currentState, isNull); }); testWidgets('can with scrollable list', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); await tester.pumpWidget(StateMarker(key: key)); final StateMarkerState keyState = key.currentState! as StateMarkerState; keyState.marker = 'marked'; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListView( itemExtent: 100.0, children: <Widget>[ SizedBox( key: const Key('container'), height: 100.0, child: StateMarker(key: key), ), ], ), ), ); expect(key.currentState, equals(keyState)); expect(keyState.marker, equals('marked')); await tester.pumpWidget(StateMarker(key: key)); expect(key.currentState, equals(keyState)); expect(keyState.marker, equals('marked')); }); testWidgets('Reparent during update children', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); await tester.pumpWidget(Stack( textDirection: TextDirection.ltr, children: <Widget>[ StateMarker(key: key), const SizedBox(width: 100.0, height: 100.0), ], )); final StateMarkerState keyState = key.currentState!as StateMarkerState; keyState.marker = 'marked'; await tester.pumpWidget(Stack( textDirection: TextDirection.ltr, children: <Widget>[ const SizedBox(width: 100.0, height: 100.0), StateMarker(key: key), ], )); expect(key.currentState, equals(keyState)); expect(keyState.marker, equals('marked')); await tester.pumpWidget(Stack( textDirection: TextDirection.ltr, children: <Widget>[ StateMarker(key: key), const SizedBox(width: 100.0, height: 100.0), ], )); expect(key.currentState, equals(keyState)); expect(keyState.marker, equals('marked')); }); testWidgets('Reparent to child during update children', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); await tester.pumpWidget(Stack( textDirection: TextDirection.ltr, children: <Widget>[ const SizedBox(width: 100.0, height: 100.0), StateMarker(key: key), const SizedBox(width: 100.0, height: 100.0), ], )); final StateMarkerState keyState = key.currentState! as StateMarkerState; keyState.marker = 'marked'; await tester.pumpWidget(Stack( textDirection: TextDirection.ltr, children: <Widget>[ SizedBox(width: 100.0, height: 100.0, child: StateMarker(key: key)), const SizedBox(width: 100.0, height: 100.0), ], )); expect(key.currentState, equals(keyState)); expect(keyState.marker, equals('marked')); await tester.pumpWidget(Stack( textDirection: TextDirection.ltr, children: <Widget>[ const SizedBox(width: 100.0, height: 100.0), StateMarker(key: key), const SizedBox(width: 100.0, height: 100.0), ], )); expect(key.currentState, equals(keyState)); expect(keyState.marker, equals('marked')); await tester.pumpWidget(Stack( textDirection: TextDirection.ltr, children: <Widget>[ const SizedBox(width: 100.0, height: 100.0), SizedBox(width: 100.0, height: 100.0, child: StateMarker(key: key)), ], )); expect(key.currentState, equals(keyState)); expect(keyState.marker, equals('marked')); await tester.pumpWidget(Stack( textDirection: TextDirection.ltr, children: <Widget>[ const SizedBox(width: 100.0, height: 100.0), StateMarker(key: key), const SizedBox(width: 100.0, height: 100.0), ], )); expect(key.currentState, equals(keyState)); expect(keyState.marker, equals('marked')); }); testWidgets('Deactivate implies build', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); final List<String> log = <String>[]; final DeactivateLogger logger = DeactivateLogger(key: key, log: log); await tester.pumpWidget( Container(key: UniqueKey(), child: logger), ); expect(log, equals(<String>['build'])); await tester.pumpWidget( Container(key: UniqueKey(), child: logger), ); expect(log, equals(<String>['build', 'deactivate', 'build'])); log.clear(); await tester.pump(); expect(log, isEmpty); }); testWidgets('Reparenting with multiple moves', (WidgetTester tester) async { final GlobalKey key1 = GlobalKey(); final GlobalKey key2 = GlobalKey(); final GlobalKey key3 = GlobalKey(); await tester.pumpWidget( Row( textDirection: TextDirection.ltr, children: <Widget>[ StateMarker( key: key1, child: StateMarker( key: key2, child: StateMarker( key: key3, child: StateMarker(child: Container(width: 100.0)), ), ), ), ], ), ); await tester.pumpWidget( Row( textDirection: TextDirection.ltr, children: <Widget>[ StateMarker( key: key2, child: StateMarker(child: Container(width: 100.0)), ), StateMarker( key: key1, child: StateMarker( key: key3, child: StateMarker(child: Container(width: 100.0)), ), ), ], ), ); }); }
flutter/packages/flutter/test/widgets/reparent_state_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/reparent_state_test.dart", "repo_id": "flutter", "token_count": 4621 }
705
// 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:fake_async/fake_async.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; // This test is very fragile and bypasses some zone-related checks. // It is written this way to verify some invariants that would otherwise // be difficult to check. // Do not use this test as a guide for writing good Flutter code. class TestBinding extends WidgetsFlutterBinding { @override void initInstances() { super.initInstances(); _instance = this; } @override bool debugCheckZone(String entryPoint) { return true; } static TestBinding get instance => BindingBase.checkInstance(_instance); static TestBinding? _instance; static TestBinding ensureInitialized() { if (TestBinding._instance == null) { TestBinding(); } return TestBinding.instance; } } void main() { setUp(() { TestBinding.ensureInitialized(); WidgetsBinding.instance.resetEpoch(); }); test('WidgetBinding build rendering tree and warm up frame back to back', () { final FakeAsync fakeAsync = FakeAsync(); fakeAsync.run((FakeAsync async) { runApp( const MaterialApp( home: Material( child: Text('test'), ), ), ); // Rendering tree is not built synchronously. expect(WidgetsBinding.instance.rootElement, isNull); fakeAsync.flushTimers(); expect(WidgetsBinding.instance.rootElement, isNotNull); }); }); }
flutter/packages/flutter/test/widgets/run_app_async_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/run_app_async_test.dart", "repo_id": "flutter", "token_count": 567 }
706
// 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 }
707
// 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 }
708
// 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 }
709
// 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 }
710
// 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'; import 'semantics_tester.dart'; void main() { group('Sliver Semantics', () { setUp(() { debugResetSemanticsIdCounter(); }); _tests(); }); } void _tests() { testWidgets('excludeFromScrollable works correctly', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); const double appBarExpandedHeight = 200.0; final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); final List<Widget> listChildren = List<Widget>.generate(30, (int i) { return SizedBox( height: appBarExpandedHeight, child: Text('Item $i'), ); }); await tester.pumpWidget( Semantics( textDirection: TextDirection.ltr, child: Localizations( locale: const Locale('en', 'us'), delegates: const <LocalizationsDelegate<dynamic>>[ DefaultWidgetsLocalizations.delegate, DefaultMaterialLocalizations.delegate, ], child: Directionality( textDirection: TextDirection.ltr, child: MediaQuery( data: const MediaQueryData(), child: CustomScrollView( controller: scrollController, slivers: <Widget>[ const SliverAppBar( pinned: true, expandedHeight: appBarExpandedHeight, title: Text('Semantics Test with Slivers'), ), SliverList( delegate: SliverChildListDelegate(listChildren), ), ], ), ), ), ), ), ); // AppBar is child of node with semantic scroll actions. expect(semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics( id: 1, textDirection: TextDirection.ltr, children: <TestSemantics>[ TestSemantics( id: 2, children: <TestSemantics>[ TestSemantics( id: 7, children: <TestSemantics>[ TestSemantics( id: 8, flags: <SemanticsFlag>[ SemanticsFlag.namesRoute, SemanticsFlag.isHeader, ], label: 'Semantics Test with Slivers', textDirection: TextDirection.ltr, ), ], ), TestSemantics( id: 9, flags: <SemanticsFlag>[ SemanticsFlag.hasImplicitScrolling, ], actions: <SemanticsAction>[SemanticsAction.scrollUp], children: <TestSemantics>[ TestSemantics( id: 3, label: 'Item 0', textDirection: TextDirection.ltr, ), TestSemantics( id: 4, label: 'Item 1', textDirection: TextDirection.ltr, ), TestSemantics( id: 5, flags: <SemanticsFlag>[SemanticsFlag.isHidden], label: 'Item 2', textDirection: TextDirection.ltr, ), TestSemantics( id: 6, flags: <SemanticsFlag>[SemanticsFlag.isHidden], label: 'Item 3', textDirection: TextDirection.ltr, ), ], ), ], ), ], ), ], ), ignoreRect: true, ignoreTransform: true, )); // Scroll down far enough to reach the pinned state of the app bar. scrollController.jumpTo(appBarExpandedHeight); await tester.pump(); // App bar is NOT a child of node with semantic scroll actions. expect(semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics( id: 1, textDirection: TextDirection.ltr, children: <TestSemantics>[ TestSemantics( id: 2, children: <TestSemantics>[ TestSemantics( id: 7, tags: <SemanticsTag>[RenderViewport.excludeFromScrolling], children: <TestSemantics>[ TestSemantics( id: 8, flags: <SemanticsFlag>[ SemanticsFlag.namesRoute, SemanticsFlag.isHeader, ], label: 'Semantics Test with Slivers', textDirection: TextDirection.ltr, ), ], ), TestSemantics( id: 9, actions: <SemanticsAction>[ SemanticsAction.scrollUp, SemanticsAction.scrollDown, ], flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling], children: <TestSemantics>[ TestSemantics( id: 3, label: 'Item 0', textDirection: TextDirection.ltr, ), TestSemantics( id: 4, label: 'Item 1', textDirection: TextDirection.ltr, ), TestSemantics( id: 5, label: 'Item 2', textDirection: TextDirection.ltr, ), TestSemantics( id: 6, flags: <SemanticsFlag>[SemanticsFlag.isHidden], label: 'Item 3', textDirection: TextDirection.ltr, ), TestSemantics( id: 10, flags: <SemanticsFlag>[SemanticsFlag.isHidden], label: 'Item 4', textDirection: TextDirection.ltr, ), ], ), ], ), ], ), ], ), ignoreRect: true, ignoreTransform: true, )); // Scroll halfway back to the top, app bar is no longer in pinned state. scrollController.jumpTo(appBarExpandedHeight / 2); await tester.pump(); // AppBar is child of node with semantic scroll actions. expect(semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics( id: 1, textDirection: TextDirection.ltr, children: <TestSemantics>[ TestSemantics( id: 2, children: <TestSemantics>[ TestSemantics( id: 7, children: <TestSemantics>[ TestSemantics( id: 8, flags: <SemanticsFlag>[ SemanticsFlag.namesRoute, SemanticsFlag.isHeader, ], label: 'Semantics Test with Slivers', textDirection: TextDirection.ltr, ), ], ), TestSemantics( id: 9, flags: <SemanticsFlag>[ SemanticsFlag.hasImplicitScrolling, ], actions: <SemanticsAction>[ SemanticsAction.scrollUp, SemanticsAction.scrollDown, ], children: <TestSemantics>[ TestSemantics( id: 3, label: 'Item 0', textDirection: TextDirection.ltr, ), TestSemantics( id: 4, label: 'Item 1', textDirection: TextDirection.ltr, ), TestSemantics( id: 5, label: 'Item 2', textDirection: TextDirection.ltr, ), TestSemantics( id: 6, flags: <SemanticsFlag>[SemanticsFlag.isHidden], label: 'Item 3', textDirection: TextDirection.ltr, ), ], ), ], ), ], ), ], ), ignoreRect: true, ignoreTransform: true, )); semantics.dispose(); }); testWidgets('Offscreen sliver are hidden in semantics tree', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); const double containerHeight = 200.0; final ScrollController scrollController = ScrollController( initialScrollOffset: containerHeight * 1.5, ); addTearDown(scrollController.dispose); final List<Widget> slivers = List<Widget>.generate(30, (int i) { return SliverToBoxAdapter( child: SizedBox( height: containerHeight, child: Text('Item $i', textDirection: TextDirection.ltr), ), ); }); await tester.pumpWidget( Semantics( textDirection: TextDirection.ltr, child: Localizations( locale: const Locale('en', 'us'), delegates: const <LocalizationsDelegate<dynamic>>[ DefaultWidgetsLocalizations.delegate, DefaultMaterialLocalizations.delegate, ], child: Directionality( textDirection: TextDirection.ltr, child: Center( child: SizedBox( height: containerHeight, child: CustomScrollView( controller: scrollController, slivers: slivers, ), ), ), ), ), ), ); expect(semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics( textDirection: TextDirection.ltr, children: <TestSemantics>[ TestSemantics( children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[ SemanticsFlag.hasImplicitScrolling, ], actions: <SemanticsAction>[ SemanticsAction.scrollUp, SemanticsAction.scrollDown, ], children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.isHidden], label: 'Item 0', textDirection: TextDirection.ltr, ), TestSemantics( label: 'Item 1', textDirection: TextDirection.ltr, ), TestSemantics( label: 'Item 2', textDirection: TextDirection.ltr, ), TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.isHidden], label: 'Item 3', textDirection: TextDirection.ltr, ), ], ), ], ), ], ), ], ), ignoreRect: true, ignoreTransform: true, ignoreId: true, )); semantics.dispose(); }); testWidgets('SemanticsNodes of Slivers are in paint order', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final List<Widget> slivers = List<Widget>.generate(5, (int i) { return SliverToBoxAdapter( child: SizedBox( height: 20.0, child: Text('Item $i'), ), ); }); await tester.pumpWidget( Semantics( textDirection: TextDirection.ltr, child: Localizations( locale: const Locale('en', 'us'), delegates: const <LocalizationsDelegate<dynamic>>[ DefaultWidgetsLocalizations.delegate, DefaultMaterialLocalizations.delegate, ], child: Directionality( textDirection: TextDirection.ltr, child: CustomScrollView( slivers: slivers, ), ), ), ), ); expect(semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics( textDirection: TextDirection.ltr, children: <TestSemantics>[ TestSemantics( children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[ SemanticsFlag.hasImplicitScrolling, ], children: <TestSemantics>[ TestSemantics( label: 'Item 4', textDirection: TextDirection.ltr, ), TestSemantics( label: 'Item 3', textDirection: TextDirection.ltr, ), TestSemantics( label: 'Item 2', textDirection: TextDirection.ltr, ), TestSemantics( label: 'Item 1', textDirection: TextDirection.ltr, ), TestSemantics( label: 'Item 0', textDirection: TextDirection.ltr, ), ], ), ], ), ], ), ], ), ignoreRect: true, ignoreTransform: true, ignoreId: true, childOrder: DebugSemanticsDumpOrder.inverseHitTest, )); semantics.dispose(); }); testWidgets('SemanticsNodes of a sliver fully covered by another overlapping sliver are excluded', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final List<Widget> listChildren = List<Widget>.generate(10, (int i) { return SizedBox( height: 200.0, child: Text('Item $i', textDirection: TextDirection.ltr), ); }); final ScrollController controller = ScrollController(initialScrollOffset: 280.0); addTearDown(controller.dispose); await tester.pumpWidget(Semantics( textDirection: TextDirection.ltr, child: Localizations( locale: const Locale('en', 'us'), delegates: const <LocalizationsDelegate<dynamic>>[ DefaultWidgetsLocalizations.delegate, DefaultMaterialLocalizations.delegate, ], child: Directionality( textDirection: TextDirection.ltr, child: MediaQuery( data: const MediaQueryData(), child: CustomScrollView( slivers: <Widget>[ const SliverAppBar( pinned: true, expandedHeight: 100.0, title: Text('AppBar'), ), SliverList( delegate: SliverChildListDelegate(listChildren), ), ], controller: controller, ), ), ), ), )); expect(semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics( textDirection: TextDirection.ltr, children: <TestSemantics>[ TestSemantics( children: <TestSemantics>[ TestSemantics( tags: <SemanticsTag>[RenderViewport.excludeFromScrolling], children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[ SemanticsFlag.namesRoute, SemanticsFlag.isHeader, ], label: 'AppBar', textDirection: TextDirection.ltr, ), ], ), TestSemantics( actions: <SemanticsAction>[ SemanticsAction.scrollUp, SemanticsAction.scrollDown, ], flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling], children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.isHidden], label: 'Item 0', textDirection: TextDirection.ltr, ), TestSemantics( label: 'Item 1', textDirection: TextDirection.ltr, ), TestSemantics( label: 'Item 2', textDirection: TextDirection.ltr, ), TestSemantics( label: 'Item 3', textDirection: TextDirection.ltr, ), TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.isHidden], label: 'Item 4', textDirection: TextDirection.ltr, ), TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.isHidden], label: 'Item 5', textDirection: TextDirection.ltr, ), ], ), ], ), ], ), ], ), ignoreTransform: true, ignoreId: true, ignoreRect: true, )); semantics.dispose(); }); testWidgets('Slivers fully covered by another overlapping sliver are hidden', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final ScrollController controller = ScrollController(initialScrollOffset: 280.0); addTearDown(controller.dispose); final List<Widget> slivers = List<Widget>.generate(10, (int i) { return SliverToBoxAdapter( child: SizedBox( height: 200.0, child: Text('Item $i', textDirection: TextDirection.ltr), ), ); }); await tester.pumpWidget(Semantics( textDirection: TextDirection.ltr, child: Localizations( locale: const Locale('en', 'us'), delegates: const <LocalizationsDelegate<dynamic>>[ DefaultWidgetsLocalizations.delegate, DefaultMaterialLocalizations.delegate, ], child: Directionality( textDirection: TextDirection.ltr, child: MediaQuery( data: const MediaQueryData(), child: CustomScrollView( controller: controller, slivers: <Widget>[ const SliverAppBar( pinned: true, expandedHeight: 100.0, title: Text('AppBar'), ), ...slivers, ], ), ), ), ), )); expect(semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics( textDirection: TextDirection.ltr, children: <TestSemantics>[ TestSemantics( children: <TestSemantics>[ TestSemantics( tags: <SemanticsTag>[RenderViewport.excludeFromScrolling], children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[ SemanticsFlag.namesRoute, SemanticsFlag.isHeader, ], label: 'AppBar', textDirection: TextDirection.ltr, ), ], ), TestSemantics( actions: <SemanticsAction>[ SemanticsAction.scrollUp, SemanticsAction.scrollDown, ], flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling], children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.isHidden], label: 'Item 0', textDirection: TextDirection.ltr, ), TestSemantics( label: 'Item 1', textDirection: TextDirection.ltr, ), TestSemantics( label: 'Item 2', textDirection: TextDirection.ltr, ), TestSemantics( label: 'Item 3', textDirection: TextDirection.ltr, ), TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.isHidden], label: 'Item 4', textDirection: TextDirection.ltr, ), TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.isHidden], label: 'Item 5', textDirection: TextDirection.ltr, ), ], ), ], ), ], ), ], ), ignoreTransform: true, ignoreRect: true, ignoreId: true, )); semantics.dispose(); }); testWidgets('SemanticsNodes of a sliver fully covered by another overlapping sliver are excluded (reverse)', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final List<Widget> listChildren = List<Widget>.generate(10, (int i) { return SizedBox( height: 200.0, child: Text('Item $i', textDirection: TextDirection.ltr), ); }); final ScrollController controller = ScrollController(initialScrollOffset: 280.0); addTearDown(controller.dispose); await tester.pumpWidget(Semantics( textDirection: TextDirection.ltr, child: Localizations( locale: const Locale('en', 'us'), delegates: const <LocalizationsDelegate<dynamic>>[ DefaultWidgetsLocalizations.delegate, DefaultMaterialLocalizations.delegate, ], child: Directionality( textDirection: TextDirection.ltr, child: MediaQuery( data: const MediaQueryData(), child: CustomScrollView( reverse: true, // This is the important setting for this test. slivers: <Widget>[ const SliverAppBar( pinned: true, expandedHeight: 100.0, title: Text('AppBar'), ), SliverList( delegate: SliverChildListDelegate(listChildren), ), ], controller: controller, ), ), ), ), )); expect(semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics( textDirection: TextDirection.ltr, children: <TestSemantics>[ TestSemantics( children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[ SemanticsFlag.hasImplicitScrolling, ], actions: <SemanticsAction>[ SemanticsAction.scrollUp, SemanticsAction.scrollDown, ], children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.isHidden], label: 'Item 5', textDirection: TextDirection.ltr, ), TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.isHidden], label: 'Item 4', textDirection: TextDirection.ltr, ), TestSemantics( label: 'Item 3', textDirection: TextDirection.ltr, ), TestSemantics( label: 'Item 2', textDirection: TextDirection.ltr, ), TestSemantics( label: 'Item 1', textDirection: TextDirection.ltr, ), TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.isHidden], label: 'Item 0', textDirection: TextDirection.ltr, ), ], ), TestSemantics( tags: <SemanticsTag>[RenderViewport.excludeFromScrolling], children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[ SemanticsFlag.namesRoute, SemanticsFlag.isHeader, ], label: 'AppBar', textDirection: TextDirection.ltr, ), ], ), ], ), ], ), ], ), ignoreTransform: true, ignoreId: true, ignoreRect: true, )); semantics.dispose(); }); testWidgets('Slivers fully covered by another overlapping sliver are hidden (reverse)', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final ScrollController controller = ScrollController(initialScrollOffset: 280.0); addTearDown(controller.dispose); final List<Widget> slivers = List<Widget>.generate(10, (int i) { return SliverToBoxAdapter( child: SizedBox( height: 200.0, child: Text('Item $i', textDirection: TextDirection.ltr), ), ); }); await tester.pumpWidget(Semantics( textDirection: TextDirection.ltr, child: Localizations( locale: const Locale('en', 'us'), delegates: const <LocalizationsDelegate<dynamic>>[ DefaultWidgetsLocalizations.delegate, DefaultMaterialLocalizations.delegate, ], child: Directionality( textDirection: TextDirection.ltr, child: MediaQuery( data: const MediaQueryData(), child: CustomScrollView( reverse: true, // This is the important setting for this test. controller: controller, slivers: <Widget>[ const SliverAppBar( pinned: true, expandedHeight: 100.0, title: Text('AppBar'), ), ...slivers, ], ), ), ), ), )); expect(semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics( textDirection: TextDirection.ltr, children: <TestSemantics>[ TestSemantics( children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[ SemanticsFlag.hasImplicitScrolling, ], actions: <SemanticsAction>[ SemanticsAction.scrollUp, SemanticsAction.scrollDown, ], children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.isHidden], label: 'Item 5', textDirection: TextDirection.ltr, ), TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.isHidden], label: 'Item 4', textDirection: TextDirection.ltr, ), TestSemantics( label: 'Item 3', textDirection: TextDirection.ltr, ), TestSemantics( label: 'Item 2', textDirection: TextDirection.ltr, ), TestSemantics( label: 'Item 1', textDirection: TextDirection.ltr, ), TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.isHidden], label: 'Item 0', textDirection: TextDirection.ltr, ), ], ), TestSemantics( tags: <SemanticsTag>[RenderViewport.excludeFromScrolling], children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[ SemanticsFlag.namesRoute, SemanticsFlag.isHeader, ], label: 'AppBar', textDirection: TextDirection.ltr, ), ], ), ], ), ], ), ], ), ignoreTransform: true, ignoreId: true, ignoreRect: true, )); semantics.dispose(); }); testWidgets('Slivers fully covered by another overlapping sliver are hidden (with center sliver)', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final ScrollController controller = ScrollController(initialScrollOffset: 280.0); addTearDown(controller.dispose); final GlobalKey forwardAppBarKey = GlobalKey(debugLabel: 'forward app bar'); final List<Widget> forwardChildren = List<Widget>.generate(10, (int i) { return SizedBox( height: 200.0, child: Text('Forward Item $i', textDirection: TextDirection.ltr), ); }); final List<Widget> backwardChildren = List<Widget>.generate(10, (int i) { return SizedBox( height: 200.0, child: Text('Backward Item $i', textDirection: TextDirection.ltr), ); }); await tester.pumpWidget(Semantics( textDirection: TextDirection.ltr, child: Directionality( textDirection: TextDirection.ltr, child: Localizations( locale: const Locale('en', 'us'), delegates: const <LocalizationsDelegate<dynamic>>[ DefaultWidgetsLocalizations.delegate, DefaultMaterialLocalizations.delegate, ], child: MediaQuery( data: const MediaQueryData(), child: Scrollable( controller: controller, viewportBuilder: (BuildContext context, ViewportOffset offset) { return Viewport( offset: offset, center: forwardAppBarKey, slivers: <Widget>[ SliverList( delegate: SliverChildListDelegate(backwardChildren), ), const SliverAppBar( pinned: true, expandedHeight: 100.0, flexibleSpace: FlexibleSpaceBar( title: Text('Backward app bar', textDirection: TextDirection.ltr), ), ), SliverAppBar( pinned: true, key: forwardAppBarKey, expandedHeight: 100.0, flexibleSpace: const FlexibleSpaceBar( title: Text('Forward app bar', textDirection: TextDirection.ltr), ), ), SliverList( delegate: SliverChildListDelegate(forwardChildren), ), ], ); }, ), ), ), ), )); // 'Forward Item 0' is covered by app bar. expect(semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics( textDirection: TextDirection.ltr, children: <TestSemantics>[ TestSemantics( children: <TestSemantics>[ TestSemantics( tags: <SemanticsTag>[RenderViewport.excludeFromScrolling], children: <TestSemantics>[ TestSemantics(), TestSemantics( children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[ SemanticsFlag.namesRoute, SemanticsFlag.isHeader, ], label: 'Forward app bar', textDirection: TextDirection.ltr, ), ], ), ], ), TestSemantics( actions: <SemanticsAction>[ SemanticsAction.scrollUp, SemanticsAction.scrollDown, ], flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling], children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.isHidden], label: 'Forward Item 0', textDirection: TextDirection.ltr, ), TestSemantics( label: 'Forward Item 1', textDirection: TextDirection.ltr, ), TestSemantics( label: 'Forward Item 2', textDirection: TextDirection.ltr, ), TestSemantics( label: 'Forward Item 3', textDirection: TextDirection.ltr, ), TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.isHidden], label: 'Forward Item 4', textDirection: TextDirection.ltr, ), TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.isHidden], label: 'Forward Item 5', textDirection: TextDirection.ltr, ), ], ), ], ), ], ), ], ), ignoreTransform: true, ignoreRect: true, ignoreId: true, )); controller.jumpTo(-880.0); await tester.pumpAndSettle(); // 'Backward Item 0' is covered by app bar. expect(semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics( textDirection: TextDirection.ltr, children: <TestSemantics>[ TestSemantics( children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[ SemanticsFlag.hasImplicitScrolling, ], actions: <SemanticsAction>[ SemanticsAction.scrollUp, SemanticsAction.scrollDown, ], children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.isHidden], label: 'Backward Item 5', textDirection: TextDirection.ltr, ), TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.isHidden], label: 'Backward Item 4', textDirection: TextDirection.ltr, ), TestSemantics( label: 'Backward Item 3', textDirection: TextDirection.ltr, ), TestSemantics( label: 'Backward Item 2', textDirection: TextDirection.ltr, ), TestSemantics( label: 'Backward Item 1', textDirection: TextDirection.ltr, ), TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.isHidden], label: 'Backward Item 0', textDirection: TextDirection.ltr, ), ], ), TestSemantics( tags: <SemanticsTag>[RenderViewport.excludeFromScrolling], children: <TestSemantics>[ TestSemantics(), TestSemantics( children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[ SemanticsFlag.namesRoute, SemanticsFlag.isHeader, ], label: 'Backward app bar', textDirection: TextDirection.ltr, ), ], ), ], ), ], ), ], ), ], ), ignoreTransform: true, ignoreRect: true, ignoreId: true, )); semantics.dispose(); }); }
flutter/packages/flutter/test/widgets/sliver_semantics_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/sliver_semantics_test.dart", "repo_id": "flutter", "token_count": 23438 }
711
// 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('Spacer takes up space.', (WidgetTester tester) async { await tester.pumpWidget(const Column( children: <Widget>[ SizedBox(width: 10.0, height: 10.0), Spacer(), SizedBox(width: 10.0, height: 10.0), ], )); final Rect spacerRect = tester.getRect(find.byType(Spacer)); expect(spacerRect.size, const Size(0.0, 580.0)); expect(spacerRect.topLeft, const Offset(400.0, 10.0)); }); testWidgets('Spacer takes up space proportional to flex.', (WidgetTester tester) async { const Spacer spacer1 = Spacer(); const Spacer spacer2 = Spacer(); const Spacer spacer3 = Spacer(flex: 2); const Spacer spacer4 = Spacer(flex: 4); await tester.pumpWidget(const Row( textDirection: TextDirection.rtl, children: <Widget>[ SizedBox(width: 10.0, height: 10.0), spacer1, SizedBox(width: 10.0, height: 10.0), spacer2, SizedBox(width: 10.0, height: 10.0), spacer3, SizedBox(width: 10.0, height: 10.0), spacer4, SizedBox(width: 10.0, height: 10.0), ], )); final Rect spacer1Rect = tester.getRect(find.byType(Spacer).at(0)); final Rect spacer2Rect = tester.getRect(find.byType(Spacer).at(1)); final Rect spacer3Rect = tester.getRect(find.byType(Spacer).at(2)); final Rect spacer4Rect = tester.getRect(find.byType(Spacer).at(3)); expect(spacer1Rect.size.height, 0.0); expect(spacer1Rect.size.width, moreOrLessEquals(93.8, epsilon: 0.1)); expect(spacer1Rect.left, moreOrLessEquals(696.3, epsilon: 0.1)); expect(spacer2Rect.size.width, moreOrLessEquals(93.8, epsilon: 0.1)); expect(spacer2Rect.left, moreOrLessEquals(592.5, epsilon: 0.1)); expect(spacer3Rect.size.width, spacer2Rect.size.width * 2.0); expect(spacer3Rect.left, moreOrLessEquals(395.0, epsilon: 0.1)); expect(spacer4Rect.size.width, spacer3Rect.size.width * 2.0); expect(spacer4Rect.left, moreOrLessEquals(10.0, epsilon: 0.1)); }); testWidgets('Spacer takes up space.', (WidgetTester tester) async { await tester.pumpWidget(const UnconstrainedBox( constrainedAxis: Axis.vertical, child: Column( children: <Widget>[ SizedBox(width: 20.0, height: 10.0), Spacer(), SizedBox(width: 10.0, height: 10.0), ], ), )); final Rect spacerRect = tester.getRect(find.byType(Spacer)); final Rect flexRect = tester.getRect(find.byType(Column)); expect(spacerRect.size, const Size(0.0, 580.0)); expect(spacerRect.topLeft, const Offset(400.0, 10.0)); expect(flexRect, const Rect.fromLTWH(390.0, 0.0, 20.0, 600.0)); }); }
flutter/packages/flutter/test/widgets/spacer_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/spacer_test.dart", "repo_id": "flutter", "token_count": 1269 }
712
// 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('positions itself at anchorAbove if it fits', (WidgetTester tester) async { late StateSetter setState; const double height = 43.0; const double anchorBelowY = 500.0; double anchorAboveY = 0.0; await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: StatefulBuilder( builder: (BuildContext context, StateSetter setter) { setState = setter; return CustomSingleChildLayout( delegate: TextSelectionToolbarLayoutDelegate( anchorAbove: Offset(50.0, anchorAboveY), anchorBelow: const Offset(50.0, anchorBelowY), ), child: Container( width: 200.0, height: height, color: const Color(0xffff0000), ), ); }, ), ), ), ); // When the toolbar doesn't fit above aboveAnchor, it positions itself below // belowAnchor. double toolbarY = tester.getTopLeft(find.byType(Container)).dy; expect(toolbarY, equals(anchorBelowY)); // Even when it barely doesn't fit. setState(() { anchorAboveY = height - 1.0; }); await tester.pump(); toolbarY = tester.getTopLeft(find.byType(Container)).dy; expect(toolbarY, equals(anchorBelowY)); // When it does fit above aboveAnchor, it positions itself there. setState(() { anchorAboveY = height; }); await tester.pump(); toolbarY = tester.getTopLeft(find.byType(Container)).dy; expect(toolbarY, equals(anchorAboveY - height)); }); }
flutter/packages/flutter/test/widgets/text_selection_toolbar_layout_delegate_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/text_selection_toolbar_layout_delegate_test.dart", "repo_id": "flutter", "token_count": 858 }
713
// 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_test/flutter_test.dart'; import 'two_dimensional_utils.dart'; void main() { group('TwoDimensionalChildDelegate', () { group('TwoDimensionalChildBuilderDelegate', () { testWidgets('repaintBoundaries', (WidgetTester tester) async { // Default - adds repaint boundaries late final TwoDimensionalChildBuilderDelegate delegate1; addTearDown(() => delegate1.dispose()); await tester.pumpWidget(simpleBuilderTest( delegate: delegate1 = TwoDimensionalChildBuilderDelegate( // Only build 1 child maxXIndex: 0, maxYIndex: 0, builder: (BuildContext context, ChildVicinity vicinity) { return SizedBox( height: 200, width: 200, child: Center(child: Text('C${vicinity.xIndex}:R${vicinity.yIndex}')), ); } ) )); await tester.pumpAndSettle(); switch (defaultTargetPlatform) { case TargetPlatform.android: case TargetPlatform.fuchsia: expect(find.byType(RepaintBoundary), findsNWidgets(7)); case TargetPlatform.iOS: case TargetPlatform.linux: case TargetPlatform.macOS: case TargetPlatform.windows: expect(find.byType(RepaintBoundary), findsNWidgets(3)); } // None late final TwoDimensionalChildBuilderDelegate delegate2; addTearDown(() => delegate2.dispose()); await tester.pumpWidget(simpleBuilderTest( delegate: delegate2 = TwoDimensionalChildBuilderDelegate( // Only build 1 child maxXIndex: 0, maxYIndex: 0, addRepaintBoundaries: false, builder: (BuildContext context, ChildVicinity vicinity) { return SizedBox( height: 200, width: 200, child: Center(child: Text('C${vicinity.xIndex}:R${vicinity.yIndex}')), ); } ) )); await tester.pumpAndSettle(); switch (defaultTargetPlatform) { case TargetPlatform.android: case TargetPlatform.fuchsia: expect(find.byType(RepaintBoundary), findsNWidgets(6)); case TargetPlatform.iOS: case TargetPlatform.linux: case TargetPlatform.macOS: case TargetPlatform.windows: expect(find.byType(RepaintBoundary), findsNWidgets(2)); } }, variant: TargetPlatformVariant.all()); testWidgets('will return null from build for exceeding maxXIndex and maxYIndex', (WidgetTester tester) async { late BuildContext capturedContext; final TwoDimensionalChildBuilderDelegate delegate = TwoDimensionalChildBuilderDelegate( // Only build 1 child maxXIndex: 0, maxYIndex: 0, addRepaintBoundaries: false, builder: (BuildContext context, ChildVicinity vicinity) { capturedContext = context; return SizedBox( height: 200, width: 200, child: Center(child: Text('C${vicinity.xIndex}:R${vicinity.yIndex}')), ); } ); addTearDown(delegate.dispose); await tester.pumpWidget(simpleBuilderTest( delegate: delegate, )); await tester.pumpAndSettle(); // maxXIndex expect( delegate.build(capturedContext, const ChildVicinity(xIndex: 1, yIndex: 0)), isNull, ); // maxYIndex expect( delegate.build(capturedContext, const ChildVicinity(xIndex: 0, yIndex: 1)), isNull, ); // Both expect( delegate.build(capturedContext, const ChildVicinity(xIndex: 1, yIndex: 1)), isNull, ); }, variant: TargetPlatformVariant.all()); test('maxXIndex and maxYIndex assertions', () { final TwoDimensionalChildBuilderDelegate delegate = TwoDimensionalChildBuilderDelegate( maxXIndex: 0, maxYIndex: 0, builder: (BuildContext context, ChildVicinity vicinity) { return const SizedBox.shrink(); } ); // Update delegate.maxXIndex = -1; // No exception. expect( () { delegate.maxXIndex = -2; }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains('value == null || value >= -1'), ), ), ); delegate.maxYIndex = -1; // No exception expect( () { delegate.maxYIndex = -2; }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains('value == null || value >= -1'), ), ), ); // Constructor expect( () { TwoDimensionalChildBuilderDelegate( maxXIndex: -2, maxYIndex: 0, builder: (BuildContext context, ChildVicinity vicinity) { return const SizedBox.shrink(); } ); }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains('maxXIndex == null || maxXIndex >= -1'), ), ), ); expect( () { TwoDimensionalChildBuilderDelegate( maxXIndex: 0, maxYIndex: -2, builder: (BuildContext context, ChildVicinity vicinity) { return const SizedBox.shrink(); } ); }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains('maxYIndex == null || maxYIndex >= -1'), ), ), ); }); testWidgets('throws an error when builder throws', (WidgetTester tester) async { final List<Object> exceptions = <Object>[]; final FlutterExceptionHandler? oldHandler = FlutterError.onError; FlutterError.onError = (FlutterErrorDetails details) { exceptions.add(details.exception); }; final TwoDimensionalChildBuilderDelegate delegate = TwoDimensionalChildBuilderDelegate( // Only build 1 child maxXIndex: 0, maxYIndex: 0, addRepaintBoundaries: false, builder: (BuildContext context, ChildVicinity vicinity) { throw 'Builder error!'; } ); addTearDown(delegate.dispose); await tester.pumpWidget(simpleBuilderTest( delegate: delegate, )); await tester.pumpAndSettle(); FlutterError.onError = oldHandler; expect(exceptions.isNotEmpty, isTrue); expect(exceptions.length, 1); expect(exceptions[0] as String, contains('Builder error!')); }, variant: TargetPlatformVariant.all()); testWidgets('shouldRebuild', (WidgetTester tester) async { expect(builderDelegate.shouldRebuild(builderDelegate), isTrue); }, variant: TargetPlatformVariant.all()); testWidgets('builder delegate supports automatic keep alive - default true', (WidgetTester tester) async { const ChildVicinity firstCell = ChildVicinity(xIndex: 0, yIndex: 0); final ScrollController verticalController = ScrollController(); addTearDown(verticalController.dispose); final UniqueKey checkBoxKey = UniqueKey(); final TwoDimensionalChildBuilderDelegate builderDelegate = TwoDimensionalChildBuilderDelegate( maxXIndex: 5, maxYIndex: 5, builder: (BuildContext context, ChildVicinity vicinity) { return SizedBox.square( dimension: 200, child: Center(child: vicinity == firstCell ? KeepAliveCheckBox(key: checkBoxKey) : Text('R${vicinity.xIndex}:C${vicinity.yIndex}') ), ); } ); addTearDown(builderDelegate.dispose); await tester.pumpWidget(simpleBuilderTest( delegate: builderDelegate, verticalDetails: ScrollableDetails.vertical(controller: verticalController), )); await tester.pumpAndSettle(); expect(verticalController.hasClients, isTrue); expect(verticalController.position.pixels, 0.0); expect(find.byKey(checkBoxKey), findsOneWidget); expect( tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, isFalse, ); expect( tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, isFalse, ); // Scroll away, disposing of the checkbox. verticalController.jumpTo(verticalController.position.maxScrollExtent); await tester.pump(); expect(verticalController.position.pixels, 600.0); expect(find.byKey(checkBoxKey), findsNothing); // Bring back into view, still unchecked, not kept alive. verticalController.jumpTo(0.0); await tester.pump(); expect(verticalController.position.pixels, 0.0); expect(find.byKey(checkBoxKey), findsOneWidget); await tester.tap(find.byKey(checkBoxKey)); await tester.pumpAndSettle(); expect( tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, isTrue, ); expect( tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, isTrue, ); // Scroll away again, checkbox should be kept alive now. verticalController.jumpTo(verticalController.position.maxScrollExtent); await tester.pump(); expect(verticalController.position.pixels, 600.0); expect(find.byKey(checkBoxKey), findsOneWidget); expect( tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, isTrue, ); expect( tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, isTrue, ); // Bring back into view, still checked, after being kept alive. verticalController.jumpTo(0.0); await tester.pump(); expect(verticalController.position.pixels, 0.0); expect(find.byKey(checkBoxKey), findsOneWidget); expect( tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, isTrue, ); expect( tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, isTrue, ); }); testWidgets('Keep alive works with additional parent data widgets', (WidgetTester tester) async { const ChildVicinity firstCell = ChildVicinity(xIndex: 0, yIndex: 0); final ScrollController verticalController = ScrollController(); addTearDown(verticalController.dispose); final UniqueKey checkBoxKey = UniqueKey(); final TwoDimensionalChildBuilderDelegate builderDelegate = TwoDimensionalChildBuilderDelegate( maxXIndex: 5, maxYIndex: 5, addRepaintBoundaries: false, builder: (BuildContext context, ChildVicinity vicinity) { // The delegate will add a KeepAlive ParentDataWidget, this add an // additional ParentDataWidget. return TestParentDataWidget( testValue: 20, child: SizedBox.square( dimension: 200, child: Center(child: vicinity == firstCell ? KeepAliveCheckBox(key: checkBoxKey) : Text('R${vicinity.xIndex}:C${vicinity.yIndex}') ), ), ); } ); await tester.pumpWidget(simpleBuilderTest( delegate: builderDelegate, verticalDetails: ScrollableDetails.vertical(controller: verticalController), )); await tester.pumpAndSettle(); expect(verticalController.hasClients, isTrue); expect(verticalController.position.pixels, 0.0); expect(find.byKey(checkBoxKey), findsOneWidget); expect( tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, isFalse, ); expect( tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, isFalse, ); RenderSimpleBuilderTableViewport viewport = getViewport(tester, checkBoxKey) as RenderSimpleBuilderTableViewport; TestExtendedParentData parentData = viewport.parentDataOf(viewport.testGetChildFor(firstCell)!); // Check parent data from both ParentDataWidgets expect(parentData.testValue, 20); expect(parentData.keepAlive, isFalse); // Scroll away, disposing of the checkbox. verticalController.jumpTo(verticalController.position.maxScrollExtent); await tester.pump(); expect(verticalController.position.pixels, 600.0); expect(find.byKey(checkBoxKey), findsNothing); // Bring back into view, still unchecked, not kept alive. verticalController.jumpTo(0.0); await tester.pump(); expect(verticalController.position.pixels, 0.0); expect(find.byKey(checkBoxKey), findsOneWidget); // Check the box to set keep alive to true. await tester.tap(find.byKey(checkBoxKey)); await tester.pumpAndSettle(); expect( tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, isTrue, ); expect( tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, isTrue, ); viewport = getViewport(tester, checkBoxKey) as RenderSimpleBuilderTableViewport; parentData = viewport.parentDataOf(viewport.testGetChildFor(firstCell)!); // Check parent data from both ParentDataWidgets expect(parentData.testValue, 20); expect(parentData.keepAlive, isTrue); // Scroll away again, checkbox should be kept alive now. verticalController.jumpTo(verticalController.position.maxScrollExtent); await tester.pump(); expect(verticalController.position.pixels, 600.0); expect(find.byKey(checkBoxKey), findsOneWidget); expect( tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, isTrue, ); expect( tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, isTrue, ); viewport = getViewport(tester, checkBoxKey) as RenderSimpleBuilderTableViewport; parentData = viewport.parentDataOf(viewport.testGetChildFor(firstCell)!); // Check parent data from both ParentDataWidgets expect(parentData.testValue, 20); expect(parentData.keepAlive, isTrue); // Bring back into view, still checked, after being kept alive. verticalController.jumpTo(0.0); await tester.pump(); expect(verticalController.position.pixels, 0.0); expect(find.byKey(checkBoxKey), findsOneWidget); expect( tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, isTrue, ); expect( tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, isTrue, ); viewport = getViewport(tester, checkBoxKey) as RenderSimpleBuilderTableViewport; parentData = viewport.parentDataOf(viewport.testGetChildFor(firstCell)!); // Check parent data from both ParentDataWidgets expect(parentData.testValue, 20); expect(parentData.keepAlive, isTrue); }); testWidgets('builder delegate will not add automatic keep alives', (WidgetTester tester) async { const ChildVicinity firstCell = ChildVicinity(xIndex: 0, yIndex: 0); final ScrollController verticalController = ScrollController(); addTearDown(verticalController.dispose); final UniqueKey checkBoxKey = UniqueKey(); final TwoDimensionalChildBuilderDelegate builderDelegate = TwoDimensionalChildBuilderDelegate( maxXIndex: 5, maxYIndex: 5, addAutomaticKeepAlives: false, // No keeping alive this time builder: (BuildContext context, ChildVicinity vicinity) { return SizedBox.square( dimension: 200, child: Center(child: vicinity == firstCell ? KeepAliveCheckBox(key: checkBoxKey) : Text('R${vicinity.xIndex}:C${vicinity.yIndex}') ), ); } ); addTearDown(builderDelegate.dispose); await tester.pumpWidget(simpleBuilderTest( delegate: builderDelegate, verticalDetails: ScrollableDetails.vertical(controller: verticalController), )); await tester.pumpAndSettle(); expect(verticalController.hasClients, isTrue); expect(verticalController.position.pixels, 0.0); expect(find.byKey(checkBoxKey), findsOneWidget); expect( tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, isFalse, ); expect( tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, isFalse, ); // Scroll away, disposing of the checkbox. verticalController.jumpTo(verticalController.position.maxScrollExtent); await tester.pump(); expect(verticalController.position.pixels, 600.0); expect(find.byKey(checkBoxKey), findsNothing); // Bring back into view, still unchecked, not kept alive. verticalController.jumpTo(0.0); await tester.pump(); expect(verticalController.position.pixels, 0.0); expect(find.byKey(checkBoxKey), findsOneWidget); await tester.tap(find.byKey(checkBoxKey)); await tester.pumpAndSettle(); expect( tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, isTrue, ); expect( tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, isTrue, ); // Scroll away again, checkbox should not be kept alive since the // delegate did not add automatic keep alive. verticalController.jumpTo(verticalController.position.maxScrollExtent); await tester.pump(); expect(verticalController.position.pixels, 600.0); expect(find.byKey(checkBoxKey), findsNothing); // Bring back into view, not checked, having not been kept alive. verticalController.jumpTo(0.0); await tester.pump(); expect(verticalController.position.pixels, 0.0); expect(find.byKey(checkBoxKey), findsOneWidget); expect( tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, isFalse, ); expect( tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, isFalse, ); }); }); group('TwoDimensionalChildListDelegate', () { testWidgets('repaintBoundaries', (WidgetTester tester) async { final List<List<Widget>> children = <List<Widget>>[]; children.add(<Widget>[ const SizedBox( height: 200, width: 200, child: Center(child: Text('R0:C0')), ) ]); // Default - adds repaint boundaries late final TwoDimensionalChildListDelegate delegate1; addTearDown(() => delegate1.dispose()); await tester.pumpWidget(simpleListTest( delegate: delegate1 = TwoDimensionalChildListDelegate( // Only builds 1 child children: children, ) )); await tester.pumpAndSettle(); // In the tests below the number of RepaintBoundary widgets depends on: // ModalRoute - builds 2 // GlowingOverscrollIndicator - builds 2 // TwoDimensionalChildListDelegate - builds 1 unless addRepaintBoundaries is false void expectModalRoute() { expect(ModalRoute.of(tester.element(find.byType(SimpleListTableViewport))), isA<MaterialPageRoute<void>>()); } switch (defaultTargetPlatform) { case TargetPlatform.fuchsia: expectModalRoute(); expect(find.byType(GlowingOverscrollIndicator), findsNWidgets(2)); expect(find.byType(RepaintBoundary), findsNWidgets(7)); case TargetPlatform.android: case TargetPlatform.iOS: case TargetPlatform.linux: case TargetPlatform.macOS: case TargetPlatform.windows: expectModalRoute(); expect(find.byType(RepaintBoundary), findsNWidgets(3)); } // None late final TwoDimensionalChildListDelegate delegate2; addTearDown(() => delegate2.dispose()); await tester.pumpWidget(simpleListTest( delegate: delegate2 = TwoDimensionalChildListDelegate( // Different children triggers rebuild children: <List<Widget>>[<Widget>[Container()]], addRepaintBoundaries: false, ) )); await tester.pumpAndSettle(); switch (defaultTargetPlatform) { case TargetPlatform.fuchsia: expectModalRoute(); expect(find.byType(GlowingOverscrollIndicator), findsNWidgets(2)); expect(find.byType(RepaintBoundary), findsNWidgets(6)); case TargetPlatform.android: case TargetPlatform.iOS: case TargetPlatform.linux: case TargetPlatform.macOS: case TargetPlatform.windows: expectModalRoute(); expect(find.byType(RepaintBoundary), findsNWidgets(2)); } }, variant: TargetPlatformVariant.all()); testWidgets('will return null for a ChildVicinity outside of list bounds', (WidgetTester tester) async { final List<List<Widget>> children = <List<Widget>>[]; children.add(<Widget>[ const SizedBox( height: 200, width: 200, child: Center(child: Text('R0:C0')), ) ]); final TwoDimensionalChildListDelegate delegate = TwoDimensionalChildListDelegate( // Only builds 1 child children: children, ); addTearDown(delegate.dispose); // X index expect( delegate.build(_NullBuildContext(), const ChildVicinity(xIndex: 1, yIndex: 0)), isNull, ); // Y index expect( delegate.build(_NullBuildContext(), const ChildVicinity(xIndex: 0, yIndex: 1)), isNull, ); // Both expect( delegate.build(_NullBuildContext(), const ChildVicinity(xIndex: 1, yIndex: 1)), isNull, ); }, variant: TargetPlatformVariant.all()); testWidgets('shouldRebuild', (WidgetTester tester) async { final List<List<Widget>> children = <List<Widget>>[]; children.add(<Widget>[ const SizedBox( height: 200, width: 200, child: Center(child: Text('R0:C0')), ) ]); final TwoDimensionalChildListDelegate delegate = TwoDimensionalChildListDelegate( // Only builds 1 child children: children, ); addTearDown(delegate.dispose); expect(delegate.shouldRebuild(delegate), isFalse); final List<List<Widget>> newChildren = <List<Widget>>[]; final TwoDimensionalChildListDelegate oldDelegate = TwoDimensionalChildListDelegate( children: newChildren, ); addTearDown(oldDelegate.dispose); expect(delegate.shouldRebuild(oldDelegate), isTrue); }, variant: TargetPlatformVariant.all()); }); testWidgets('list delegate supports automatic keep alive - default true', (WidgetTester tester) async { final UniqueKey checkBoxKey = UniqueKey(); final Widget originCell = SizedBox.square( dimension: 200, child: Center(child: KeepAliveCheckBox(key: checkBoxKey) ), ); const Widget otherCell = SizedBox.square(dimension: 200); final ScrollController verticalController = ScrollController(); addTearDown(verticalController.dispose); final TwoDimensionalChildListDelegate listDelegate = TwoDimensionalChildListDelegate( children: <List<Widget>>[ <Widget>[originCell, otherCell, otherCell, otherCell, otherCell], <Widget>[otherCell, otherCell, otherCell, otherCell, otherCell], <Widget>[otherCell, otherCell, otherCell, otherCell, otherCell], <Widget>[otherCell, otherCell, otherCell, otherCell, otherCell], <Widget>[otherCell, otherCell, otherCell, otherCell, otherCell], ], ); addTearDown(listDelegate.dispose); await tester.pumpWidget(simpleListTest( delegate: listDelegate, verticalDetails: ScrollableDetails.vertical(controller: verticalController), )); await tester.pumpAndSettle(); expect(verticalController.hasClients, isTrue); expect(verticalController.position.pixels, 0.0); expect(find.byKey(checkBoxKey), findsOneWidget); expect( tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, isFalse, ); expect( tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, isFalse, ); // Scroll away, disposing of the checkbox. verticalController.jumpTo(verticalController.position.maxScrollExtent); await tester.pump(); expect(verticalController.position.pixels, 400.0); expect(find.byKey(checkBoxKey), findsNothing); // Bring back into view, still unchecked, not kept alive. verticalController.jumpTo(0.0); await tester.pump(); expect(verticalController.position.pixels, 0.0); expect(find.byKey(checkBoxKey), findsOneWidget); await tester.tap(find.byKey(checkBoxKey)); await tester.pumpAndSettle(); expect( tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, isTrue, ); expect( tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, isTrue, ); // Scroll away again, checkbox should be kept alive now. verticalController.jumpTo(verticalController.position.maxScrollExtent); await tester.pump(); expect(verticalController.position.pixels, 400.0); expect(find.byKey(checkBoxKey), findsOneWidget); expect( tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, isTrue, ); expect( tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, isTrue, ); // Bring back into view, still checked, after being kept alive. verticalController.jumpTo(0.0); await tester.pump(); expect(verticalController.position.pixels, 0.0); expect(find.byKey(checkBoxKey), findsOneWidget); expect( tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, isTrue, ); expect( tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, isTrue, ); }); testWidgets('list delegate will not add automatic keep alives', (WidgetTester tester) async { final UniqueKey checkBoxKey = UniqueKey(); final Widget originCell = SizedBox.square( dimension: 200, child: Center(child: KeepAliveCheckBox(key: checkBoxKey) ), ); const Widget otherCell = SizedBox.square(dimension: 200); final ScrollController verticalController = ScrollController(); addTearDown(verticalController.dispose); final TwoDimensionalChildListDelegate listDelegate = TwoDimensionalChildListDelegate( addAutomaticKeepAlives: false, children: <List<Widget>>[ <Widget>[originCell, otherCell, otherCell, otherCell, otherCell], <Widget>[otherCell, otherCell, otherCell, otherCell, otherCell], <Widget>[otherCell, otherCell, otherCell, otherCell, otherCell], <Widget>[otherCell, otherCell, otherCell, otherCell, otherCell], <Widget>[otherCell, otherCell, otherCell, otherCell, otherCell], ], ); addTearDown(listDelegate.dispose); await tester.pumpWidget(simpleListTest( delegate: listDelegate, verticalDetails: ScrollableDetails.vertical(controller: verticalController), )); await tester.pumpAndSettle(); expect(verticalController.hasClients, isTrue); expect(verticalController.position.pixels, 0.0); expect(find.byKey(checkBoxKey), findsOneWidget); expect( tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, isFalse, ); expect( tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, isFalse, ); // Scroll away, disposing of the checkbox. verticalController.jumpTo(verticalController.position.maxScrollExtent); await tester.pump(); expect(verticalController.position.pixels, 400.0); expect(find.byKey(checkBoxKey), findsNothing); // Bring back into view, still unchecked, not kept alive. verticalController.jumpTo(0.0); await tester.pump(); expect(verticalController.position.pixels, 0.0); expect(find.byKey(checkBoxKey), findsOneWidget); await tester.tap(find.byKey(checkBoxKey)); await tester.pumpAndSettle(); expect( tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, isTrue, ); expect( tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, isTrue, ); // Scroll away again, checkbox should not be kept alive since the // delegate did not add automatic keep alive. verticalController.jumpTo(verticalController.position.maxScrollExtent); await tester.pump(); expect(verticalController.position.pixels, 400.0); expect(find.byKey(checkBoxKey), findsNothing); // Bring back into view, not checked, having not been kept alive. verticalController.jumpTo(0.0); await tester.pump(); expect(verticalController.position.pixels, 0.0); expect(find.byKey(checkBoxKey), findsOneWidget); expect( tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, isFalse, ); expect( tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, isFalse, ); }); }); group('TwoDimensionalScrollable', () { testWidgets('.of, .maybeOf', (WidgetTester tester) async { late BuildContext capturedContext; final TwoDimensionalChildBuilderDelegate delegate = TwoDimensionalChildBuilderDelegate( maxXIndex: 0, maxYIndex: 0, builder: (BuildContext context, ChildVicinity vicinity) { capturedContext = context; return const SizedBox.square(dimension: 200); } ); addTearDown(delegate.dispose); await tester.pumpWidget(simpleBuilderTest( delegate: delegate, )); await tester.pumpAndSettle(); expect(TwoDimensionalScrollable.of(capturedContext), isNotNull); expect(TwoDimensionalScrollable.maybeOf(capturedContext), isNotNull); await tester.pumpWidget(Builder( builder: (BuildContext context) { capturedContext = context; TwoDimensionalScrollable.of(context); return Container(); } )); await tester.pumpAndSettle(); final dynamic exception = tester.takeException(); expect(exception, isFlutterError); final FlutterError error = exception as FlutterError; expect(error.toString(), contains( 'TwoDimensionalScrollable.of() was called with a context that does ' 'not contain a TwoDimensionalScrollable widget.' )); expect(TwoDimensionalScrollable.maybeOf(capturedContext), isNull); }, variant: TargetPlatformVariant.all()); testWidgets('horizontal and vertical getters', (WidgetTester tester) async { late BuildContext capturedContext; final TwoDimensionalChildBuilderDelegate delegate = TwoDimensionalChildBuilderDelegate( maxXIndex: 0, maxYIndex: 0, builder: (BuildContext context, ChildVicinity vicinity) { capturedContext = context; return const SizedBox.square(dimension: 200); } ); addTearDown(delegate.dispose); await tester.pumpWidget(simpleBuilderTest( delegate: delegate, )); await tester.pumpAndSettle(); final TwoDimensionalScrollableState scrollable = TwoDimensionalScrollable.of(capturedContext); expect(scrollable.verticalScrollable.position.pixels, 0.0); expect(scrollable.horizontalScrollable.position.pixels, 0.0); }, variant: TargetPlatformVariant.all()); testWidgets('creates fallback ScrollControllers if not provided by ScrollableDetails', (WidgetTester tester) async { late BuildContext capturedContext; final TwoDimensionalChildBuilderDelegate delegate = TwoDimensionalChildBuilderDelegate( maxXIndex: 0, maxYIndex: 0, builder: (BuildContext context, ChildVicinity vicinity) { capturedContext = context; return const SizedBox.square(dimension: 200); } ); addTearDown(delegate.dispose); await tester.pumpWidget(simpleBuilderTest( delegate: delegate, )); await tester.pumpAndSettle(); // Vertical final ScrollableState vertical = Scrollable.of(capturedContext, axis: Axis.vertical); expect(vertical.widget.controller, isNotNull); // Horizontal final ScrollableState horizontal = Scrollable.of(capturedContext, axis: Axis.horizontal); expect(horizontal.widget.controller, isNotNull); }, variant: TargetPlatformVariant.all()); testWidgets('asserts the axis directions do not conflict with one another', (WidgetTester tester) async { final List<Object> exceptions = <Object>[]; final FlutterExceptionHandler? oldHandler = FlutterError.onError; FlutterError.onError = (FlutterErrorDetails details) { exceptions.add(details.exception); }; // Horizontal mismatch await tester.pumpWidget(TwoDimensionalScrollable( horizontalDetails: const ScrollableDetails.horizontal(), verticalDetails: const ScrollableDetails.horizontal(), viewportBuilder: (BuildContext context, ViewportOffset verticalPosition, ViewportOffset horizontalPosition) { return Container(); }, )); // Vertical mismatch await tester.pumpWidget(TwoDimensionalScrollable( horizontalDetails: const ScrollableDetails.vertical(), verticalDetails: const ScrollableDetails.vertical(), viewportBuilder: (BuildContext context, ViewportOffset verticalPosition, ViewportOffset horizontalPosition) { return Container(); }, )); // Both await tester.pumpWidget(TwoDimensionalScrollable( horizontalDetails: const ScrollableDetails.vertical(), verticalDetails: const ScrollableDetails.horizontal(), viewportBuilder: (BuildContext context, ViewportOffset verticalPosition, ViewportOffset horizontalPosition) { return Container(); }, )); expect(exceptions.length, 3); for (final Object exception in exceptions) { expect(exception, isAssertionError); expect((exception as AssertionError).message, contains('are not Axis')); } FlutterError.onError = oldHandler; }, variant: TargetPlatformVariant.all()); testWidgets('correctly sets restorationIds', (WidgetTester tester) async { late BuildContext capturedContext; // with restorationID set await tester.pumpWidget(WidgetsApp( color: const Color(0xFFFFFFFF), restorationScopeId: 'Test ID', builder: (BuildContext context, Widget? child) => TwoDimensionalScrollable( restorationId: 'Custom Restoration ID', horizontalDetails: const ScrollableDetails.horizontal(), verticalDetails: const ScrollableDetails.vertical(), viewportBuilder: (BuildContext context, ViewportOffset verticalPosition, ViewportOffset horizontalPosition) { return SizedBox.square( dimension: 200, child: Builder( builder: (BuildContext context) { capturedContext = context; return Container(); }, ) ); }, ), )); await tester.pumpAndSettle(); expect( RestorationScope.of(capturedContext).restorationId, 'Custom Restoration ID', ); expect( Scrollable.of(capturedContext, axis: Axis.vertical).widget.restorationId, 'OuterVerticalTwoDimensionalScrollable', ); expect( Scrollable.of(capturedContext, axis: Axis.horizontal).widget.restorationId, 'InnerHorizontalTwoDimensionalScrollable', ); // default restorationID await tester.pumpWidget(TwoDimensionalScrollable( horizontalDetails: const ScrollableDetails.horizontal(), verticalDetails: const ScrollableDetails.vertical(), viewportBuilder: (BuildContext context, ViewportOffset verticalPosition, ViewportOffset horizontalPosition) { return SizedBox.square( dimension: 200, child: Builder( builder: (BuildContext context) { capturedContext = context; return Container(); }, ) ); }, )); await tester.pumpAndSettle(); expect( RestorationScope.maybeOf(capturedContext), isNull, ); expect( Scrollable.of(capturedContext, axis: Axis.vertical).widget.restorationId, 'OuterVerticalTwoDimensionalScrollable', ); expect( Scrollable.of(capturedContext, axis: Axis.horizontal).widget.restorationId, 'InnerHorizontalTwoDimensionalScrollable', ); }, variant: TargetPlatformVariant.all()); testWidgets('Restoration works', (WidgetTester tester) async { await tester.pumpWidget(WidgetsApp( color: const Color(0xFFFFFFFF), restorationScopeId: 'Test ID', builder: (BuildContext context, Widget? child) => TwoDimensionalScrollable( restorationId: 'Custom Restoration ID', horizontalDetails: const ScrollableDetails.horizontal(), verticalDetails: const ScrollableDetails.vertical(), viewportBuilder: (BuildContext context, ViewportOffset verticalPosition, ViewportOffset horizontalPosition) { return SimpleBuilderTableViewport( verticalOffset: verticalPosition, verticalAxisDirection: AxisDirection.down, horizontalOffset: horizontalPosition, horizontalAxisDirection: AxisDirection.right, delegate: builderDelegate, mainAxis: Axis.vertical, ); }, ), )); await tester.pumpAndSettle(); await restoreScrollAndVerify(tester); }, variant: TargetPlatformVariant.all()); testWidgets('Inner Scrollables receive the correct details from TwoDimensionalScrollable', (WidgetTester tester) async { // Default late BuildContext capturedContext; await tester.pumpWidget(TwoDimensionalScrollable( horizontalDetails: const ScrollableDetails.horizontal(), verticalDetails: const ScrollableDetails.vertical(), viewportBuilder: (BuildContext context, ViewportOffset verticalPosition, ViewportOffset horizontalPosition) { return SizedBox.square( dimension: 200, child: Builder( builder: (BuildContext context) { capturedContext = context; return Container(); }, ) ); }, )); await tester.pumpAndSettle(); // Vertical ScrollableState vertical = Scrollable.of(capturedContext, axis: Axis.vertical); expect(vertical.widget.key, isNotNull); expect(vertical.widget.axisDirection, AxisDirection.down); expect(vertical.widget.controller, isNotNull); expect(vertical.widget.physics, isNull); expect(vertical.widget.clipBehavior, Clip.hardEdge); expect(vertical.widget.incrementCalculator, isNull); expect(vertical.widget.excludeFromSemantics, isFalse); expect(vertical.widget.restorationId, 'OuterVerticalTwoDimensionalScrollable'); expect(vertical.widget.dragStartBehavior, DragStartBehavior.start); // Horizontal ScrollableState horizontal = Scrollable.of(capturedContext, axis: Axis.horizontal); expect(horizontal.widget.key, isNotNull); expect(horizontal.widget.axisDirection, AxisDirection.right); expect(horizontal.widget.controller, isNotNull); expect(horizontal.widget.physics, isNull); expect(horizontal.widget.clipBehavior, Clip.hardEdge); expect(horizontal.widget.incrementCalculator, isNull); expect(horizontal.widget.excludeFromSemantics, isFalse); expect(horizontal.widget.restorationId, 'InnerHorizontalTwoDimensionalScrollable'); expect(horizontal.widget.dragStartBehavior, DragStartBehavior.start); // Customized final ScrollController horizontalController = ScrollController(); addTearDown(horizontalController.dispose); final ScrollController verticalController = ScrollController(); addTearDown(verticalController.dispose); double calculator(_) => 0.0; await tester.pumpWidget(TwoDimensionalScrollable( incrementCalculator: calculator, excludeFromSemantics: true, dragStartBehavior: DragStartBehavior.down, horizontalDetails: ScrollableDetails.horizontal( reverse: true, controller: horizontalController, physics: const ClampingScrollPhysics(), decorationClipBehavior: Clip.antiAlias, ), verticalDetails: ScrollableDetails.vertical( reverse: true, controller: verticalController, physics: const AlwaysScrollableScrollPhysics(), decorationClipBehavior: Clip.antiAliasWithSaveLayer, ), viewportBuilder: (BuildContext context, ViewportOffset verticalPosition, ViewportOffset horizontalPosition) { return SizedBox.square( dimension: 200, child: Builder( builder: (BuildContext context) { capturedContext = context; return Container(); }, ) ); }, )); await tester.pumpAndSettle(); // Vertical vertical = Scrollable.of(capturedContext, axis: Axis.vertical); expect(vertical.widget.key, isNotNull); expect(vertical.widget.axisDirection, AxisDirection.up); expect(vertical.widget.controller, verticalController); expect(vertical.widget.physics, const AlwaysScrollableScrollPhysics()); expect(vertical.widget.clipBehavior, Clip.antiAliasWithSaveLayer); expect( vertical.widget.incrementCalculator!(ScrollIncrementDetails( type: ScrollIncrementType.line, metrics: verticalController.position, )), 0.0, ); expect(vertical.widget.excludeFromSemantics, isTrue); expect(vertical.widget.restorationId, 'OuterVerticalTwoDimensionalScrollable'); expect(vertical.widget.dragStartBehavior, DragStartBehavior.down); // Horizontal horizontal = Scrollable.of(capturedContext, axis: Axis.horizontal); expect(horizontal.widget.key, isNotNull); expect(horizontal.widget.axisDirection, AxisDirection.left); expect(horizontal.widget.controller, horizontalController); expect(horizontal.widget.physics, const ClampingScrollPhysics()); expect(horizontal.widget.clipBehavior, Clip.antiAlias); expect( horizontal.widget.incrementCalculator!(ScrollIncrementDetails( type: ScrollIncrementType.line, metrics: horizontalController.position, )), 0.0, ); expect(horizontal.widget.excludeFromSemantics, isTrue); expect(horizontal.widget.restorationId, 'InnerHorizontalTwoDimensionalScrollable'); expect(horizontal.widget.dragStartBehavior, DragStartBehavior.down); }, variant: TargetPlatformVariant.all()); group('DiagonalDragBehavior', () { testWidgets('none (default)', (WidgetTester tester) async { // Vertical and horizontal axes are locked. final ScrollController verticalController = ScrollController(); addTearDown(verticalController.dispose); final ScrollController horizontalController = ScrollController(); addTearDown(horizontalController.dispose); await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: simpleBuilderTest( verticalDetails: ScrollableDetails.vertical(controller: verticalController), horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), ) )); await tester.pumpAndSettle(); final Finder findScrollable = find.byElementPredicate((Element e) => e.widget is TwoDimensionalScrollable); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); await tester.drag(findScrollable, const Offset(0.0, -100.0)); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 80.0); expect(horizontalController.position.pixels, 0.0); await tester.drag(findScrollable, const Offset(-100.0, 0.0)); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 80.0); expect(horizontalController.position.pixels, 80.0); // Drag with and x and y offset, only vertical will accept the gesture // since the x is < kTouchSlop await tester.drag(findScrollable, const Offset(-10.0, -50.0)); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 110.0); expect(horizontalController.position.pixels, 80.0); // Drag with and x and y offset, only horizontal will accept the gesture // since the y is < kTouchSlop await tester.drag(findScrollable, const Offset(-50.0, -10.0)); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 110.0); expect(horizontalController.position.pixels, 110.0); // Drag with and x and y offset, only vertical will accept the gesture // x is > kTouchSlop, larger offset wins await tester.drag(findScrollable, const Offset(-20.0, -50.0)); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 140.0); expect(horizontalController.position.pixels, 110.0); // Drag with and x and y offset, only horizontal will accept the gesture // y is > kTouchSlop, larger offset wins await tester.drag(findScrollable, const Offset(-50.0, -20.0)); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 140.0); expect(horizontalController.position.pixels, 140.0); }, variant: TargetPlatformVariant.all()); testWidgets('weightedEvent', (WidgetTester tester) async { // For weighted event, the winning axis is locked for the duration of // the gesture. final ScrollController verticalController = ScrollController(); addTearDown(verticalController.dispose); final ScrollController horizontalController = ScrollController(); addTearDown(horizontalController.dispose); await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: simpleBuilderTest( diagonalDrag: DiagonalDragBehavior.weightedEvent, verticalDetails: ScrollableDetails.vertical(controller: verticalController), horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), ) )); await tester.pumpAndSettle(); final Finder findScrollable = find.byElementPredicate((Element e) => e.widget is TwoDimensionalScrollable); // Locks to vertical axis - simple. expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); TestGesture gesture = await tester.startGesture(tester.getCenter(findScrollable)); // In this case, the vertical axis clearly wins. Offset secondLocation = tester.getCenter(findScrollable) + const Offset(0.0, -50.0); await gesture.moveTo(secondLocation); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 50.0); expect(horizontalController.position.pixels, 0.0); // Gesture has not ended yet, move with horizontal diff Offset thirdLocation = secondLocation + const Offset(-30, -15); await gesture.moveTo(thirdLocation); await tester.pumpAndSettle(); // Only vertical diff applied expect(verticalController.position.pixels, 65.0); expect(horizontalController.position.pixels, 0.0); await gesture.up(); await tester.pumpAndSettle(); // Lock to vertical axis - scrolls diagonally until certain verticalController.jumpTo(0.0); horizontalController.jumpTo(0.0); await tester.pump(); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); gesture = await tester.startGesture(tester.getCenter(findScrollable)); // In this case, the no one clearly wins, so it moves diagonally. secondLocation = tester.getCenter(findScrollable) + const Offset(-50.0, -50.0); await gesture.moveTo(secondLocation); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 50.0); expect(horizontalController.position.pixels, 50.0); // Gesture has not ended yet, move clearly indicating vertical thirdLocation = secondLocation + const Offset(-20, -50); await gesture.moveTo(thirdLocation); await tester.pumpAndSettle(); // Only vertical diff applied expect(verticalController.position.pixels, 100.0); expect(horizontalController.position.pixels, 50.0); // Gesture has not ended yet, and vertical axis has won for the gesture // continue only vertical scrolling. Offset fourthLocation = thirdLocation + const Offset(-30, -30); await gesture.moveTo(fourthLocation); await tester.pumpAndSettle(); // Only vertical diff applied expect(verticalController.position.pixels, 130.0); expect(horizontalController.position.pixels, 50.0); await gesture.up(); await tester.pumpAndSettle(); // Locks to horizontal axis - simple. verticalController.jumpTo(0.0); horizontalController.jumpTo(0.0); await tester.pump(); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); gesture = await tester.startGesture(tester.getCenter(findScrollable)); // In this case, the horizontal axis clearly wins. secondLocation = tester.getCenter(findScrollable) + const Offset(-50.0, 0.0); await gesture.moveTo(secondLocation); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 50.0); // Gesture has not ended yet, move with vertical diff thirdLocation = secondLocation + const Offset(-15, -30); await gesture.moveTo(thirdLocation); await tester.pumpAndSettle(); // Only vertical diff applied expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 65.0); await gesture.up(); await tester.pumpAndSettle(); // Lock to horizontal axis - scrolls diagonally until certain verticalController.jumpTo(0.0); horizontalController.jumpTo(0.0); await tester.pump(); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); gesture = await tester.startGesture(tester.getCenter(findScrollable)); // In this case, the no one clearly wins, so it moves diagonally. secondLocation = tester.getCenter(findScrollable) + const Offset(-50.0, -50.0); await gesture.moveTo(secondLocation); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 50.0); expect(horizontalController.position.pixels, 50.0); // Gesture has not ended yet, move clearly indicating horizontal thirdLocation = secondLocation + const Offset(-50, -20); await gesture.moveTo(thirdLocation); await tester.pumpAndSettle(); // Only horizontal diff applied expect(verticalController.position.pixels, 50.0); expect(horizontalController.position.pixels, 100.0); // Gesture has not ended yet, and horizontal axis has won for the gesture // continue only horizontal scrolling. fourthLocation = thirdLocation + const Offset(-30, -30); await gesture.moveTo(fourthLocation); await tester.pumpAndSettle(); // Only horizontal diff applied expect(verticalController.position.pixels, 50.0); expect(horizontalController.position.pixels, 130.0); await gesture.up(); await tester.pumpAndSettle(); }, variant: TargetPlatformVariant.all()); testWidgets('weightedContinuous', (WidgetTester tester) async { // For weighted continuous, the winning axis can change if the axis // differential for the gesture exceeds kTouchSlop. So it can lock, and // remain locked, if the user maintains a generally straight gesture, // otherwise it will unlock and re-evaluate. final ScrollController verticalController = ScrollController(); addTearDown(verticalController.dispose); final ScrollController horizontalController = ScrollController(); addTearDown(horizontalController.dispose); await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: simpleBuilderTest( diagonalDrag: DiagonalDragBehavior.weightedContinuous, verticalDetails: ScrollableDetails.vertical(controller: verticalController), horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), ) )); await tester.pumpAndSettle(); final Finder findScrollable = find.byElementPredicate((Element e) => e.widget is TwoDimensionalScrollable); // Locks to vertical, and then unlocks, resets to horizontal, then // unlocks and scrolls diagonally. expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); final TestGesture gesture = await tester.startGesture(tester.getCenter(findScrollable)); // In this case, the vertical axis clearly wins. final Offset secondLocation = tester.getCenter(findScrollable) + const Offset(0.0, -50.0); await gesture.moveTo(secondLocation); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 50.0); expect(horizontalController.position.pixels, 0.0); // Gesture has not ended yet, move with horizontal diff, but still // dominant vertical final Offset thirdLocation = secondLocation + const Offset(-15, -50); await gesture.moveTo(thirdLocation); await tester.pumpAndSettle(); // Only vertical diff applied since kTouchSlop was not exceeded in the // horizontal axis from one drag event to the next. expect(verticalController.position.pixels, 100.0); expect(horizontalController.position.pixels, 0.0); // Gesture has not ended yet, move with unlocking horizontal diff final Offset fourthLocation = thirdLocation + const Offset(-50, -15); await gesture.moveTo(fourthLocation); await tester.pumpAndSettle(); // Only horizontal diff applied expect(verticalController.position.pixels, 100.0); expect(horizontalController.position.pixels, 50.0); // Gesture has not ended yet, move with unlocking diff that results in // diagonal move since neither wins. final Offset fifthLocation = fourthLocation + const Offset(-50, -50); await gesture.moveTo(fifthLocation); await tester.pumpAndSettle(); // Only horizontal diff applied expect(verticalController.position.pixels, 150.0); expect(horizontalController.position.pixels, 100.0); await gesture.up(); await tester.pumpAndSettle(); }, variant: TargetPlatformVariant.all()); testWidgets('free', (WidgetTester tester) async { // For free, anything goes. final ScrollController verticalController = ScrollController(); addTearDown(verticalController.dispose); final ScrollController horizontalController = ScrollController(); addTearDown(horizontalController.dispose); await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: simpleBuilderTest( diagonalDrag: DiagonalDragBehavior.free, verticalDetails: ScrollableDetails.vertical(controller: verticalController), horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), ) )); await tester.pumpAndSettle(); final Finder findScrollable = find.byElementPredicate((Element e) => e.widget is TwoDimensionalScrollable); // Nothing locks. expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); final TestGesture gesture = await tester.startGesture(tester.getCenter(findScrollable)); final Offset secondLocation = tester.getCenter(findScrollable) + const Offset(0.0, -50.0); await gesture.moveTo(secondLocation); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 50.0); expect(horizontalController.position.pixels, 0.0); final Offset thirdLocation = secondLocation + const Offset(-15, -50); await gesture.moveTo(thirdLocation); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 100.0); expect(horizontalController.position.pixels, 15.0); final Offset fourthLocation = thirdLocation + const Offset(-50, -15); await gesture.moveTo(fourthLocation); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 115.0); expect(horizontalController.position.pixels, 65.0); final Offset fifthLocation = fourthLocation + const Offset(-50, -50); await gesture.moveTo(fifthLocation); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 165.0); expect(horizontalController.position.pixels, 115.0); await gesture.up(); await tester.pumpAndSettle(); }); }); }); testWidgets('TwoDimensionalViewport asserts against axes mismatch', (WidgetTester tester) async { // Horizontal mismatch expect( () { final ViewportOffset verticalOffset = ViewportOffset.fixed(0.0); addTearDown(verticalOffset.dispose); final ViewportOffset horizontalOffset = ViewportOffset.fixed(0.0); addTearDown(horizontalOffset.dispose); SimpleBuilderTableViewport( verticalOffset: verticalOffset, verticalAxisDirection: AxisDirection.left, horizontalOffset: horizontalOffset, horizontalAxisDirection: AxisDirection.right, delegate: builderDelegate, mainAxis: Axis.vertical, ); }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains('AxisDirection is not Axis.'), ), ), ); // Vertical mismatch expect( () { final ViewportOffset verticalOffset = ViewportOffset.fixed(0.0); addTearDown(verticalOffset.dispose); final ViewportOffset horizontalOffset = ViewportOffset.fixed(0.0); addTearDown(horizontalOffset.dispose); SimpleBuilderTableViewport( verticalOffset: verticalOffset, verticalAxisDirection: AxisDirection.up, horizontalOffset: horizontalOffset, horizontalAxisDirection: AxisDirection.down, delegate: builderDelegate, mainAxis: Axis.vertical, ); }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains('AxisDirection is not Axis.'), ), ), ); // Both expect( () { final ViewportOffset verticalOffset = ViewportOffset.fixed(0.0); addTearDown(verticalOffset.dispose); final ViewportOffset horizontalOffset = ViewportOffset.fixed(0.0); addTearDown(horizontalOffset.dispose); SimpleBuilderTableViewport( verticalOffset: verticalOffset, verticalAxisDirection: AxisDirection.left, horizontalOffset: horizontalOffset, horizontalAxisDirection: AxisDirection.down, delegate: builderDelegate, mainAxis: Axis.vertical, ); }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains('AxisDirection is not Axis.'), ), ), ); }); test('TwoDimensionalViewportParentData', () { // Default vicinity is invalid final TwoDimensionalViewportParentData parentData = TwoDimensionalViewportParentData(); expect(parentData.vicinity, ChildVicinity.invalid); // toString parentData ..vicinity = const ChildVicinity(xIndex: 10, yIndex: 10) ..paintOffset = const Offset(20.0, 20.0) ..layoutOffset = const Offset(20.0, 20.0); expect( parentData.toString(), 'vicinity=(xIndex: 10, yIndex: 10); layoutOffset=Offset(20.0, 20.0); ' 'paintOffset=Offset(20.0, 20.0); not visible; ', ); }); test('ChildVicinity comparable', () { const ChildVicinity baseVicinity = ChildVicinity(xIndex: 0, yIndex: 0); const ChildVicinity sameXVicinity = ChildVicinity(xIndex: 0, yIndex: 2); const ChildVicinity sameYVicinity = ChildVicinity(xIndex: 3, yIndex: 0); const ChildVicinity sameNothingVicinity = ChildVicinity(xIndex: 20, yIndex: 30); // == expect(baseVicinity == baseVicinity, isTrue); expect(baseVicinity == sameXVicinity, isFalse); expect(baseVicinity == sameYVicinity, isFalse); expect(baseVicinity == sameNothingVicinity, isFalse); // compareTo expect(baseVicinity.compareTo(baseVicinity), 0); expect(baseVicinity.compareTo(sameXVicinity), -2); expect(baseVicinity.compareTo(sameYVicinity), -3); expect(baseVicinity.compareTo(sameNothingVicinity), -20); // toString expect(baseVicinity.toString(), '(xIndex: 0, yIndex: 0)'); expect(sameXVicinity.toString(), '(xIndex: 0, yIndex: 2)'); expect(sameYVicinity.toString(), '(xIndex: 3, yIndex: 0)'); expect(sameNothingVicinity.toString(), '(xIndex: 20, yIndex: 30)'); }); group('RenderTwoDimensionalViewport', () { testWidgets('asserts against axes mismatch', (WidgetTester tester) async { // Horizontal mismatch expect( () { final ViewportOffset verticalOffset = ViewportOffset.fixed(0.0); addTearDown(verticalOffset.dispose); final ViewportOffset horizontalOffset = ViewportOffset.fixed(0.0); addTearDown(horizontalOffset.dispose); RenderSimpleBuilderTableViewport( verticalOffset: verticalOffset, verticalAxisDirection: AxisDirection.left, horizontalOffset: horizontalOffset, horizontalAxisDirection: AxisDirection.right, delegate: builderDelegate, mainAxis: Axis.vertical, childManager: _NullBuildContext(), ); }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains('AxisDirection is not Axis.'), ), ), ); // Vertical mismatch expect( () { final ViewportOffset verticalOffset = ViewportOffset.fixed(0.0); addTearDown(verticalOffset.dispose); final ViewportOffset horizontalOffset = ViewportOffset.fixed(0.0); addTearDown(horizontalOffset.dispose); RenderSimpleBuilderTableViewport( verticalOffset: verticalOffset, verticalAxisDirection: AxisDirection.up, horizontalOffset: horizontalOffset, horizontalAxisDirection: AxisDirection.down, delegate: builderDelegate, mainAxis: Axis.vertical, childManager: _NullBuildContext(), ); }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains('AxisDirection is not Axis.'), ), ), ); // Both expect( () { final ViewportOffset verticalOffset = ViewportOffset.fixed(0.0); addTearDown(verticalOffset.dispose); final ViewportOffset horizontalOffset = ViewportOffset.fixed(0.0); addTearDown(horizontalOffset.dispose); RenderSimpleBuilderTableViewport( verticalOffset: verticalOffset, verticalAxisDirection: AxisDirection.left, horizontalOffset: horizontalOffset, horizontalAxisDirection: AxisDirection.down, delegate: builderDelegate, mainAxis: Axis.vertical, childManager: _NullBuildContext(), ); }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains('AxisDirection is not Axis.'), ), ), ); }); testWidgets('getters', (WidgetTester tester) async { final UniqueKey childKey = UniqueKey(); final TwoDimensionalChildBuilderDelegate delegate = TwoDimensionalChildBuilderDelegate( maxXIndex: 0, maxYIndex: 0, builder: (BuildContext context, ChildVicinity vicinity) { return SizedBox.square(key: childKey, dimension: 200); } ); addTearDown(delegate.dispose); final ViewportOffset verticalOffset = ViewportOffset.fixed(10.0); addTearDown(verticalOffset.dispose); final ViewportOffset horizontalOffset = ViewportOffset.fixed(20.0); addTearDown(horizontalOffset.dispose); final RenderSimpleBuilderTableViewport renderViewport = RenderSimpleBuilderTableViewport( verticalOffset: verticalOffset, verticalAxisDirection: AxisDirection.down, horizontalOffset: horizontalOffset, horizontalAxisDirection: AxisDirection.right, delegate: delegate, mainAxis: Axis.vertical, childManager: _NullBuildContext(), ); addTearDown(renderViewport.dispose); expect(renderViewport.clipBehavior, Clip.hardEdge); expect(renderViewport.cacheExtent, RenderAbstractViewport.defaultCacheExtent); expect(renderViewport.isRepaintBoundary, isTrue); expect(renderViewport.sizedByParent, isTrue); // No size yet, should assert. expect( () { renderViewport.viewportDimension; }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains('hasSize'), ), ), ); expect(renderViewport.horizontalOffset.pixels, 20.0); expect(renderViewport.horizontalAxisDirection, AxisDirection.right); expect(renderViewport.verticalOffset.pixels, 10.0); expect(renderViewport.verticalAxisDirection, AxisDirection.down); expect(renderViewport.delegate, delegate); expect(renderViewport.mainAxis, Axis.vertical); // viewportDimension when hasSize await tester.pumpWidget(simpleBuilderTest( delegate: delegate, )); await tester.pumpAndSettle(); final RenderTwoDimensionalViewport viewport = getViewport(tester, childKey); expect(viewport.viewportDimension, const Size(800.0, 600.0)); }, variant: TargetPlatformVariant.all()); testWidgets('Children are organized according to mainAxis', (WidgetTester tester) async { final Map<ChildVicinity, UniqueKey> childKeys = <ChildVicinity, UniqueKey>{}; final TwoDimensionalChildBuilderDelegate delegate = TwoDimensionalChildBuilderDelegate( maxXIndex: 5, maxYIndex: 5, builder: (BuildContext context, ChildVicinity vicinity) { childKeys[vicinity] = childKeys[vicinity] ?? UniqueKey(); return SizedBox.square(key: childKeys[vicinity], dimension: 200); } ); addTearDown(delegate.dispose); TwoDimensionalViewportParentData parentDataOf(RenderBox child) { return child.parentData! as TwoDimensionalViewportParentData; } // mainAxis is vertical (default) await tester.pumpWidget(simpleBuilderTest( delegate: delegate, )); await tester.pumpAndSettle(); RenderTwoDimensionalViewport viewport = getViewport( tester, childKeys.values.first, ); expect(viewport.mainAxis, Axis.vertical); // first child expect( parentDataOf(viewport.firstChild!).vicinity, const ChildVicinity(xIndex: 0, yIndex: 0), ); expect( parentDataOf(viewport.childAfter(viewport.firstChild!)!).vicinity, const ChildVicinity(xIndex: 1, yIndex: 0), ); expect( viewport.childBefore(viewport.firstChild!), isNull, ); // last child expect( parentDataOf(viewport.lastChild!).vicinity, const ChildVicinity(xIndex: 4, yIndex: 3), ); expect( viewport.childAfter(viewport.lastChild!), isNull, ); expect( parentDataOf(viewport.childBefore(viewport.lastChild!)!).vicinity, const ChildVicinity(xIndex: 3, yIndex: 3), ); // mainAxis is horizontal await tester.pumpWidget(simpleBuilderTest( delegate: delegate, mainAxis: Axis.horizontal, )); await tester.pumpAndSettle(); viewport = getViewport(tester, childKeys.values.first); expect(viewport.mainAxis, Axis.horizontal); // first child expect( parentDataOf(viewport.firstChild!).vicinity, const ChildVicinity(xIndex: 0, yIndex: 0), ); expect( parentDataOf(viewport.childAfter(viewport.firstChild!)!).vicinity, const ChildVicinity(xIndex: 0, yIndex: 1), ); expect( viewport.childBefore(viewport.firstChild!), isNull, ); // last child expect( parentDataOf(viewport.lastChild!).vicinity, const ChildVicinity(xIndex: 4, yIndex: 3), ); expect( viewport.childAfter(viewport.lastChild!), isNull, ); expect( parentDataOf(viewport.childBefore(viewport.lastChild!)!).vicinity, const ChildVicinity(xIndex: 4, yIndex: 2), ); }, variant: TargetPlatformVariant.all()); testWidgets('sets up parent data', (WidgetTester tester) async { // Also tests computeAbsolutePaintOffsetFor & computeChildPaintExtent // Regression test for https://github.com/flutter/flutter/issues/128723 final Map<ChildVicinity, UniqueKey> childKeys = <ChildVicinity, UniqueKey>{}; final TwoDimensionalChildBuilderDelegate delegate = TwoDimensionalChildBuilderDelegate( maxXIndex: 5, maxYIndex: 5, builder: (BuildContext context, ChildVicinity vicinity) { childKeys[vicinity] = childKeys[vicinity] ?? UniqueKey(); return SizedBox.square(key: childKeys[vicinity], dimension: 200); } ); addTearDown(delegate.dispose); // parent data is TwoDimensionalViewportParentData TwoDimensionalViewportParentData parentDataOf(RenderBox child) { return child.parentData! as TwoDimensionalViewportParentData; } await tester.pumpWidget(simpleBuilderTest( delegate: delegate, useCacheExtent: true, )); await tester.pumpAndSettle(); RenderTwoDimensionalViewport viewport = getViewport( tester, childKeys.values.first, ); // first child // parentData is computed correctly - normal axes // - layoutOffset, paintOffset, isVisible, ChildVicinity TwoDimensionalViewportParentData childParentData = parentDataOf(viewport.firstChild!); expect(childParentData.vicinity, const ChildVicinity(xIndex: 0, yIndex: 0)); expect(childParentData.isVisible, isTrue); expect(childParentData.paintOffset, Offset.zero); expect(childParentData.layoutOffset, Offset.zero); // The last child is in the cache extent, and should not be visible. childParentData = parentDataOf(viewport.lastChild!); expect(childParentData.vicinity, const ChildVicinity(xIndex: 5, yIndex: 5)); expect(childParentData.isVisible, isFalse); expect(childParentData.paintOffset, const Offset(1000.0, 1000.0)); expect(childParentData.layoutOffset, const Offset(1000.0, 1000.0)); // parentData is computed correctly - reverse axes // - vertical reverse await tester.pumpWidget(simpleBuilderTest( delegate: delegate, verticalDetails: const ScrollableDetails.vertical(reverse: true), )); await tester.pumpAndSettle(); viewport = getViewport(tester, childKeys.values.first); childParentData = parentDataOf(viewport.firstChild!); expect(childParentData.vicinity, const ChildVicinity(xIndex: 0, yIndex: 0)); expect(childParentData.isVisible, isTrue); expect(childParentData.paintOffset, const Offset(0.0, 400.0)); expect(childParentData.layoutOffset, Offset.zero); // The last child is in the cache extent, and should not be visible. childParentData = parentDataOf(viewport.lastChild!); expect(childParentData.vicinity, const ChildVicinity(xIndex: 5, yIndex: 5)); expect(childParentData.isVisible, isFalse); expect(childParentData.paintOffset, const Offset(1000.0, -600.0)); expect(childParentData.layoutOffset, const Offset(1000.0, 1000.0)); // - horizontal reverse await tester.pumpWidget(simpleBuilderTest( delegate: delegate, horizontalDetails: const ScrollableDetails.horizontal(reverse: true), )); await tester.pumpAndSettle(); viewport = getViewport(tester, childKeys.values.first); childParentData = parentDataOf(viewport.firstChild!); expect(childParentData.vicinity, const ChildVicinity(xIndex: 0, yIndex: 0)); expect(childParentData.isVisible, isTrue); expect(childParentData.paintOffset, const Offset(600.0, 0.0)); expect(childParentData.layoutOffset, Offset.zero); // The last child is in the cache extent, and should not be visible. childParentData = parentDataOf(viewport.lastChild!); expect(childParentData.vicinity, const ChildVicinity(xIndex: 5, yIndex: 5)); expect(childParentData.isVisible, isFalse); expect(childParentData.paintOffset, const Offset(-400.0, 1000.0)); expect(childParentData.layoutOffset, const Offset(1000.0, 1000.0)); // - both reverse await tester.pumpWidget(simpleBuilderTest( delegate: delegate, horizontalDetails: const ScrollableDetails.horizontal(reverse: true), verticalDetails: const ScrollableDetails.vertical(reverse: true), )); await tester.pumpAndSettle(); viewport = getViewport(tester, childKeys.values.first); childParentData = parentDataOf(viewport.firstChild!); expect(childParentData.vicinity, const ChildVicinity(xIndex: 0, yIndex: 0)); expect(childParentData.isVisible, isTrue); expect(childParentData.paintOffset, const Offset(600.0, 400.0)); expect(childParentData.layoutOffset, Offset.zero); // The last child is in the cache extent, and should not be visible. childParentData = parentDataOf(viewport.lastChild!); expect(childParentData.vicinity, const ChildVicinity(xIndex: 5, yIndex: 5)); expect(childParentData.isVisible, isFalse); expect(childParentData.paintOffset, const Offset(-400.0, -600.0)); expect(childParentData.layoutOffset, const Offset(1000.0, 1000.0)); // Change the scroll positions to test partially visible. final ScrollController verticalController = ScrollController(); addTearDown(verticalController.dispose); final ScrollController horizontalController = ScrollController(); addTearDown(horizontalController.dispose); await tester.pumpWidget(simpleBuilderTest( delegate: delegate, horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), verticalDetails: ScrollableDetails.vertical(controller: verticalController), )); await tester.pumpAndSettle(); verticalController.jumpTo(50.0); horizontalController.jumpTo(50.0); await tester.pump(); viewport = getViewport(tester, childKeys.values.first); childParentData = parentDataOf(viewport.firstChild!); expect(childParentData.vicinity, const ChildVicinity(xIndex: 0, yIndex: 0)); expect(childParentData.isVisible, isTrue); expect(childParentData.paintOffset, const Offset(-50.0, -50.0)); expect(childParentData.layoutOffset, const Offset(-50.0, -50.0)); }, variant: TargetPlatformVariant.all()); testWidgets('debugDescribeChildren', (WidgetTester tester) async { final Map<ChildVicinity, UniqueKey> childKeys = <ChildVicinity, UniqueKey>{}; final TwoDimensionalChildBuilderDelegate delegate = TwoDimensionalChildBuilderDelegate( maxXIndex: 5, maxYIndex: 5, builder: (BuildContext context, ChildVicinity vicinity) { childKeys[vicinity] = childKeys[vicinity] ?? UniqueKey(); return SizedBox.square(key: childKeys[vicinity], dimension: 200); } ); addTearDown(delegate.dispose); await tester.pumpWidget(simpleBuilderTest( delegate: delegate, )); await tester.pumpAndSettle(); final RenderTwoDimensionalViewport viewport = getViewport( tester, childKeys.values.first, ); final List<DiagnosticsNode> result = viewport.debugDescribeChildren(); expect(result.length, 20); expect( result.first.toString(), equalsIgnoringHashCodes('(xIndex: 0, yIndex: 0): RenderRepaintBoundary#00000'), ); expect( result.last.toString(), equalsIgnoringHashCodes('(xIndex: 4, yIndex: 3): RenderRepaintBoundary#00000 NEEDS-PAINT'), ); }, variant: TargetPlatformVariant.all()); testWidgets('asserts that both axes are bounded', (WidgetTester tester) async { final List<Object> exceptions = <Object>[]; final FlutterExceptionHandler? oldHandler = FlutterError.onError; FlutterError.onError = (FlutterErrorDetails details) { exceptions.add(details.exception); }; // Compose unbounded - vertical axis await tester.pumpWidget(WidgetsApp( color: const Color(0xFFFFFFFF), builder: (BuildContext context, Widget? child) => Column( children: <Widget>[ SimpleBuilderTableView(delegate: builderDelegate) ] ), )); await tester.pumpAndSettle(); FlutterError.onError = oldHandler; expect(exceptions.isNotEmpty, isTrue); expect((exceptions[0] as FlutterError).message, contains('unbounded')); exceptions.clear(); FlutterError.onError = (FlutterErrorDetails details) { exceptions.add(details.exception); }; // Compose unbounded - horizontal axis await tester.pumpWidget(WidgetsApp( color: const Color(0xFFFFFFFF), builder: (BuildContext context, Widget? child) => Row( children: <Widget>[ SimpleBuilderTableView(delegate: builderDelegate) ] ), )); await tester.pumpAndSettle(); FlutterError.onError = oldHandler; expect(exceptions.isNotEmpty, isTrue); expect((exceptions[0] as FlutterError).message, contains('unbounded')); }, variant: TargetPlatformVariant.all()); testWidgets('computeDryLayout asserts axes are bounded', (WidgetTester tester) async { final UniqueKey childKey = UniqueKey(); final TwoDimensionalChildBuilderDelegate delegate = TwoDimensionalChildBuilderDelegate( maxXIndex: 0, maxYIndex: 0, builder: (BuildContext context, ChildVicinity vicinity) { return SizedBox.square(key: childKey, dimension: 200); } ); addTearDown(delegate.dispose); // Call computeDryLayout with unbounded constraints await tester.pumpWidget(simpleBuilderTest(delegate: delegate)); final RenderTwoDimensionalViewport viewport = getViewport( tester, childKey, ); expect( () { viewport.computeDryLayout(const BoxConstraints()); }, throwsA( isA<FlutterError>().having( (FlutterError error) => error.message, 'error.message', contains('unbounded'), ), ), ); }, variant: TargetPlatformVariant.all()); testWidgets('correctly resizes dimensions', (WidgetTester tester) async { final UniqueKey childKey = UniqueKey(); final TwoDimensionalChildBuilderDelegate delegate = TwoDimensionalChildBuilderDelegate( maxXIndex: 0, maxYIndex: 0, builder: (BuildContext context, ChildVicinity vicinity) { return SizedBox.square(key: childKey, dimension: 200); } ); addTearDown(delegate.dispose); await tester.pumpWidget(simpleBuilderTest( delegate: delegate, )); await tester.pumpAndSettle(); RenderTwoDimensionalViewport viewport = getViewport( tester, childKey, ); expect(viewport.viewportDimension, const Size(800.0, 600.0)); tester.view.physicalSize = const Size(300.0, 300.0); tester.view.devicePixelRatio = 1; await tester.pumpWidget(simpleBuilderTest( delegate: delegate, )); await tester.pumpAndSettle(); viewport = getViewport(tester, childKey); expect(viewport.viewportDimension, const Size(300.0, 300.0)); tester.view.resetPhysicalSize(); tester.view.resetDevicePixelRatio(); }, variant: TargetPlatformVariant.all()); testWidgets('Rebuilds when delegate changes', (WidgetTester tester) async { final UniqueKey firstChildKey = UniqueKey(); final TwoDimensionalChildBuilderDelegate delegate = TwoDimensionalChildBuilderDelegate( maxXIndex: 0, maxYIndex: 0, addRepaintBoundaries: false, builder: (BuildContext context, ChildVicinity vicinity) { return SizedBox.square(key: firstChildKey, dimension: 200); } ); addTearDown(delegate.dispose); await tester.pumpWidget(simpleBuilderTest( delegate: delegate, )); RenderTwoDimensionalViewport viewport = getViewport(tester, firstChildKey); expect(viewport.firstChild, tester.renderObject<RenderBox>(find.byKey(firstChildKey))); // New delegate final UniqueKey newChildKey = UniqueKey(); final TwoDimensionalChildBuilderDelegate newDelegate = TwoDimensionalChildBuilderDelegate( maxXIndex: 0, maxYIndex: 0, addRepaintBoundaries: false, builder: (BuildContext context, ChildVicinity vicinity) { return Container(key: newChildKey, height: 300, width: 300, color: const Color(0xFFFFFFFF)); } ); addTearDown(() => newDelegate.dispose()); await tester.pumpWidget(simpleBuilderTest( delegate: newDelegate, )); viewport = getViewport(tester, newChildKey); expect(firstChildKey, isNot(newChildKey)); expect(find.byKey(firstChildKey), findsNothing); expect(find.byKey(newChildKey), findsOneWidget); expect(viewport.firstChild, tester.renderObject<RenderBox>(find.byKey(newChildKey))); }, variant: TargetPlatformVariant.all()); testWidgets('hitTestChildren', (WidgetTester tester) async { final List<ChildVicinity> taps = <ChildVicinity>[]; final Map<ChildVicinity, UniqueKey> childKeys = <ChildVicinity, UniqueKey>{}; final TwoDimensionalChildBuilderDelegate delegate = TwoDimensionalChildBuilderDelegate( maxXIndex: 19, maxYIndex: 19, builder: (BuildContext context, ChildVicinity vicinity) { childKeys[vicinity] = childKeys[vicinity] ?? UniqueKey(); return SizedBox.square( dimension: 200, child: Center( child: FloatingActionButton( key: childKeys[vicinity], onPressed: () { taps.add(vicinity); }, ), ), ); } ); addTearDown(delegate.dispose); await tester.pumpWidget(simpleBuilderTest( delegate: delegate, useCacheExtent: true, // Untappable children are rendered in the cache extent )); await tester.pumpAndSettle(); // Regular orientation // Offset at center of first child await tester.tapAt(const Offset(100.0, 100.0)); await tester.pump(); expect(taps.contains(const ChildVicinity(xIndex: 0, yIndex: 0)), isTrue); // Offset by child location await tester.tap(find.byKey(childKeys[const ChildVicinity(xIndex: 2, yIndex: 2)]!)); await tester.pump(); expect(taps.contains(const ChildVicinity(xIndex: 2, yIndex: 2)), isTrue); // Offset out of bounds await tester.tap( find.byKey(childKeys[const ChildVicinity(xIndex: 5, yIndex: 5)]!), warnIfMissed: false, ); await tester.pump(); expect(taps.contains(const ChildVicinity(xIndex: 5, yIndex: 5)), isFalse); // Reversed await tester.pumpWidget(simpleBuilderTest( delegate: delegate, verticalDetails: const ScrollableDetails.vertical(reverse: true), horizontalDetails: const ScrollableDetails.horizontal(reverse: true), useCacheExtent: true, // Untappable children are rendered in the cache extent )); await tester.pumpAndSettle(); // Offset at center of first child await tester.tapAt(const Offset(700.0, 500.0)); await tester.pump(); expect(taps.contains(const ChildVicinity(xIndex: 0, yIndex: 0)), isTrue); // Offset by child location await tester.tap(find.byKey(childKeys[const ChildVicinity(xIndex: 2, yIndex: 2)]!)); await tester.pump(); expect(taps.contains(const ChildVicinity(xIndex: 2, yIndex: 2)), isTrue); // Offset out of bounds await tester.tap( find.byKey(childKeys[const ChildVicinity(xIndex: 5, yIndex: 5)]!), warnIfMissed: false, ); await tester.pump(); expect(taps.contains(const ChildVicinity(xIndex: 5, yIndex: 5)), isFalse); }, variant: TargetPlatformVariant.all()); testWidgets('getChildFor', (WidgetTester tester) async { final Map<ChildVicinity, UniqueKey> childKeys = <ChildVicinity, UniqueKey>{}; final TwoDimensionalChildBuilderDelegate delegate = TwoDimensionalChildBuilderDelegate( maxXIndex: 5, maxYIndex: 5, builder: (BuildContext context, ChildVicinity vicinity) { childKeys[vicinity] = childKeys[vicinity] ?? UniqueKey(); return SizedBox.square(key: childKeys[vicinity], dimension: 200); } ); addTearDown(delegate.dispose); await tester.pumpWidget(simpleBuilderTest( delegate: delegate, )); await tester.pumpAndSettle(); final RenderSimpleBuilderTableViewport viewport = getViewport( tester, childKeys.values.first, ) as RenderSimpleBuilderTableViewport; // returns child expect( viewport.testGetChildFor(const ChildVicinity(xIndex: 0, yIndex: 0)), isNotNull, ); expect( viewport.testGetChildFor(const ChildVicinity(xIndex: 0, yIndex: 0)), viewport.firstChild, ); // returns null expect( viewport.testGetChildFor(const ChildVicinity(xIndex: 10, yIndex: 10)), isNull, ); }, variant: TargetPlatformVariant.all()); testWidgets('asserts vicinity is valid when children are asked to build', (WidgetTester tester) async { final Map<ChildVicinity, UniqueKey> childKeys = <ChildVicinity, UniqueKey>{}; final TwoDimensionalChildBuilderDelegate delegate = TwoDimensionalChildBuilderDelegate( maxXIndex: 5, maxYIndex: 5, builder: (BuildContext context, ChildVicinity vicinity) { childKeys[vicinity] = childKeys[vicinity] ?? UniqueKey(); return SizedBox.square(key: childKeys[vicinity], dimension: 200); } ); addTearDown(delegate.dispose); await tester.pumpWidget(simpleBuilderTest( delegate: delegate, )); await tester.pumpAndSettle(); final RenderTwoDimensionalViewport viewport = getViewport( tester, childKeys.values.first, ); expect( () { viewport.buildOrObtainChildFor(ChildVicinity.invalid); }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains('ChildVicinity.invalid'), ), ), ); }, variant: TargetPlatformVariant.all()); testWidgets('asserts that content dimensions have been applied', (WidgetTester tester) async { final TwoDimensionalChildBuilderDelegate delegate = TwoDimensionalChildBuilderDelegate( maxXIndex: 5, maxYIndex: 5, builder: (BuildContext context, ChildVicinity vicinity) { return const SizedBox.square(dimension: 200); } ); addTearDown(delegate.dispose); await tester.pumpWidget(simpleBuilderTest( delegate: delegate, // Will cause the test implementation to not set dimensions applyDimensions: false, )); final FlutterError error = tester.takeException() as FlutterError; expect(error.message, contains('was not given content dimensions')); }, variant: TargetPlatformVariant.all()); testWidgets('will not rebuild a child if it can be reused', (WidgetTester tester) async { final List<ChildVicinity> builtChildren = <ChildVicinity>[]; final ScrollController controller = ScrollController(); addTearDown(controller.dispose); final TwoDimensionalChildBuilderDelegate delegate = TwoDimensionalChildBuilderDelegate( maxXIndex: 5, maxYIndex: 5, builder: (BuildContext context, ChildVicinity vicinity) { builtChildren.add(vicinity); return const SizedBox.square(dimension: 200); } ); addTearDown(delegate.dispose); await tester.pumpWidget(simpleBuilderTest( delegate: delegate, verticalDetails: ScrollableDetails.vertical(controller: controller), )); expect(controller.position.pixels, 0.0); expect(builtChildren.length, 20); expect(builtChildren[0], const ChildVicinity(xIndex: 0, yIndex: 0)); builtChildren.clear(); controller.jumpTo(1.0); // Move slightly to trigger another layout await tester.pump(); expect(controller.position.pixels, 1.0); expect(builtChildren.length, 5); // Next row of children was built // Children from the first layout pass were re-used, not rebuilt. expect( builtChildren.contains(const ChildVicinity(xIndex: 0, yIndex: 0)), isFalse, ); }, variant: TargetPlatformVariant.all()); testWidgets('asserts the layoutOffset has been set by the subclass', (WidgetTester tester) async { final TwoDimensionalChildBuilderDelegate delegate = TwoDimensionalChildBuilderDelegate( maxXIndex: 5, maxYIndex: 5, builder: (BuildContext context, ChildVicinity vicinity) { return const SizedBox.square(dimension: 200); } ); addTearDown(delegate.dispose); await tester.pumpWidget(simpleBuilderTest( delegate: delegate, // Will cause the test implementation to not set the layoutOffset of // the parent data setLayoutOffset: false, )); final AssertionError error = tester.takeException() as AssertionError; expect(error.message, contains('was not provided a layoutOffset')); }, variant: TargetPlatformVariant.all()); testWidgets('asserts the children have a size after layoutChildSequence', (WidgetTester tester) async { final TwoDimensionalChildBuilderDelegate delegate = TwoDimensionalChildBuilderDelegate( maxXIndex: 5, maxYIndex: 5, builder: (BuildContext context, ChildVicinity vicinity) { return const SizedBox.square(dimension: 200); } ); addTearDown(delegate.dispose); await tester.pumpWidget(simpleBuilderTest( delegate: delegate, // Will cause the test implementation to not actually layout the // children it asked for. forgetToLayoutChild: true, )); final AssertionError error = tester.takeException() as AssertionError; expect(error.toString(), contains('child.hasSize')); }, variant: TargetPlatformVariant.all()); testWidgets('does not support intrinsics', (WidgetTester tester) async { final Map<ChildVicinity, UniqueKey> childKeys = <ChildVicinity, UniqueKey>{}; final TwoDimensionalChildBuilderDelegate delegate = TwoDimensionalChildBuilderDelegate( maxXIndex: 5, maxYIndex: 5, builder: (BuildContext context, ChildVicinity vicinity) { childKeys[vicinity] = childKeys[vicinity] ?? UniqueKey(); return SizedBox.square(key: childKeys[vicinity], dimension: 200); } ); addTearDown(delegate.dispose); await tester.pumpWidget(simpleBuilderTest( delegate: delegate, )); await tester.pumpAndSettle(); final RenderTwoDimensionalViewport viewport = getViewport( tester, childKeys.values.first, ); expect( () { viewport.computeMinIntrinsicWidth(100); }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains('does not support returning intrinsic dimensions'), ), ), ); expect( () { viewport.computeMaxIntrinsicWidth(100); }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains('does not support returning intrinsic dimensions'), ), ), ); expect( () { viewport.computeMinIntrinsicHeight(100); }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains('does not support returning intrinsic dimensions'), ), ), ); expect( () { viewport.computeMaxIntrinsicHeight(100); }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains('does not support returning intrinsic dimensions'), ), ), ); }, variant: TargetPlatformVariant.all()); group('showOnScreen & showInViewport', () { Finder findKey(ChildVicinity vicinity) { return find.byKey(ValueKey<ChildVicinity>(vicinity)); } testWidgets('getOffsetToReveal', (WidgetTester tester) async { await tester.pumpWidget(simpleBuilderTest(useCacheExtent: true)); RenderAbstractViewport viewport = tester.allRenderObjects.whereType<RenderAbstractViewport>().first; final RevealedOffset verticalOffset = viewport.getOffsetToReveal( tester.renderObject(findKey(const ChildVicinity(xIndex: 5, yIndex: 5))), 1.0, axis: Axis.vertical, ); final RevealedOffset horizontalOffset = viewport.getOffsetToReveal( tester.renderObject(findKey(const ChildVicinity(xIndex: 5, yIndex: 5))), 1.0, axis: Axis.horizontal, ); expect(verticalOffset.offset, 600.0); expect(verticalOffset.rect, const Rect.fromLTRB(1000.0, 400.0, 1200.0, 600.0)); expect(horizontalOffset.offset, 400.0); expect(horizontalOffset.rect, const Rect.fromLTRB(600.0, 1000.0, 800.0, 1200.0)); // default is to use mainAxis when axis is not provided, mainAxis // defaults to Axis.vertical. RevealedOffset defaultOffset = viewport.getOffsetToReveal( tester.renderObject(findKey(const ChildVicinity(xIndex: 5, yIndex: 5))), 1.0, ); expect(defaultOffset.offset, verticalOffset.offset); expect(defaultOffset.rect, verticalOffset.rect); // mainAxis as Axis.horizontal await tester.pumpWidget(simpleBuilderTest( useCacheExtent: true, mainAxis: Axis.horizontal, )); viewport = tester.allRenderObjects.whereType<RenderAbstractViewport>().first; defaultOffset = viewport.getOffsetToReveal( tester.renderObject(findKey(const ChildVicinity(xIndex: 5, yIndex: 5))), 1.0, ); expect(defaultOffset.offset, horizontalOffset.offset); expect(defaultOffset.rect, horizontalOffset.rect); }); testWidgets('Axis.vertical', (WidgetTester tester) async { await tester.pumpWidget(simpleBuilderTest(useCacheExtent: true)); // Child visible at origin expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 0, yIndex: 0))).dy, equals(0.0), ); tester.renderObject(find.byKey( const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 0, yIndex: 0)), skipOffstage: false, )).showOnScreen(); await tester.pump(); expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 0, yIndex: 0))).dy, equals(0.0), ); // (0, 3) is in the cache extent, and will be brought into view next expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 0, yIndex: 3))).dy, equals(600.0), ); tester.renderObject(find.byKey( const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 0, yIndex: 3)), skipOffstage: false, )).showOnScreen(); await tester.pump(); // Now in view expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 0, yIndex: 3))).dy, equals(400.0), ); // If already visible, no change tester.renderObject(find.byKey( const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 0, yIndex: 3)), skipOffstage: false, )).showOnScreen(); await tester.pump(); expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 0, yIndex: 3))).dy, equals(400.0), ); }); testWidgets('Axis.horizontal', (WidgetTester tester) async { await tester.pumpWidget(simpleBuilderTest(useCacheExtent: true)); tester.renderObject(find.byKey( const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 1, yIndex: 0)), skipOffstage: false, )).showOnScreen(); await tester.pump(); expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 1, yIndex: 0))).dx, equals(200.0), // No change since already fully visible ); // (5, 0) is now in the cache extent, and will be brought into view next expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 5, yIndex: 0))).dx, equals(1000.0), ); tester.renderObject(find.byKey( const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 5, yIndex: 0)), skipOffstage: false, )).showOnScreen(); await tester.pump(); // Now in view expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 5, yIndex: 0))).dx, equals(600.0), ); // If already in position, no change tester.renderObject(find.byKey( const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 5, yIndex: 0)), skipOffstage: false, )).showOnScreen(); await tester.pump(); expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 5, yIndex: 0))).dx, equals(600.0), ); }); testWidgets('both axes', (WidgetTester tester) async { await tester.pumpWidget(simpleBuilderTest(useCacheExtent: true)); tester.renderObject(find.byKey( const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 1, yIndex: 1)), skipOffstage: false, )).showOnScreen(); await tester.pump(); expect( tester.getRect(findKey(const ChildVicinity(xIndex: 1, yIndex: 1))), const Rect.fromLTRB(200.0, 200.0, 400.0, 400.0), ); // (5, 4) is in the cache extent, and will be brought into view next expect( tester.getRect(findKey(const ChildVicinity(xIndex: 5, yIndex: 4))), const Rect.fromLTRB(1000.0, 800.0, 1200.0, 1000.0), ); tester.renderObject(find.byKey( const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 5, yIndex: 4)), skipOffstage: false, )).showOnScreen(); await tester.pump(); // Now in view expect( tester.getRect(findKey(const ChildVicinity(xIndex: 5, yIndex: 4))), const Rect.fromLTRB(600.0, 200.0, 800.0, 400.0), ); // If already visible, no change tester.renderObject(find.byKey( const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 5, yIndex: 4)), skipOffstage: false, )).showOnScreen(); await tester.pump(); expect( tester.getRect(findKey(const ChildVicinity(xIndex: 5, yIndex: 4))), const Rect.fromLTRB(600.0, 200.0, 800.0, 400.0), ); }); testWidgets('Axis.vertical reverse', (WidgetTester tester) async { await tester.pumpWidget(simpleBuilderTest( verticalDetails: const ScrollableDetails.vertical(reverse: true), useCacheExtent: true, )); expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 0, yIndex: 0))).dy, equals(400.0), ); tester.renderObject(find.byKey( const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 0, yIndex: 0)), skipOffstage: false, )).showOnScreen(); await tester.pump(); // Already visible so no change. expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 0, yIndex: 0))).dy, equals(400.0), ); // (0, 3) is in the cache extent, and will be brought into view next expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 0, yIndex: 3))).dy, equals(-200.0), ); tester.renderObject(find.byKey( const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 0, yIndex: 3)), skipOffstage: false, )).showOnScreen(); await tester.pump(); // Now in view expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 0, yIndex: 3))).dy, equals(0.0), ); // If already visible, no change tester.renderObject(find.byKey( const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 0, yIndex: 3)), skipOffstage: false, )).showOnScreen(); await tester.pump(); expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 0, yIndex: 3))).dy, equals(0.0), ); }); testWidgets('Axis.horizontal reverse', (WidgetTester tester) async { await tester.pumpWidget(simpleBuilderTest( horizontalDetails: const ScrollableDetails.horizontal(reverse: true), useCacheExtent: true, )); expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 0, yIndex: 0))).dx, equals(600.0), ); tester.renderObject(find.byKey( const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 0, yIndex: 0)), skipOffstage: false, )).showOnScreen(); await tester.pump(); // Already visible so no change. expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 0, yIndex: 0))).dx, equals(600.0), ); // (4, 0) is in the cache extent, and will be brought into view next expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 4, yIndex: 0))).dx, equals(-200.0), ); tester.renderObject(find.byKey( const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 4, yIndex: 0)), skipOffstage: false, )).showOnScreen(); await tester.pump(); expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 4, yIndex: 0))).dx, equals(0.0), ); // If already visible, no change tester.renderObject(find.byKey( const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 4, yIndex: 0)), skipOffstage: false, )).showOnScreen(); await tester.pump(); expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 4, yIndex: 0))).dx, equals(0.0), ); }); testWidgets('both axes reverse', (WidgetTester tester) async { await tester.pumpWidget(simpleBuilderTest( verticalDetails: const ScrollableDetails.vertical(reverse: true), horizontalDetails: const ScrollableDetails.horizontal(reverse: true), useCacheExtent: true, )); tester.renderObject(find.byKey( const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 1, yIndex: 1)), skipOffstage: false, )).showOnScreen(); await tester.pump(); expect( tester.getRect(findKey(const ChildVicinity(xIndex: 1, yIndex: 1))), const Rect.fromLTRB(400.0, 200.0, 600.0, 400.0), ); // (5, 4) is in the cache extent, and will be brought into view next expect( tester.getRect(findKey(const ChildVicinity(xIndex: 5, yIndex: 4))), const Rect.fromLTRB(-400.0, -400.0, -200.0, -200.0), ); tester.renderObject(find.byKey( const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 5, yIndex: 4)), skipOffstage: false, )).showOnScreen(); await tester.pump(); // Now in view expect( tester.getRect(findKey(const ChildVicinity(xIndex: 5, yIndex: 4))), const Rect.fromLTRB(0.0, 200.0, 200.0, 400.0), ); // If already visible, no change tester.renderObject(find.byKey( const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 5, yIndex: 4)), skipOffstage: false, )).showOnScreen(); await tester.pump(); expect( tester.getRect(findKey(const ChildVicinity(xIndex: 5, yIndex: 4))), const Rect.fromLTRB(0.0, 200.0, 200.0, 400.0), ); }); }); testWidgets('correctly reorders children and wont throw assertion failure', (WidgetTester tester) async { final TwoDimensionalChildBuilderDelegate delegate1 = TwoDimensionalChildBuilderDelegate( maxXIndex: 5, maxYIndex: 5, addAutomaticKeepAlives: false, addRepaintBoundaries: false, builder: (BuildContext context, ChildVicinity vicinity) { ValueKey<int>? key; if (vicinity == const ChildVicinity(xIndex: 1, yIndex: 1)) { key = const ValueKey<int>(1); } else if (vicinity == const ChildVicinity(xIndex: 1, yIndex: 2)) { key = const ValueKey<int>(2); } return SizedBox.square(key: key, dimension: 200); }); final TwoDimensionalChildBuilderDelegate delegate2 = TwoDimensionalChildBuilderDelegate( maxXIndex: 5, maxYIndex: 5, addAutomaticKeepAlives: false, addRepaintBoundaries: false, builder: (BuildContext context, ChildVicinity vicinity) { ValueKey<int>? key; if (vicinity == const ChildVicinity(xIndex: 0, yIndex: 0)) { key = const ValueKey<int>(1); } else if (vicinity == const ChildVicinity(xIndex: 1, yIndex: 1)) { key = const ValueKey<int>(2); } return SizedBox.square(key: key, dimension: 200); }); addTearDown(delegate1.dispose); addTearDown(delegate2.dispose); await tester.pumpWidget(simpleBuilderTest(delegate: delegate1)); expect(tester.getRect(find.byKey(const ValueKey<int>(1))), const Rect.fromLTWH(200.0, 200.0, 200.0, 200.0)); await tester.pumpWidget(simpleBuilderTest(delegate: delegate2)); expect(tester.getRect(find.byKey(const ValueKey<int>(1))), const Rect.fromLTWH(0.0, 0.0, 200.0, 200.0)); await tester.pumpWidget(simpleBuilderTest(delegate: delegate1)); expect(tester.getRect(find.byKey(const ValueKey<int>(1))), const Rect.fromLTWH(200.0, 200.0, 200.0, 200.0)); }, variant: TargetPlatformVariant.all()); testWidgets('state is preserved after reordering', (WidgetTester tester) async { final TwoDimensionalChildBuilderDelegate delegate1 = TwoDimensionalChildBuilderDelegate( maxXIndex: 5, maxYIndex: 5, addAutomaticKeepAlives: false, addRepaintBoundaries: false, builder: (BuildContext context, ChildVicinity vicinity) { ValueKey<int>? key; if (vicinity == const ChildVicinity(xIndex: 1, yIndex: 1)) { key = const ValueKey<int>(1); } else if (vicinity == const ChildVicinity(xIndex: 1, yIndex: 2)) { key = const ValueKey<int>(2); } return Checkbox(key: key, value: false, onChanged: (_) {}); }); final TwoDimensionalChildBuilderDelegate delegate2 = TwoDimensionalChildBuilderDelegate( maxXIndex: 5, maxYIndex: 5, addAutomaticKeepAlives: false, addRepaintBoundaries: false, builder: (BuildContext context, ChildVicinity vicinity) { ValueKey<int>? key; if (vicinity == const ChildVicinity(xIndex: 0, yIndex: 0)) { key = const ValueKey<int>(1); } else if (vicinity == const ChildVicinity(xIndex: 1, yIndex: 1)) { key = const ValueKey<int>(2); } return Checkbox(key: key, value: false, onChanged: (_) {}); }); addTearDown(delegate1.dispose); addTearDown(delegate2.dispose); await tester.pumpWidget(simpleBuilderTest(delegate: delegate1)); final State stateBeforeReordering = tester.state(find.byKey(const ValueKey<int>(2))); await tester.pumpWidget(simpleBuilderTest(delegate: delegate2)); expect(tester.state(find.byKey(const ValueKey<int>(2))), stateBeforeReordering); await tester.pumpWidget(simpleBuilderTest(delegate: delegate1)); expect(tester.state(find.byKey(const ValueKey<int>(2))), stateBeforeReordering); }, variant: TargetPlatformVariant.all()); }); } class _TestVicinity extends ChildVicinity { const _TestVicinity({required super.xIndex, required super.yIndex}); } class _TestBaseDelegate extends TwoDimensionalChildDelegate { //ignore: unused_element // Would fail analysis without covariant @override Widget? build(BuildContext context, _TestVicinity vicinity) => null; @override bool shouldRebuild(covariant TwoDimensionalChildDelegate oldDelegate) => false; } class _TestBuilderDelegate extends TwoDimensionalChildBuilderDelegate { //ignore: unused_element _TestBuilderDelegate({required super.builder}); // Would fail analysis without covariant @override Widget? build(BuildContext context, _TestVicinity vicinity) { return super.build(context, vicinity); } } class _TestListDelegate extends TwoDimensionalChildListDelegate { //ignore: unused_element _TestListDelegate({required super.children}); // Would fail analysis without covariant @override Widget? build(BuildContext context, _TestVicinity vicinity) { return super.build(context, vicinity); } } RenderTwoDimensionalViewport getViewport(WidgetTester tester, Key childKey) { return RenderAbstractViewport.of( tester.renderObject(find.byKey(childKey)) ) as RenderSimpleBuilderTableViewport; } class _NullBuildContext implements BuildContext, TwoDimensionalChildManager { @override dynamic noSuchMethod(Invocation invocation) => throw UnimplementedError(); } Future<void> restoreScrollAndVerify(WidgetTester tester) async { final Finder findScrollable = find.byElementPredicate((Element e) => e.widget is TwoDimensionalScrollable); tester.state<TwoDimensionalScrollableState>(findScrollable).horizontalScrollable.position.jumpTo(100); tester.state<TwoDimensionalScrollableState>(findScrollable).verticalScrollable.position.jumpTo(100); await tester.pump(); await tester.restartAndRestore(); expect( tester.state<TwoDimensionalScrollableState>(findScrollable).horizontalScrollable.position.pixels, 100.0, ); expect( tester.state<TwoDimensionalScrollableState>(findScrollable).verticalScrollable.position.pixels, 100.0, ); final TestRestorationData data = await tester.getRestorationData(); tester.state<TwoDimensionalScrollableState>(findScrollable).horizontalScrollable.position.jumpTo(0); tester.state<TwoDimensionalScrollableState>(findScrollable).verticalScrollable.position.jumpTo(0); await tester.pump(); await tester.restoreFrom(data); expect( tester.state<TwoDimensionalScrollableState>(findScrollable).horizontalScrollable.position.pixels, 100.0, ); expect( tester.state<TwoDimensionalScrollableState>(findScrollable).verticalScrollable.position.pixels, 100.0, ); } // Validates covariant through analysis. mixin _SomeDelegateMixin on TwoDimensionalChildDelegate {} class _SomeRenderTwoDimensionalViewport extends RenderTwoDimensionalViewport { // ignore: unused_element _SomeRenderTwoDimensionalViewport({ required super.horizontalOffset, required super.horizontalAxisDirection, required super.verticalOffset, required super.verticalAxisDirection, required _SomeDelegateMixin super.delegate, required super.mainAxis, required super.childManager, }); @override _SomeDelegateMixin get delegate => super.delegate as _SomeDelegateMixin; @override set delegate(_SomeDelegateMixin value) { // Analysis would fail without covariant super.delegate = value; } @override RenderBox? getChildFor(_TestVicinity vicinity) { // Analysis would fail without covariant return super.getChildFor(vicinity); } @override void layoutChildSequence() {} }
flutter/packages/flutter/test/widgets/two_dimensional_viewport_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/two_dimensional_viewport_test.dart", "repo_id": "flutter", "token_count": 48707 }
714
// 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/cupertino.dart'; void main() { // Generic reference variables. BuildContext context; RenderObjectWidget renderObjectWidget; RenderObject renderObject; Object object; // Change made in https://github.com/flutter/flutter/pull/41859 CupertinoTextThemeData themeData = CupertinoTextThemeData(brightness: Brightness.dark); themeData.copyWith(brightness: Brightness.light); themeData = CupertinoTextThemeData(error: ''); themeData.copyWith(error: ''); // Changes made in https://github.com/flutter/flutter/pull/44189 const Element element = Element(myWidget); element.inheritFromElement(ancestor); element.inheritFromWidgetOfExactType(targetType); element.ancestorInheritedElementForWidgetOfExactType(targetType); element.ancestorWidgetOfExactType(targetType); element.ancestorStateOfType(TypeMatcher<targetType>()); element.rootAncestorStateOfType(TypeMatcher<targetType>()); element.ancestorRenderObjectOfType(TypeMatcher<targetType>()); // Changes made in https://github.com/flutter/flutter/pull/45941 and https://github.com/flutter/flutter/pull/83843 final WidgetsBinding binding = WidgetsBinding.instance!; binding.deferFirstFrameReport(); binding.allowFirstFrameReport(); // Changes made in https://github.com/flutter/flutter/pull/44189 const StatefulElement statefulElement = StatefulElement(myWidget); statefulElement.inheritFromElement(ancestor); // Changes made in https://github.com/flutter/flutter/pull/44189 const BuildContext buildContext = Element(myWidget); buildContext.inheritFromElement(ancestor); buildContext.inheritFromWidgetOfExactType(targetType); buildContext.ancestorInheritedElementForWidgetOfExactType(targetType); buildContext.ancestorWidgetOfExactType(targetType); buildContext.ancestorStateOfType(TypeMatcher<targetType>()); buildContext.rootAncestorStateOfType(TypeMatcher<targetType>()); buildContext.ancestorRenderObjectOfType(TypeMatcher<targetType>()); // Changes made in https://github.com/flutter/flutter/pull/66305 const Stack stack = Stack(overflow: Overflow.visible); const Stack stack = Stack(overflow: Overflow.clip); const Stack stack = Stack(error: ''); final behavior = stack.overflow; // Changes made in https://github.com/flutter/flutter/pull/61648 const Form form = Form(autovalidate: true); const Form form = Form(autovalidate: false); const Form form = Form(error: ''); final autoMode = form.autovalidate; // Changes made in https://github.com/flutter/flutter/pull/61648 const FormField formField = FormField(autovalidate: true); const FormField formField = FormField(autovalidate: false); const FormField formField = FormField(error: ''); final autoMode = formField.autovalidate; // Changes made in https://github.com/flutter/flutter/pull/68736 MediaQuery.of(context, nullOk: true); MediaQuery.of(context, nullOk: false); MediaQuery.of(error: ''); // Changes made in https://github.com/flutter/flutter/pull/70726 Navigator.of(context, nullOk: true); Navigator.of(context, nullOk: false); Navigator.of(error: ''); // Changes made in https://github.com/flutter/flutter/pull/68910 Router.of(context, nullOk: true); Router.of(context, nullOk: false); Router.of(error: ''); // Changes made in https://github.com/flutter/flutter/pull/68911 Localizations.localeOf(context, nullOk: true); Localizations.localeOf(context, nullOk: false); Localizations.localeOf(error: ''); // Changes made in https://github.com/flutter/flutter/pull/68917 FocusTraversalOrder.of(context, nullOk: true); FocusTraversalOrder.of(context, nullOk: false); FocusTraversalOrder.of(error: ''); FocusTraversalGroup.of(error: ''); FocusTraversalGroup.of(context, nullOk: true); FocusTraversalGroup.of(context, nullOk: false); Focus.of(context, nullOk: true); Focus.of(context, nullOk: false); Focus.of(error: ''); // Changes made in https://github.com/flutter/flutter/pull/68921 Shortcuts.of(context, nullOk: true); Shortcuts.of(context, nullOk: false); Shortcuts.of(error: ''); Actions.find(error: ''); Actions.find(context, nullOk: true); Actions.find(context, nullOk: false); Actions.handler(context, nullOk: true); Actions.handler(context, nullOk: false); Actions.handler(error: ''); Actions.invoke(error: ''); Actions.invoke(context, nullOk: true); Actions.invoke(context, nullOk: false); // Changes made in https://github.com/flutter/flutter/pull/68925 AnimatedList.of(context, nullOk: true); AnimatedList.of(context, nullOk: false); AnimatedList.of(error: ''); SliverAnimatedList.of(error: ''); SliverAnimatedList.of(context, nullOk: true); SliverAnimatedList.of(context, nullOk: false); // Changes made in https://github.com/flutter/flutter/pull/68905 CupertinoDynamicColor.resolve(Color(0), context, nullOk: true); CupertinoDynamicColor.resolve(Color(0), context, nullOk: false); CupertinoDynamicColor.resolve(error: ''); CupertinoDynamicColor.resolveFrom(error: ''); CupertinoDynamicColor.resolveFrom(context, nullOk: true); CupertinoDynamicColor.resolveFrom(context, nullOk: false); CupertinoUserInterfaceLevel.of(context, nullOk: true); CupertinoUserInterfaceLevel.of(context, nullOk: false); CupertinoUserInterfaceLevel.of(error: ''); // Changes made in https://github.com/flutter/flutter/pull/68736 CupertinoTheme.brightnessOf(context, nullOk: true); CupertinoTheme.brightnessOf(context, nullOk: false); CupertinoTheme.brightnessOf(error: ''); // Changes made in https://github.com/flutter/flutter/pull/68905 CupertinoThemeData.resolveFrom(context, nullOk: true); CupertinoThemeData.resolveFrom(context, nullOk: false); CupertinoThemeData.resolveFrom(error: ''); NoDefaultCupertinoThemeData.resolveFrom(error: ''); NoDefaultCupertinoThemeData.resolveFrom(context, nullOk: true); NoDefaultCupertinoThemeData.resolveFrom(context, nullOk: false); CupertinoTextThemeData.resolveFrom(context, nullOk: true); CupertinoTextThemeData.resolveFrom(context, nullOk: false); CupertinoTextThemeData.resolveFrom(error: ''); // Changes made in https://github.com/flutter/flutter/pull/72043 CupertinoTextField(maxLengthEnforced: true); CupertinoTextField(maxLengthEnforced: false); CupertinoTextField(error: ''); CupertinoTextField.borderless(error: ''); CupertinoTextField.borderless(maxLengthEnforced: true); CupertinoTextField.borderless(maxLengthEnforced: false); final CupertinoTextField textField; textField.maxLengthEnforced; // Changes made in https://github.com/flutter/flutter/pull/59127 const BottomNavigationBarItem bottomNavigationBarItem = BottomNavigationBarItem(title: myTitle); const BottomNavigationBarItem bottomNavigationBarItem = BottomNavigationBarItem(); const BottomNavigationBarItem bottomNavigationBarItem = BottomNavigationBarItem(error: ''); bottomNavigationBarItem.title; // Changes made in https://github.com/flutter/flutter/pull/79160 Draggable draggable = Draggable(); draggable = Draggable(error: ''); draggable = Draggable(dragAnchor: DragAnchor.child); draggable = Draggable(dragAnchor: DragAnchor.pointer); draggable.dragAnchor; // Changes made in https://github.com/flutter/flutter/pull/79160 LongPressDraggable longPressDraggable = LongPressDraggable(); longPressDraggable = LongPressDraggable(error: ''); longPressDraggable = LongPressDraggable(dragAnchor: DragAnchor.child); longPressDraggable = LongPressDraggable(dragAnchor: DragAnchor.pointer); longPressDraggable.dragAnchor; // Changes made in https://github.com/flutter/flutter/pull/64254 final LeafRenderObjectElement leafElement = LeafRenderObjectElement(); leafElement.insertChildRenderObject(renderObject, object); leafElement.moveChildRenderObject(renderObject, object); leafElement.removeChildRenderObject(renderObject); final ListWheelElement listWheelElement = ListWheelElement(); listWheelElement.insertChildRenderObject(renderObject, object); listWheelElement.moveChildRenderObject(renderObject, object); listWheelElement.removeChildRenderObject(renderObject); final MultiChildRenderObjectElement multiChildRenderObjectElement = MultiChildRenderObjectElement(); multiChildRenderObjectElement.insertChildRenderObject(renderObject, object); multiChildRenderObjectElement.moveChildRenderObject(renderObject, object); multiChildRenderObjectElement.removeChildRenderObject(renderObject); final SingleChildRenderObjectElement singleChildRenderObjectElement = SingleChildRenderObjectElement(); singleChildRenderObjectElement.insertChildRenderObject(renderObject, object); singleChildRenderObjectElement.moveChildRenderObject(renderObject, object); singleChildRenderObjectElement.removeChildRenderObject(renderObject); final SliverMultiBoxAdaptorElement sliverMultiBoxAdaptorElement = SliverMultiBoxAdaptorElement(); sliverMultiBoxAdaptorElement.insertChildRenderObject(renderObject, object); sliverMultiBoxAdaptorElement.moveChildRenderObject(renderObject, object); sliverMultiBoxAdaptorElement.removeChildRenderObject(renderObject); final RenderObjectToWidgetElement renderObjectToWidgetElement = RenderObjectToWidgetElement(widget); renderObjectToWidgetElement.insertChildRenderObject(renderObject, object); renderObjectToWidgetElement.moveChildRenderObject(renderObject, object); renderObjectToWidgetElement.removeChildRenderObject(renderObject); // Changes made in https://flutter.dev/docs/release/breaking-changes/clip-behavior ListWheelScrollView listWheelScrollView = ListWheelScrollView(); listWheelScrollView = ListWheelScrollView(clipToSize: true); listWheelScrollView = ListWheelScrollView(clipToSize: false); listWheelScrollView = ListWheelScrollView(error: ''); listWheelScrollView = ListWheelScrollView.useDelegate(); listWheelScrollView = ListWheelScrollView.useDelegate(clipToSize: true); listWheelScrollView = ListWheelScrollView.useDelegate(clipToSize: false); listWheelScrollView = ListWheelScrollView.useDelegate(error: ''); listWheelScrollView.clipToSize; ListWheelViewport listWheelViewport = ListWheelViewport(); listWheelViewport = ListWheelViewport(clipToSize: true); listWheelViewport = ListWheelViewport(clipToSize: false); listWheelViewport = ListWheelViewport(error: ''); listWheelViewport.clipToSize; // Changes made in https://github.com/flutter/flutter/pull/87839 OverscrollIndicatorNotification notification = OverscrollIndicatorNotification(leading: true); notification = OverscrollIndicatorNotification(error: ''); notification.disallowGlow(); // Changes made in https://github.com/flutter/flutter/pull/96957 CupertinoScrollbar scrollbar = CupertinoScrollbar(isAlwaysShown: true); bool nowShowing = scrollbar.isAlwaysShown; RawScrollbar rawScrollbar = RawScrollbar(isAlwaysShown: true); nowShowing = rawScrollbar.isAlwaysShown; // Change made in https://github.com/flutter/flutter/pull/100381 TextSelectionOverlay.fadeDuration; // Changes made in https://github.com/flutter/flutter/pull/78588 final ScrollBehavior scrollBehavior = ScrollBehavior(); scrollBehavior.buildViewportChrome(context, child, axisDirection); final CupertinoScrollBehavior cupertinoScrollBehavior = CupertinoScrollBehavior(); cupertinoScrollBehavior.buildViewportChrome(context, child, axisDirection); // Changes made in https://github.com/flutter/flutter/pull/114459 MediaQuery.boldTextOverride(context); // Changes made in https://github.com/flutter/flutter/pull/122555 final ScrollableDetails details = ScrollableDetails( direction: AxisDirection.down, clipBehavior: Clip.none, ); final Clip clip = details.clipBehavior; final PlatformMenuBar platformMenuBar = PlatformMenuBar(menus: <PlatformMenuItem>[], body: const SizedBox()); final Widget bodyValue = platformMenuBar.body; }
flutter/packages/flutter/test_fixes/cupertino/cupertino.dart/0
{ "file_path": "flutter/packages/flutter/test_fixes/cupertino/cupertino.dart", "repo_id": "flutter", "token_count": 3644 }
715
// 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/86198 SliverAppBar sliverAppBar = SliverAppBar(); sliverAppBar = SliverAppBar(brightness: Brightness.light); sliverAppBar = SliverAppBar(brightness: Brightness.dark); sliverAppBar = SliverAppBar(error: ''); sliverAppBar.brightness; TextTheme myTextTheme = TextTheme(); SliverAppBar sliverAppBar = SliverAppBar(); sliverAppBar = SliverAppBar(textTheme: myTextTheme); SliverAppBar sliverAppBar = SliverAppBar(); sliverAppBar = SliverAppBar(backwardsCompatibility: true); sliverAppBar = SliverAppBar(backwardsCompatibility: false); sliverAppBar.backwardsCompatibility; // Removing field reference not supported. }
flutter/packages/flutter/test_fixes/material/sliver_app_bar.dart/0
{ "file_path": "flutter/packages/flutter/test_fixes/material/sliver_app_bar.dart", "repo_id": "flutter", "token_count": 287 }
716
# Private Test Runner These are tests of private interfaces that can't easily happen in the regular flutter tests due to problems with test and implementation interdependence. This gets around the problem of parts existing in more than one library by making a copy of the code under test. The test script `bin/test_private.dart` tests private interfaces by copying the code under test into a temporary workspace. The test is then free to make the copied flutter source into a "part" of its own library by declaring a library and using the `part` directive with a relative path to include the parts. This way the test and the private interface are part of the same library, and the private interface can be accessed by the test. The tests are run like so: ```shell dart run bin/test_private.dart ``` One limitation is that the copied private API needs to be separable enough to be copied, so it needs to be in its own separate files. To add a private test, add a manifest file of the form (assuming "my_private_test" is the name of the test) to the [test](test) subdir: ```json { "tests": [ "my_private_test.dart" ], "pubspec": "my_private_test.pubspec.yaml", "deps": [ "lib/src/subpackage/my_private_implementation.dart", ] } ``` It will copy the files in `deps` relative to the `packages/flutter` directory into a similar relative path structure in the test temporary directory tree. It will copy the `pubspec` file into `pubspec.yaml` in the test temporary directory, and copy all of the `tests` into the top of the test temporary directory tree. Each test gets its own temporary directory tree under a generated temporary directory in the system temp dir that is removed at the end of the run, or under the path given to `--temp-dir` on the command line. If a temporary directory is given explicitly, it will not be deleted at the end of the run.
flutter/packages/flutter/test_private/README.md/0
{ "file_path": "flutter/packages/flutter/test_private/README.md", "repo_id": "flutter", "token_count": 504 }
717
// 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 'enum_util.dart'; import 'message.dart'; /// A Flutter Driver command that requests an application health check. class GetHealth extends Command { /// Create a health check command. const GetHealth({ super.timeout }); /// Deserializes this command from the value generated by [serialize]. GetHealth.deserialize(super.json) : super.deserialize(); @override String get kind => 'get_health'; @override bool get requiresRootWidgetAttached => false; } /// A description of application state. enum HealthStatus { /// Application is known to be in a good shape and should be able to respond. ok, /// Application is not known to be in a good shape and may be unresponsive. bad, } final EnumIndex<HealthStatus> _healthStatusIndex = EnumIndex<HealthStatus>(HealthStatus.values); /// A description of the application state, as provided in response to a /// [FlutterDriver.checkHealth] test. class Health extends Result { /// Creates a [Health] object with the given [status]. const Health(this.status); /// The status represented by this object. /// /// If the application responded, this will be [HealthStatus.ok]. final HealthStatus status; /// Deserializes the result from JSON. static Health fromJson(Map<String, dynamic> json) { return Health(_healthStatusIndex.lookupBySimpleName(json['status'] as String)); } @override Map<String, dynamic> toJson() => <String, dynamic>{ 'status': _healthStatusIndex.toSimpleName(status), }; }
flutter/packages/flutter_driver/lib/src/common/health.dart/0
{ "file_path": "flutter/packages/flutter_driver/lib/src/common/health.dart", "repo_id": "flutter", "token_count": 464 }
718
// 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'; /// Profiling related timeline events. /// /// We do not use a profiling category for these as all the dart timeline events /// have the same profiling category "embedder". const Set<String> kProfilingEvents = <String>{ _kCpuProfile, _kGpuProfile, _kMemoryProfile, }; // These field names need to be in-sync with: // https://github.com/flutter/engine/blob/master/shell/profiling/sampling_profiler.cc const String _kCpuProfile = 'CpuUsage'; const String _kGpuProfile = 'GpuUsage'; const String _kMemoryProfile = 'MemoryUsage'; /// Represents the supported profiling event types. enum ProfileType { /// Profiling events corresponding to CPU usage. CPU, /// Profiling events corresponding to GPU usage. GPU, /// Profiling events corresponding to memory usage. Memory, } /// Summarizes [TimelineEvents]s corresponding to [kProfilingEvents] category. /// /// A sample event (some fields have been omitted for brevity): /// ```json /// { /// "category": "embedder", /// "name": "CpuUsage", /// "ts": 121120, /// "args": { /// "total_cpu_usage": "20.5", /// "num_threads": "6" /// } /// }, /// ``` /// This class provides methods to compute the average and percentile information /// for supported profiles, i.e, CPU, Memory and GPU. Not all of these exist for /// all the platforms. class ProfilingSummarizer { ProfilingSummarizer._(this.eventByType); /// Creates a ProfilingSummarizer given the timeline events. static ProfilingSummarizer fromEvents(List<TimelineEvent> profilingEvents) { final Map<ProfileType, List<TimelineEvent>> eventsByType = <ProfileType, List<TimelineEvent>>{}; for (final TimelineEvent event in profilingEvents) { assert(kProfilingEvents.contains(event.name)); final ProfileType type = _getProfileType(event.name); eventsByType[type] ??= <TimelineEvent>[]; eventsByType[type]!.add(event); } return ProfilingSummarizer._(eventsByType); } /// Key is the type of profiling event, for e.g. CPU, GPU, Memory. final Map<ProfileType, List<TimelineEvent>> eventByType; /// Returns the average, 90th and 99th percentile summary of CPU, GPU and Memory /// usage from the recorded events. If a given profile type isn't available /// for any reason, the map will not contain the said profile type. Map<String, dynamic> summarize() { final Map<String, dynamic> summary = <String, dynamic>{}; summary.addAll(_summarize(ProfileType.CPU, 'cpu_usage')); summary.addAll(_summarize(ProfileType.GPU, 'gpu_usage')); summary.addAll(_summarize(ProfileType.Memory, 'memory_usage')); return summary; } Map<String, double> _summarize(ProfileType profileType, String name) { final Map<String, double> summary = <String, double>{}; if (!hasProfilingInfo(profileType)) { return summary; } summary['average_$name'] = computeAverage(profileType); summary['90th_percentile_$name'] = computePercentile(profileType, 90); summary['99th_percentile_$name'] = computePercentile(profileType, 99); return summary; } /// Returns true if there are events in the timeline corresponding to [profileType]. bool hasProfilingInfo(ProfileType profileType) { if (eventByType.containsKey(profileType)) { return eventByType[profileType]!.isNotEmpty; } else { return false; } } /// Computes the average of the `profileType` over the recorded events. double computeAverage(ProfileType profileType) { final List<TimelineEvent> events = eventByType[profileType]!; assert(events.isNotEmpty); final double total = events .map((TimelineEvent e) => _getProfileValue(profileType, e)) .reduce((double a, double b) => a + b); return total / events.length; } /// The [percentile]-th percentile `profileType` over the recorded events. double computePercentile(ProfileType profileType, double percentile) { final List<TimelineEvent> events = eventByType[profileType]!; assert(events.isNotEmpty); final List<double> doubles = events .map((TimelineEvent e) => _getProfileValue(profileType, e)) .toList(); return findPercentile(doubles, percentile); } static ProfileType _getProfileType(String? eventName) { switch (eventName) { case _kCpuProfile: return ProfileType.CPU; case _kGpuProfile: return ProfileType.GPU; case _kMemoryProfile: return ProfileType.Memory; default: throw Exception('Invalid profiling event: $eventName.'); } } double _getProfileValue(ProfileType profileType, TimelineEvent e) { switch (profileType) { case ProfileType.CPU: return _getArgValue('total_cpu_usage', e); case ProfileType.GPU: return _getArgValue('gpu_usage', e); case ProfileType.Memory: final double dirtyMem = _getArgValue('dirty_memory_usage', e); final double ownedSharedMem = _getArgValue('owned_shared_memory_usage', e); return dirtyMem + ownedSharedMem; } } double _getArgValue(String argKey, TimelineEvent e) { assert(e.arguments!.containsKey(argKey)); final dynamic argVal = e.arguments![argKey]; assert(argVal is String); return double.parse(argVal as String); } }
flutter/packages/flutter_driver/lib/src/driver/profiling_summarizer.dart/0
{ "file_path": "flutter/packages/flutter_driver/lib/src/driver/profiling_summarizer.dart", "repo_id": "flutter", "token_count": 1854 }
719
// 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_driver/flutter_driver.dart'; import 'package:flutter_driver/src/driver/gpu_sumarizer.dart'; import '../common.dart'; TimelineEvent newGPUTraceEvent(double ms) => TimelineEvent(<String, dynamic>{ 'name': 'GPUStart', 'ph': 'b', 'args': <String, String>{ 'FrameTimeMS': ms.toString() }, }); void main() { test('Can process GPU frame times.', () { final GpuSumarizer summarizer = GpuSumarizer(<TimelineEvent>[ newGPUTraceEvent(4.233), newGPUTraceEvent(7.22), newGPUTraceEvent(9.1), newGPUTraceEvent(40.23), ]); expect(summarizer.computeAverageGPUTime(), closeTo(15.19, 0.1)); expect(summarizer.computePercentileGPUTime(50.0), closeTo(9.1, 0.1)); expect(summarizer.computeWorstGPUTime(), 40.23); }); }
flutter/packages/flutter_driver/test/src/gpu_summarizer_test.dart/0
{ "file_path": "flutter/packages/flutter_driver/test/src/gpu_summarizer_test.dart", "repo_id": "flutter", "token_count": 365 }
720
# Flutter Framework localizations This package contains the localizations used by the Flutter framework itself. See the [localization README](./lib/src/l10n/README.md) for more detailed information about the localizations themselves. ## Adding a new string to localizations If you (someone contributing to the Flutter framework) want to add a new string to the `MaterialLocalizations`, `WidgetsLocalizations` or the `CupertinoLocalizations` objects (e.g. because you've added a new widget and it has a tooltip), follow these steps (these instructions are for `MaterialLocalizations`, but apply equally to `CupertinoLocalizations` and `WidgetsLocalizations`, with appropriate name substitutions): 1. ### For messages without parameters, add new getter ``` String get showMenuTooltip; ``` to the localizations class `MaterialLocalizations`, in [`packages/flutter/lib/src/material/material_localizations.dart`](https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/material/material_localizations.dart); ### For messages with parameters, add new function ``` String aboutListTileTitle(String applicationName); ``` to the same localization class. 2. Implement a default return value in `DefaultMaterialLocalizations` in the same file as in step 1. ### Messages without parameters: ``` @override String get showMenuTooltip => 'Show menu'; ``` ### Messages with parameters: ``` @override String aboutListTileTitle(String applicationName) => 'About $applicationName'; ``` For messages with parameters, do also add the function to `GlobalMaterialLocalizations` in [`packages/flutter_localizations/lib/src/material_localizations.dart`](https://github.com/flutter/flutter/blob/master/packages/flutter_localizations/lib/src/material_localizations.dart), and add a raw getter as demonstrated below: ``` /// The raw version of [aboutListTileTitle], with `$applicationName` verbatim /// in the string. @protected String get aboutListTileTitleRaw; @override String aboutListTileTitle(String applicationName) { final String text = aboutListTileTitleRaw; return text.replaceFirst(r'$applicationName', applicationName); } ``` 3. Add a test to `test/material/localizations_test.dart` that verifies that this new value is implemented. 4. Update the `flutter_localizations` package. To add a new string to the `flutter_localizations` package, you must first add it to the English translations (`lib/src/l10n/material_en.arb`), including a description. ### Messages without parameters: ``` "showMenuTooltip": "Show menu", "@showMenuTooltip": { "description": "The tooltip for the button that shows a popup menu." }, ``` ### Messages with parameters: ``` "aboutListTileTitle": "About $applicationName", "@aboutListTileTitle": { "description": "The default title for the drawer item that shows an about page for the application. The value of $applicationName is the name of the application, like GMail or Chrome.", "parameters": "applicationName" }, ``` Then you need to add new entries for the string to all of the other language locale files by running: ``` dart dev/tools/localization/bin/gen_missing_localizations.dart ``` Which will copy the English strings into the other locales as placeholders until they can be translated. Finally you need to re-generate lib/src/l10n/localizations.dart by running: ``` dart dev/tools/localization/bin/gen_localizations.dart --overwrite ``` If you got an error when running this command, [this issue](https://github.com/flutter/flutter/issues/104601) might be helpful. TL;DR: If you got the same type of errors as discussed in the issue, run this instead: ``` dart dev/tools/localization/bin/gen_localizations.dart --overwrite --remove-undefined ``` There is a [localization README](./lib/src/l10n/README.md) file with further information in the `lib/src/l10n/` directory. 5. If you are a Google employee, you should then also follow the instructions at `go/flutter-l10n`. If you're not, don't worry about it. ## Updating an existing string If you or someone contributing to the Flutter framework wants to modify an existing string in the MaterialLocalizations objects, follow these steps: 1. Modify the default value of the relevant getter(s) in `DefaultMaterialLocalizations` below. 2. Update the `flutter_localizations` package. Modify the out-of-date English strings in `lib/src/l10n/material_en.arb`. You also need to re-generate `lib/src/l10n/localizations.dart` by running: ``` dart dev/tools/localization/bin/gen_localizations.dart --overwrite ``` This script may result in your updated getters being created in newer locales and set to the old value of the strings. This is to be expected. Leave them as they were generated, and they will be picked up for translation. There is a [localization README](./lib/src/l10n/README.md) file with further information in the `lib/src/l10n/` directory. 3. If you are a Google employee, you should then also follow the instructions at `go/flutter-l10n`. If you're not, don't worry about it.
flutter/packages/flutter_localizations/README.md/0
{ "file_path": "flutter/packages/flutter_localizations/README.md", "repo_id": "flutter", "token_count": 1574 }
721
{ "datePickerHourSemanticsLabelOne": "klokken $hour", "datePickerHourSemanticsLabelOther": "klokken $hour", "datePickerMinuteSemanticsLabelOne": "1 minut", "datePickerMinuteSemanticsLabelOther": "$minute minutter", "datePickerDateOrder": "dmy", "datePickerDateTimeOrder": "date_time_dayPeriod", "anteMeridiemAbbreviation": "AM", "postMeridiemAbbreviation": "PM", "todayLabel": "I dag", "alertDialogLabel": "Underretning", "timerPickerHourLabelOne": "time", "timerPickerHourLabelOther": "timer", "timerPickerMinuteLabelOne": "min.", "timerPickerMinuteLabelOther": "min.", "timerPickerSecondLabelOne": "sek.", "timerPickerSecondLabelOther": "sek.", "cutButtonLabel": "Klip", "copyButtonLabel": "Kopiér", "pasteButtonLabel": "Indsæt", "clearButtonLabel": "Clear", "selectAllButtonLabel": "Vælg alt", "tabSemanticsLabel": "Fane $tabIndex af $tabCount", "modalBarrierDismissLabel": "Afvis", "searchTextFieldPlaceholderLabel": "Søg", "noSpellCheckReplacementsLabel": "Der blev ikke fundet nogen erstatninger", "menuDismissLabel": "Luk menu", "lookUpButtonLabel": "Slå op", "searchWebButtonLabel": "Søg på nettet", "shareButtonLabel": "Del…" }
flutter/packages/flutter_localizations/lib/src/l10n/cupertino_da.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_da.arb", "repo_id": "flutter", "token_count": 435 }
722
{ "datePickerHourSemanticsLabelOne": "$hour:00", "datePickerHourSemanticsLabelOther": "$hour:00", "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": "Ներդիր $tabIndex՝ $tabCount-ից", "modalBarrierDismissLabel": "Փակել", "searchTextFieldPlaceholderLabel": "Որոնում", "noSpellCheckReplacementsLabel": "Փոխարինումներ չեն գտնվել", "menuDismissLabel": "Փակել ընտրացանկը", "lookUpButtonLabel": "Փնտրել", "searchWebButtonLabel": "Որոնել համացանցում", "shareButtonLabel": "Կիսվել...", "clearButtonLabel": "Clear" }
flutter/packages/flutter_localizations/lib/src/l10n/cupertino_hy.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_hy.arb", "repo_id": "flutter", "token_count": 691 }
723
{ "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": "$tabCount-н $tabIndex-р таб", "modalBarrierDismissLabel": "Үл хэрэгсэх", "searchTextFieldPlaceholderLabel": "Хайх", "noSpellCheckReplacementsLabel": "Ямар ч орлуулалт олдсонгүй", "menuDismissLabel": "Цэсийг хаах", "lookUpButtonLabel": "Дээшээ харах", "searchWebButtonLabel": "Вебээс хайх", "shareButtonLabel": "Хуваалцах...", "clearButtonLabel": "Clear" }
flutter/packages/flutter_localizations/lib/src/l10n/cupertino_mn.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_mn.arb", "repo_id": "flutter", "token_count": 640 }
724
{ "datePickerHourSemanticsLabelFew": "$hour hodiny", "datePickerHourSemanticsLabelMany": "$hour hodiny", "datePickerMinuteSemanticsLabelFew": "$minute minúty", "datePickerMinuteSemanticsLabelMany": "$minute minúty", "timerPickerHourLabelFew": "hodiny", "timerPickerHourLabelMany": "hodiny", "timerPickerMinuteLabelFew": "min", "timerPickerMinuteLabelMany": "min", "timerPickerSecondLabelFew": "s", "timerPickerSecondLabelMany": "s", "datePickerHourSemanticsLabelOne": "$hour hodina", "datePickerHourSemanticsLabelOther": "$hour hodín", "datePickerMinuteSemanticsLabelOne": "1 minúta", "datePickerMinuteSemanticsLabelOther": "$minute minút", "datePickerDateOrder": "mdy", "datePickerDateTimeOrder": "date_time_dayPeriod", "anteMeridiemAbbreviation": "AM", "postMeridiemAbbreviation": "PM", "todayLabel": "Dnes", "alertDialogLabel": "Upozornenie", "timerPickerHourLabelOne": "hodina", "timerPickerHourLabelOther": "hodín", "timerPickerMinuteLabelOne": "min", "timerPickerMinuteLabelOther": "min", "timerPickerSecondLabelOne": "s", "timerPickerSecondLabelOther": "s", "cutButtonLabel": "Vystrihnúť", "copyButtonLabel": "Kopírovať", "pasteButtonLabel": "Prilepiť", "selectAllButtonLabel": "Označiť všetko", "tabSemanticsLabel": "Karta $tabIndex z $tabCount", "modalBarrierDismissLabel": "Odmietnuť", "searchTextFieldPlaceholderLabel": "Hľadať", "noSpellCheckReplacementsLabel": "Nenašli sa žiadne náhrady", "menuDismissLabel": "Zavrieť ponuku", "lookUpButtonLabel": "Pohľad nahor", "searchWebButtonLabel": "Hľadať na webe", "shareButtonLabel": "Zdieľať…", "clearButtonLabel": "Clear" }
flutter/packages/flutter_localizations/lib/src/l10n/cupertino_sk.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_sk.arb", "repo_id": "flutter", "token_count": 638 }
725
{ "datePickerHourSemanticsLabelOne": "$hour 点", "datePickerHourSemanticsLabelOther": "$hour 点", "datePickerMinuteSemanticsLabelOne": "1 分钟", "datePickerMinuteSemanticsLabelOther": "$minute 分钟", "datePickerDateOrder": "ymd", "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_zh.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_zh.arb", "repo_id": "flutter", "token_count": 500 }
726
{ "licensesPackageDetailTextFew": "$licenseCount licence", "remainingTextFieldCharacterCountFew": "Još $remainingCount znaka", "scriptCategory": "English-like", "timeOfDayFormat": "HH:mm", "selectedRowCountTitleFew": "Odabrane su $selectedRowCount stavke", "openAppDrawerTooltip": "Otvorite meni za navigaciju", "backButtonTooltip": "Nazad", "closeButtonTooltip": "Zatvaranje", "deleteButtonTooltip": "Brisanje", "nextMonthTooltip": "Sljedeći mjesec", "previousMonthTooltip": "Prethodni mjesec", "nextPageTooltip": "Sljedeća stranica", "firstPageTooltip": "Prva stranica", "lastPageTooltip": "Posljednja stranica", "previousPageTooltip": "Prethodna stranica", "showMenuTooltip": "Prikaži meni", "aboutListTileTitle": "O aplikaciji $applicationName", "licensesPageTitle": "Licence", "pageRowsInfoTitle": "$firstRow–$lastRow od $rowCount", "pageRowsInfoTitleApproximate": "$firstRow–$lastRow od oko $rowCount", "rowsPerPageTitle": "Broj redova po stranici:", "tabLabel": "$tabIndex. kartica od $tabCount", "selectedRowCountTitleOne": "Odabrana je jedna stavka", "selectedRowCountTitleOther": "Odabrano je $selectedRowCount stavki", "cancelButtonLabel": "Otkaži", "closeButtonLabel": "Zatvori", "continueButtonLabel": "Nastavi", "copyButtonLabel": "Kopiraj", "cutButtonLabel": "Izreži", "scanTextButtonLabel": "Skeniraj tekst", "okButtonLabel": "Uredu", "pasteButtonLabel": "Zalijepi", "selectAllButtonLabel": "Odaberi sve", "viewLicensesButtonLabel": "Prikaži licence", "anteMeridiemAbbreviation": "prijepodne", "postMeridiemAbbreviation": "poslijepodne", "timePickerHourModeAnnouncement": "Odaberite sat", "timePickerMinuteModeAnnouncement": "Odaberite minute", "modalBarrierDismissLabel": "Odbaci", "signedInLabel": "Prijavljeni ste", "hideAccountsLabel": "Sakrij račune", "showAccountsLabel": "Prikaži račune", "drawerLabel": "Meni za navigaciju", "popupMenuLabel": "Skočni meni", "dialogLabel": "Dijaloški okvir", "alertDialogLabel": "Upozorenje", "searchFieldLabel": "Pretražite", "reorderItemToStart": "Pomjerite na početak", "reorderItemToEnd": "Pomjerite na kraj", "reorderItemUp": "Pomjeri nagore", "reorderItemDown": "Pomjeri nadolje", "reorderItemLeft": "Pomjeri lijevo", "reorderItemRight": "Pomjeri desno", "expandedIconTapHint": "Suzi", "collapsedIconTapHint": "Proširi", "remainingTextFieldCharacterCountOne": "Još jedan znak", "remainingTextFieldCharacterCountOther": "Još $remainingCount znakova", "refreshIndicatorSemanticLabel": "Osvježi", "moreButtonTooltip": "Više", "dateSeparator": ".", "dateHelpText": "dd. mm. gggg.", "selectYearSemanticsLabel": "Odaberite godinu", "unspecifiedDate": "Datum", "unspecifiedDateRange": "Raspon datuma", "dateInputLabel": "Unesite datum", "dateRangeStartLabel": "Datum početka", "dateRangeEndLabel": "Datum završetka", "dateRangeStartDateSemanticLabel": "Datum početka: $fullDate", "dateRangeEndDateSemanticLabel": "Datum završetka: $fullDate", "invalidDateFormatLabel": "Nevažeći format.", "invalidDateRangeLabel": "Nevažeći raspon.", "dateOutOfRangeLabel": "Izvan raspona.", "saveButtonLabel": "Sačuvaj", "datePickerHelpText": "Odaberite datum", "dateRangePickerHelpText": "Odaberite period", "calendarModeButtonLabel": "Prebacite na kalendar", "inputDateModeButtonLabel": "Prebacite na unos teksta", "timePickerDialHelpText": "Odaberite vrijeme", "timePickerInputHelpText": "Unesite vrijeme", "timePickerHourLabel": "Sat", "timePickerMinuteLabel": "Minuta", "invalidTimeLabel": "Unesite ispravno vrijeme", "dialModeButtonLabel": "Prebacivanje na način rada alata za biranje", "inputTimeModeButtonLabel": "Prebacivanje na način rada unosa teksta", "licensesPackageDetailTextZero": "No licenses", "licensesPackageDetailTextOne": "1 licenca", "licensesPackageDetailTextOther": "$licenseCount licenci", "keyboardKeyAlt": "Alt", "keyboardKeyAltGraph": "Alt Gr", "keyboardKeyBackspace": "Backspace", "keyboardKeyCapsLock": "Caps Lock", "keyboardKeyChannelDown": "prethodni kanal", "keyboardKeyChannelUp": "sljedeći kanal", "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": "Pg Up", "keyboardKeyPower": "tipka za uključivanje", "keyboardKeyPowerOff": "tipka za isključivanje", "keyboardKeyPrintScreen": "Prt Sc", "keyboardKeyScrollLock": "Scroll Lock", "keyboardKeySelect": "Select", "keyboardKeySpace": "tipka za razmak", "keyboardKeyMetaMacOs": "Command", "keyboardKeyMetaWindows": "Win", "menuBarMenuLabel": "Meni trake menija", "currentDateLabel": "Danas", "scrimLabel": "Rubno", "bottomSheetLabel": "Donja tabela", "scrimOnTapHint": "Zatvori: $modalRouteContentName", "keyboardKeyShift": "Shift", "expansionTileExpandedHint": "sužavanje dvostrukim dodirom", "expansionTileCollapsedHint": "proširivanje dvostrukim dodirom", "expansionTileExpandedTapHint": "Sužavanje", "expansionTileCollapsedTapHint": "Proširivanje za više detalja", "expandedHint": "Suženo", "collapsedHint": "Prošireno", "menuDismissLabel": "Odbacivanje menija", "lookUpButtonLabel": "Pogled nagore", "searchWebButtonLabel": "Pretraži Web", "shareButtonLabel": "Dijeli...", "clearButtonTooltip": "Clear text", "selectedDateLabel": "Selected" }
flutter/packages/flutter_localizations/lib/src/l10n/material_bs.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_bs.arb", "repo_id": "flutter", "token_count": 2485 }
727
{ "licensesPackageDetailTextTwo": "$licenseCount רישיונות", "licensesPackageDetailTextMany": "$licenseCount רישיונות", "remainingTextFieldCharacterCountTwo": "נותרו $remainingCount תווים", "remainingTextFieldCharacterCountMany": "נותרו $remainingCount תווים", "scriptCategory": "English-like", "timeOfDayFormat": "H:mm", "selectedRowCountTitleOne": "פריט אחד נבחר", "selectedRowCountTitleTwo": "$selectedRowCount פריטים נבחרו", "selectedRowCountTitleMany": "$selectedRowCount פריטים נבחרו", "openAppDrawerTooltip": "פתיחה של תפריט הניווט", "backButtonTooltip": "הקודם", "closeButtonTooltip": "סגירה", "deleteButtonTooltip": "מחיקה", "nextMonthTooltip": "החודש הבא", "previousMonthTooltip": "החודש הקודם", "nextPageTooltip": "הדף הבא", "previousPageTooltip": "הדף הקודם", "firstPageTooltip": "לדף הראשון", "lastPageTooltip": "לדף האחרון", "showMenuTooltip": "הצגת התפריט", "aboutListTileTitle": "מידע על $applicationName", "licensesPageTitle": "רישיונות", "pageRowsInfoTitle": "$lastRow–$firstRow מתוך $rowCount", "pageRowsInfoTitleApproximate": "$lastRow–$firstRow מתוך כ-$rowCount", "rowsPerPageTitle": "שורות בכל דף:", "tabLabel": "כרטיסייה $tabIndex מתוך $tabCount", "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": "נותר תו אחד", "remainingTextFieldCharacterCountOther": "נותרו $remainingCount תווים", "refreshIndicatorSemanticLabel": "רענון", "moreButtonTooltip": "עוד", "dateSeparator": ".", "dateHelpText": "dd.mm.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": "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": "Page Down", "keyboardKeyPageUp": "Page Up", "keyboardKeyPower": "הפעלה", "keyboardKeyPowerOff": "כיבוי", "keyboardKeyPrintScreen": "Print Screen", "keyboardKeyScrollLock": "Scroll Lock", "keyboardKeySelect": "Select", "keyboardKeySpace": "רווח", "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_he.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_he.arb", "repo_id": "flutter", "token_count": 3118 }
728
{ "licensesPackageDetailTextFew": "$licenseCount licencijos", "licensesPackageDetailTextMany": "$licenseCount licencijos", "remainingTextFieldCharacterCountFew": "Liko $remainingCount simboliai", "remainingTextFieldCharacterCountMany": "Liko $remainingCount simbolio", "scriptCategory": "English-like", "timeOfDayFormat": "HH:mm", "selectedRowCountTitleFew": "Pasirinkti $selectedRowCount elementai", "selectedRowCountTitleMany": "Pasirinkta $selectedRowCount elemento", "openAppDrawerTooltip": "Atidaryti naršymo meniu", "backButtonTooltip": "Atgal", "closeButtonTooltip": "Uždaryti", "deleteButtonTooltip": "Ištrinti", "nextMonthTooltip": "Kitas mėnuo", "previousMonthTooltip": "Ankstesnis mėnuo", "nextPageTooltip": "Kitas puslapis", "previousPageTooltip": "Ankstesnis puslapis", "firstPageTooltip": "Pirmas puslapis", "lastPageTooltip": "Paskutinis puslapis", "showMenuTooltip": "Rodyti meniu", "aboutListTileTitle": "Apie „$applicationName“", "licensesPageTitle": "Licencijos", "pageRowsInfoTitle": "$firstRow–$lastRow iš $rowCount", "pageRowsInfoTitleApproximate": "$firstRow–$lastRow iš maždaug $rowCount", "rowsPerPageTitle": "Eilučių puslapyje:", "tabLabel": "$tabIndex skirtukas iš $tabCount", "selectedRowCountTitleOne": "Pasirinktas 1 elementas", "selectedRowCountTitleOther": "Pasirinkta $selectedRowCount elementų", "cancelButtonLabel": "Atšaukti", "closeButtonLabel": "Uždaryti", "continueButtonLabel": "Tęsti", "copyButtonLabel": "Kopijuoti", "cutButtonLabel": "Iškirpti", "scanTextButtonLabel": "Nuskaityti tekstą", "okButtonLabel": "GERAI", "pasteButtonLabel": "Įklijuoti", "selectAllButtonLabel": "Pasirinkti viską", "viewLicensesButtonLabel": "Peržiūrėti licencijas", "anteMeridiemAbbreviation": "priešpiet", "postMeridiemAbbreviation": "popiet", "timePickerHourModeAnnouncement": "Pasirinkite valandas", "timePickerMinuteModeAnnouncement": "Pasirinkite minutes", "modalBarrierDismissLabel": "Atsisakyti", "signedInLabel": "Prisijungta", "hideAccountsLabel": "Slėpti paskyras", "showAccountsLabel": "Rodyti paskyras", "drawerLabel": "Naršymo meniu", "popupMenuLabel": "Iššokantysis meniu", "dialogLabel": "Dialogo langas", "alertDialogLabel": "Įspėjimas", "searchFieldLabel": "Paieška", "reorderItemToStart": "Perkelti į pradžią", "reorderItemToEnd": "Perkelti į pabaigą", "reorderItemUp": "Perkelti aukštyn", "reorderItemDown": "Perkelti žemyn", "reorderItemLeft": "Perkelti kairėn", "reorderItemRight": "Perkelti dešinėn", "expandedIconTapHint": "Sutraukti", "collapsedIconTapHint": "Išskleisti", "remainingTextFieldCharacterCountOne": "Liko 1 simbolis", "remainingTextFieldCharacterCountOther": "Liko $remainingCount simbolių", "refreshIndicatorSemanticLabel": "Atnaujinti", "moreButtonTooltip": "Daugiau", "dateSeparator": ".", "dateHelpText": "yyyy/mm/dd/", "selectYearSemanticsLabel": "Pasirinkite metus", "unspecifiedDate": "Data", "unspecifiedDateRange": "Dienų seka", "dateInputLabel": "Įveskite datą", "dateRangeStartLabel": "Pradžios data", "dateRangeEndLabel": "Pabaigos data", "dateRangeStartDateSemanticLabel": "Pradžios data: $fullDate", "dateRangeEndDateSemanticLabel": "Pabaigos data: $fullDate", "invalidDateFormatLabel": "Netinkamas formatas.", "invalidDateRangeLabel": "Netinkamas diapazonas.", "dateOutOfRangeLabel": "Nepatenka į diapazoną.", "saveButtonLabel": "Išsaugoti", "datePickerHelpText": "Pasirinkite datą", "dateRangePickerHelpText": "Pasirinkite diapazoną", "calendarModeButtonLabel": "Perjungti į kalendorių", "inputDateModeButtonLabel": "Perjungti į įvestį", "timePickerDialHelpText": "Pasirinkite laiką", "timePickerInputHelpText": "Įveskite laiką", "timePickerHourLabel": "Valandos", "timePickerMinuteLabel": "Minutės", "invalidTimeLabel": "Įveskite tinkamą laiką", "dialModeButtonLabel": "Perjungti į ciferblato parinkiklio režimą", "inputTimeModeButtonLabel": "Perjungti į teksto įvesties režimą", "licensesPackageDetailTextZero": "No licenses", "licensesPackageDetailTextOne": "1 licencija", "licensesPackageDetailTextOther": "$licenseCount licencijų", "keyboardKeyAlt": "Alt", "keyboardKeyAltGraph": "AltGr", "keyboardKeyBackspace": "Naikinimo klavišas", "keyboardKeyCapsLock": "Caps Lock", "keyboardKeyChannelDown": "Ankstesnis kanalas", "keyboardKeyChannelUp": "Kitas kanalas", "keyboardKeyControl": "Ctrl", "keyboardKeyDelete": "Del", "keyboardKeyEject": "Išimti", "keyboardKeyEnd": "End", "keyboardKeyEscape": "Esc", "keyboardKeyFn": "Fn", "keyboardKeyHome": "Home", "keyboardKeyInsert": "Insert", "keyboardKeyMeta": "Meta", "keyboardKeyNumLock": "Num Lock", "keyboardKeyNumpad1": "Skaitm 1", "keyboardKeyNumpad2": "Skaitm 2", "keyboardKeyNumpad3": "Skaitm 3", "keyboardKeyNumpad4": "Skaitm 4", "keyboardKeyNumpad5": "Skaitm 5", "keyboardKeyNumpad6": "Skaitm 6", "keyboardKeyNumpad7": "Skaitm 7", "keyboardKeyNumpad8": "Skaitm 8", "keyboardKeyNumpad9": "Skaitm 9", "keyboardKeyNumpad0": "Skaitm 0", "keyboardKeyNumpadAdd": "Skaitm +", "keyboardKeyNumpadComma": "Skaitm ,", "keyboardKeyNumpadDecimal": "Skaitm .", "keyboardKeyNumpadDivide": "Skaitm /", "keyboardKeyNumpadEnter": "Skaitm „Enter“", "keyboardKeyNumpadEqual": "Skaitm =", "keyboardKeyNumpadMultiply": "Skaitm *", "keyboardKeyNumpadParenLeft": "Skaitm (", "keyboardKeyNumpadParenRight": "Skaitm )", "keyboardKeyNumpadSubtract": "Skaitm -", "keyboardKeyPageDown": "PgDown", "keyboardKeyPageUp": "PgUp", "keyboardKeyPower": "Maitinimas", "keyboardKeyPowerOff": "Išjungti", "keyboardKeyPrintScreen": "Print Screen", "keyboardKeyScrollLock": "Scroll Lock", "keyboardKeySelect": "Select", "keyboardKeySpace": "Tarpas", "keyboardKeyMetaMacOs": "Command", "keyboardKeyMetaWindows": "Win", "menuBarMenuLabel": "Meniu juostos meniu", "currentDateLabel": "Šiandien", "scrimLabel": "Užsklanda", "bottomSheetLabel": "Apatinis lapas", "scrimOnTapHint": "Uždaryti „$modalRouteContentName“", "keyboardKeyShift": "Shift", "expansionTileExpandedHint": "dukart palieskite, kad sutrauktumėte", "expansionTileCollapsedHint": "dukart palieskite, kad išskleistumėte", "expansionTileExpandedTapHint": "Sutraukti", "expansionTileCollapsedTapHint": "Išskleiskite, jei reikia daugiau išsamios informacijos", "expandedHint": "Sutraukta", "collapsedHint": "Išskleista", "menuDismissLabel": "Atsisakyti meniu", "lookUpButtonLabel": "Ieškoti", "searchWebButtonLabel": "Ieškoti žiniatinklyje", "shareButtonLabel": "Bendrinti...", "clearButtonTooltip": "Clear text", "selectedDateLabel": "Selected" }
flutter/packages/flutter_localizations/lib/src/l10n/material_lt.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_lt.arb", "repo_id": "flutter", "token_count": 2697 }
729
{ "anteMeridiemAbbreviation": "AM", "selectedRowCountTitleOne": "1 item selecionado", "postMeridiemAbbreviation": "PM", "scriptCategory": "English-like", "timeOfDayFormat": "HH:mm", "@anteMeridiemAbbreviation": {"notUsed":"portuguese time format does not use a.m. indicator"}, "@postMeridiemAbbreviation": {"notUsed":"portuguese time format does not use p.m. indicator"}, "openAppDrawerTooltip": "Abrir menu de navegação", "backButtonTooltip": "Voltar", "closeButtonTooltip": "Fechar", "deleteButtonTooltip": "Excluir", "nextMonthTooltip": "Próximo mês", "previousMonthTooltip": "Mês anterior", "nextPageTooltip": "Próxima página", "previousPageTooltip": "Página anterior", "firstPageTooltip": "Primeira página", "lastPageTooltip": "Última página", "showMenuTooltip": "Mostrar menu", "aboutListTileTitle": "Sobre o app $applicationName", "licensesPageTitle": "Licenças", "pageRowsInfoTitle": "$firstRow – $lastRow de $rowCount", "pageRowsInfoTitleApproximate": "$firstRow – $lastRow de aproximadamente $rowCount", "rowsPerPageTitle": "Linhas por página:", "tabLabel": "Guia $tabIndex de $tabCount", "selectedRowCountTitleOther": "$selectedRowCount itens selecionados", "cancelButtonLabel": "Cancelar", "closeButtonLabel": "Fechar", "continueButtonLabel": "Continuar", "copyButtonLabel": "Copiar", "cutButtonLabel": "Cortar", "scanTextButtonLabel": "Digitalizar texto", "okButtonLabel": "OK", "pasteButtonLabel": "Colar", "selectAllButtonLabel": "Selecionar tudo", "viewLicensesButtonLabel": "Acessar licenças", "timePickerHourModeAnnouncement": "Selecione as horas", "timePickerMinuteModeAnnouncement": "Selecione os minutos", "signedInLabel": "Conectado a", "hideAccountsLabel": "Ocultar contas", "showAccountsLabel": "Mostrar contas", "modalBarrierDismissLabel": "Dispensar", "drawerLabel": "Menu de navegação", "popupMenuLabel": "Menu pop-up", "dialogLabel": "Caixa de diálogo", "alertDialogLabel": "Alerta", "searchFieldLabel": "Pesquisa", "reorderItemToStart": "Mover para o início", "reorderItemToEnd": "Mover para o final", "reorderItemUp": "Mover para cima", "reorderItemDown": "Mover para baixo", "reorderItemLeft": "Mover para a esquerda", "reorderItemRight": "Mover para a direita", "expandedIconTapHint": "Recolher", "collapsedIconTapHint": "Abrir", "remainingTextFieldCharacterCountOne": "1 caractere restante", "remainingTextFieldCharacterCountOther": "$remainingCount caracteres restantes", "refreshIndicatorSemanticLabel": "Atualizar", "moreButtonTooltip": "Mais", "dateSeparator": "/", "dateHelpText": "dd/mm/aaaa", "selectYearSemanticsLabel": "Selecione o ano", "unspecifiedDate": "Data", "unspecifiedDateRange": "Período", "dateInputLabel": "Inserir data", "dateRangeStartLabel": "Data de início", "dateRangeEndLabel": "Data de término", "dateRangeStartDateSemanticLabel": "Data de início $fullDate", "dateRangeEndDateSemanticLabel": "Data de término $fullDate", "invalidDateFormatLabel": "Formato inválido.", "invalidDateRangeLabel": "Intervalo inválido.", "dateOutOfRangeLabel": "Fora de alcance.", "saveButtonLabel": "Salvar", "datePickerHelpText": "Selecione a data", "dateRangePickerHelpText": "Selecione o intervalo", "calendarModeButtonLabel": "Mudar para agenda", "inputDateModeButtonLabel": "Mudar para modo de entrada", "timePickerDialHelpText": "Selecione o horário", "timePickerInputHelpText": "Insira o horário", "timePickerHourLabel": "Hora", "timePickerMinuteLabel": "Minuto", "invalidTimeLabel": "Insira um horário válido", "dialModeButtonLabel": "Mudar para o modo de seleção de discagem", "inputTimeModeButtonLabel": "Mudar para o modo de entrada de texto", "licensesPackageDetailTextZero": "No licenses", "licensesPackageDetailTextOne": "1 licença", "licensesPackageDetailTextOther": "$licenseCount licenças", "keyboardKeyAlt": "Alt", "keyboardKeyAltGraph": "AltGr", "keyboardKeyBackspace": "Backspace", "keyboardKeyCapsLock": "Caps Lock", "keyboardKeyChannelDown": "Canais para baixo", "keyboardKeyChannelUp": "Canais para cima", "keyboardKeyControl": "Ctrl", "keyboardKeyDelete": "Del", "keyboardKeyEject": "Ejetar", "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": "Liga/desliga", "keyboardKeyPowerOff": "Desligar", "keyboardKeyPrintScreen": "Print Screen", "keyboardKeyScrollLock": "Scroll Lock", "keyboardKeySelect": "Selecionar", "keyboardKeySpace": "Espaço", "keyboardKeyMetaMacOs": "Command", "keyboardKeyMetaWindows": "Win", "menuBarMenuLabel": "Menu da barra de menus", "currentDateLabel": "Hoje", "scrimLabel": "Scrim", "bottomSheetLabel": "Página inferior", "scrimOnTapHint": "Fechar $modalRouteContentName", "keyboardKeyShift": "Shift", "expansionTileExpandedHint": "toque duas vezes para fechar", "expansionTileCollapsedHint": "Toque duas vezes para abrir", "expansionTileExpandedTapHint": "Feche", "expansionTileCollapsedTapHint": "Abra para mostrar mais detalhes", "expandedHint": "Fechado.", "collapsedHint": "Aberto.", "menuDismissLabel": "Dispensar menu", "lookUpButtonLabel": "Pesquisar", "searchWebButtonLabel": "Pesquisar na Web", "shareButtonLabel": "Compartilhar…", "clearButtonTooltip": "Clear text", "selectedDateLabel": "Selected" }
flutter/packages/flutter_localizations/lib/src/l10n/material_pt.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_pt.arb", "repo_id": "flutter", "token_count": 2361 }
730
{ "scriptCategory": "English-like", "timeOfDayFormat": "HH:mm", "openAppDrawerTooltip": "Gezinme menüsünü aç", "backButtonTooltip": "Geri", "closeButtonTooltip": "Kapat", "deleteButtonTooltip": "Sil", "nextMonthTooltip": "Gelecek ay", "previousMonthTooltip": "Önceki ay", "nextPageTooltip": "Sonraki sayfa", "previousPageTooltip": "Önceki sayfa", "firstPageTooltip": "İlk sayfa", "lastPageTooltip": "Son sayfa", "showMenuTooltip": "Menüyü göster", "aboutListTileTitle": "$applicationName Hakkında", "licensesPageTitle": "Lisanslar", "pageRowsInfoTitle": "$firstRow-$lastRow / $rowCount", "pageRowsInfoTitleApproximate": "$firstRow-$lastRow / $rowCount", "rowsPerPageTitle": "Sayfa başına satır sayısı:", "tabLabel": "Sekme $tabIndex / $tabCount", "selectedRowCountTitleOne": "1 öğe seçildi", "selectedRowCountTitleOther": "$selectedRowCount öğe seçildi", "cancelButtonLabel": "İptal", "closeButtonLabel": "Kapat", "continueButtonLabel": "Devam", "copyButtonLabel": "Kopyala", "cutButtonLabel": "Kes", "scanTextButtonLabel": "Metin tara", "okButtonLabel": "Tamam", "pasteButtonLabel": "Yapıştır", "selectAllButtonLabel": "Tümünü seç", "viewLicensesButtonLabel": "Lisansları göster", "anteMeridiemAbbreviation": "ÖÖ", "postMeridiemAbbreviation": "ÖS", "timePickerHourModeAnnouncement": "Saati seçin", "timePickerMinuteModeAnnouncement": "Dakikayı seçin", "signedInLabel": "Oturum açıldı", "hideAccountsLabel": "Hesapları gizle", "showAccountsLabel": "Hesapları göster", "modalBarrierDismissLabel": "Kapat", "drawerLabel": "Gezinme menüsü", "popupMenuLabel": "Popup menü", "dialogLabel": "İletişim kutusu", "alertDialogLabel": "Uyarı", "searchFieldLabel": "Ara", "reorderItemToStart": "Başa taşı", "reorderItemToEnd": "Sona taşı", "reorderItemUp": "Yukarı taşı", "reorderItemDown": "Aşağı taşı", "reorderItemLeft": "Sola taşı", "reorderItemRight": "Sağa taşı", "expandedIconTapHint": "Daralt", "collapsedIconTapHint": "Genişlet", "remainingTextFieldCharacterCountOne": "1 karakter kaldı", "remainingTextFieldCharacterCountOther": "$remainingCount karakter kaldı", "refreshIndicatorSemanticLabel": "Yenile", "moreButtonTooltip": "Diğer", "dateSeparator": ".", "dateHelpText": "gg.aa.yyyy", "selectYearSemanticsLabel": "Yılı seçin", "unspecifiedDate": "Tarih", "unspecifiedDateRange": "Tarih Aralığı", "dateInputLabel": "Tarih Girin", "dateRangeStartLabel": "Başlangıç Tarihi", "dateRangeEndLabel": "Bitiş Tarihi", "dateRangeStartDateSemanticLabel": "Başlangıç tarihi $fullDate", "dateRangeEndDateSemanticLabel": "Bitiş tarihi $fullDate", "invalidDateFormatLabel": "Geçersiz biçim.", "invalidDateRangeLabel": "Geçersiz aralık.", "dateOutOfRangeLabel": "Kapsama alanı dışında.", "saveButtonLabel": "Kaydet", "datePickerHelpText": "Tarih seçin", "dateRangePickerHelpText": "Aralık seçin", "calendarModeButtonLabel": "Takvime geç", "inputDateModeButtonLabel": "Girişe geç", "timePickerDialHelpText": "Saat seçin", "timePickerInputHelpText": "Saat girin", "timePickerHourLabel": "Saat", "timePickerMinuteLabel": "Dakika", "invalidTimeLabel": "Geçerli bir saat girin", "dialModeButtonLabel": "Dairesel seçici moduna geç", "inputTimeModeButtonLabel": "Metin giriş moduna geç", "licensesPackageDetailTextZero": "No licenses", "licensesPackageDetailTextOne": "1 lisans", "licensesPackageDetailTextOther": "$licenseCount lisans", "keyboardKeyAlt": "Alt", "keyboardKeyAltGraph": "AltGr", "keyboardKeyBackspace": "Geri Tuşu", "keyboardKeyCapsLock": "Caps Lock", "keyboardKeyChannelDown": "Kanal Aşağı", "keyboardKeyChannelUp": "Kanal Yukarı", "keyboardKeyControl": "Ctrl", "keyboardKeyDelete": "Del", "keyboardKeyEject": "Çıkar", "keyboardKeyEnd": "Son", "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": "Güç", "keyboardKeyPowerOff": "Kapat", "keyboardKeyPrintScreen": "Ekranı Yazdır", "keyboardKeyScrollLock": "Scroll Lock", "keyboardKeySelect": "Seç", "keyboardKeySpace": "Boşluk", "keyboardKeyMetaMacOs": "Komut", "keyboardKeyMetaWindows": "Win", "menuBarMenuLabel": "Menü çubuğu menüsü", "currentDateLabel": "Bugün", "scrimLabel": "opaklık katmanı", "bottomSheetLabel": "alt sayfa", "scrimOnTapHint": "$modalRouteContentName içeriğini kapat", "keyboardKeyShift": "üst karakter", "expansionTileExpandedHint": "daraltmak için iki kez dokunun", "expansionTileCollapsedHint": "genişletmek için iki kez dokunun", "expansionTileExpandedTapHint": "Daralt", "expansionTileCollapsedTapHint": "Daha fazla ayrıntı için genişletin", "expandedHint": "Daraltıldı", "collapsedHint": "Genişletildi", "menuDismissLabel": "Menüyü kapat", "lookUpButtonLabel": "Ara", "searchWebButtonLabel": "Web'de Ara", "shareButtonLabel": "Paylaş...", "clearButtonTooltip": "Clear text", "selectedDateLabel": "Selected" }
flutter/packages/flutter_localizations/lib/src/l10n/material_tr.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_tr.arb", "repo_id": "flutter", "token_count": 2364 }
731
{ "reorderItemToStart": "চালু করতে সরান", "reorderItemToEnd": "একদম শেষের দিকে যান", "reorderItemUp": "উপরের দিকে সরান", "reorderItemDown": "নিচের দিকে সরান", "reorderItemLeft": "বাঁদিকে সরান", "reorderItemRight": "ডানদিকে সরান" }
flutter/packages/flutter_localizations/lib/src/l10n/widgets_bn.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_bn.arb", "repo_id": "flutter", "token_count": 240 }
732
{ "reorderItemToStart": "પ્રારંભમાં ખસેડો", "reorderItemToEnd": "અંતમાં ખસેડો", "reorderItemUp": "ઉપર ખસેડો", "reorderItemDown": "નીચે ખસેડો", "reorderItemLeft": "ડાબે ખસેડો", "reorderItemRight": "જમણે ખસેડો" }
flutter/packages/flutter_localizations/lib/src/l10n/widgets_gu.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_gu.arb", "repo_id": "flutter", "token_count": 255 }
733
{ "reorderItemToStart": "ຍ້າຍໄປເລີ່ມຕົ້ນ", "reorderItemToEnd": "ຍ້າຍໄປສິ້ນສຸດ", "reorderItemUp": "ຍ້າຍຂຶ້ນ", "reorderItemDown": "ຍ້າຍລົງ", "reorderItemLeft": "ຍ້າຍໄປຊ້າຍ", "reorderItemRight": "ຍ້າຍໄປຂວາ" }
flutter/packages/flutter_localizations/lib/src/l10n/widgets_lo.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_lo.arb", "repo_id": "flutter", "token_count": 252 }
734
{ "reorderItemToStart": "Move to the start", "reorderItemToEnd": "Move to the end", "reorderItemUp": "Move up", "reorderItemDown": "Move down", "reorderItemLeft": "Move left", "reorderItemRight": "Move right" }
flutter/packages/flutter_localizations/lib/src/l10n/widgets_ps.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_ps.arb", "repo_id": "flutter", "token_count": 82 }
735
// 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'; import 'package:flutter/cupertino.dart'; import 'package:flutter/services.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:path/path.dart' as path; import '../test_utils.dart'; final String rootDirectoryPath = Directory.current.path; void main() { for (final String language in kCupertinoSupportedLanguages) { testWidgets('translations exist for $language', (WidgetTester tester) async { final Locale locale = Locale(language); expect(GlobalCupertinoLocalizations.delegate.isSupported(locale), isTrue); final CupertinoLocalizations localizations = await GlobalCupertinoLocalizations.delegate.load(locale); expect(localizations.datePickerYear(0), isNotNull); expect(localizations.datePickerYear(1), isNotNull); expect(localizations.datePickerYear(2), isNotNull); expect(localizations.datePickerYear(10), isNotNull); expect(localizations.datePickerMonth(1), isNotNull); expect(localizations.datePickerMonth(2), isNotNull); expect(localizations.datePickerMonth(11), isNotNull); expect(localizations.datePickerMonth(12), isNotNull); expect(localizations.datePickerStandaloneMonth(1), isNotNull); expect(localizations.datePickerStandaloneMonth(2), isNotNull); expect(localizations.datePickerStandaloneMonth(11), isNotNull); expect(localizations.datePickerStandaloneMonth(12), isNotNull); expect(localizations.datePickerDayOfMonth(0), isNotNull); expect(localizations.datePickerDayOfMonth(1), isNotNull); expect(localizations.datePickerDayOfMonth(2), isNotNull); expect(localizations.datePickerDayOfMonth(10), isNotNull); expect(localizations.datePickerDayOfMonth(0, 1), isNotNull); expect(localizations.datePickerDayOfMonth(1, 2), isNotNull); expect(localizations.datePickerDayOfMonth(2, 3), isNotNull); expect(localizations.datePickerDayOfMonth(10, 4), isNotNull); expect(localizations.datePickerMediumDate(DateTime(2019, 3, 25)), isNotNull); expect(localizations.datePickerHour(0), isNotNull); expect(localizations.datePickerHour(1), isNotNull); expect(localizations.datePickerHour(2), isNotNull); expect(localizations.datePickerHour(10), isNotNull); expect(localizations.datePickerHourSemanticsLabel(0), isNotNull); expect(localizations.datePickerHourSemanticsLabel(1), isNotNull); expect(localizations.datePickerHourSemanticsLabel(2), isNotNull); expect(localizations.datePickerHourSemanticsLabel(10), isNotNull); expect(localizations.datePickerHourSemanticsLabel(0), isNot(contains(r'$hour'))); expect(localizations.datePickerHourSemanticsLabel(1), isNot(contains(r'$hour'))); expect(localizations.datePickerHourSemanticsLabel(2), isNot(contains(r'$hour'))); expect(localizations.datePickerHourSemanticsLabel(10), isNot(contains(r'$hour'))); expect(localizations.datePickerDateOrder, isNotNull); expect(localizations.datePickerDateTimeOrder, isNotNull); expect(localizations.anteMeridiemAbbreviation, isNotNull); expect(localizations.postMeridiemAbbreviation, isNotNull); expect(localizations.alertDialogLabel, isNotNull); expect(localizations.timerPickerHour(0), isNotNull); expect(localizations.timerPickerHour(1), isNotNull); expect(localizations.timerPickerHour(2), isNotNull); expect(localizations.timerPickerHour(10), isNotNull); expect(localizations.timerPickerMinute(0), isNotNull); expect(localizations.timerPickerMinute(1), isNotNull); expect(localizations.timerPickerMinute(2), isNotNull); expect(localizations.timerPickerMinute(10), isNotNull); expect(localizations.timerPickerSecond(0), isNotNull); expect(localizations.timerPickerSecond(1), isNotNull); expect(localizations.timerPickerSecond(2), isNotNull); expect(localizations.timerPickerSecond(10), isNotNull); expect(localizations.timerPickerHourLabel(0), isNotNull); expect(localizations.timerPickerHourLabel(1), isNotNull); expect(localizations.timerPickerHourLabel(2), isNotNull); expect(localizations.timerPickerHourLabel(10), isNotNull); expect(localizations.timerPickerMinuteLabel(0), isNotNull); expect(localizations.timerPickerMinuteLabel(1), isNotNull); expect(localizations.timerPickerMinuteLabel(2), isNotNull); expect(localizations.timerPickerMinuteLabel(10), isNotNull); expect(localizations.timerPickerSecondLabel(0), isNotNull); expect(localizations.timerPickerSecondLabel(1), isNotNull); expect(localizations.timerPickerSecondLabel(2), isNotNull); expect(localizations.timerPickerSecondLabel(10), isNotNull); expect(localizations.cutButtonLabel, isNotNull); expect(localizations.copyButtonLabel, isNotNull); expect(localizations.pasteButtonLabel, isNotNull); expect(localizations.selectAllButtonLabel, isNotNull); expect(localizations.tabSemanticsLabel(tabIndex: 2, tabCount: 5), isNotNull); expect(localizations.tabSemanticsLabel(tabIndex: 2, tabCount: 5), isNot(contains(r'$tabIndex'))); expect(localizations.tabSemanticsLabel(tabIndex: 2, tabCount: 5), isNot(contains(r'$tabCount'))); expect(() => localizations.tabSemanticsLabel(tabIndex: 0, tabCount: 5), throwsAssertionError); expect(() => localizations.tabSemanticsLabel(tabIndex: 2, tabCount: 0), throwsAssertionError); }); } testWidgets('Spot check French', (WidgetTester tester) async { const Locale locale = Locale('fr'); expect(GlobalCupertinoLocalizations.delegate.isSupported(locale), isTrue); final CupertinoLocalizations localizations = await GlobalCupertinoLocalizations.delegate.load(locale); expect(localizations, isA<CupertinoLocalizationFr>()); expect(localizations.alertDialogLabel, 'Alerte'); expect(localizations.datePickerHourSemanticsLabel(1), '1 heure'); expect(localizations.datePickerHourSemanticsLabel(12), '12 heures'); expect(localizations.pasteButtonLabel, 'Coller'); expect(localizations.datePickerDateOrder, DatePickerDateOrder.dmy); expect(localizations.timerPickerSecondLabel(20), 's'); expect(localizations.selectAllButtonLabel, 'Tout sélectionner'); expect(localizations.timerPickerMinute(10), '10'); }); testWidgets('Spot check Chinese', (WidgetTester tester) async { const Locale locale = Locale('zh'); expect(GlobalCupertinoLocalizations.delegate.isSupported(locale), isTrue); final CupertinoLocalizations localizations = await GlobalCupertinoLocalizations.delegate.load(locale); expect(localizations, isA<CupertinoLocalizationZh>()); expect(localizations.alertDialogLabel, '提醒'); expect(localizations.datePickerHourSemanticsLabel(1), '1 点'); expect(localizations.datePickerHourSemanticsLabel(12), '12 点'); expect(localizations.pasteButtonLabel, '粘贴'); expect(localizations.datePickerDateOrder, DatePickerDateOrder.ymd); expect(localizations.timerPickerSecondLabel(20), '秒'); expect(localizations.selectAllButtonLabel, '全选'); expect(localizations.timerPickerMinute(10), '10'); }); // Regression test for https://github.com/flutter/flutter/issues/53036. testWidgets('`nb` uses `no` as its synonym when `nb` arb file is not present', (WidgetTester tester) async { final File nbCupertinoArbFile = File( path.join(rootDirectoryPath, 'lib', 'src', 'l10n', 'cupertino_nb.arb'), ); final File noCupertinoArbFile = File( path.join(rootDirectoryPath, 'lib', 'src', 'l10n', 'cupertino_no.arb'), ); if (noCupertinoArbFile.existsSync() && !nbCupertinoArbFile.existsSync()) { Locale locale = const Locale.fromSubtags(languageCode: 'no'); expect(GlobalCupertinoLocalizations.delegate.isSupported(locale), isTrue); CupertinoLocalizations localizations = await GlobalCupertinoLocalizations.delegate.load(locale); expect(localizations, isA<CupertinoLocalizationNo>()); final String pasteButtonLabelNo = localizations.pasteButtonLabel; final String copyButtonLabelNo = localizations.copyButtonLabel; final String cutButtonLabelNo = localizations.cutButtonLabel; locale = const Locale.fromSubtags(languageCode: 'nb'); expect(GlobalCupertinoLocalizations.delegate.isSupported(locale), isTrue); localizations = await GlobalCupertinoLocalizations.delegate.load(locale); expect(localizations, isA<CupertinoLocalizationNb>()); expect(localizations.pasteButtonLabel, pasteButtonLabelNo); expect(localizations.copyButtonLabel, copyButtonLabelNo); expect(localizations.cutButtonLabel, cutButtonLabelNo); } }); // Regression test for https://github.com/flutter/flutter/issues/36704. testWidgets('kn arb file should be properly Unicode escaped', (WidgetTester tester) async { final File file = File( path.join(rootDirectoryPath, 'lib', 'src', 'l10n', 'cupertino_kn.arb'), ); final Map<String, dynamic> bundle = json.decode(file.readAsStringSync()) as Map<String, dynamic>; // Encodes the arb resource values if they have not already been // encoded. encodeBundleTranslations(bundle); // Generates the encoded arb output file in as a string. final String encodedArbFile = generateArbString(bundle); // After encoding the bundles, the generated string should match // the existing material_kn.arb. if (Platform.isWindows) { // On Windows, the character '\n' can output the two-character sequence // '\r\n' (and when reading the file back, '\r\n' is translated back // into a single '\n' character). expect(file.readAsStringSync().replaceAll('\r\n', '\n'), encodedArbFile); } else { expect(file.readAsStringSync(), encodedArbFile); } }); // Regression test for https://github.com/flutter/flutter/issues/110451. testWidgets('Finnish translation for tab label', (WidgetTester tester) async { const Locale locale = Locale('fi'); expect(GlobalCupertinoLocalizations.delegate.isSupported(locale), isTrue); final CupertinoLocalizations localizations = await GlobalCupertinoLocalizations.delegate.load(locale); expect(localizations, isA<CupertinoLocalizationFi>()); expect(localizations.tabSemanticsLabel(tabIndex: 1, tabCount: 2), 'Välilehti 1 kautta 2'); }); // Regression test for https://github.com/flutter/flutter/issues/130874. testWidgets('buildButtonItems builds a localized "No Replacements found" button when no suggestions', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( locale: const Locale('ru'), localizationsDelegates: GlobalCupertinoLocalizations.delegates, supportedLocales: const <Locale>[Locale('en'), Locale('ru')], home: _FakeEditableText() ), ); final _FakeEditableTextState editableTextState = tester.state(find.byType(_FakeEditableText)); final List<ContextMenuButtonItem>? buttonItems = CupertinoSpellCheckSuggestionsToolbar.buildButtonItems(editableTextState); expect(buttonItems, isNotNull); expect(buttonItems, hasLength(1)); expect(buttonItems!.first.label, 'Варианты замены не найдены'); expect(buttonItems.first.onPressed, isNull); }); // Regression test for https://github.com/flutter/flutter/issues/141764 testWidgets('zh-CN translation for look up label', (WidgetTester tester) async { const Locale locale = Locale('zh'); expect(GlobalCupertinoLocalizations.delegate.isSupported(locale), isTrue); final CupertinoLocalizations localizations = await GlobalCupertinoLocalizations.delegate.load(locale); expect(localizations, isA<CupertinoLocalizationZh>()); expect(localizations.lookUpButtonLabel, '查询'); }); } class _FakeEditableText extends EditableText { _FakeEditableText() : super( controller: TextEditingController(), focusNode: FocusNode(), backgroundCursorColor: CupertinoColors.white, cursorColor: CupertinoColors.white, style: const TextStyle(), ); @override _FakeEditableTextState createState() => _FakeEditableTextState(); } class _FakeEditableTextState extends EditableTextState { _FakeEditableTextState(); @override TextEditingValue get currentTextEditingValue => TextEditingValue.empty; @override SuggestionSpan? findSuggestionSpanAtCursorIndex(int cursorIndex) { return const SuggestionSpan( TextRange( start: 0, end: 0, ), <String>[], ); } }
flutter/packages/flutter_localizations/test/cupertino/translations_test.dart/0
{ "file_path": "flutter/packages/flutter_localizations/test/cupertino/translations_test.dart", "repo_id": "flutter", "token_count": 4477 }
736
// 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/services.dart'; import 'binding.dart'; /// Shim to support the obsolete [setMockMessageHandler] and /// [checkMockMessageHandler] methods on [BinaryMessenger] in tests. /// /// The implementations defer to [TestDefaultBinaryMessengerBinding.defaultBinaryMessenger]. /// /// Rather than calling [setMockMessageHandler] on the /// `ServicesBinding.defaultBinaryMessenger`, use /// `tester.binding.defaultBinaryMessenger.setMockMessageHandler` directly. This /// more accurately represents the actual method invocation. extension TestBinaryMessengerExtension on BinaryMessenger { /// Shim for [TestDefaultBinaryMessenger.setMockMessageHandler]. @Deprecated( 'Use tester.binding.defaultBinaryMessenger.setMockMessageHandler or ' 'TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMessageHandler instead. ' 'For the first argument, pass channel.name. ' 'This feature was deprecated after v3.9.0-19.0.pre.' ) void setMockMessageHandler(String channel, MessageHandler? handler) { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMessageHandler(channel, handler); } /// Shim for [TestDefaultBinaryMessenger.checkMockMessageHandler]. @Deprecated( 'Use tester.binding.defaultBinaryMessenger.checkMockMessageHandler or ' 'TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.checkMockMessageHandler instead. ' 'For the first argument, pass channel.name. ' 'This feature was deprecated after v3.9.0-19.0.pre.' ) bool checkMockMessageHandler(String channel, Object? handler) { return TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.checkMockMessageHandler(channel, handler); } } /// Shim to support the obsolete [setMockMessageHandler] and /// [checkMockMessageHandler] methods on [BasicMessageChannel] in tests. /// /// The implementations defer to [TestDefaultBinaryMessengerBinding.defaultBinaryMessenger]. /// /// Rather than calling [setMockMessageHandler] on the message channel, use /// `tester.binding.defaultBinaryMessenger.setMockDecodedMessageHandler` /// directly. This more accurately represents the actual method invocation. extension TestBasicMessageChannelExtension<T> on BasicMessageChannel<T> { /// Shim for [TestDefaultBinaryMessenger.setMockDecodedMessageHandler]. @Deprecated( 'Use tester.binding.defaultBinaryMessenger.setMockDecodedMessageHandler or ' 'TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockDecodedMessageHandler instead. ' 'Pass the channel as the first argument. ' 'This feature was deprecated after v3.9.0-19.0.pre.' ) void setMockMessageHandler(Future<T> Function(T? message)? handler) { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockDecodedMessageHandler<T>(this, handler); } /// Shim for [TestDefaultBinaryMessenger.checkMockMessageHandler]. @Deprecated( 'Use tester.binding.defaultBinaryMessenger.checkMockMessageHandler or ' 'TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.checkMockMessageHandler instead. ' 'For the first argument, pass channel.name. ' 'This feature was deprecated after v3.9.0-19.0.pre.' ) bool checkMockMessageHandler(Object? handler) { return TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.checkMockMessageHandler(name, handler); } } /// Shim to support the obsolete [setMockMethodCallHandler] and /// [checkMockMethodCallHandler] methods on [MethodChannel] in tests. /// /// The implementations defer to [TestDefaultBinaryMessengerBinding.defaultBinaryMessenger]. /// /// Rather than calling [setMockMethodCallHandler] on the method channel, use /// `tester.binding.defaultBinaryMessenger.setMockMethodCallHandler` directly. /// This more accurately represents the actual method invocation. extension TestMethodChannelExtension on MethodChannel { /// Shim for [TestDefaultBinaryMessenger.setMockMethodCallHandler]. @Deprecated( 'Use tester.binding.defaultBinaryMessenger.setMockMethodCallHandler or ' 'TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler instead. ' 'Pass the channel as the first argument. ' 'This feature was deprecated after v3.9.0-19.0.pre.' ) void setMockMethodCallHandler(Future<dynamic>? Function(MethodCall call)? handler) { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(this, handler); } /// Shim for [TestDefaultBinaryMessenger.checkMockMessageHandler]. @Deprecated( 'Use tester.binding.defaultBinaryMessenger.checkMockMessageHandler or ' 'TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.checkMockMessageHandler instead. ' 'For the first argument, pass channel.name. ' 'This feature was deprecated after v3.9.0-19.0.pre.' ) bool checkMockMethodCallHandler(Object? handler) { return TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.checkMockMessageHandler(name, handler); } }
flutter/packages/flutter_test/lib/src/deprecated.dart/0
{ "file_path": "flutter/packages/flutter_test/lib/src/deprecated.dart", "repo_id": "flutter", "token_count": 1523 }
737
// 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:ui' as ui; import 'package:fake_async/fake_async.dart'; import 'package:flutter/services.dart'; import 'mock_event_channel.dart'; import 'widget_tester.dart'; /// A function which takes the name of the method channel, it's handler, /// platform message and asynchronously returns an encoded response. typedef AllMessagesHandler = Future<ByteData?>? Function( String channel, MessageHandler? handler, ByteData? message); /// A [BinaryMessenger] subclass that is used as the default binary messenger /// under testing environment. /// /// It tracks status of data sent across the Flutter platform barrier, which is /// useful for testing frameworks to monitor and synchronize against the /// platform messages. /// /// ## Messages from the framework to the platform /// /// Messages are sent from the framework to the platform via the /// [send] method. /// /// To intercept a message sent from the framework to the platform, /// consider using [setMockMessageHandler], /// [setMockDecodedMessageHandler], and [setMockMethodCallHandler] /// (see also [checkMockMessageHandler]). /// /// To wait for all pending framework-to-platform messages, the /// [platformMessagesFinished] getter provides an appropriate /// [Future]. The [pendingMessageCount] getter returns the current /// number of outstanding messages. /// /// ## Messages from the platform to the framework /// /// The platform sends messages via the [ChannelBuffers] API. Mock /// messages can be sent to the framework using /// [handlePlatformMessage]. /// /// Listeners for these messages are configured using [setMessageHandler]. class TestDefaultBinaryMessenger extends BinaryMessenger { /// Creates a [TestDefaultBinaryMessenger] instance. TestDefaultBinaryMessenger( this.delegate, { Map<String, MessageHandler> outboundHandlers = const <String, MessageHandler>{}, }) { _outboundHandlers.addAll(outboundHandlers); } /// The delegate [BinaryMessenger]. final BinaryMessenger delegate; // The handlers for messages from the engine (including fake // messages sent by handlePlatformMessage). final Map<String, MessageHandler> _inboundHandlers = <String, MessageHandler>{}; /// Send a mock message to the framework as if it came from the platform. /// /// If a listener has been set using [setMessageHandler], that listener is /// invoked to handle the message, and this method returns a future that /// completes with that handler's result. /// /// {@template flutter.flutter_test.TestDefaultBinaryMessenger.handlePlatformMessage.asyncHandlers} /// It is strongly recommended that all handlers used with this API be /// synchronous (not requiring any microtasks to complete), because /// [testWidgets] tests run in a [FakeAsync] zone in which microtasks do not /// progress except when time is explicitly advanced (e.g. with /// [WidgetTester.pump]), which means that `await`ing a [Future] will result /// in the test hanging. /// {@endtemplate} /// /// If no listener is configured, this method returns right away with null. /// /// The `callback` argument, if non-null, will be called just before this /// method's future completes, either with the result of the listener /// registered with [setMessageHandler], or with null if no listener has /// been registered. /// /// Messages can also be sent via [ChannelBuffers.push] (see /// [ServicesBinding.channelBuffers]); the effect is the same, though that API /// will not wait for a response. // TODO(ianh): When the superclass `handlePlatformMessage` is removed, // remove this @override (but leave the method). @override Future<ByteData?> handlePlatformMessage( String channel, ByteData? data, ui.PlatformMessageResponseCallback? callback, ) { Future<ByteData?>? result; if (_inboundHandlers.containsKey(channel)) { result = _inboundHandlers[channel]!(data); } result ??= Future<ByteData?>.value(); if (callback != null) { result = result.then((ByteData? result) { callback(result); return result; }); } return result; } @override void setMessageHandler(String channel, MessageHandler? handler) { if (handler == null) { _inboundHandlers.remove(channel); delegate.setMessageHandler(channel, null); } else { _inboundHandlers[channel] = handler; // used to handle fake messages sent via handlePlatformMessage delegate.setMessageHandler(channel, handler); // used to handle real messages from the engine } } final List<Future<ByteData?>> _pendingMessages = <Future<ByteData?>>[]; /// The number of incomplete/pending calls sent to the platform channels. int get pendingMessageCount => _pendingMessages.length; // Handlers that intercept and respond to outgoing messages, // pretending to be the platform. final Map<String, MessageHandler> _outboundHandlers = <String, MessageHandler>{}; // The outbound callbacks that were actually registered, so that we // can implement the [checkMockMessageHandler] method. final Map<String, Object> _outboundHandlerIdentities = <String, Object>{}; /// Handler that intercepts and responds to outgoing messages, pretending /// to be the platform, for all channels. AllMessagesHandler? allMessagesHandler; @override Future<ByteData?>? send(String channel, ByteData? message) { final Future<ByteData?>? resultFuture; final MessageHandler? handler = _outboundHandlers[channel]; if (allMessagesHandler != null) { resultFuture = allMessagesHandler!(channel, handler, message); } else if (handler != null) { resultFuture = handler(message); } else { resultFuture = delegate.send(channel, message); } if (resultFuture != null) { _pendingMessages.add(resultFuture); resultFuture // TODO(srawlins): Fix this static issue, // https://github.com/flutter/flutter/issues/105750. // ignore: body_might_complete_normally_catch_error .catchError((Object error) { /* errors are the responsibility of the caller */ }) .whenComplete(() => _pendingMessages.remove(resultFuture)); } return resultFuture; } /// Returns a Future that completes after all the platform calls are finished. /// /// If a new platform message is sent after this method is called, this new /// message is not tracked. Use with [pendingMessageCount] to guarantee no /// pending message calls. Future<void> get platformMessagesFinished { return Future.wait<void>(_pendingMessages); } /// Set a callback for intercepting messages sent to the platform on /// the given channel, without decoding them. /// /// Intercepted messages are not forwarded to the platform. /// /// The given callback will replace the currently registered /// callback for that channel, if any. To stop intercepting messages /// at all, pass null as the handler. /// /// The handler's return value, if non-null, is used as a response, /// unencoded. /// /// {@macro flutter.flutter_test.TestDefaultBinaryMessenger.handlePlatformMessage.asyncHandlers} /// /// The `identity` argument, if non-null, is used to identify the /// callback when checked by [checkMockMessageHandler]. If null, the /// `handler` is used instead. (This allows closures to be passed as /// the `handler` with an alias used as the `identity` so that a /// reference to the closure need not be used. In practice, this is /// used by [setMockDecodedMessageHandler] and /// [setMockMethodCallHandler] to allow [checkMockMessageHandler] to /// recognize the closures that were passed to those methods even /// though those methods wrap those closures when passing them to /// this method.) /// /// Registered callbacks are cleared after each test. /// /// See also: /// /// * [checkMockMessageHandler], which can verify if a handler is still /// registered, which is useful in tests to ensure that no unexpected /// handlers are being registered. /// /// * [setMockDecodedMessageHandler], which wraps this method but /// decodes the messages using a [MessageCodec]. /// /// * [setMockMethodCallHandler], which wraps this method but decodes /// the messages using a [MethodCodec]. /// /// * [setMockStreamHandler], which wraps [setMockMethodCallHandler] to /// handle [EventChannel] messages. void setMockMessageHandler(String channel, MessageHandler? handler, [ Object? identity ]) { if (handler == null) { _outboundHandlers.remove(channel); _outboundHandlerIdentities.remove(channel); } else { identity ??= handler; _outboundHandlers[channel] = handler; _outboundHandlerIdentities[channel] = identity; } } /// Set a callback for intercepting messages sent to the platform on /// the given channel. /// /// Intercepted messages are not forwarded to the platform. /// /// The given callback will replace the currently registered /// callback for that channel, if any. To stop intercepting messages /// at all, pass null as the handler. /// /// Messages are decoded using the codec of the channel. /// /// The handler's return value, if non-null, is used as a response, /// after encoding it using the channel's codec. /// /// {@macro flutter.flutter_test.TestDefaultBinaryMessenger.handlePlatformMessage.asyncHandlers} /// /// Registered callbacks are cleared after each test. /// /// See also: /// /// * [checkMockMessageHandler], which can verify if a handler is still /// registered, which is useful in tests to ensure that no unexpected /// handlers are being registered. /// /// * [setMockMessageHandler], which is similar but provides raw /// access to the underlying bytes. /// /// * [setMockMethodCallHandler], which is similar but decodes /// the messages using a [MethodCodec]. /// /// * [setMockStreamHandler], which wraps [setMockMethodCallHandler] to /// handle [EventChannel] messages. void setMockDecodedMessageHandler<T>(BasicMessageChannel<T> channel, Future<T> Function(T? message)? handler) { if (handler == null) { setMockMessageHandler(channel.name, null); return; } setMockMessageHandler(channel.name, (ByteData? message) async { return channel.codec.encodeMessage(await handler(channel.codec.decodeMessage(message))); }, handler); } /// Set a callback for intercepting method calls sent to the /// platform on the given channel. /// /// Intercepted method calls are not forwarded to the platform. /// /// The given callback will replace the currently registered /// callback for that channel, if any. To stop intercepting messages /// at all, pass null as the handler. /// /// Methods are decoded using the codec of the channel. /// /// The handler's return value, if non-null, is used as a response, /// after re-encoding it using the channel's codec. /// /// To send an error, throw a [PlatformException] in the handler. /// Other exceptions are not caught. /// /// {@macro flutter.flutter_test.TestDefaultBinaryMessenger.handlePlatformMessage.asyncHandlers} /// /// Registered callbacks are cleared after each test. /// /// See also: /// /// * [checkMockMessageHandler], which can verify if a handler is still /// registered, which is useful in tests to ensure that no unexpected /// handlers are being registered. /// /// * [setMockMessageHandler], which is similar but provides raw /// access to the underlying bytes. /// /// * [setMockDecodedMessageHandler], which is similar but decodes /// the messages using a [MessageCodec]. void setMockMethodCallHandler(MethodChannel channel, Future<Object?>? Function(MethodCall message)? handler) { if (handler == null) { setMockMessageHandler(channel.name, null); return; } setMockMessageHandler(channel.name, (ByteData? message) async { final MethodCall call = channel.codec.decodeMethodCall(message); try { return channel.codec.encodeSuccessEnvelope(await handler(call)); } on PlatformException catch (error) { return channel.codec.encodeErrorEnvelope( code: error.code, message: error.message, details: error.details, ); } on MissingPluginException { return null; } catch (error) { return channel.codec.encodeErrorEnvelope(code: 'error', message: '$error'); } }, handler); } /// Set a handler for intercepting stream events sent to the /// platform on the given channel. /// /// Intercepted method calls are not forwarded to the platform. /// /// The given handler will replace the currently registered /// handler for that channel, if any. To stop intercepting messages /// at all, pass null as the handler. /// /// Events are decoded using the codec of the channel. /// /// The handler's stream messages are used as a response, after encoding /// them using the channel's codec. /// /// To send an error, pass the error information to the handler's event sink. /// /// {@macro flutter.flutter_test.TestDefaultBinaryMessenger.handlePlatformMessage.asyncHandlers} /// /// Registered handlers are cleared after each test. /// /// See also: /// /// * [setMockMethodCallHandler], which is the similar method for /// [MethodChannel]. /// /// * [setMockMessageHandler], which is similar but provides raw /// access to the underlying bytes. /// /// * [setMockDecodedMessageHandler], which is similar but decodes /// the messages using a [MessageCodec]. void setMockStreamHandler(EventChannel channel, MockStreamHandler? handler) { if (handler == null) { setMockMessageHandler(channel.name, null); return; } final StreamController<Object?> controller = StreamController<Object?>(); addTearDown(controller.close); setMockMethodCallHandler(MethodChannel(channel.name, channel.codec), (MethodCall call) async { switch (call.method) { case 'listen': return handler.onListen(call.arguments, MockStreamHandlerEventSink(controller.sink)); case 'cancel': return handler.onCancel(call.arguments); default: throw UnimplementedError('Method ${call.method} not implemented'); } }); final StreamSubscription<Object?> sub = controller.stream.listen( (Object? e) => handlePlatformMessage( channel.name, channel.codec.encodeSuccessEnvelope(e), null, ), ); addTearDown(sub.cancel); sub.onError((Object? e) { if (e is! PlatformException) { throw ArgumentError('Stream error must be a PlatformException'); } handlePlatformMessage( channel.name, channel.codec.encodeErrorEnvelope( code: e.code, message: e.message, details: e.details, ), null, ); }); sub.onDone(() => handlePlatformMessage(channel.name, null, null)); } /// Returns true if the `handler` argument matches the `handler` /// previously passed to [setMockMessageHandler], /// [setMockDecodedMessageHandler], or [setMockMethodCallHandler]. /// /// Specifically, it compares the argument provided to the `identity` /// argument provided to [setMockMessageHandler], defaulting to the /// `handler` argument passed to that method is `identity` was null. /// /// This method is useful for tests or test harnesses that want to assert the /// mock handler for the specified channel has not been altered by a previous /// test. /// /// Passing null for the `handler` returns true if the handler for the /// `channel` is not set. /// /// Registered callbacks are cleared after each test. bool checkMockMessageHandler(String channel, Object? handler) => _outboundHandlerIdentities[channel] == handler; }
flutter/packages/flutter_test/lib/src/test_default_binary_messenger.dart/0
{ "file_path": "flutter/packages/flutter_test/lib/src/test_default_binary_messenger.dart", "repo_id": "flutter", "token_count": 4834 }
738
// 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:io' as io; import 'dart:typed_data'; import 'dart:ui' as ui; import 'package:file/memory.dart'; import 'package:flutter/foundation.dart' show DiagnosticLevel, DiagnosticPropertiesBuilder, DiagnosticsNode, FlutterError; import 'package:flutter_test/flutter_test.dart' as test_package; import 'package:flutter_test/flutter_test.dart' hide test; // 1x1 transparent pixel const List<int> _kExpectedPngBytes = <int>[ 137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 1, 0, 0, 0, 1, 8, 6, 0, 0, 0, 31, 21, 196, 137, 0, 0, 0, 11, 73, 68, 65, 84, 120, 1, 99, 97, 0, 2, 0, 0, 25, 0, 5, 144, 240, 54, 245, 0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130, ]; // 1x1 colored pixel const List<int> _kColorFailurePngBytes = <int>[ 137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 1, 0, 0, 0, 1, 8, 6, 0, 0, 0, 31, 21, 196, 137, 0, 0, 0, 13, 73, 68, 65, 84, 120, 1, 99, 249, 207, 240, 255, 63, 0, 7, 18, 3, 2, 164, 147, 160, 197, 0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130, ]; // 1x2 transparent pixel const List<int> _kSizeFailurePngBytes = <int>[ 137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 1, 0, 0,0, 2, 8, 6, 0, 0, 0, 153, 129, 182, 39, 0, 0, 0, 14, 73, 68, 65, 84, 120, 1, 99, 97, 0, 2, 22, 16, 1, 0, 0, 70, 0, 9, 112, 117, 150, 160, 0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130, ]; void main() { late MemoryFileSystem fs; setUp(() { final FileSystemStyle style = io.Platform.isWindows ? FileSystemStyle.windows : FileSystemStyle.posix; fs = MemoryFileSystem(style: style); }); /// Converts posix-style paths to the style associated with [fs]. /// /// This allows us to deal in posix-style paths in the tests. String fix(String path) { if (path.startsWith('/')) { path = '${fs.style.drive}$path'; } return path.replaceAll('/', fs.path.separator); } void test(String description, FutureOr<void> Function() body) { test_package.test(description, () async { await io.IOOverrides.runZoned<FutureOr<void>>( body, createDirectory: (String path) => fs.directory(path), createFile: (String path) => fs.file(path), createLink: (String path) => fs.link(path), getCurrentDirectory: () => fs.currentDirectory, setCurrentDirectory: (String path) => fs.currentDirectory = path, getSystemTempDirectory: () => fs.systemTempDirectory, stat: (String path) => fs.stat(path), statSync: (String path) => fs.statSync(path), fseIdentical: (String p1, String p2) => fs.identical(p1, p2), fseIdenticalSync: (String p1, String p2) => fs.identicalSync(p1, p2), fseGetType: (String path, bool followLinks) => fs.type(path, followLinks: followLinks), fseGetTypeSync: (String path, bool followLinks) => fs.typeSync(path, followLinks: followLinks), fsWatch: (String a, int b, bool c) => throw UnsupportedError('unsupported'), fsWatchIsSupported: () => fs.isWatchSupported, ); }); } group('goldenFileComparator', () { test('is initialized by test framework', () { expect(goldenFileComparator, isNotNull); expect(goldenFileComparator, isA<LocalFileComparator>()); final LocalFileComparator comparator = goldenFileComparator as LocalFileComparator; expect(comparator.basedir.path, contains('flutter_test')); }); test('image comparison should not loop over all pixels when the data is the same', () async { final List<int> invalidImageData1 = Uint8List.fromList(<int>[127]); final List<int> invalidImageData2 = Uint8List.fromList(<int>[127]); // This will fail if the comparison algorithm tries to generate the images // to loop over every pixel which is not necessary when test and master // is exactly the same (for performance reasons). await GoldenFileComparator.compareLists(invalidImageData1, invalidImageData2); }); }); group('LocalFileComparator', () { late LocalFileComparator comparator; setUp(() { comparator = LocalFileComparator(fs.file(fix('/golden_test.dart')).uri, pathStyle: fs.path.style); }); test('calculates basedir correctly', () { expect(comparator.basedir, fs.file(fix('/')).uri); comparator = LocalFileComparator(fs.file(fix('/foo/bar/golden_test.dart')).uri, pathStyle: fs.path.style); expect(comparator.basedir, fs.directory(fix('/foo/bar/')).uri); }); test('can be instantiated with uri that represents file in same folder', () { comparator = LocalFileComparator(Uri.parse('foo_test.dart'), pathStyle: fs.path.style); expect(comparator.basedir, Uri.parse('./')); }); test('throws if local output is not awaited', () { try { comparator.generateFailureOutput( ComparisonResult(passed: false, diffPercent: 1.0), Uri.parse('foo_test.dart'), Uri.parse('/foo/bar/'), ); TestAsyncUtils.verifyAllScopesClosed(); fail('unexpectedly did not throw'); } on FlutterError catch (e) { final List<String> lines = e.message.split('\n'); expectSync(lines[0], 'Asynchronous call to guarded function leaked.'); expectSync(lines[1], 'You must use "await" with all Future-returning test APIs.'); expectSync( lines[2], matches(r'^The guarded method "generateFailureOutput" from class ' r'LocalComparisonOutput was called from .*goldens_test.dart on line ' r'[0-9]+, but never completed before its parent scope closed\.$'), ); expectSync(lines.length, 3); final DiagnosticPropertiesBuilder propertiesBuilder = DiagnosticPropertiesBuilder(); e.debugFillProperties(propertiesBuilder); final List<DiagnosticsNode> information = propertiesBuilder.properties; expectSync(information.length, 3); expectSync(information[0].level, DiagnosticLevel.summary); expectSync(information[1].level, DiagnosticLevel.hint); expectSync(information[2].level, DiagnosticLevel.info); } }); group('compare', () { Future<bool> doComparison([ String golden = 'golden.png' ]) { final Uri uri = fs.file(fix(golden)).uri; return comparator.compare( Uint8List.fromList(_kExpectedPngBytes), uri, ); } group('succeeds', () { test('when golden file is in same folder as test', () async { fs.file(fix('/golden.png')).writeAsBytesSync(_kExpectedPngBytes); final bool success = await doComparison(); expect(success, isTrue); }); test('when golden file is in subfolder of test', () async { fs.file(fix('/sub/foo.png')) ..createSync(recursive: true) ..writeAsBytesSync(_kExpectedPngBytes); final bool success = await doComparison('sub/foo.png'); expect(success, isTrue); }); group('when comparator instantiated with uri that represents file in same folder', () { test('and golden file is in same folder as test', () async { fs.file(fix('/foo/bar/golden.png')) ..createSync(recursive: true) ..writeAsBytesSync(_kExpectedPngBytes); fs.currentDirectory = fix('/foo/bar'); comparator = LocalFileComparator(Uri.parse('local_test.dart'), pathStyle: fs.path.style); final bool success = await doComparison(); expect(success, isTrue); }); test('and golden file is in subfolder of test', () async { fs.file(fix('/foo/bar/baz/golden.png')) ..createSync(recursive: true) ..writeAsBytesSync(_kExpectedPngBytes); fs.currentDirectory = fix('/foo/bar'); comparator = LocalFileComparator(Uri.parse('local_test.dart'), pathStyle: fs.path.style); final bool success = await doComparison('baz/golden.png'); expect(success, isTrue); }); }); }); group('fails', () { test('and generates correct output in the correct base location', () async { comparator = LocalFileComparator(Uri.parse('local_test.dart'), pathStyle: fs.path.style); await fs.file(fix('/golden.png')).writeAsBytes(_kColorFailurePngBytes); await expectLater( () => doComparison(), throwsA(isFlutterError.having( (FlutterError error) => error.message, 'message', contains('100.00%, 1px diff detected'), )), ); final io.File master = fs.file( fix('/failures/golden_masterImage.png') ); final io.File test = fs.file( fix('/failures/golden_testImage.png') ); final io.File isolated = fs.file( fix('/failures/golden_isolatedDiff.png') ); final io.File masked = fs.file( fix('/failures/golden_maskedDiff.png') ); expect(master.existsSync(), isTrue); expect(test.existsSync(), isTrue); expect(isolated.existsSync(), isTrue); expect(masked.existsSync(), isTrue); }); test('and generates correct output when files are in a subdirectory', () async { comparator = LocalFileComparator(Uri.parse('local_test.dart'), pathStyle: fs.path.style); fs.file(fix('subdir/golden.png')) ..createSync(recursive:true) ..writeAsBytesSync(_kColorFailurePngBytes); await expectLater( () => doComparison('subdir/golden.png'), throwsA(isFlutterError.having( (FlutterError error) => error.message, 'message', contains('100.00%, 1px diff detected'), )), ); final io.File master = fs.file( fix('/failures/golden_masterImage.png') ); final io.File test = fs.file( fix('/failures/golden_testImage.png') ); final io.File isolated = fs.file( fix('/failures/golden_isolatedDiff.png') ); final io.File masked = fs.file( fix('/failures/golden_maskedDiff.png') ); expect(master.existsSync(), isTrue); expect(test.existsSync(), isTrue); expect(isolated.existsSync(), isTrue); expect(masked.existsSync(), isTrue); }); test('and generates correct output when images are not the same size', () async { await fs.file(fix('/golden.png')).writeAsBytes(_kSizeFailurePngBytes); await expectLater( () => doComparison(), throwsA(isFlutterError.having( (FlutterError error) => error.message, 'message', contains('image sizes do not match'), )), ); final io.File master = fs.file( fix('/failures/golden_masterImage.png') ); final io.File test = fs.file( fix('/failures/golden_testImage.png') ); final io.File isolated = fs.file( fix('/failures/golden_isolatedDiff.png') ); final io.File masked = fs.file( fix('/failures/golden_maskedDiff.png') ); expect(master.existsSync(), isTrue); expect(test.existsSync(), isTrue); expect(isolated.existsSync(), isFalse); expect(masked.existsSync(), isFalse); }); test('when golden file does not exist', () async { await expectLater( () => doComparison(), throwsA(isA<TestFailure>().having( (TestFailure error) => error.message, 'message', contains('Could not be compared against non-existent file'), )), ); }); test('when images are not the same size', () async{ await fs.file(fix('/golden.png')).writeAsBytes(_kSizeFailurePngBytes); await expectLater( () => doComparison(), throwsA(isFlutterError.having( (FlutterError error) => error.message, 'message', contains('image sizes do not match'), )), ); }); test('when pixels do not match', () async{ await fs.file(fix('/golden.png')).writeAsBytes(_kColorFailurePngBytes); await expectLater( () => doComparison(), throwsA(isFlutterError.having( (FlutterError error) => error.message, 'message', contains('100.00%, 1px diff detected'), )), ); }); test('when golden bytes are empty', () async { await fs.file(fix('/golden.png')).writeAsBytes(<int>[]); await expectLater( () => doComparison(), throwsA(isFlutterError.having( (FlutterError error) => error.message, 'message', contains('null image provided'), )), ); }); }); }); group('update', () { test('updates existing file', () async { fs.file(fix('/golden.png')).writeAsBytesSync(_kExpectedPngBytes); const List<int> newBytes = <int>[11, 12, 13]; await comparator.update(fs.file('golden.png').uri, Uint8List.fromList(newBytes)); expect(fs.file(fix('/golden.png')).readAsBytesSync(), newBytes); }); test('creates non-existent file', () async { expect(fs.file(fix('/foo.png')).existsSync(), isFalse); const List<int> newBytes = <int>[11, 12, 13]; await comparator.update(fs.file('foo.png').uri, Uint8List.fromList(newBytes)); expect(fs.file(fix('/foo.png')).existsSync(), isTrue); expect(fs.file(fix('/foo.png')).readAsBytesSync(), newBytes); }); }); group('getTestUri', () { test('updates file name with version number', () { final Uri key = Uri.parse('foo.png'); final Uri key1 = comparator.getTestUri(key, 1); expect(key1, Uri.parse('foo.1.png')); }); test('does nothing for null version number', () { final Uri key = Uri.parse('foo.png'); final Uri keyNull = comparator.getTestUri(key, null); expect(keyNull, Uri.parse('foo.png')); }); }); }); group('ComparisonResult', () { group('dispose', () { test('disposes diffs images', () async { final ui.Image image1 = await createTestImage(width: 10, height: 10, cache: false); final ui.Image image2 = await createTestImage(width: 15, height: 5, cache: false); final ui.Image image3 = await createTestImage(width: 5, height: 10, cache: false); final ComparisonResult result = ComparisonResult( passed: false, diffPercent: 1.0, diffs: <String, ui.Image>{ 'image1': image1, 'image2': image2, 'image3': image3, } ); expect(image1.debugDisposed, isFalse); expect(image2.debugDisposed, isFalse); expect(image3.debugDisposed, isFalse); result.dispose(); expect(image1.debugDisposed, isTrue); expect(image2.debugDisposed, isTrue); expect(image3.debugDisposed, isTrue); }); }); }); }
flutter/packages/flutter_test/test/goldens_test.dart/0
{ "file_path": "flutter/packages/flutter_test/test/goldens_test.dart", "repo_id": "flutter", "token_count": 6864 }
739
// 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/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'multi_view_testing.dart'; void main() { testWidgets('can find nodes in an view when no view is specified', (WidgetTester tester) async { final List<FlutterView> views = <FlutterView>[ for (int i = 0; i < 3; i++) FakeView(tester.view, viewId: i + 100) ]; await pumpViews(tester: tester, views: views); expect(find.semantics.byLabel('View0Child0'), findsOne); expect(find.semantics.byLabel('View1Child1'), findsOne); expect(find.semantics.byLabel('View2Child2'), findsOne); }); testWidgets('can find nodes only in specified view', (WidgetTester tester) async { final List<FlutterView> views = <FlutterView>[ for (int i = 0; i < 3; i++) FakeView(tester.view, viewId: i + 100) ]; await pumpViews(tester: tester, views: views); expect(find.semantics.byLabel('View0Child0', view: views[0]), findsOne); expect(find.semantics.byLabel('View0Child0', view: views[1]), findsNothing); expect(find.semantics.byLabel('View0Child0', view: views[2]), findsNothing); expect(find.semantics.byLabel('View1Child1', view: views[0]), findsNothing); expect(find.semantics.byLabel('View1Child1', view: views[1]), findsOne); expect(find.semantics.byLabel('View1Child1', view: views[2]), findsNothing); expect(find.semantics.byLabel('View2Child2', view: views[0]), findsNothing); expect(find.semantics.byLabel('View2Child2', view: views[1]), findsNothing); expect(find.semantics.byLabel('View2Child2', view: views[2]), findsOne); }); } Future<void> pumpViews({required WidgetTester tester, required List<FlutterView> views}) { final List<Widget> viewWidgets = <Widget>[ for (int i = 0; i < 3; i++) View( view: views[i], child: Center( child: Column( children: <Widget>[ for (int c = 0; c < 5; c++) Semantics(container: true, child: Text('View${i}Child$c')), ], ), ), ), ]; return tester.pumpWidget( wrapWithView: false, Directionality( textDirection: TextDirection.ltr, child: ViewCollection( views: viewWidgets, ), ), ); }
flutter/packages/flutter_test/test/semantics_finder_test.dart/0
{ "file_path": "flutter/packages/flutter_test/test/semantics_finder_test.dart", "repo_id": "flutter", "token_count": 965 }
740
// 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:collection/collection.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'utils/fake_and_mock_utils.dart'; void main() { group('TestFlutterView', () { FlutterView trueImplicitView() => PlatformDispatcher.instance.implicitView!; FlutterView boundImplicitView() => WidgetsBinding.instance.platformDispatcher.implicitView!; tearDown(() { final TestFlutterView view = (WidgetsBinding.instance as TestWidgetsFlutterBinding).platformDispatcher.views.single; view.reset(); }); testWidgets('can handle new methods without breaking', (WidgetTester tester) async { final dynamic testView = tester.view; // ignore: avoid_dynamic_calls expect(testView.someNewProperty, null); }); testWidgets('can fake devicePixelRatio', (WidgetTester tester) async { verifyPropertyFaked<double>( tester: tester, realValue: trueImplicitView().devicePixelRatio, fakeValue: 2.5, propertyRetriever: () => boundImplicitView().devicePixelRatio, propertyFaker: (_, double fakeValue) { tester.view.devicePixelRatio = fakeValue; }, ); }); testWidgets('can reset devicePixelRatio', (WidgetTester tester) async { verifyPropertyReset<double>( tester: tester, fakeValue: 2.5, propertyRetriever: () => boundImplicitView().devicePixelRatio, propertyResetter: () { tester.view.resetDevicePixelRatio(); }, propertyFaker: (double fakeValue) { tester.view.devicePixelRatio = fakeValue; }, ); }); testWidgets('updating devicePixelRatio also updates display.devicePixelRatio', (WidgetTester tester) async { tester.view.devicePixelRatio = tester.view.devicePixelRatio + 1; expect(tester.view.display.devicePixelRatio, tester.view.devicePixelRatio); }); testWidgets('can fake displayFeatures', (WidgetTester tester) async { verifyPropertyFaked<List<DisplayFeature>>( tester: tester, realValue: trueImplicitView().displayFeatures, fakeValue: <DisplayFeature>[const DisplayFeature(bounds: Rect.fromLTWH(0, 0, 500, 30), type: DisplayFeatureType.unknown, state: DisplayFeatureState.unknown)], propertyRetriever: () => boundImplicitView().displayFeatures, propertyFaker: (_, List<DisplayFeature> fakeValue) { tester.view.displayFeatures = fakeValue; }, ); }); testWidgets('can reset displayFeatures', (WidgetTester tester) async { verifyPropertyReset<List<DisplayFeature>>( tester: tester, fakeValue: <DisplayFeature>[const DisplayFeature(bounds: Rect.fromLTWH(0, 0, 500, 30), type: DisplayFeatureType.unknown, state: DisplayFeatureState.unknown)], propertyRetriever: () => boundImplicitView().displayFeatures, propertyResetter: () { tester.view.resetDisplayFeatures(); }, propertyFaker: (List<DisplayFeature> fakeValue) { tester.view.displayFeatures = fakeValue; }, ); }); testWidgets('can fake padding', (WidgetTester tester) async { verifyPropertyFaked<ViewPadding>( tester: tester, realValue: trueImplicitView().padding, fakeValue: FakeViewPadding.zero, propertyRetriever: () => boundImplicitView().padding, propertyFaker: (_, ViewPadding fakeValue) { tester.view.padding = fakeValue as FakeViewPadding; }, matcher: matchesViewPadding ); }); testWidgets('can reset padding', (WidgetTester tester) async { verifyPropertyReset<ViewPadding>( tester: tester, fakeValue: FakeViewPadding.zero, propertyRetriever: () => boundImplicitView().padding, propertyResetter: () { tester.view.resetPadding(); }, propertyFaker: (ViewPadding fakeValue) { tester.view.padding = fakeValue as FakeViewPadding; }, matcher: matchesViewPadding ); }); testWidgets('can fake physicalSize', (WidgetTester tester) async { verifyPropertyFaked<Size>( tester: tester, realValue: trueImplicitView().physicalSize, fakeValue: const Size(50, 50), propertyRetriever: () => boundImplicitView().physicalSize, propertyFaker: (_, Size fakeValue) { tester.view.physicalSize = fakeValue; }, ); }); testWidgets('faking physicalSize fakes physicalConstraints', (WidgetTester tester) async { const Size fakeSize = Size(50, 50); verifyPropertyFaked<ViewConstraints>( tester: tester, realValue: trueImplicitView().physicalConstraints, fakeValue: ViewConstraints.tight(fakeSize), propertyRetriever: () => boundImplicitView().physicalConstraints, propertyFaker: (_, __) { tester.view.physicalSize = fakeSize; }, ); }); testWidgets('can reset physicalSize', (WidgetTester tester) async { verifyPropertyReset<Size>( tester: tester, fakeValue: const Size(50, 50), propertyRetriever: () => boundImplicitView().physicalSize, propertyResetter: () { tester.view.resetPhysicalSize(); }, propertyFaker: (Size fakeValue) { tester.view.physicalSize = fakeValue; }, ); }); testWidgets('resetting physicalSize resets physicalConstraints', (WidgetTester tester) async { const Size fakeSize = Size(50, 50); verifyPropertyReset<ViewConstraints>( tester: tester, fakeValue: ViewConstraints.tight(fakeSize), propertyRetriever: () => boundImplicitView().physicalConstraints, propertyResetter: () { tester.view.resetPhysicalSize(); }, propertyFaker: (_) { tester.view.physicalSize = fakeSize; }, ); }); testWidgets('can fake physicalConstraints', (WidgetTester tester) async { verifyPropertyFaked<ViewConstraints>( tester: tester, realValue: trueImplicitView().physicalConstraints, fakeValue: const ViewConstraints(minWidth: 1, maxWidth: 2, minHeight: 3, maxHeight: 4), propertyRetriever: () => boundImplicitView().physicalConstraints, propertyFaker: (_, ViewConstraints fakeValue) { tester.view.physicalConstraints = fakeValue; }, ); }); testWidgets('can reset physicalConstraints', (WidgetTester tester) async { verifyPropertyReset<ViewConstraints>( tester: tester, fakeValue: const ViewConstraints(minWidth: 1, maxWidth: 2, minHeight: 3, maxHeight: 4), propertyRetriever: () => boundImplicitView().physicalConstraints, propertyResetter: () { tester.view.resetPhysicalConstraints(); }, propertyFaker: (ViewConstraints fakeValue) { tester.view.physicalConstraints = fakeValue; }, ); }); testWidgets('can fake systemGestureInsets', (WidgetTester tester) async { verifyPropertyFaked<ViewPadding>( tester: tester, realValue: trueImplicitView().systemGestureInsets, fakeValue: FakeViewPadding.zero, propertyRetriever: () => boundImplicitView().systemGestureInsets, propertyFaker: (_, ViewPadding fakeValue) { tester.view.systemGestureInsets = fakeValue as FakeViewPadding; }, matcher: matchesViewPadding ); }); testWidgets('can reset systemGestureInsets', (WidgetTester tester) async { verifyPropertyReset<ViewPadding>( tester: tester, fakeValue: FakeViewPadding.zero, propertyRetriever: () => boundImplicitView().systemGestureInsets, propertyResetter: () { tester.view.resetSystemGestureInsets(); }, propertyFaker: (ViewPadding fakeValue) { tester.view.systemGestureInsets = fakeValue as FakeViewPadding; }, matcher: matchesViewPadding ); }); testWidgets('can fake viewInsets', (WidgetTester tester) async { verifyPropertyFaked<ViewPadding>( tester: tester, realValue: trueImplicitView().viewInsets, fakeValue: FakeViewPadding.zero, propertyRetriever: () => boundImplicitView().viewInsets, propertyFaker: (_, ViewPadding fakeValue) { tester.view.viewInsets = fakeValue as FakeViewPadding; }, matcher: matchesViewPadding ); }); testWidgets('can reset viewInsets', (WidgetTester tester) async { verifyPropertyReset<ViewPadding>( tester: tester, fakeValue: FakeViewPadding.zero, propertyRetriever: () => boundImplicitView().viewInsets, propertyResetter: () { tester.view.resetViewInsets(); }, propertyFaker: (ViewPadding fakeValue) { tester.view.viewInsets = fakeValue as FakeViewPadding; }, matcher: matchesViewPadding ); }); testWidgets('can fake viewPadding', (WidgetTester tester) async { verifyPropertyFaked<ViewPadding>( tester: tester, realValue: trueImplicitView().viewPadding, fakeValue: FakeViewPadding.zero, propertyRetriever: () => boundImplicitView().viewPadding, propertyFaker: (_, ViewPadding fakeValue) { tester.view.viewPadding = fakeValue as FakeViewPadding; }, matcher: matchesViewPadding ); }); testWidgets('can reset viewPadding', (WidgetTester tester) async { verifyPropertyReset<ViewPadding>( tester: tester, fakeValue: FakeViewPadding.zero, propertyRetriever: () => boundImplicitView().viewPadding, propertyResetter: () { tester.view.resetViewPadding(); }, propertyFaker: (ViewPadding fakeValue) { tester.view.viewPadding = fakeValue as FakeViewPadding; }, matcher: matchesViewPadding ); }); testWidgets('can clear out fake properties all at once', (WidgetTester tester) async { final FlutterViewSnapshot initial = FlutterViewSnapshot(tester.view); tester.view.devicePixelRatio = 7; tester.view.displayFeatures = <DisplayFeature>[const DisplayFeature(bounds: Rect.fromLTWH(0, 0, 20, 300), type: DisplayFeatureType.unknown, state: DisplayFeatureState.unknown)]; tester.view.padding = FakeViewPadding.zero; tester.view.systemGestureInsets = FakeViewPadding.zero; tester.view.viewInsets = FakeViewPadding.zero; tester.view.viewPadding = FakeViewPadding.zero; tester.view.gestureSettings = const GestureSettings(physicalTouchSlop: 4, physicalDoubleTapSlop: 5); final FlutterViewSnapshot faked = FlutterViewSnapshot(tester.view); tester.view.reset(); final FlutterViewSnapshot reset = FlutterViewSnapshot(tester.view); expect(initial, isNot(matchesSnapshot(faked))); expect(initial, matchesSnapshot(reset)); }); testWidgets('render is passed through to backing FlutterView', (WidgetTester tester) async { final Scene expectedScene = SceneBuilder().build(); final _FakeFlutterView backingView = _FakeFlutterView(); final TestFlutterView view = TestFlutterView( view: backingView, platformDispatcher: tester.binding.platformDispatcher, display: _FakeDisplay(), ); view.render(expectedScene); expect(backingView.lastRenderedScene, isNotNull); expect(backingView.lastRenderedScene, expectedScene); }); testWidgets('updateSemantics is passed through to backing FlutterView', (WidgetTester tester) async { final SemanticsUpdate expectedUpdate = SemanticsUpdateBuilder().build(); final _FakeFlutterView backingView = _FakeFlutterView(); final TestFlutterView view = TestFlutterView( view: backingView, platformDispatcher: tester.binding.platformDispatcher, display: _FakeDisplay(), ); view.updateSemantics(expectedUpdate); expect(backingView.lastSemanticsUpdate, isNotNull); expect(backingView.lastSemanticsUpdate, expectedUpdate); }); }); } Matcher matchesSnapshot(FlutterViewSnapshot expected) => _FlutterViewSnapshotMatcher(expected); class _FlutterViewSnapshotMatcher extends Matcher { _FlutterViewSnapshotMatcher(this.expected); final FlutterViewSnapshot expected; @override Description describe(Description description) { description.add('snapshot of a FlutterView matches'); return description; } @override Description describeMismatch(dynamic item, Description mismatchDescription, Map<dynamic, dynamic> matchState, bool verbose) { assert(item is FlutterViewSnapshot, 'Can only match against snapshots of FlutterView.'); final FlutterViewSnapshot actual = item as FlutterViewSnapshot; if (actual.devicePixelRatio != expected.devicePixelRatio) { mismatchDescription.add('actual.devicePixelRatio (${actual.devicePixelRatio}) did not match expected.devicePixelRatio (${expected.devicePixelRatio})'); } if (!actual.displayFeatures.equals(expected.displayFeatures)) { mismatchDescription.add('actual.displayFeatures did not match expected.devicePixelRatio'); mismatchDescription.addAll('Actual: [', ',', ']', actual.displayFeatures); mismatchDescription.addAll('Expected: [', ',', ']', expected.displayFeatures); } if (actual.gestureSettings != expected.gestureSettings) { mismatchDescription.add('actual.gestureSettings (${actual.gestureSettings}) did not match expected.gestureSettings (${expected.gestureSettings})'); } final Matcher paddingMatcher = matchesViewPadding(expected.padding); if (!paddingMatcher.matches(actual.padding, matchState)) { mismatchDescription.add('actual.padding (${actual.padding}) did not match expected.padding (${expected.padding})'); paddingMatcher.describeMismatch(actual.padding, mismatchDescription, matchState, verbose); } if (actual.physicalSize != expected.physicalSize) { mismatchDescription.add('actual.physicalSize (${actual.physicalSize}) did not match expected.physicalSize (${expected.physicalSize})'); } final Matcher systemGestureInsetsMatcher = matchesViewPadding(expected.systemGestureInsets); if (!systemGestureInsetsMatcher.matches(actual.systemGestureInsets, matchState)) { mismatchDescription.add('actual.systemGestureInsets (${actual.systemGestureInsets}) did not match expected.systemGestureInsets (${expected.systemGestureInsets})'); systemGestureInsetsMatcher.describeMismatch(actual.systemGestureInsets, mismatchDescription, matchState, verbose); } if (actual.viewId != expected.viewId) { mismatchDescription.add('actual.viewId (${actual.viewId}) did not match expected.viewId (${expected.viewId})'); } final Matcher viewInsetsMatcher = matchesViewPadding(expected.viewInsets); if (!viewInsetsMatcher.matches(actual.viewInsets, matchState)) { mismatchDescription.add('actual.viewInsets (${actual.viewInsets}) did not match expected.viewInsets (${expected.viewInsets})'); viewInsetsMatcher.describeMismatch(actual.viewInsets, mismatchDescription, matchState, verbose); } final Matcher viewPaddingMatcher = matchesViewPadding(expected.viewPadding); if (!viewPaddingMatcher.matches(actual.viewPadding, matchState)) { mismatchDescription.add('actual.viewPadding (${actual.viewPadding}) did not match expected.devicePixelRatio (${expected.viewPadding})'); viewPaddingMatcher.describeMismatch(actual.viewPadding, mismatchDescription, matchState, verbose); } return mismatchDescription; } @override bool matches(dynamic item, Map<dynamic, dynamic> matchState) { assert(item is FlutterViewSnapshot, 'Can only match against snapshots of FlutterView.'); final FlutterViewSnapshot actual = item as FlutterViewSnapshot; return actual.devicePixelRatio == expected.devicePixelRatio && actual.displayFeatures.equals(expected.displayFeatures) && actual.gestureSettings == expected.gestureSettings && matchesViewPadding(expected.padding).matches(actual.padding, matchState) && actual.physicalSize == expected.physicalSize && matchesViewPadding(expected.systemGestureInsets).matches(actual.padding, matchState) && actual.viewId == expected.viewId && matchesViewPadding(expected.viewInsets).matches(actual.viewInsets, matchState) && matchesViewPadding(expected.viewPadding).matches(actual.viewPadding, matchState); } } class FlutterViewSnapshot { FlutterViewSnapshot(FlutterView view) : devicePixelRatio = view.devicePixelRatio, displayFeatures = <DisplayFeature>[...view.displayFeatures], gestureSettings = view.gestureSettings, padding = view.padding, physicalSize = view.physicalSize, systemGestureInsets = view.systemGestureInsets, viewId = view.viewId, viewInsets = view.viewInsets, viewPadding = view.viewPadding; final double devicePixelRatio; final List<DisplayFeature> displayFeatures; final GestureSettings gestureSettings; final ViewPadding padding; final Size physicalSize; final ViewPadding systemGestureInsets; final Object viewId; final ViewPadding viewInsets; final ViewPadding viewPadding; } class _FakeFlutterView extends Fake implements FlutterView { SemanticsUpdate? lastSemanticsUpdate; Scene? lastRenderedScene; @override void updateSemantics(SemanticsUpdate update) { lastSemanticsUpdate = update; } @override void render(Scene scene, {Size? size}) { lastRenderedScene = scene; } } class _FakeDisplay extends Fake implements TestDisplay { }
flutter/packages/flutter_test/test/view_test.dart/0
{ "file_path": "flutter/packages/flutter_test/test/view_test.dart", "repo_id": "flutter", "token_count": 6638 }
741
// 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. /** * @fileoverview OSA Script to interact with Xcode. Functionality includes * checking if a given project is open in Xcode, starting a debug session for * a given project, and stopping a debug session for a given project. */ 'use strict'; /** * OSA Script `run` handler that is called when the script is run. When ran * with `osascript`, arguments are passed from the command line to the direct * parameter of the `run` handler as a list of strings. * * @param {?Array<string>=} args_array * @returns {!RunJsonResponse} The validated command. */ function run(args_array = []) { let args; try { args = new CommandArguments(args_array); } catch (e) { return new RunJsonResponse(false, `Failed to parse arguments: ${e}`).stringify(); } const xcodeResult = getXcode(args); if (xcodeResult.error != null) { return new RunJsonResponse(false, xcodeResult.error).stringify(); } const xcode = xcodeResult.result; if (args.command === 'check-workspace-opened') { const result = getWorkspaceDocument(xcode, args); return new RunJsonResponse(result.error == null, result.error).stringify(); } else if (args.command === 'debug') { const result = debugApp(xcode, args); return new RunJsonResponse(result.error == null, result.error, result.result).stringify(); } else if (args.command === 'stop') { const result = stopApp(xcode, args); return new RunJsonResponse(result.error == null, result.error).stringify(); } else { return new RunJsonResponse(false, 'Unknown command').stringify(); } } /** * Parsed and validated arguments passed from the command line. */ class CommandArguments { /** * * @param {!Array<string>} args List of arguments passed from the command line. */ constructor(args) { this.command = this.validatedCommand(args[0]); const parsedArguments = this.parseArguments(args); this.xcodePath = this.validatedStringArgument('--xcode-path', parsedArguments['--xcode-path']); this.projectPath = this.validatedStringArgument('--project-path', parsedArguments['--project-path']); this.projectName = this.validatedStringArgument('--project-name', parsedArguments['--project-name']); this.expectedConfigurationBuildDir = this.validatedStringArgument( '--expected-configuration-build-dir', parsedArguments['--expected-configuration-build-dir'], ); this.workspacePath = this.validatedStringArgument('--workspace-path', parsedArguments['--workspace-path']); this.targetDestinationId = this.validatedStringArgument('--device-id', parsedArguments['--device-id']); this.targetSchemeName = this.validatedStringArgument('--scheme', parsedArguments['--scheme']); this.skipBuilding = this.validatedBoolArgument('--skip-building', parsedArguments['--skip-building']); this.launchArguments = this.validatedJsonArgument('--launch-args', parsedArguments['--launch-args']); this.closeWindowOnStop = this.validatedBoolArgument('--close-window', parsedArguments['--close-window']); this.promptToSaveBeforeClose = this.validatedBoolArgument('--prompt-to-save', parsedArguments['--prompt-to-save']); this.verbose = this.validatedBoolArgument('--verbose', parsedArguments['--verbose']); if (this.verbose === true) { console.log(JSON.stringify(this)); } } /** * Validates the command is available. * * @param {?string} command * @returns {!string} The validated command. * @throws Will throw an error if command is not recognized. */ validatedCommand(command) { const allowedCommands = ['check-workspace-opened', 'debug', 'stop']; if (allowedCommands.includes(command) === false) { throw `Unrecognized Command: ${command}`; } return command; } /** * Returns map of commands to map of allowed arguments. For each command, if * an argument flag is a key, than that flag is allowed for that command. If * the value for the key is true, then it is required for the command. * * @returns {!string} Map of commands to allowed and optionally required * arguments. */ argumentSettings() { return { 'check-workspace-opened': { '--xcode-path': true, '--project-path': true, '--workspace-path': true, '--verbose': false, }, 'debug': { '--xcode-path': true, '--project-path': true, '--workspace-path': true, '--project-name': true, '--expected-configuration-build-dir': false, '--device-id': true, '--scheme': true, '--skip-building': true, '--launch-args': true, '--verbose': false, }, 'stop': { '--xcode-path': true, '--project-path': true, '--workspace-path': true, '--close-window': true, '--prompt-to-save': true, '--verbose': false, }, }; } /** * Validates the flag is allowed for the current command. * * @param {!string} flag * @param {?string} value * @returns {!bool} * @throws Will throw an error if the flag is not allowed for the current * command and the value is not null, undefined, or empty. */ isArgumentAllowed(flag, value) { const isAllowed = this.argumentSettings()[this.command].hasOwnProperty(flag); if (isAllowed === false && (value != null && value !== '')) { throw `The flag ${flag} is not allowed for the command ${this.command}.`; } return isAllowed; } /** * Validates required flag has a value. * * @param {!string} flag * @param {?string} value * @throws Will throw an error if the flag is required for the current * command and the value is not null, undefined, or empty. */ validateRequiredArgument(flag, value) { const isRequired = this.argumentSettings()[this.command][flag] === true; if (isRequired === true && (value == null || value === '')) { throw `Missing value for ${flag}`; } } /** * Parses the command line arguments into an object. * * @param {!Array<string>} args List of arguments passed from the command line. * @returns {!Object.<string, string>} Object mapping flag to value. * @throws Will throw an error if flag does not begin with '--'. */ parseArguments(args) { const valuesPerFlag = {}; for (let index = 1; index < args.length; index++) { const entry = args[index]; let flag; let value; const splitIndex = entry.indexOf('='); if (splitIndex === -1) { flag = entry; value = args[index + 1]; // If the flag is allowed for the command, and the next value in the // array is null/undefined or also a flag, treat the flag like a boolean // flag and set the value to 'true'. if (this.isArgumentAllowed(flag) && (value == null || value.startsWith('--'))) { value = 'true'; } else { index++; } } else { flag = entry.substring(0, splitIndex); value = entry.substring(splitIndex + 1, entry.length + 1); } if (flag.startsWith('--') === false) { throw `Unrecognized Flag: ${flag}`; } valuesPerFlag[flag] = value; } return valuesPerFlag; } /** * Validates the flag is allowed and `value` is valid. If the flag is not * allowed for the current command, return `null`. * * @param {!string} flag * @param {?string} value * @returns {!string} * @throws Will throw an error if the flag is allowed and `value` is null, * undefined, or empty. */ validatedStringArgument(flag, value) { if (this.isArgumentAllowed(flag, value) === false) { return null; } this.validateRequiredArgument(flag, value); return value; } /** * Validates the flag is allowed, validates `value` is valid, and converts * `value` to a boolean. A `value` of null, undefined, or empty, it will * return true. If the flag is not allowed for the current command, will * return `null`. * * @param {!string} flag * @param {?string} value * @returns {?boolean} * @throws Will throw an error if the flag is allowed and `value` is not * null, undefined, empty, 'true', or 'false'. */ validatedBoolArgument(flag, value) { if (this.isArgumentAllowed(flag, value) === false) { return null; } if (value == null || value === '') { return false; } if (value !== 'true' && value !== 'false') { throw `Invalid value for ${flag}`; } return value === 'true'; } /** * Validates the flag is allowed, `value` is valid, and parses `value` as JSON. * If the flag is not allowed for the current command, will return `null`. * * @param {!string} flag * @param {?string} value * @returns {!Object} * @throws Will throw an error if the flag is allowed and the value is * null, undefined, or empty. Will also throw an error if parsing fails. */ validatedJsonArgument(flag, value) { if (this.isArgumentAllowed(flag, value) === false) { return null; } this.validateRequiredArgument(flag, value); try { return JSON.parse(value); } catch (e) { throw `Error parsing ${flag}: ${e}`; } } } /** * Response to return in `run` function. */ class RunJsonResponse { /** * * @param {!bool} success Whether the command was successful. * @param {?string=} errorMessage Defaults to null. * @param {?DebugResult=} debugResult Curated results from Xcode's debug * function. Defaults to null. */ constructor(success, errorMessage = null, debugResult = null) { this.status = success; this.errorMessage = errorMessage; this.debugResult = debugResult; } /** * Converts this object to a JSON string. * * @returns {!string} * @throws Throws an error if conversion fails. */ stringify() { return JSON.stringify(this); } } /** * Utility class to return a result along with a potential error. */ class FunctionResult { /** * * @param {?Object} result * @param {?string=} error Defaults to null. */ constructor(result, error = null) { this.result = result; this.error = error; } } /** * Curated results from Xcode's debug function. Mirrors parts of * `scheme action result` from Xcode's Script Editor dictionary. */ class DebugResult { /** * * @param {!Object} result */ constructor(result) { this.completed = result.completed(); this.status = result.status(); this.errorMessage = result.errorMessage(); } } /** * Get the Xcode application from the given path. Since macs can have multiple * Xcode version, we use the path to target the specific Xcode application. * If the Xcode app is not running, return null with an error. * * @param {!CommandArguments} args * @returns {!FunctionResult} Return either an `Application` (Mac Scripting class) * or null as the `result`. */ function getXcode(args) { try { const xcode = Application(args.xcodePath); const isXcodeRunning = xcode.running(); if (isXcodeRunning === false) { return new FunctionResult(null, 'Xcode is not running'); } return new FunctionResult(xcode); } catch (e) { return new FunctionResult(null, `Failed to get Xcode application: ${e}`); } } /** * After setting the active run destination to the targeted device, uses Xcode * debug function from Mac Scripting for Xcode to install the app on the device * and start a debugging session using the 'run' or 'run without building' scheme * action (depending on `args.skipBuilding`). Waits for the debugging session * to start running. * * @param {!Application} xcode An `Application` (Mac Scripting class) for Xcode. * @param {!CommandArguments} args * @returns {!FunctionResult} Return either a `DebugResult` or null as the `result`. */ function debugApp(xcode, args) { const workspaceResult = waitForWorkspaceToLoad(xcode, args); if (workspaceResult.error != null) { return new FunctionResult(null, workspaceResult.error); } const targetWorkspace = workspaceResult.result; const destinationResult = getTargetDestination( targetWorkspace, args.targetDestinationId, args.verbose, ); if (destinationResult.error != null) { return new FunctionResult(null, destinationResult.error) } // If expectedConfigurationBuildDir is available, ensure that it matches the // build settings. if (args.expectedConfigurationBuildDir != null && args.expectedConfigurationBuildDir !== '') { const updateResult = waitForConfigurationBuildDirToUpdate(targetWorkspace, args); if (updateResult.error != null) { return new FunctionResult(null, updateResult.error); } } try { // Documentation from the Xcode Script Editor dictionary indicates that the // `debug` function has a parameter called `runDestinationSpecifier` which // is used to specify which device to debug the app on. It also states that // it should be the same as the xcodebuild -destination specifier. It also // states that if not specified, the `activeRunDestination` is used instead. // // Experimentation has shown that the `runDestinationSpecifier` does not work. // It will always use the `activeRunDestination`. To mitigate this, we set // the `activeRunDestination` to the targeted device prior to starting the debug. targetWorkspace.activeRunDestination = destinationResult.result; const actionResult = targetWorkspace.debug({ scheme: args.targetSchemeName, skipBuilding: args.skipBuilding, commandLineArguments: args.launchArguments, }); // Wait until scheme action has started up to a max of 10 minutes. // This does not wait for app to install, launch, or start debug session. // Potential statuses include: not yet started/‌running/‌cancelled/‌failed/‌error occurred/‌succeeded. const checkFrequencyInSeconds = 0.5; const maxWaitInSeconds = 10 * 60; // 10 minutes const iterations = maxWaitInSeconds * (1 / checkFrequencyInSeconds); const verboseLogInterval = 10 * (1 / checkFrequencyInSeconds); for (let i = 0; i < iterations; i++) { if (actionResult.status() !== 'not yet started') { break; } if (args.verbose === true && i % verboseLogInterval === 0) { console.log(`Action result status: ${actionResult.status()}`); } delay(checkFrequencyInSeconds); } return new FunctionResult(new DebugResult(actionResult)); } catch (e) { return new FunctionResult(null, `Failed to start debugging session: ${e}`); } } /** * Iterates through available run destinations looking for one with a matching * `deviceId`. If device is not found, return null with an error. * * @param {!WorkspaceDocument} targetWorkspace A `WorkspaceDocument` (Xcode Mac * Scripting class). * @param {!string} deviceId * @param {?bool=} verbose Defaults to false. * @returns {!FunctionResult} Return either a `RunDestination` (Xcode Mac * Scripting class) or null as the `result`. */ function getTargetDestination(targetWorkspace, deviceId, verbose = false) { try { for (let destination of targetWorkspace.runDestinations()) { const device = destination.device(); if (verbose === true && device != null) { console.log(`Device: ${device.name()} (${device.deviceIdentifier()})`); } if (device != null && device.deviceIdentifier() === deviceId) { return new FunctionResult(destination); } } return new FunctionResult( null, 'Unable to find target device. Ensure that the device is paired, ' + 'unlocked, connected, and has an iOS version at least as high as the ' + 'Minimum Deployment.', ); } catch (e) { return new FunctionResult(null, `Failed to get target destination: ${e}`); } } /** * Waits for the workspace to load. If the workspace is not loaded or in the * process of opening, it will wait up to 10 minutes. * * @param {!Application} xcode An `Application` (Mac Scripting class) for Xcode. * @param {!CommandArguments} args * @returns {!FunctionResult} Return either a `WorkspaceDocument` (Xcode Mac * Scripting class) or null as the `result`. */ function waitForWorkspaceToLoad(xcode, args) { try { const checkFrequencyInSeconds = 0.5; const maxWaitInSeconds = 10 * 60; // 10 minutes const verboseLogInterval = 10 * (1 / checkFrequencyInSeconds); const iterations = maxWaitInSeconds * (1 / checkFrequencyInSeconds); for (let i = 0; i < iterations; i++) { // Every 10 seconds, print the list of workspaces if verbose const verbose = args.verbose && i % verboseLogInterval === 0; const workspaceResult = getWorkspaceDocument(xcode, args, verbose); if (workspaceResult.error == null) { const document = workspaceResult.result; if (document.loaded() === true) { return new FunctionResult(document, null); } } else if (verbose === true) { console.log(workspaceResult.error); } delay(checkFrequencyInSeconds); } return new FunctionResult(null, 'Timed out waiting for workspace to load'); } catch (e) { return new FunctionResult(null, `Failed to wait for workspace to load: ${e}`); } } /** * Gets workspace opened in Xcode matching the projectPath or workspacePath * from the command line arguments. If workspace is not found, return null with * an error. * * @param {!Application} xcode An `Application` (Mac Scripting class) for Xcode. * @param {!CommandArguments} args * @param {?bool=} verbose Defaults to false. * @returns {!FunctionResult} Return either a `WorkspaceDocument` (Xcode Mac * Scripting class) or null as the `result`. */ function getWorkspaceDocument(xcode, args, verbose = false) { const privatePrefix = '/private'; try { const documents = xcode.workspaceDocuments(); for (let document of documents) { const filePath = document.file().toString(); if (verbose === true) { console.log(`Workspace: ${filePath}`); } if (filePath === args.projectPath || filePath === args.workspacePath) { return new FunctionResult(document); } // Sometimes when the project is in a temporary directory, it'll be // prefixed with `/private` but the args will not. Remove the // prefix before matching. if (filePath.startsWith(privatePrefix) === true) { const filePathWithoutPrefix = filePath.slice(privatePrefix.length); if (filePathWithoutPrefix === args.projectPath || filePathWithoutPrefix === args.workspacePath) { return new FunctionResult(document); } } } } catch (e) { return new FunctionResult(null, `Failed to get workspace: ${e}`); } return new FunctionResult(null, `Failed to get workspace.`); } /** * Stops all debug sessions in the target workspace. * * @param {!Application} xcode An `Application` (Mac Scripting class) for Xcode. * @param {!CommandArguments} args * @returns {!FunctionResult} Always returns null as the `result`. */ function stopApp(xcode, args) { const workspaceResult = getWorkspaceDocument(xcode, args); if (workspaceResult.error != null) { return new FunctionResult(null, workspaceResult.error); } const targetDocument = workspaceResult.result; try { targetDocument.stop(); if (args.closeWindowOnStop === true) { // Wait a couple seconds before closing Xcode, otherwise it'll prompt the // user to stop the app. delay(2); targetDocument.close({ saving: args.promptToSaveBeforeClose === true ? 'ask' : 'no', }); } } catch (e) { return new FunctionResult(null, `Failed to stop app: ${e}`); } return new FunctionResult(null, null); } /** * Gets resolved build setting for CONFIGURATION_BUILD_DIR and waits until its * value matches the `--expected-configuration-build-dir` argument. Waits up to * 2 minutes. * * @param {!WorkspaceDocument} targetWorkspace A `WorkspaceDocument` (Xcode Mac * Scripting class). * @param {!CommandArguments} args * @returns {!FunctionResult} Always returns null as the `result`. */ function waitForConfigurationBuildDirToUpdate(targetWorkspace, args) { // Get the project let project; try { project = targetWorkspace.projects().find(x => x.name() == args.projectName); } catch (e) { return new FunctionResult(null, `Failed to find project ${args.projectName}: ${e}`); } if (project == null) { return new FunctionResult(null, `Failed to find project ${args.projectName}.`); } // Get the target let target; try { // The target is probably named the same as the project, but if not, just use the first. const targets = project.targets(); target = targets.find(x => x.name() == args.projectName); if (target == null && targets.length > 0) { target = targets[0]; if (args.verbose) { console.log(`Failed to find target named ${args.projectName}, picking first target: ${target.name()}.`); } } } catch (e) { return new FunctionResult(null, `Failed to find target: ${e}`); } if (target == null) { return new FunctionResult(null, `Failed to find target.`); } try { // Use the first build configuration (Debug). Any should do since they all // include Generated.xcconfig. const buildConfig = target.buildConfigurations()[0]; const buildSettings = buildConfig.resolvedBuildSettings().reverse(); // CONFIGURATION_BUILD_DIR is often at (reverse) index 225 for Xcode // projects, so check there first. If it's not there, search the build // settings (which can be a little slow). const defaultIndex = 225; let configurationBuildDirSettings; if (buildSettings[defaultIndex] != null && buildSettings[defaultIndex].name() === 'CONFIGURATION_BUILD_DIR') { configurationBuildDirSettings = buildSettings[defaultIndex]; } else { configurationBuildDirSettings = buildSettings.find(x => x.name() === 'CONFIGURATION_BUILD_DIR'); } if (configurationBuildDirSettings == null) { // This should not happen, even if it's not set by Flutter, there should // always be a resolved build setting for CONFIGURATION_BUILD_DIR. return new FunctionResult(null, `Unable to find CONFIGURATION_BUILD_DIR.`); } // Wait up to 2 minutes for the CONFIGURATION_BUILD_DIR to update to the // expected value. const checkFrequencyInSeconds = 0.5; const maxWaitInSeconds = 2 * 60; // 2 minutes const verboseLogInterval = 10 * (1 / checkFrequencyInSeconds); const iterations = maxWaitInSeconds * (1 / checkFrequencyInSeconds); for (let i = 0; i < iterations; i++) { const verbose = args.verbose && i % verboseLogInterval === 0; const configurationBuildDir = configurationBuildDirSettings.value(); if (configurationBuildDir === args.expectedConfigurationBuildDir) { console.log(`CONFIGURATION_BUILD_DIR: ${configurationBuildDir}`); return new FunctionResult(null, null); } if (verbose) { console.log(`Current CONFIGURATION_BUILD_DIR: ${configurationBuildDir} while expecting ${args.expectedConfigurationBuildDir}`); } delay(checkFrequencyInSeconds); } return new FunctionResult(null, 'Timed out waiting for CONFIGURATION_BUILD_DIR to update.'); } catch (e) { return new FunctionResult(null, `Failed to get CONFIGURATION_BUILD_DIR: ${e}`); } }
flutter/packages/flutter_tools/bin/xcode_debug.js/0
{ "file_path": "flutter/packages/flutter_tools/bin/xcode_debug.js", "repo_id": "flutter", "token_count": 8065 }
742
import org.gradle.api.Plugin import org.gradle.api.initialization.Settings import java.nio.file.Paths apply plugin: FlutterAppPluginLoaderPlugin class FlutterAppPluginLoaderPlugin implements Plugin<Settings> { @Override void apply(Settings settings) { def flutterProjectRoot = settings.settingsDir.parentFile if(!settings.ext.hasProperty('flutterSdkPath')) { def properties = new Properties() def localPropertiesFile = new File(settings.rootProject.projectDir, "local.properties") localPropertiesFile.withInputStream { properties.load(it) } settings.ext.flutterSdkPath = properties.getProperty("flutter.sdk") assert settings.ext.flutterSdkPath != null, "flutter.sdk not set in local.properties" } // Load shared gradle functions settings.apply from: Paths.get(settings.ext.flutterSdkPath, "packages", "flutter_tools", "gradle", "src", "main", "groovy", "native_plugin_loader.groovy") List<Map<String, Object>> nativePlugins = settings.ext.nativePluginLoader.getPlugins(flutterProjectRoot) nativePlugins.each { androidPlugin -> def pluginDirectory = new File(androidPlugin.path as String, 'android') assert pluginDirectory.exists() settings.include(":${androidPlugin.name}") settings.project(":${androidPlugin.name}").projectDir = pluginDirectory } } }
flutter/packages/flutter_tools/gradle/src/main/groovy/app_plugin_loader.groovy/0
{ "file_path": "flutter/packages/flutter_tools/gradle/src/main/groovy/app_plugin_loader.groovy", "repo_id": "flutter", "token_count": 540 }
743
<component name="ProjectRunConfigurationManager"> <configuration default="false" name="flutter_tools" type="DartCommandLineRunConfigurationType" factoryName="Dart Command Line Application"> <option name="filePath" value="$PROJECT_DIR$/packages/flutter_tools/bin/flutter_tools.dart" /> <method /> </configuration> </component>
flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/flutter_tools.xml.copy.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/flutter_tools.xml.copy.tmpl", "repo_id": "flutter", "token_count": 99 }
744
<component name="ProjectRunConfigurationManager"> <configuration default="false" name="manual_tests - focus" type="FlutterRunConfigurationType" factoryName="Flutter" singleton="false"> <option name="filePath" value="$PROJECT_DIR$/dev/manual_tests/lib/focus.dart" /> <method v="2" /> </configuration> </component>
flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/manual_tests___focus.xml.copy.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/manual_tests___focus.xml.copy.tmpl", "repo_id": "flutter", "token_count": 103 }
745
// 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/file_system.dart'; import '../base/io.dart'; import '../base/process.dart'; import '../base/utils.dart'; import '../base/version.dart'; import '../convert.dart'; import '../globals.dart' as globals; import '../ios/plist_parser.dart'; import 'android_studio_validator.dart'; // Android Studio layout: // Linux/Windows: // $HOME/.AndroidStudioX.Y/system/.home // $HOME/.cache/Google/AndroidStudioX.Y/.home // macOS: // /Applications/Android Studio.app/Contents/ // $HOME/Applications/Android Studio.app/Contents/ // Match Android Studio >= 4.1 base folder (AndroidStudio*.*) // and < 4.1 (.AndroidStudio*.*) final RegExp _dotHomeStudioVersionMatcher = RegExp(r'^\.?(AndroidStudio[^\d]*)([\d.]+)'); class AndroidStudio { /// A [version] value of null represents an unknown version. AndroidStudio( this.directory, { this.version, this.configuredPath, this.studioAppName = 'AndroidStudio', this.presetPluginsPath, }) { _initAndValidate(); } static AndroidStudio? fromMacOSBundle( String bundlePath, { String? configuredPath, }) { final String studioPath = globals.fs.path.join(bundlePath, 'Contents'); final String plistFile = globals.fs.path.join(studioPath, 'Info.plist'); final Map<String, dynamic> plistValues = globals.plistParser.parseFile(plistFile); // If we've found a JetBrainsToolbox wrapper, ignore it. if (plistValues.containsKey('JetBrainsToolboxApp')) { return null; } final String? versionString = plistValues[PlistParser.kCFBundleShortVersionStringKey] as String?; Version? version; if (versionString != null) { version = Version.parse(versionString); } String? pathsSelectorValue; final Map<String, dynamic>? jvmOptions = castStringKeyedMap(plistValues['JVMOptions']); if (jvmOptions != null) { final Map<String, dynamic>? jvmProperties = castStringKeyedMap(jvmOptions['Properties']); if (jvmProperties != null) { pathsSelectorValue = jvmProperties['idea.paths.selector'] as String; } } final int? major = version?.major; final int? minor = version?.minor; String? presetPluginsPath; final String? homeDirPath = globals.fsUtils.homeDirPath; if (homeDirPath != null && pathsSelectorValue != null) { if (major != null && major >= 4 && minor != null && minor >= 1) { presetPluginsPath = globals.fs.path.join( homeDirPath, 'Library', 'Application Support', 'Google', pathsSelectorValue, ); } else { presetPluginsPath = globals.fs.path.join( homeDirPath, 'Library', 'Application Support', pathsSelectorValue, ); } } return AndroidStudio( studioPath, version: version, presetPluginsPath: presetPluginsPath, configuredPath: configuredPath, ); } static AndroidStudio? fromHomeDot(Directory homeDotDir) { final Match? versionMatch = _dotHomeStudioVersionMatcher.firstMatch(homeDotDir.basename); if (versionMatch?.groupCount != 2) { return null; } final Version? version = Version.parse(versionMatch![2]); final String? studioAppName = versionMatch[1]; if (studioAppName == null || version == null) { return null; } final int major = version.major; final int minor = version.minor; // The install path is written in a .home text file, // it location is in <base dir>/.home for Android Studio >= 4.1 // and <base dir>/system/.home for Android Studio < 4.1 String dotHomeFilePath; if (major >= 4 && minor >= 1) { dotHomeFilePath = globals.fs.path.join(homeDotDir.path, '.home'); } else { dotHomeFilePath = globals.fs.path.join(homeDotDir.path, 'system', '.home'); } String? installPath; try { installPath = globals.fs.file(dotHomeFilePath).readAsStringSync(); } on Exception { // ignored, installPath will be null, which is handled below } if (installPath != null && globals.fs.isDirectorySync(installPath)) { return AndroidStudio( installPath, version: version, studioAppName: studioAppName, ); } return null; } final String directory; final String studioAppName; /// The version of Android Studio. /// /// A null value represents an unknown version. final Version? version; final String? configuredPath; final String? presetPluginsPath; String? _javaPath; bool _isValid = false; final List<String> _validationMessages = <String>[]; /// The path of the JDK bundled with Android Studio. /// /// This will be null if the bundled JDK could not be found or run. /// /// If you looking to invoke the java binary or add it to the system /// environment variables, consider using the [Java] class instead. String? get javaPath => _javaPath; bool get isValid => _isValid; String? get pluginsPath { if (presetPluginsPath != null) { return presetPluginsPath!; } // TODO(andrewkolos): This is a bug. We shouldn't treat an unknown // version as equivalent to 0.0. // See https://github.com/flutter/flutter/issues/121468. final int major = version?.major ?? 0; final int minor = version?.minor ?? 0; final String? homeDirPath = globals.fsUtils.homeDirPath; if (homeDirPath == null) { return null; } if (globals.platform.isMacOS) { /// plugin path of Android Studio has been changed after version 4.1. if (major >= 4 && minor >= 1) { return globals.fs.path.join( homeDirPath, 'Library', 'Application Support', 'Google', 'AndroidStudio$major.$minor', ); } else { return globals.fs.path.join( homeDirPath, 'Library', 'Application Support', 'AndroidStudio$major.$minor', ); } } else { // JetBrains Toolbox write plugins here final String toolboxPluginsPath = '$directory.plugins'; if (globals.fs.directory(toolboxPluginsPath).existsSync()) { return toolboxPluginsPath; } if (major >= 4 && minor >= 1 && globals.platform.isLinux) { return globals.fs.path.join( homeDirPath, '.local', 'share', 'Google', '$studioAppName$major.$minor', ); } return globals.fs.path.join( homeDirPath, '.$studioAppName$major.$minor', 'config', 'plugins', ); } } List<String> get validationMessages => _validationMessages; /// Locates the newest, valid version of Android Studio. /// /// In the case that `--android-studio-dir` is configured, the version of /// Android Studio found at that location is always returned, even if it is /// invalid. static AndroidStudio? latestValid() { final Directory? configuredStudioDir = _configuredDir(); // Find all available Studio installations. final List<AndroidStudio> studios = allInstalled(); if (studios.isEmpty) { return null; } final AndroidStudio? manuallyConfigured = studios .where((AndroidStudio studio) => studio.configuredPath != null && configuredStudioDir != null && _pathsAreEqual(studio.configuredPath!, configuredStudioDir.path)) .firstOrNull; if (manuallyConfigured != null) { return manuallyConfigured; } AndroidStudio? newest; for (final AndroidStudio studio in studios.where((AndroidStudio s) => s.isValid)) { if (newest == null) { newest = studio; continue; } // We prefer installs with known versions. if (studio.version != null && newest.version == null) { newest = studio; } else if (studio.version != null && newest.version != null && studio.version! > newest.version!) { newest = studio; } else if (studio.version == null && newest.version == null && studio.directory.compareTo(newest.directory) > 0) { newest = studio; } } return newest; } static List<AndroidStudio> allInstalled() => globals.platform.isMacOS ? _allMacOS() : _allLinuxOrWindows(); static List<AndroidStudio> _allMacOS() { final List<FileSystemEntity> candidatePaths = <FileSystemEntity>[]; void checkForStudio(String path) { if (!globals.fs.isDirectorySync(path)) { return; } try { final Iterable<Directory> directories = globals.fs .directory(path) .listSync(followLinks: false) .whereType<Directory>(); for (final Directory directory in directories) { final String name = directory.basename; // An exact match, or something like 'Android Studio 3.0 Preview.app'. if (name.startsWith('Android Studio') && name.endsWith('.app')) { candidatePaths.add(directory); } else if (!directory.path.endsWith('.app')) { checkForStudio(directory.path); } } } on Exception catch (e) { globals.printTrace('Exception while looking for Android Studio: $e'); } } checkForStudio('/Applications'); final String? homeDirPath = globals.fsUtils.homeDirPath; if (homeDirPath != null) { checkForStudio(globals.fs.path.join( homeDirPath, 'Applications', )); } Directory? configuredStudioDir = _configuredDir(); if (configuredStudioDir != null) { if (configuredStudioDir.basename == 'Contents') { configuredStudioDir = configuredStudioDir.parent; } if (!candidatePaths .any((FileSystemEntity e) => _pathsAreEqual(e.path, configuredStudioDir!.path))) { candidatePaths.add(configuredStudioDir); } } // Query Spotlight for unexpected installation locations. String spotlightQueryResult = ''; try { final ProcessResult spotlightResult = globals.processManager.runSync(<String>[ 'mdfind', // com.google.android.studio, com.google.android.studio-EAP 'kMDItemCFBundleIdentifier="com.google.android.studio*"', ]); spotlightQueryResult = spotlightResult.stdout as String; } on ProcessException { // The Spotlight query is a nice-to-have, continue checking known installation locations. } for (final String studioPath in LineSplitter.split(spotlightQueryResult)) { final Directory appBundle = globals.fs.directory(studioPath); if (!candidatePaths.any((FileSystemEntity e) => e.path == studioPath)) { candidatePaths.add(appBundle); } } return candidatePaths .map<AndroidStudio?>((FileSystemEntity e) { if (configuredStudioDir == null) { return AndroidStudio.fromMacOSBundle(e.path); } return AndroidStudio.fromMacOSBundle( e.path, configuredPath: _pathsAreEqual(configuredStudioDir.path, e.path) ? configuredStudioDir.path : null, ); }) .whereType<AndroidStudio>() .toList(); } static List<AndroidStudio> _allLinuxOrWindows() { final List<AndroidStudio> studios = <AndroidStudio>[]; bool alreadyFoundStudioAt(String path, { Version? newerThan }) { return studios.any((AndroidStudio studio) { if (studio.directory != path) { return false; } if (newerThan != null) { if (studio.version == null) { return false; } return studio.version!.compareTo(newerThan) >= 0; } return true; }); } // Read all $HOME/.AndroidStudio*/system/.home // or $HOME/.cache/Google/AndroidStudio*/.home files. // There may be several pointing to the same installation, // so we grab only the latest one. final String? homeDirPath = globals.fsUtils.homeDirPath; if (homeDirPath != null && globals.fs.directory(homeDirPath).existsSync()) { final Directory homeDir = globals.fs.directory(homeDirPath); final List<Directory> directoriesToSearch = <Directory>[homeDir]; // >=4.1 has new install location at $HOME/.cache/Google final String cacheDirPath = globals.fs.path.join(homeDirPath, '.cache', 'Google'); if (globals.fs.isDirectorySync(cacheDirPath)) { directoriesToSearch.add(globals.fs.directory(cacheDirPath)); } final List<Directory> entities = <Directory>[]; for (final Directory baseDir in directoriesToSearch) { final Iterable<Directory> directories = baseDir.listSync(followLinks: false).whereType<Directory>(); entities.addAll(directories.where((Directory directory) => _dotHomeStudioVersionMatcher.hasMatch(directory.basename))); } for (final Directory entity in entities) { final AndroidStudio? studio = AndroidStudio.fromHomeDot(entity); if (studio != null && !alreadyFoundStudioAt(studio.directory, newerThan: studio.version)) { studios.removeWhere((AndroidStudio other) => other.directory == studio.directory); studios.add(studio); } } } // Discover Android Studio > 4.1 if (globals.platform.isWindows && globals.platform.environment.containsKey('LOCALAPPDATA')) { final Directory cacheDir = globals.fs.directory(globals.fs.path.join(globals.platform.environment['LOCALAPPDATA']!, 'Google')); if (!cacheDir.existsSync()) { return studios; } for (final Directory dir in cacheDir.listSync().whereType<Directory>()) { final String name = globals.fs.path.basename(dir.path); AndroidStudioValidator.idToTitle.forEach((String id, String title) { if (name.startsWith(id)) { final String version = name.substring(id.length); String? installPath; try { installPath = globals.fs.file(globals.fs.path.join(dir.path, '.home')).readAsStringSync(); } on FileSystemException { // ignored } if (installPath != null && globals.fs.isDirectorySync(installPath)) { final AndroidStudio studio = AndroidStudio( installPath, version: Version.parse(version), studioAppName: title, ); if (!alreadyFoundStudioAt(studio.directory, newerThan: studio.version)) { studios.removeWhere((AndroidStudio other) => _pathsAreEqual(other.directory, studio.directory)); studios.add(studio); } } } }); } } final String? configuredStudioDir = globals.config.getValue('android-studio-dir') as String?; if (configuredStudioDir != null) { final AndroidStudio? matchingAlreadyFoundInstall = studios .where((AndroidStudio other) => _pathsAreEqual(configuredStudioDir, other.directory)) .firstOrNull; if (matchingAlreadyFoundInstall != null) { studios.remove(matchingAlreadyFoundInstall); studios.add( AndroidStudio( configuredStudioDir, configuredPath: configuredStudioDir, version: matchingAlreadyFoundInstall.version, ), ); } else { studios.add(AndroidStudio(configuredStudioDir, configuredPath: configuredStudioDir)); } } if (globals.platform.isLinux) { void checkWellKnownPath(String path) { if (globals.fs.isDirectorySync(path) && !alreadyFoundStudioAt(path)) { studios.add(AndroidStudio(path)); } } // Add /opt/android-studio and $HOME/android-studio, if they exist. checkWellKnownPath('/opt/android-studio'); checkWellKnownPath('${globals.fsUtils.homeDirPath}/android-studio'); } return studios; } /// Gets the Android Studio install directory set by the user, if it is configured. /// /// The returned [Directory], if not null, is guaranteed to have existed during /// this function's execution. static Directory? _configuredDir() { final String? configuredPath = globals.config.getValue('android-studio-dir') as String?; if (configuredPath == null) { return null; } final Directory result = globals.fs.directory(configuredPath); bool? configuredStudioPathExists; String? exceptionMessage; try { configuredStudioPathExists = result.existsSync(); } on FileSystemException catch (e) { exceptionMessage = e.toString(); } if (configuredStudioPathExists == false || exceptionMessage != null) { throwToolExit(''' Could not find the Android Studio installation at the manually configured path "$configuredPath". ${exceptionMessage == null ? '' : 'Encountered exception: $exceptionMessage\n\n'} Please verify that the path is correct and update it by running this command: flutter config --android-studio-dir '<path>' To have flutter search for Android Studio installations automatically, remove the configured path by running this command: flutter config --android-studio-dir '''); } return result; } static String? extractStudioPlistValueWithMatcher(String plistValue, RegExp keyMatcher) { return keyMatcher.stringMatch(plistValue)?.split('=').last.trim().replaceAll('"', ''); } void _initAndValidate() { _isValid = false; _validationMessages.clear(); if (configuredPath != null) { _validationMessages.add('android-studio-dir = $configuredPath'); } if (!globals.fs.isDirectorySync(directory)) { _validationMessages.add('Android Studio not found at $directory'); return; } final String javaPath; if (globals.platform.isMacOS) { if (version != null && version!.major < 2020) { javaPath = globals.fs.path.join(directory, 'jre', 'jdk', 'Contents', 'Home'); } else if (version != null && version!.major < 2022) { javaPath = globals.fs.path.join(directory, 'jre', 'Contents', 'Home'); // See https://github.com/flutter/flutter/issues/125246 for more context. } else { javaPath = globals.fs.path.join(directory, 'jbr', 'Contents', 'Home'); } } else { if (version != null && version!.major < 2022) { javaPath = globals.fs.path.join(directory, 'jre'); } else { javaPath = globals.fs.path.join(directory, 'jbr'); } } final String javaExecutable = globals.fs.path.join(javaPath, 'bin', 'java'); if (!globals.processManager.canRun(javaExecutable)) { _validationMessages.add('Unable to find bundled Java version.'); } else { RunResult? result; try { result = globals.processUtils.runSync(<String>[javaExecutable, '-version']); } on ProcessException catch (e) { _validationMessages.add('Failed to run Java: $e'); } if (result != null && result.exitCode == 0) { final List<String> versionLines = result.stderr.split('\n'); final String javaVersion = versionLines.length >= 2 ? versionLines[1] : versionLines[0]; _validationMessages.add('Java version $javaVersion'); _javaPath = javaPath; _isValid = true; } else { _validationMessages.add('Unable to determine bundled Java version.'); } } } @override String toString() => 'Android Studio ($version)'; } bool _pathsAreEqual(String path, String other) { return globals.fs.path.canonicalize(path) == globals.fs.path.canonicalize(other); }
flutter/packages/flutter_tools/lib/src/android/android_studio.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/android/android_studio.dart", "repo_id": "flutter", "token_count": 7625 }
746
// 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:meta/meta.dart'; import 'package:process/process.dart'; import 'base/common.dart'; import 'base/file_system.dart'; import 'base/os.dart'; import 'base/platform.dart'; import 'base/user_messages.dart'; import 'base/utils.dart'; import 'build_info.dart'; import 'cache.dart'; import 'globals.dart' as globals; enum Artifact { /// The tool which compiles a dart kernel file into native code. genSnapshot, /// The flutter tester binary. flutterTester, flutterFramework, flutterXcframework, /// The framework directory of the macOS desktop. flutterMacOSFramework, flutterMacOSXcframework, vmSnapshotData, isolateSnapshotData, icuData, platformKernelDill, platformLibrariesJson, flutterPatchedSdkPath, /// The root directory of the dart SDK. engineDartSdkPath, /// The dart binary used to execute any of the required snapshots. engineDartBinary, /// The dart binary for running aot snapshots engineDartAotRuntime, /// The snapshot of frontend_server compiler. frontendServerSnapshotForEngineDartSdk, /// The dart snapshot of the dart2js compiler. dart2jsSnapshot, /// The dart snapshot of the dart2wasm compiler. dart2wasmSnapshot, /// The root of the Linux desktop sources. linuxDesktopPath, // The root of the cpp headers for Linux desktop. linuxHeaders, /// The root of the Windows desktop sources. windowsDesktopPath, /// The root of the cpp client code for Windows desktop. windowsCppClientWrapper, /// The root of the sky_engine package. skyEnginePath, // Fuchsia artifacts from the engine prebuilts. fuchsiaKernelCompiler, fuchsiaFlutterRunner, /// Tools related to subsetting or icon font files. fontSubset, constFinder, /// The location of file generators. flutterToolsFileGenerators, /// Pre-built desktop debug app. flutterPreviewDevice, } /// A subset of [Artifact]s that are platform and build mode independent enum HostArtifact { /// The root of the web implementation of the dart SDK. flutterWebSdk, /// The libraries JSON file for web release builds. flutterWebLibrariesJson, // The flutter.js bootstrapping file provided by the engine. flutterJsDirectory, /// Folder that contains platform dill files for the web sdk. webPlatformKernelFolder, /// The summary dill for the dartdevc target. webPlatformDDCKernelDill, /// The summary dill with null safety enabled for the dartdevc target.g webPlatformDDCSoundKernelDill, /// The summary dill for the dartdevc target. webPlatformDart2JSKernelDill, /// The summary dill with null safety enabled for the dartdevc target. webPlatformDart2JSSoundKernelDill, /// The precompiled SDKs and sourcemaps for web debug builds with the AMD module system. // TODO(markzipan): delete these when DDC's AMD module system is deprecated, https://github.com/flutter/flutter/issues/142060. webPrecompiledAmdSdk, webPrecompiledAmdSdkSourcemaps, webPrecompiledAmdCanvaskitSdk, webPrecompiledAmdCanvaskitSdkSourcemaps, webPrecompiledAmdCanvaskitAndHtmlSdk, webPrecompiledAmdCanvaskitAndHtmlSdkSourcemaps, webPrecompiledAmdSoundSdk, webPrecompiledAmdSoundSdkSourcemaps, webPrecompiledAmdCanvaskitSoundSdk, webPrecompiledAmdCanvaskitSoundSdkSourcemaps, webPrecompiledAmdCanvaskitAndHtmlSoundSdk, webPrecompiledAmdCanvaskitAndHtmlSoundSdkSourcemaps, /// The precompiled SDKs and sourcemaps for web debug builds with the DDC module system. webPrecompiledDdcSdk, webPrecompiledDdcSdkSourcemaps, webPrecompiledDdcCanvaskitSdk, webPrecompiledDdcCanvaskitSdkSourcemaps, webPrecompiledDdcCanvaskitAndHtmlSdk, webPrecompiledDdcCanvaskitAndHtmlSdkSourcemaps, webPrecompiledDdcSoundSdk, webPrecompiledDdcSoundSdkSourcemaps, webPrecompiledDdcCanvaskitSoundSdk, webPrecompiledDdcCanvaskitSoundSdkSourcemaps, webPrecompiledDdcCanvaskitAndHtmlSoundSdk, webPrecompiledDdcCanvaskitAndHtmlSoundSdkSourcemaps, iosDeploy, idevicesyslog, idevicescreenshot, iproxy, /// The root of the sky_engine package. skyEnginePath, // The Impeller shader compiler. impellerc, // The Impeller Scene 3D model importer. scenec, // Impeller's tessellation library. libtessellator, } // TODO(knopp): Remove once darwin artifacts are universal and moved out of darwin-x64 String _enginePlatformDirectoryName(TargetPlatform platform) { if (platform == TargetPlatform.darwin) { return 'darwin-x64'; } return getNameForTargetPlatform(platform); } // Remove android target platform type. TargetPlatform? _mapTargetPlatform(TargetPlatform? targetPlatform) { switch (targetPlatform) { case TargetPlatform.android: return TargetPlatform.android_arm64; case TargetPlatform.ios: case TargetPlatform.darwin: case TargetPlatform.linux_x64: case TargetPlatform.linux_arm64: case TargetPlatform.windows_x64: case TargetPlatform.windows_arm64: case TargetPlatform.fuchsia_arm64: case TargetPlatform.fuchsia_x64: case TargetPlatform.tester: case TargetPlatform.web_javascript: case TargetPlatform.android_arm: case TargetPlatform.android_arm64: case TargetPlatform.android_x64: case TargetPlatform.android_x86: case null: return targetPlatform; } } String? _artifactToFileName(Artifact artifact, Platform hostPlatform, [ BuildMode? mode ]) { final String exe = hostPlatform.isWindows ? '.exe' : ''; switch (artifact) { case Artifact.genSnapshot: return 'gen_snapshot'; case Artifact.flutterTester: return 'flutter_tester$exe'; case Artifact.flutterFramework: return 'Flutter.framework'; case Artifact.flutterXcframework: return 'Flutter.xcframework'; case Artifact.flutterMacOSFramework: return 'FlutterMacOS.framework'; case Artifact.flutterMacOSXcframework: return 'FlutterMacOS.xcframework'; case Artifact.vmSnapshotData: return 'vm_isolate_snapshot.bin'; case Artifact.isolateSnapshotData: return 'isolate_snapshot.bin'; case Artifact.icuData: return 'icudtl.dat'; case Artifact.platformKernelDill: return 'platform_strong.dill'; case Artifact.platformLibrariesJson: return 'libraries.json'; case Artifact.flutterPatchedSdkPath: assert(false, 'No filename for sdk path, should not be invoked'); return null; case Artifact.engineDartSdkPath: return 'dart-sdk'; case Artifact.engineDartBinary: return 'dart$exe'; case Artifact.engineDartAotRuntime: return 'dartaotruntime$exe'; case Artifact.dart2jsSnapshot: return 'dart2js.dart.snapshot'; case Artifact.dart2wasmSnapshot: return 'dart2wasm_product.snapshot'; case Artifact.frontendServerSnapshotForEngineDartSdk: return 'frontend_server_aot.dart.snapshot'; case Artifact.linuxDesktopPath: return ''; case Artifact.linuxHeaders: return 'flutter_linux'; case Artifact.windowsCppClientWrapper: return 'cpp_client_wrapper'; case Artifact.windowsDesktopPath: return ''; case Artifact.skyEnginePath: return 'sky_engine'; case Artifact.fuchsiaKernelCompiler: return 'kernel_compiler.snapshot'; case Artifact.fuchsiaFlutterRunner: final String jitOrAot = mode!.isJit ? '_jit' : '_aot'; final String productOrNo = mode.isRelease ? '_product' : ''; return 'flutter$jitOrAot${productOrNo}_runner-0.far'; case Artifact.fontSubset: return 'font-subset$exe'; case Artifact.constFinder: return 'const_finder.dart.snapshot'; case Artifact.flutterToolsFileGenerators: return ''; case Artifact.flutterPreviewDevice: return 'flutter_preview$exe'; } } String _hostArtifactToFileName(HostArtifact artifact, Platform platform) { final String exe = platform.isWindows ? '.exe' : ''; String dll = '.so'; if (platform.isWindows) { dll = '.dll'; } else if (platform.isMacOS) { dll = '.dylib'; } switch (artifact) { case HostArtifact.flutterWebSdk: return ''; case HostArtifact.flutterJsDirectory: return 'flutter_js'; case HostArtifact.iosDeploy: return 'ios-deploy'; case HostArtifact.idevicesyslog: return 'idevicesyslog'; case HostArtifact.idevicescreenshot: return 'idevicescreenshot'; case HostArtifact.iproxy: return 'iproxy'; case HostArtifact.skyEnginePath: return 'sky_engine'; case HostArtifact.webPlatformKernelFolder: return 'kernel'; case HostArtifact.webPlatformDDCKernelDill: return 'ddc_outline.dill'; case HostArtifact.webPlatformDDCSoundKernelDill: return 'ddc_outline_sound.dill'; case HostArtifact.webPlatformDart2JSKernelDill: return 'dart2js_platform_unsound.dill'; case HostArtifact.webPlatformDart2JSSoundKernelDill: return 'dart2js_platform.dill'; case HostArtifact.flutterWebLibrariesJson: return 'libraries.json'; case HostArtifact.webPrecompiledAmdSdk: case HostArtifact.webPrecompiledAmdCanvaskitSdk: case HostArtifact.webPrecompiledAmdCanvaskitAndHtmlSdk: case HostArtifact.webPrecompiledAmdSoundSdk: case HostArtifact.webPrecompiledAmdCanvaskitSoundSdk: case HostArtifact.webPrecompiledAmdCanvaskitAndHtmlSoundSdk: case HostArtifact.webPrecompiledDdcSdk: case HostArtifact.webPrecompiledDdcCanvaskitSdk: case HostArtifact.webPrecompiledDdcCanvaskitAndHtmlSdk: case HostArtifact.webPrecompiledDdcSoundSdk: case HostArtifact.webPrecompiledDdcCanvaskitSoundSdk: case HostArtifact.webPrecompiledDdcCanvaskitAndHtmlSoundSdk: return 'dart_sdk.js'; case HostArtifact.webPrecompiledAmdSdkSourcemaps: case HostArtifact.webPrecompiledAmdCanvaskitSdkSourcemaps: case HostArtifact.webPrecompiledAmdCanvaskitAndHtmlSdkSourcemaps: case HostArtifact.webPrecompiledAmdSoundSdkSourcemaps: case HostArtifact.webPrecompiledAmdCanvaskitSoundSdkSourcemaps: case HostArtifact.webPrecompiledAmdCanvaskitAndHtmlSoundSdkSourcemaps: case HostArtifact.webPrecompiledDdcSdkSourcemaps: case HostArtifact.webPrecompiledDdcCanvaskitSdkSourcemaps: case HostArtifact.webPrecompiledDdcCanvaskitAndHtmlSdkSourcemaps: case HostArtifact.webPrecompiledDdcSoundSdkSourcemaps: case HostArtifact.webPrecompiledDdcCanvaskitSoundSdkSourcemaps: case HostArtifact.webPrecompiledDdcCanvaskitAndHtmlSoundSdkSourcemaps: return 'dart_sdk.js.map'; case HostArtifact.impellerc: return 'impellerc$exe'; case HostArtifact.scenec: return 'scenec$exe'; case HostArtifact.libtessellator: return 'libtessellator$dll'; } } class EngineBuildPaths { const EngineBuildPaths({ required this.targetEngine, required this.hostEngine, required this.webSdk, }); final String? targetEngine; final String? hostEngine; final String? webSdk; } /// Information about a local engine build (i.e. `--local-engine[-host]=...`). /// /// See https://github.com/flutter/flutter/wiki/The-flutter-tool#using-a-locally-built-engine-with-the-flutter-tool /// for more information about local engine builds. class LocalEngineInfo { /// Creates a reference to a local engine build. /// /// The [targetOutPath] and [hostOutPath] are assumed to be resolvable /// paths to the built engine artifacts for the target (device) and host /// (build) platforms, respectively. const LocalEngineInfo({ required this.targetOutPath, required this.hostOutPath, }); /// The path to the engine artifacts for the target (device) platform. /// /// For example, if the target platform is Android debug, this would be a path /// like `/path/to/engine/src/out/android_debug_unopt`. To retrieve just the /// name (platform), see [localTargetName]. final String targetOutPath; /// The path to the engine artifacts for the host (build) platform. /// /// For example, if the host platform is debug, this would be a path like /// `/path/to/engine/src/out/host_debug_unopt`. To retrieve just the name /// (platform), see [localHostName]. final String hostOutPath; /// The name of the target (device) platform, i.e. `android_debug_unopt`. String get localTargetName => globals.fs.path.basename(targetOutPath); /// The name of the host (build) platform, e.g. `host_debug_unopt`. String get localHostName => globals.fs.path.basename(hostOutPath); } // Manages the engine artifacts of Flutter. abstract class Artifacts { /// A test-specific implementation of artifacts that returns stable paths for /// all artifacts. /// /// If a [fileSystem] is not provided, creates a new [MemoryFileSystem] instance. /// /// Creates a [LocalEngineArtifacts] if `localEngine` is non-null @visibleForTesting factory Artifacts.test({FileSystem? fileSystem}) { return _TestArtifacts(fileSystem ?? MemoryFileSystem.test()); } /// A test-specific implementation of artifacts that returns stable paths for /// all artifacts, and uses a local engine. /// /// If a [fileSystem] is not provided, creates a new [MemoryFileSystem] instance. @visibleForTesting factory Artifacts.testLocalEngine({ required String localEngine, required String localEngineHost, FileSystem? fileSystem, }) { return _TestLocalEngine( localEngine, localEngineHost, fileSystem ?? MemoryFileSystem.test()); } static Artifacts getLocalEngine(EngineBuildPaths engineBuildPaths) { Artifacts artifacts = CachedArtifacts( fileSystem: globals.fs, platform: globals.platform, cache: globals.cache, operatingSystemUtils: globals.os ); if (engineBuildPaths.hostEngine != null && engineBuildPaths.targetEngine != null) { artifacts = CachedLocalEngineArtifacts( engineBuildPaths.hostEngine!, engineOutPath: engineBuildPaths.targetEngine!, cache: globals.cache, fileSystem: globals.fs, processManager: globals.processManager, platform: globals.platform, operatingSystemUtils: globals.os, parent: artifacts, ); } if (engineBuildPaths.webSdk != null) { artifacts = CachedLocalWebSdkArtifacts( parent: artifacts, webSdkPath: engineBuildPaths.webSdk!, fileSystem: globals.fs, platform: globals.platform, operatingSystemUtils: globals.os ); } return artifacts; } /// Returns the requested [artifact] for the [platform], [mode], and [environmentType] combination. String getArtifactPath( Artifact artifact, { TargetPlatform? platform, BuildMode? mode, EnvironmentType? environmentType, }); /// Retrieve a host specific artifact that does not depend on the /// current build mode or environment. FileSystemEntity getHostArtifact( HostArtifact artifact, ); // Returns which set of engine artifacts is currently used for the [platform] // and [mode] combination. String getEngineType(TargetPlatform platform, [ BuildMode? mode ]); /// Whether these artifacts correspond to a non-versioned local engine. bool get isLocalEngine; /// If these artifacts are bound to a local engine build, returns info about /// the location and name of the local engine, otherwise returns null. LocalEngineInfo? get localEngineInfo; } /// Manages the engine artifacts downloaded to the local cache. class CachedArtifacts implements Artifacts { CachedArtifacts({ required FileSystem fileSystem, required Platform platform, required Cache cache, required OperatingSystemUtils operatingSystemUtils, }) : _fileSystem = fileSystem, _platform = platform, _cache = cache, _operatingSystemUtils = operatingSystemUtils; final FileSystem _fileSystem; final Platform _platform; final Cache _cache; final OperatingSystemUtils _operatingSystemUtils; @override LocalEngineInfo? get localEngineInfo => null; @override FileSystemEntity getHostArtifact( HostArtifact artifact, ) { switch (artifact) { case HostArtifact.flutterWebSdk: final String path = _getFlutterWebSdkPath(); return _fileSystem.directory(path); case HostArtifact.flutterWebLibrariesJson: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.flutterJsDirectory: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'flutter_js'); return _fileSystem.directory(path); case HostArtifact.webPlatformKernelFolder: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel'); return _fileSystem.file(path); case HostArtifact.webPlatformDDCKernelDill: case HostArtifact.webPlatformDDCSoundKernelDill: case HostArtifact.webPlatformDart2JSKernelDill: case HostArtifact.webPlatformDart2JSSoundKernelDill: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledAmdSdk: case HostArtifact.webPrecompiledAmdSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledAmdCanvaskitSdk: case HostArtifact.webPrecompiledAmdCanvaskitSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd-canvaskit', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledAmdCanvaskitAndHtmlSdk: case HostArtifact.webPrecompiledAmdCanvaskitAndHtmlSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd-canvaskit-html', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledAmdSoundSdk: case HostArtifact.webPrecompiledAmdSoundSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd-sound', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledAmdCanvaskitSoundSdk: case HostArtifact.webPrecompiledAmdCanvaskitSoundSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd-canvaskit-sound', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledAmdCanvaskitAndHtmlSoundSdk: case HostArtifact.webPrecompiledAmdCanvaskitAndHtmlSoundSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd-canvaskit-html-sound', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledDdcSdk: case HostArtifact.webPrecompiledDdcSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'ddc', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledDdcCanvaskitSdk: case HostArtifact.webPrecompiledDdcCanvaskitSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'ddc-canvaskit', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledDdcCanvaskitAndHtmlSdk: case HostArtifact.webPrecompiledDdcCanvaskitAndHtmlSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'ddc-canvaskit-html', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledDdcSoundSdk: case HostArtifact.webPrecompiledDdcSoundSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'ddc-sound', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledDdcCanvaskitSoundSdk: case HostArtifact.webPrecompiledDdcCanvaskitSoundSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'ddc-canvaskit-sound', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledDdcCanvaskitAndHtmlSoundSdk: case HostArtifact.webPrecompiledDdcCanvaskitAndHtmlSoundSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'ddc-canvaskit-html-sound', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.idevicesyslog: case HostArtifact.idevicescreenshot: final String artifactFileName = _hostArtifactToFileName(artifact, _platform); return _cache.getArtifactDirectory('libimobiledevice').childFile(artifactFileName); case HostArtifact.skyEnginePath: final Directory dartPackageDirectory = _cache.getCacheDir('pkg'); final String path = _fileSystem.path.join(dartPackageDirectory.path, _hostArtifactToFileName(artifact, _platform)); return _fileSystem.directory(path); case HostArtifact.iosDeploy: final String artifactFileName = _hostArtifactToFileName(artifact, _platform); return _cache.getArtifactDirectory('ios-deploy').childFile(artifactFileName); case HostArtifact.iproxy: final String artifactFileName = _hostArtifactToFileName(artifact, _platform); return _cache.getArtifactDirectory('usbmuxd').childFile(artifactFileName); case HostArtifact.impellerc: case HostArtifact.scenec: case HostArtifact.libtessellator: final String artifactFileName = _hostArtifactToFileName(artifact, _platform); final String engineDir = _getEngineArtifactsPath(_currentHostPlatform(_platform, _operatingSystemUtils))!; return _fileSystem.file(_fileSystem.path.join(engineDir, artifactFileName)); } } @override String getArtifactPath( Artifact artifact, { TargetPlatform? platform, BuildMode? mode, EnvironmentType? environmentType, }) { platform = _mapTargetPlatform(platform); switch (platform) { case TargetPlatform.android: case TargetPlatform.android_arm: case TargetPlatform.android_arm64: case TargetPlatform.android_x64: case TargetPlatform.android_x86: assert(platform != TargetPlatform.android); return _getAndroidArtifactPath(artifact, platform!, mode!); case TargetPlatform.ios: return _getIosArtifactPath(artifact, platform!, mode, environmentType); case TargetPlatform.darwin: case TargetPlatform.linux_x64: case TargetPlatform.linux_arm64: case TargetPlatform.windows_x64: case TargetPlatform.windows_arm64: return _getDesktopArtifactPath(artifact, platform, mode); case TargetPlatform.fuchsia_arm64: case TargetPlatform.fuchsia_x64: return _getFuchsiaArtifactPath(artifact, platform!, mode!); case TargetPlatform.tester: case TargetPlatform.web_javascript: case null: return _getHostArtifactPath(artifact, platform ?? _currentHostPlatform(_platform, _operatingSystemUtils), mode); } } @override String getEngineType(TargetPlatform platform, [ BuildMode? mode ]) { return _fileSystem.path.basename(_getEngineArtifactsPath(platform, mode)!); } String _getDesktopArtifactPath(Artifact artifact, TargetPlatform? platform, BuildMode? mode) { // When platform is null, a generic host platform artifact is being requested // and not the gen_snapshot for darwin as a target platform. if (platform != null && artifact == Artifact.genSnapshot) { final String engineDir = _getEngineArtifactsPath(platform, mode)!; return _fileSystem.path.join(engineDir, _artifactToFileName(artifact, _platform)); } if (platform != null && artifact == Artifact.flutterMacOSFramework) { final String engineDir = _getEngineArtifactsPath(platform, mode)!; return _getMacOSEngineArtifactPath(engineDir, _fileSystem, _platform); } return _getHostArtifactPath(artifact, platform ?? _currentHostPlatform(_platform, _operatingSystemUtils), mode); } String _getAndroidArtifactPath(Artifact artifact, TargetPlatform platform, BuildMode mode) { final String engineDir = _getEngineArtifactsPath(platform, mode)!; switch (artifact) { case Artifact.genSnapshot: assert(mode != BuildMode.debug, 'Artifact $artifact only available in non-debug mode.'); final String hostPlatform = getNameForHostPlatform(getCurrentHostPlatform()); return _fileSystem.path.join(engineDir, hostPlatform, _artifactToFileName(artifact, _platform)); case Artifact.engineDartSdkPath: case Artifact.engineDartBinary: case Artifact.engineDartAotRuntime: case Artifact.dart2jsSnapshot: case Artifact.dart2wasmSnapshot: case Artifact.frontendServerSnapshotForEngineDartSdk: case Artifact.constFinder: case Artifact.flutterFramework: case Artifact.flutterMacOSFramework: case Artifact.flutterMacOSXcframework: case Artifact.flutterPatchedSdkPath: case Artifact.flutterTester: case Artifact.flutterXcframework: case Artifact.fontSubset: case Artifact.fuchsiaFlutterRunner: case Artifact.fuchsiaKernelCompiler: case Artifact.icuData: case Artifact.isolateSnapshotData: case Artifact.linuxDesktopPath: case Artifact.linuxHeaders: case Artifact.platformKernelDill: case Artifact.platformLibrariesJson: case Artifact.skyEnginePath: case Artifact.vmSnapshotData: case Artifact.windowsCppClientWrapper: case Artifact.windowsDesktopPath: case Artifact.flutterToolsFileGenerators: case Artifact.flutterPreviewDevice: return _getHostArtifactPath(artifact, platform, mode); } } String _getIosArtifactPath(Artifact artifact, TargetPlatform platform, BuildMode? mode, EnvironmentType? environmentType) { switch (artifact) { case Artifact.genSnapshot: case Artifact.flutterXcframework: final String artifactFileName = _artifactToFileName(artifact, _platform)!; final String engineDir = _getEngineArtifactsPath(platform, mode)!; return _fileSystem.path.join(engineDir, artifactFileName); case Artifact.flutterFramework: final String engineDir = _getEngineArtifactsPath(platform, mode)!; return _getIosEngineArtifactPath(engineDir, environmentType, _fileSystem, _platform); case Artifact.engineDartSdkPath: case Artifact.engineDartBinary: case Artifact.engineDartAotRuntime: case Artifact.dart2jsSnapshot: case Artifact.dart2wasmSnapshot: case Artifact.frontendServerSnapshotForEngineDartSdk: case Artifact.constFinder: case Artifact.flutterMacOSFramework: case Artifact.flutterMacOSXcframework: case Artifact.flutterPatchedSdkPath: case Artifact.flutterTester: case Artifact.fontSubset: case Artifact.fuchsiaFlutterRunner: case Artifact.fuchsiaKernelCompiler: case Artifact.icuData: case Artifact.isolateSnapshotData: case Artifact.linuxDesktopPath: case Artifact.linuxHeaders: case Artifact.platformKernelDill: case Artifact.platformLibrariesJson: case Artifact.skyEnginePath: case Artifact.vmSnapshotData: case Artifact.windowsCppClientWrapper: case Artifact.windowsDesktopPath: case Artifact.flutterToolsFileGenerators: case Artifact.flutterPreviewDevice: return _getHostArtifactPath(artifact, platform, mode); } } String _getFuchsiaArtifactPath(Artifact artifact, TargetPlatform platform, BuildMode mode) { final String root = _fileSystem.path.join( _cache.getArtifactDirectory('flutter_runner').path, 'flutter', platform.fuchsiaArchForTargetPlatform, mode.isRelease ? 'release' : mode.toString(), ); final String runtime = mode.isJit ? 'jit' : 'aot'; switch (artifact) { case Artifact.genSnapshot: final String genSnapshot = mode.isRelease ? 'gen_snapshot_product' : 'gen_snapshot'; return _fileSystem.path.join(root, runtime, 'dart_binaries', genSnapshot); case Artifact.flutterPatchedSdkPath: const String artifactFileName = 'flutter_runner_patched_sdk'; return _fileSystem.path.join(root, runtime, artifactFileName); case Artifact.platformKernelDill: final String artifactFileName = _artifactToFileName(artifact, _platform, mode)!; return _fileSystem.path.join(root, runtime, 'flutter_runner_patched_sdk', artifactFileName); case Artifact.fuchsiaKernelCompiler: final String artifactFileName = _artifactToFileName(artifact, _platform, mode)!; return _fileSystem.path.join(root, runtime, 'dart_binaries', artifactFileName); case Artifact.fuchsiaFlutterRunner: final String artifactFileName = _artifactToFileName(artifact, _platform, mode)!; return _fileSystem.path.join(root, runtime, artifactFileName); case Artifact.constFinder: case Artifact.flutterFramework: case Artifact.flutterMacOSFramework: case Artifact.flutterMacOSXcframework: case Artifact.flutterTester: case Artifact.flutterXcframework: case Artifact.fontSubset: case Artifact.engineDartSdkPath: case Artifact.engineDartBinary: case Artifact.engineDartAotRuntime: case Artifact.dart2jsSnapshot: case Artifact.dart2wasmSnapshot: case Artifact.frontendServerSnapshotForEngineDartSdk: case Artifact.icuData: case Artifact.isolateSnapshotData: case Artifact.linuxDesktopPath: case Artifact.linuxHeaders: case Artifact.platformLibrariesJson: case Artifact.skyEnginePath: case Artifact.vmSnapshotData: case Artifact.windowsCppClientWrapper: case Artifact.windowsDesktopPath: case Artifact.flutterToolsFileGenerators: case Artifact.flutterPreviewDevice: return _getHostArtifactPath(artifact, platform, mode); } } String _getFlutterPatchedSdkPath(BuildMode? mode) { final String engineArtifactsPath = _cache.getArtifactDirectory('engine').path; return _fileSystem.path.join(engineArtifactsPath, 'common', mode == BuildMode.release ? 'flutter_patched_sdk_product' : 'flutter_patched_sdk'); } String _getFlutterWebSdkPath() { return _cache.getWebSdkDirectory().path; } String _getHostArtifactPath(Artifact artifact, TargetPlatform platform, BuildMode? mode) { switch (artifact) { case Artifact.genSnapshot: // For script snapshots any gen_snapshot binary will do. Returning gen_snapshot for // android_arm in profile mode because it is available on all supported host platforms. return _getAndroidArtifactPath(artifact, TargetPlatform.android_arm, BuildMode.profile); case Artifact.dart2jsSnapshot: case Artifact.dart2wasmSnapshot: case Artifact.frontendServerSnapshotForEngineDartSdk: return _fileSystem.path.join( _dartSdkPath(_cache), 'bin', 'snapshots', _artifactToFileName(artifact, _platform), ); case Artifact.flutterTester: case Artifact.vmSnapshotData: case Artifact.isolateSnapshotData: case Artifact.icuData: final String engineArtifactsPath = _cache.getArtifactDirectory('engine').path; final String platformDirName = _enginePlatformDirectoryName(platform); return _fileSystem.path.join(engineArtifactsPath, platformDirName, _artifactToFileName(artifact, _platform, mode)); case Artifact.platformKernelDill: return _fileSystem.path.join(_getFlutterPatchedSdkPath(mode), _artifactToFileName(artifact, _platform)); case Artifact.platformLibrariesJson: return _fileSystem.path.join(_getFlutterPatchedSdkPath(mode), 'lib', _artifactToFileName(artifact, _platform)); case Artifact.flutterPatchedSdkPath: return _getFlutterPatchedSdkPath(mode); case Artifact.engineDartSdkPath: return _dartSdkPath(_cache); case Artifact.engineDartBinary: case Artifact.engineDartAotRuntime: return _fileSystem.path.join(_dartSdkPath(_cache), 'bin', _artifactToFileName(artifact, _platform)); case Artifact.flutterMacOSFramework: String platformDirName = _enginePlatformDirectoryName(platform); if (mode == BuildMode.profile || mode == BuildMode.release) { platformDirName = '$platformDirName-${mode!.cliName}'; } final String engineArtifactsPath = _cache.getArtifactDirectory('engine').path; return _getMacOSEngineArtifactPath(_fileSystem.path.join(engineArtifactsPath, platformDirName), _fileSystem, _platform); case Artifact.flutterMacOSXcframework: case Artifact.linuxDesktopPath: case Artifact.windowsDesktopPath: case Artifact.linuxHeaders: // TODO(zanderso): remove once debug desktop artifacts are uploaded // under a separate directory from the host artifacts. // https://github.com/flutter/flutter/issues/38935 String platformDirName = _enginePlatformDirectoryName(platform); if (mode == BuildMode.profile || mode == BuildMode.release) { platformDirName = '$platformDirName-${mode!.cliName}'; } final String engineArtifactsPath = _cache.getArtifactDirectory('engine').path; return _fileSystem.path.join(engineArtifactsPath, platformDirName, _artifactToFileName(artifact, _platform, mode)); case Artifact.windowsCppClientWrapper: final String platformDirName = _enginePlatformDirectoryName(platform); final String engineArtifactsPath = _cache.getArtifactDirectory('engine').path; return _fileSystem.path.join(engineArtifactsPath, platformDirName, _artifactToFileName(artifact, _platform, mode)); case Artifact.skyEnginePath: final Directory dartPackageDirectory = _cache.getCacheDir('pkg'); return _fileSystem.path.join(dartPackageDirectory.path, _artifactToFileName(artifact, _platform)); case Artifact.fontSubset: case Artifact.constFinder: return _cache.getArtifactDirectory('engine') .childDirectory(_enginePlatformDirectoryName(platform)) .childFile(_artifactToFileName(artifact, _platform, mode)!) .path; case Artifact.flutterFramework: case Artifact.flutterXcframework: case Artifact.fuchsiaFlutterRunner: case Artifact.fuchsiaKernelCompiler: throw StateError('Artifact $artifact not available for platform $platform.'); case Artifact.flutterToolsFileGenerators: return _getFileGeneratorsPath(); case Artifact.flutterPreviewDevice: assert(platform == TargetPlatform.windows_x64); return _cache.getArtifactDirectory('flutter_preview').childFile('flutter_preview.exe').path; } } String? _getEngineArtifactsPath(TargetPlatform platform, [ BuildMode? mode ]) { final String engineDir = _cache.getArtifactDirectory('engine').path; final String platformName = _enginePlatformDirectoryName(platform); switch (platform) { case TargetPlatform.linux_x64: case TargetPlatform.linux_arm64: case TargetPlatform.darwin: case TargetPlatform.windows_x64: case TargetPlatform.windows_arm64: // TODO(zanderso): remove once debug desktop artifacts are uploaded // under a separate directory from the host artifacts. // https://github.com/flutter/flutter/issues/38935 if (mode == BuildMode.debug || mode == null) { return _fileSystem.path.join(engineDir, platformName); } final String suffix = mode != BuildMode.debug ? '-${snakeCase(mode.cliName, '-')}' : ''; return _fileSystem.path.join(engineDir, platformName + suffix); case TargetPlatform.fuchsia_arm64: case TargetPlatform.fuchsia_x64: case TargetPlatform.tester: case TargetPlatform.web_javascript: assert(mode == null, 'Platform $platform does not support different build modes.'); return _fileSystem.path.join(engineDir, platformName); case TargetPlatform.ios: case TargetPlatform.android_arm: case TargetPlatform.android_arm64: case TargetPlatform.android_x64: case TargetPlatform.android_x86: assert(mode != null, 'Need to specify a build mode for platform $platform.'); final String suffix = mode != BuildMode.debug ? '-${snakeCase(mode!.cliName, '-')}' : ''; return _fileSystem.path.join(engineDir, platformName + suffix); case TargetPlatform.android: assert(false, 'cannot use TargetPlatform.android to look up artifacts'); return null; } } @override bool get isLocalEngine => false; } TargetPlatform _currentHostPlatform(Platform platform, OperatingSystemUtils operatingSystemUtils) { if (platform.isMacOS) { return TargetPlatform.darwin; } if (platform.isLinux) { return operatingSystemUtils.hostPlatform == HostPlatform.linux_x64 ? TargetPlatform.linux_x64 : TargetPlatform.linux_arm64; } if (platform.isWindows) { return operatingSystemUtils.hostPlatform == HostPlatform.windows_arm64 ? TargetPlatform.windows_arm64 : TargetPlatform.windows_x64; } throw UnimplementedError('Host OS not supported.'); } String _getIosEngineArtifactPath(String engineDirectory, EnvironmentType? environmentType, FileSystem fileSystem, Platform hostPlatform) { final Directory xcframeworkDirectory = fileSystem .directory(engineDirectory) .childDirectory(_artifactToFileName(Artifact.flutterXcframework, hostPlatform)!); if (!xcframeworkDirectory.existsSync()) { throwToolExit('No xcframework found at ${xcframeworkDirectory.path}. Try running "flutter precache --ios".'); } Directory? flutterFrameworkSource; for (final Directory platformDirectory in xcframeworkDirectory.listSync().whereType<Directory>()) { if (!platformDirectory.basename.startsWith('ios-')) { continue; } // ios-x86_64-simulator, ios-arm64_x86_64-simulator, or ios-arm64. final bool simulatorDirectory = platformDirectory.basename.endsWith('-simulator'); if ((environmentType == EnvironmentType.simulator && simulatorDirectory) || (environmentType == EnvironmentType.physical && !simulatorDirectory)) { flutterFrameworkSource = platformDirectory; } } if (flutterFrameworkSource == null) { throwToolExit('No iOS frameworks found in ${xcframeworkDirectory.path}'); } return flutterFrameworkSource .childDirectory(_artifactToFileName(Artifact.flutterFramework, hostPlatform)!) .path; } String _getMacOSEngineArtifactPath( String engineDirectory, FileSystem fileSystem, Platform hostPlatform, ) { final Directory xcframeworkDirectory = fileSystem .directory(engineDirectory) .childDirectory(_artifactToFileName(Artifact.flutterMacOSXcframework, hostPlatform)!); if (!xcframeworkDirectory.existsSync()) { throwToolExit('No xcframework found at ${xcframeworkDirectory.path}. Try running "flutter precache --macos".'); } final Directory? flutterFrameworkSource = xcframeworkDirectory .listSync() .whereType<Directory>() .where((Directory platformDirectory) => platformDirectory.basename.startsWith('macos-')) .firstOrNull; if (flutterFrameworkSource == null) { throwToolExit('No macOS frameworks found in ${xcframeworkDirectory.path}'); } return flutterFrameworkSource .childDirectory(_artifactToFileName(Artifact.flutterMacOSFramework, hostPlatform)!) .path; } /// Manages the artifacts of a locally built engine. class CachedLocalEngineArtifacts implements Artifacts { CachedLocalEngineArtifacts( this._hostEngineOutPath, { required String engineOutPath, required FileSystem fileSystem, required Cache cache, required ProcessManager processManager, required Platform platform, required OperatingSystemUtils operatingSystemUtils, Artifacts? parent, }) : _fileSystem = fileSystem, localEngineInfo = LocalEngineInfo( targetOutPath: engineOutPath, hostOutPath: _hostEngineOutPath, ), _cache = cache, _processManager = processManager, _platform = platform, _operatingSystemUtils = operatingSystemUtils, _backupCache = parent ?? CachedArtifacts( fileSystem: fileSystem, platform: platform, cache: cache, operatingSystemUtils: operatingSystemUtils ); @override final LocalEngineInfo localEngineInfo; final String _hostEngineOutPath; final FileSystem _fileSystem; final Cache _cache; final ProcessManager _processManager; final Platform _platform; final OperatingSystemUtils _operatingSystemUtils; final Artifacts _backupCache; @override FileSystemEntity getHostArtifact( HostArtifact artifact, ) { switch (artifact) { case HostArtifact.flutterWebSdk: final String path = _getFlutterWebSdkPath(); return _fileSystem.directory(path); case HostArtifact.flutterWebLibrariesJson: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.flutterJsDirectory: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'flutter_js'); return _fileSystem.directory(path); case HostArtifact.webPlatformKernelFolder: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel'); return _fileSystem.file(path); case HostArtifact.webPlatformDDCKernelDill: case HostArtifact.webPlatformDDCSoundKernelDill: case HostArtifact.webPlatformDart2JSKernelDill: case HostArtifact.webPlatformDart2JSSoundKernelDill: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledAmdSdk: case HostArtifact.webPrecompiledAmdSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledAmdCanvaskitSdk: case HostArtifact.webPrecompiledAmdCanvaskitSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd-canvaskit', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledAmdCanvaskitAndHtmlSdk: case HostArtifact.webPrecompiledAmdCanvaskitAndHtmlSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd-canvaskit-html', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledAmdSoundSdk: case HostArtifact.webPrecompiledAmdSoundSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd-sound', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledAmdCanvaskitSoundSdk: case HostArtifact.webPrecompiledAmdCanvaskitSoundSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd-canvaskit-sound', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledAmdCanvaskitAndHtmlSoundSdk: case HostArtifact.webPrecompiledAmdCanvaskitAndHtmlSoundSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd-canvaskit-html-sound', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledDdcSdk: case HostArtifact.webPrecompiledDdcSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'ddc', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledDdcCanvaskitSdk: case HostArtifact.webPrecompiledDdcCanvaskitSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'ddc-canvaskit', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledDdcCanvaskitAndHtmlSdk: case HostArtifact.webPrecompiledDdcCanvaskitAndHtmlSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'ddc-canvaskit-html', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledDdcSoundSdk: case HostArtifact.webPrecompiledDdcSoundSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'ddc-sound', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledDdcCanvaskitSoundSdk: case HostArtifact.webPrecompiledDdcCanvaskitSoundSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'ddc-canvaskit-sound', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledDdcCanvaskitAndHtmlSoundSdk: case HostArtifact.webPrecompiledDdcCanvaskitAndHtmlSoundSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'ddc-canvaskit-html-sound', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.idevicesyslog: case HostArtifact.idevicescreenshot: final String artifactFileName = _hostArtifactToFileName(artifact, _platform); return _cache.getArtifactDirectory('libimobiledevice').childFile(artifactFileName); case HostArtifact.skyEnginePath: final Directory dartPackageDirectory = _cache.getCacheDir('pkg'); final String path = _fileSystem.path.join(dartPackageDirectory.path, _hostArtifactToFileName(artifact, _platform)); return _fileSystem.directory(path); case HostArtifact.iosDeploy: final String artifactFileName = _hostArtifactToFileName(artifact, _platform); return _cache.getArtifactDirectory('ios-deploy').childFile(artifactFileName); case HostArtifact.iproxy: final String artifactFileName = _hostArtifactToFileName(artifact, _platform); return _cache.getArtifactDirectory('usbmuxd').childFile(artifactFileName); case HostArtifact.impellerc: case HostArtifact.scenec: case HostArtifact.libtessellator: final String artifactFileName = _hostArtifactToFileName(artifact, _platform); final File file = _fileSystem.file(_fileSystem.path.join(_hostEngineOutPath, artifactFileName)); if (!file.existsSync()) { return _backupCache.getHostArtifact(artifact); } return file; } } @override String getArtifactPath( Artifact artifact, { TargetPlatform? platform, BuildMode? mode, EnvironmentType? environmentType, }) { platform ??= _currentHostPlatform(_platform, _operatingSystemUtils); platform = _mapTargetPlatform(platform); final bool isDirectoryArtifact = artifact == Artifact.flutterPatchedSdkPath; final String? artifactFileName = isDirectoryArtifact ? null : _artifactToFileName(artifact, _platform, mode); switch (artifact) { case Artifact.genSnapshot: return _genSnapshotPath(); case Artifact.flutterTester: return _flutterTesterPath(platform!); case Artifact.isolateSnapshotData: case Artifact.vmSnapshotData: return _fileSystem.path.join(localEngineInfo.targetOutPath, 'gen', 'flutter', 'lib', 'snapshot', artifactFileName); case Artifact.icuData: case Artifact.flutterXcframework: case Artifact.flutterMacOSXcframework: return _fileSystem.path.join(localEngineInfo.targetOutPath, artifactFileName); case Artifact.platformKernelDill: if (platform == TargetPlatform.fuchsia_x64 || platform == TargetPlatform.fuchsia_arm64) { return _fileSystem.path.join(localEngineInfo.targetOutPath, 'flutter_runner_patched_sdk', artifactFileName); } return _fileSystem.path.join(_getFlutterPatchedSdkPath(mode), artifactFileName); case Artifact.platformLibrariesJson: return _fileSystem.path.join(_getFlutterPatchedSdkPath(mode), 'lib', artifactFileName); case Artifact.flutterFramework: return _getIosEngineArtifactPath( localEngineInfo.targetOutPath, environmentType, _fileSystem, _platform); case Artifact.flutterMacOSFramework: return _getMacOSEngineArtifactPath( localEngineInfo.targetOutPath, _fileSystem, _platform); case Artifact.flutterPatchedSdkPath: // When using local engine always use [BuildMode.debug] regardless of // what was specified in [mode] argument because local engine will // have only one flutter_patched_sdk in standard location, that // is happen to be what debug(non-release) mode is using. if (platform == TargetPlatform.fuchsia_x64 || platform == TargetPlatform.fuchsia_arm64) { return _fileSystem.path.join(localEngineInfo.targetOutPath, 'flutter_runner_patched_sdk'); } return _getFlutterPatchedSdkPath(BuildMode.debug); case Artifact.skyEnginePath: return _fileSystem.path.join(_hostEngineOutPath, 'gen', 'dart-pkg', artifactFileName); case Artifact.fuchsiaKernelCompiler: final String hostPlatform = getNameForHostPlatform(getCurrentHostPlatform()); final String modeName = mode!.isRelease ? 'release' : mode.toString(); final String dartBinaries = 'dart_binaries-$modeName-$hostPlatform'; return _fileSystem.path.join(localEngineInfo.targetOutPath, 'host_bundle', dartBinaries, 'kernel_compiler.dart.snapshot'); case Artifact.fuchsiaFlutterRunner: final String jitOrAot = mode!.isJit ? '_jit' : '_aot'; final String productOrNo = mode.isRelease ? '_product' : ''; return _fileSystem.path.join(localEngineInfo.targetOutPath, 'flutter$jitOrAot${productOrNo}_runner-0.far'); case Artifact.fontSubset: return _fileSystem.path.join(_hostEngineOutPath, artifactFileName); case Artifact.constFinder: return _fileSystem.path.join(_hostEngineOutPath, 'gen', artifactFileName); case Artifact.linuxDesktopPath: case Artifact.linuxHeaders: case Artifact.windowsDesktopPath: case Artifact.windowsCppClientWrapper: return _fileSystem.path.join(_hostEngineOutPath, artifactFileName); case Artifact.engineDartSdkPath: return _getDartSdkPath(); case Artifact.engineDartBinary: case Artifact.engineDartAotRuntime: return _fileSystem.path.join(_getDartSdkPath(), 'bin', artifactFileName); case Artifact.dart2jsSnapshot: case Artifact.dart2wasmSnapshot: case Artifact.frontendServerSnapshotForEngineDartSdk: return _fileSystem.path.join(_getDartSdkPath(), 'bin', 'snapshots', artifactFileName); case Artifact.flutterToolsFileGenerators: return _getFileGeneratorsPath(); case Artifact.flutterPreviewDevice: return _backupCache.getArtifactPath( artifact, platform: platform, mode: mode, environmentType: environmentType, ); } } @override String getEngineType(TargetPlatform platform, [ BuildMode? mode ]) { return _fileSystem.path.basename(localEngineInfo.targetOutPath); } String _getFlutterPatchedSdkPath(BuildMode? buildMode) { return _fileSystem.path.join(localEngineInfo.targetOutPath, buildMode == BuildMode.release ? 'flutter_patched_sdk_product' : 'flutter_patched_sdk'); } String _getDartSdkPath() { final String builtPath = _fileSystem.path.join(_hostEngineOutPath, 'dart-sdk'); if (_fileSystem.isDirectorySync(_fileSystem.path.join(builtPath, 'bin'))) { return builtPath; } // If we couldn't find a built dart sdk, let's look for a prebuilt one. final String prebuiltPath = _fileSystem.path.join(_getFlutterPrebuiltsPath(), _getPrebuiltTarget(), 'dart-sdk'); if (_fileSystem.isDirectorySync(prebuiltPath)) { return prebuiltPath; } throw ToolExit('Unable to find a built dart sdk at: "$builtPath" or a prebuilt dart sdk at: "$prebuiltPath"'); } String _getFlutterPrebuiltsPath() { final String engineSrcPath = _fileSystem.path.dirname(_fileSystem.path.dirname(_hostEngineOutPath)); return _fileSystem.path.join(engineSrcPath, 'flutter', 'prebuilts'); } String _getPrebuiltTarget() { final TargetPlatform hostPlatform = _currentHostPlatform(_platform, _operatingSystemUtils); switch (hostPlatform) { case TargetPlatform.darwin: return 'macos-x64'; case TargetPlatform.linux_arm64: return 'linux-arm64'; case TargetPlatform.linux_x64: return 'linux-x64'; case TargetPlatform.windows_x64: return 'windows-x64'; case TargetPlatform.windows_arm64: return 'windows-arm64'; case TargetPlatform.ios: case TargetPlatform.android: case TargetPlatform.android_arm: case TargetPlatform.android_arm64: case TargetPlatform.android_x64: case TargetPlatform.android_x86: case TargetPlatform.fuchsia_arm64: case TargetPlatform.fuchsia_x64: case TargetPlatform.web_javascript: case TargetPlatform.tester: throwToolExit('Unsupported host platform: $hostPlatform'); } } String _getFlutterWebSdkPath() { return _fileSystem.path.join(localEngineInfo.targetOutPath, 'flutter_web_sdk'); } String _genSnapshotPath() { const List<String> clangDirs = <String>['.', 'clang_x64', 'clang_x86', 'clang_i386', 'clang_arm64']; final String genSnapshotName = _artifactToFileName(Artifact.genSnapshot, _platform)!; for (final String clangDir in clangDirs) { final String genSnapshotPath = _fileSystem.path.join(localEngineInfo.targetOutPath, clangDir, genSnapshotName); if (_processManager.canRun(genSnapshotPath)) { return genSnapshotPath; } } throw Exception('Unable to find $genSnapshotName'); } String _flutterTesterPath(TargetPlatform platform) { if (_platform.isLinux) { return _fileSystem.path.join(localEngineInfo.targetOutPath, _artifactToFileName(Artifact.flutterTester, _platform)); } else if (_platform.isMacOS) { return _fileSystem.path.join(localEngineInfo.targetOutPath, 'flutter_tester'); } else if (_platform.isWindows) { return _fileSystem.path.join(localEngineInfo.targetOutPath, 'flutter_tester.exe'); } throw Exception('Unsupported platform $platform.'); } @override bool get isLocalEngine => true; } class CachedLocalWebSdkArtifacts implements Artifacts { CachedLocalWebSdkArtifacts({ required Artifacts parent, required String webSdkPath, required FileSystem fileSystem, required Platform platform, required OperatingSystemUtils operatingSystemUtils }) : _parent = parent, _webSdkPath = webSdkPath, _fileSystem = fileSystem, _platform = platform, _operatingSystemUtils = operatingSystemUtils; final Artifacts _parent; final String _webSdkPath; final FileSystem _fileSystem; final Platform _platform; final OperatingSystemUtils _operatingSystemUtils; @override String getArtifactPath(Artifact artifact, {TargetPlatform? platform, BuildMode? mode, EnvironmentType? environmentType}) { if (platform == TargetPlatform.web_javascript) { switch (artifact) { case Artifact.engineDartSdkPath: return _getDartSdkPath(); case Artifact.engineDartBinary: case Artifact.engineDartAotRuntime: return _fileSystem.path.join( _getDartSdkPath(), 'bin', _artifactToFileName(artifact, _platform, mode)); case Artifact.dart2jsSnapshot: case Artifact.dart2wasmSnapshot: case Artifact.frontendServerSnapshotForEngineDartSdk: return _fileSystem.path.join( _getDartSdkPath(), 'bin', 'snapshots', _artifactToFileName(artifact, _platform, mode), ); case Artifact.genSnapshot: case Artifact.flutterTester: case Artifact.flutterFramework: case Artifact.flutterXcframework: case Artifact.flutterMacOSFramework: case Artifact.flutterMacOSXcframework: case Artifact.vmSnapshotData: case Artifact.isolateSnapshotData: case Artifact.icuData: case Artifact.platformKernelDill: case Artifact.platformLibrariesJson: case Artifact.flutterPatchedSdkPath: case Artifact.linuxDesktopPath: case Artifact.linuxHeaders: case Artifact.windowsDesktopPath: case Artifact.windowsCppClientWrapper: case Artifact.skyEnginePath: case Artifact.fuchsiaKernelCompiler: case Artifact.fuchsiaFlutterRunner: case Artifact.fontSubset: case Artifact.constFinder: case Artifact.flutterToolsFileGenerators: case Artifact.flutterPreviewDevice: break; } } return _parent.getArtifactPath(artifact, platform: platform, mode: mode, environmentType: environmentType); } @override String getEngineType(TargetPlatform platform, [BuildMode? mode]) => _parent.getEngineType(platform, mode); @override FileSystemEntity getHostArtifact( HostArtifact artifact, ) { switch (artifact) { case HostArtifact.flutterWebSdk: final String path = _getFlutterWebSdkPath(); return _fileSystem.directory(path); case HostArtifact.flutterWebLibrariesJson: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.flutterJsDirectory: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'flutter_js'); return _fileSystem.directory(path); case HostArtifact.webPlatformKernelFolder: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel'); return _fileSystem.file(path); case HostArtifact.webPlatformDDCKernelDill: case HostArtifact.webPlatformDDCSoundKernelDill: case HostArtifact.webPlatformDart2JSKernelDill: case HostArtifact.webPlatformDart2JSSoundKernelDill: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledAmdSdk: case HostArtifact.webPrecompiledAmdSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledAmdCanvaskitSdk: case HostArtifact.webPrecompiledAmdCanvaskitSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd-canvaskit', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledAmdCanvaskitAndHtmlSdk: case HostArtifact.webPrecompiledAmdCanvaskitAndHtmlSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd-canvaskit-html', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledAmdSoundSdk: case HostArtifact.webPrecompiledAmdSoundSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd-sound', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledAmdCanvaskitSoundSdk: case HostArtifact.webPrecompiledAmdCanvaskitSoundSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd-canvaskit-sound', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledAmdCanvaskitAndHtmlSoundSdk: case HostArtifact.webPrecompiledAmdCanvaskitAndHtmlSoundSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'amd-canvaskit-html-sound', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledDdcSdk: case HostArtifact.webPrecompiledDdcSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'ddc', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledDdcCanvaskitSdk: case HostArtifact.webPrecompiledDdcCanvaskitSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'ddc-canvaskit', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledDdcCanvaskitAndHtmlSdk: case HostArtifact.webPrecompiledDdcCanvaskitAndHtmlSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'ddc-canvaskit-html', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledDdcSoundSdk: case HostArtifact.webPrecompiledDdcSoundSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'ddc-sound', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledDdcCanvaskitSoundSdk: case HostArtifact.webPrecompiledDdcCanvaskitSoundSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'ddc-canvaskit-sound', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.webPrecompiledDdcCanvaskitAndHtmlSoundSdk: case HostArtifact.webPrecompiledDdcCanvaskitAndHtmlSoundSdkSourcemaps: final String path = _fileSystem.path.join(_getFlutterWebSdkPath(), 'kernel', 'ddc-canvaskit-html-sound', _hostArtifactToFileName(artifact, _platform)); return _fileSystem.file(path); case HostArtifact.iosDeploy: case HostArtifact.idevicesyslog: case HostArtifact.idevicescreenshot: case HostArtifact.iproxy: case HostArtifact.skyEnginePath: case HostArtifact.impellerc: case HostArtifact.scenec: case HostArtifact.libtessellator: return _parent.getHostArtifact(artifact); } } String _getDartSdkPath() { // If we couldn't find a built dart sdk, let's look for a prebuilt one. final String prebuiltPath = _fileSystem.path.join(_getFlutterPrebuiltsPath(), _getPrebuiltTarget(), 'dart-sdk'); if (_fileSystem.isDirectorySync(prebuiltPath)) { return prebuiltPath; } throw ToolExit('Unable to find a prebuilt dart sdk at: "$prebuiltPath"'); } String _getFlutterPrebuiltsPath() { final String engineSrcPath = _fileSystem.path.dirname(_fileSystem.path.dirname(_webSdkPath)); return _fileSystem.path.join(engineSrcPath, 'flutter', 'prebuilts'); } String _getPrebuiltTarget() { final TargetPlatform hostPlatform = _currentHostPlatform(_platform, _operatingSystemUtils); switch (hostPlatform) { case TargetPlatform.darwin: return 'macos-x64'; case TargetPlatform.linux_arm64: return 'linux-arm64'; case TargetPlatform.linux_x64: return 'linux-x64'; case TargetPlatform.windows_x64: return 'windows-x64'; case TargetPlatform.windows_arm64: return 'windows-arm64'; case TargetPlatform.ios: case TargetPlatform.android: case TargetPlatform.android_arm: case TargetPlatform.android_arm64: case TargetPlatform.android_x64: case TargetPlatform.android_x86: case TargetPlatform.fuchsia_arm64: case TargetPlatform.fuchsia_x64: case TargetPlatform.web_javascript: case TargetPlatform.tester: throwToolExit('Unsupported host platform: $hostPlatform'); } } String _getFlutterWebSdkPath() { return _fileSystem.path.join(_webSdkPath, 'flutter_web_sdk'); } @override bool get isLocalEngine => _parent.isLocalEngine; @override LocalEngineInfo? get localEngineInfo => _parent.localEngineInfo; } /// An implementation of [Artifacts] that provides individual overrides. /// /// If an artifact is not provided, the lookup delegates to the parent. class OverrideArtifacts implements Artifacts { /// Creates a new [OverrideArtifacts]. /// /// [parent] must be provided. OverrideArtifacts({ required this.parent, this.frontendServer, this.engineDartBinary, this.platformKernelDill, this.flutterPatchedSdk, }); final Artifacts parent; final File? frontendServer; final File? engineDartBinary; final File? platformKernelDill; final File? flutterPatchedSdk; @override LocalEngineInfo? get localEngineInfo => parent.localEngineInfo; @override String getArtifactPath( Artifact artifact, { TargetPlatform? platform, BuildMode? mode, EnvironmentType? environmentType, }) { if (artifact == Artifact.engineDartBinary && engineDartBinary != null) { return engineDartBinary!.path; } if (artifact == Artifact.frontendServerSnapshotForEngineDartSdk && frontendServer != null) { return frontendServer!.path; } if (artifact == Artifact.platformKernelDill && platformKernelDill != null) { return platformKernelDill!.path; } if (artifact == Artifact.flutterPatchedSdkPath && flutterPatchedSdk != null) { return flutterPatchedSdk!.path; } return parent.getArtifactPath( artifact, platform: platform, mode: mode, environmentType: environmentType, ); } @override String getEngineType(TargetPlatform platform, [ BuildMode? mode ]) => parent.getEngineType(platform, mode); @override bool get isLocalEngine => parent.isLocalEngine; @override FileSystemEntity getHostArtifact(HostArtifact artifact) { return parent.getHostArtifact( artifact, ); } } /// Locate the Dart SDK. String _dartSdkPath(Cache cache) { return cache.getRoot().childDirectory('dart-sdk').path; } class _TestArtifacts implements Artifacts { _TestArtifacts(this.fileSystem); final FileSystem fileSystem; @override LocalEngineInfo? get localEngineInfo => null; @override String getArtifactPath( Artifact artifact, { TargetPlatform? platform, BuildMode? mode, EnvironmentType? environmentType, }) { // The path to file generators is the same even in the test environment. if (artifact == Artifact.flutterToolsFileGenerators) { return _getFileGeneratorsPath(); } final StringBuffer buffer = StringBuffer(); buffer.write(artifact); if (platform != null) { buffer.write('.$platform'); } if (mode != null) { buffer.write('.$mode'); } if (environmentType != null) { buffer.write('.$environmentType'); } return buffer.toString(); } @override String getEngineType(TargetPlatform platform, [ BuildMode? mode ]) { return 'test-engine'; } @override bool get isLocalEngine => false; @override FileSystemEntity getHostArtifact(HostArtifact artifact) { return fileSystem.file(artifact.toString()); } } class _TestLocalEngine extends _TestArtifacts { _TestLocalEngine( String engineOutPath, String engineHostOutPath, super.fileSystem, ) : localEngineInfo = LocalEngineInfo( targetOutPath: engineOutPath, hostOutPath: engineHostOutPath, ); @override bool get isLocalEngine => true; @override final LocalEngineInfo localEngineInfo; } String _getFileGeneratorsPath() { final String flutterRoot = Cache.defaultFlutterRoot( fileSystem: globals.localFileSystem, platform: const LocalPlatform(), userMessages: UserMessages(), ); return globals.localFileSystem.path.join( flutterRoot, 'packages', 'flutter_tools', 'lib', 'src', 'web', 'file_generators', ); }
flutter/packages/flutter_tools/lib/src/artifacts.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/artifacts.dart", "repo_id": "flutter", "token_count": 25051 }
747
// 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'; import 'package:meta/meta.dart'; import '../convert.dart'; import 'common.dart'; import 'io.dart'; import 'terminal.dart' show OutputPreferences, Terminal, TerminalColor; import 'utils.dart'; const int kDefaultStatusPadding = 59; /// A factory for generating [Stopwatch] instances for [Status] instances. class StopwatchFactory { /// const constructor so that subclasses may be const. const StopwatchFactory(); /// Create a new [Stopwatch] instance. /// /// The optional [name] parameter is useful in tests when there are multiple /// instances being created. Stopwatch createStopwatch([String name = '']) => Stopwatch(); } typedef VoidCallback = void Function(); abstract class Logger { /// Whether or not this logger should print [printTrace] messages. bool get isVerbose => false; /// If true, silences the logger output. bool quiet = false; /// If true, this logger supports ANSI sequences and animations are enabled. bool get supportsColor; /// If true, this logger is connected to a terminal. bool get hasTerminal; /// If true, then [printError] has been called at least once for this logger /// since the last time it was set to false. bool hadErrorOutput = false; /// If true, then [printWarning] has been called at least once with its /// "fatal" argument true for this logger /// since the last time it was reset to false. bool hadWarningOutput = false; /// Causes [checkForFatalLogs] to call [throwToolExit] when it is called if /// [hadWarningOutput] is true. bool fatalWarnings = false; /// Returns the terminal attached to this logger. Terminal get terminal; OutputPreferences get _outputPreferences; /// Display an error `message` to the user. Commands should use this if they /// fail in some way. Errors are typically followed shortly by a call to /// [throwToolExit] to terminate the run. /// /// The `message` argument is printed to the stderr in [TerminalColor.red] by /// default. /// /// The `stackTrace` argument is the stack trace that will be printed if /// supplied. /// /// The `emphasis` argument will cause the output message be printed in bold text. /// /// The `color` argument will print the message in the supplied color instead /// of the default of red. Colors will not be printed if the output terminal /// doesn't support them. /// /// The `indent` argument specifies the number of spaces to indent the overall /// message. If wrapping is enabled in [outputPreferences], then the wrapped /// lines will be indented as well. /// /// If `hangingIndent` is specified, then any wrapped lines will be indented /// by this much more than the first line, if wrapping is enabled in /// [outputPreferences]. /// /// If `wrap` is specified, then it overrides the /// `outputPreferences.wrapText` setting. void printError( String message, { StackTrace? stackTrace, bool? emphasis, TerminalColor? color, int? indent, int? hangingIndent, bool? wrap, }); /// Display a warning `message` to the user. Commands should use this if they /// important information to convey to the user that is not fatal. /// /// The `message` argument is printed to the stderr in [TerminalColor.cyan] by /// default. /// /// The `emphasis` argument will cause the output message be printed in bold text. /// /// The `color` argument will print the message in the supplied color instead /// of the default of cyan. Colors will not be printed if the output terminal /// doesn't support them. /// /// The `indent` argument specifies the number of spaces to indent the overall /// message. If wrapping is enabled in [outputPreferences], then the wrapped /// lines will be indented as well. /// /// If `hangingIndent` is specified, then any wrapped lines will be indented /// by this much more than the first line, if wrapping is enabled in /// [outputPreferences]. /// /// If `wrap` is specified, then it overrides the /// `outputPreferences.wrapText` setting. void printWarning( String message, { bool? emphasis, TerminalColor? color, int? indent, int? hangingIndent, bool? wrap, bool fatal = true, }); /// Display normal output of the command. This should be used for things like /// progress messages, success messages, or just normal command output. /// /// The `message` argument is printed to the stdout. /// /// The `stackTrace` argument is the stack trace that will be printed if /// supplied. /// /// If the `emphasis` argument is true, it will cause the output message be /// printed in bold text. Defaults to false. /// /// The `color` argument will print the message in the supplied color instead /// of the default of red. Colors will not be printed if the output terminal /// doesn't support them. /// /// If `newline` is true, then a newline will be added after printing the /// status. Defaults to true. /// /// The `indent` argument specifies the number of spaces to indent the overall /// message. If wrapping is enabled in [outputPreferences], then the wrapped /// lines will be indented as well. /// /// If `hangingIndent` is specified, then any wrapped lines will be indented /// by this much more than the first line, if wrapping is enabled in /// [outputPreferences]. /// /// If `wrap` is specified, then it overrides the /// `outputPreferences.wrapText` setting. void printStatus( String message, { bool? emphasis, TerminalColor? color, bool? newline, int? indent, int? hangingIndent, bool? wrap, }); /// Display the [message] inside a box. /// /// For example, this is the generated output: /// /// ┌─ [title] ─┐ /// │ [message] │ /// └───────────┘ /// /// If a terminal is attached, the lines in [message] are automatically wrapped based on /// the available columns. /// /// Use this utility only to highlight a message in the logs. /// /// This is particularly useful when the message can be easily missed because of clutter /// generated by other commands invoked by the tool. /// /// One common use case is to provide actionable steps in a Flutter app when a Gradle /// error is printed. /// /// In the future, this output can be integrated with an IDE like VS Code to display a /// notification, and allow the user to trigger an action. e.g. run a migration. void printBox( String message, { String? title, }); /// Use this for verbose tracing output. Users can turn this output on in order /// to help diagnose issues with the toolchain or with their setup. void printTrace(String message); /// Start an indeterminate progress display. /// /// The `message` argument is the message to display to the user. /// /// The `progressId` argument provides an ID that can be used to identify /// this type of progress (e.g. `hot.reload`, `hot.restart`). /// /// The `progressIndicatorPadding` can optionally be used to specify the width /// of the space into which the `message` is placed before the progress /// indicator, if any. It is ignored if the message is longer. Status startProgress( String message, { String? progressId, int progressIndicatorPadding = kDefaultStatusPadding, }); /// A [SilentStatus] or an [AnonymousSpinnerStatus] (depending on whether the /// terminal is fancy enough), already started. Status startSpinner({ VoidCallback? onFinish, Duration? timeout, SlowWarningCallback? slowWarningCallback, TerminalColor? warningColor, }); /// Send an event to be emitted. /// /// Only surfaces a value in machine modes, Loggers may ignore this message in /// non-machine modes. void sendEvent(String name, [Map<String, dynamic>? args]) { } /// Clears all output. void clear(); /// If [fatalWarnings] is set, causes the logger to check if /// [hadWarningOutput] is true, and then to call [throwToolExit] if so. /// /// The [fatalWarnings] flag can be set from the command line with the /// "--fatal-warnings" option on commands that support it. void checkForFatalLogs() { if (fatalWarnings && (hadWarningOutput || hadErrorOutput)) { throwToolExit('Logger received ${hadErrorOutput ? 'error' : 'warning'} output ' 'during the run, and "--fatal-warnings" is enabled.'); } } } /// A [Logger] that forwards all methods to another logger. /// /// Classes can derive from this to add functionality to an existing [Logger]. class DelegatingLogger implements Logger { @visibleForTesting @protected DelegatingLogger(this._delegate); final Logger _delegate; @override bool get quiet => _delegate.quiet; @override set quiet(bool value) => _delegate.quiet = value; @override bool get hasTerminal => _delegate.hasTerminal; @override Terminal get terminal => _delegate.terminal; @override OutputPreferences get _outputPreferences => _delegate._outputPreferences; @override bool get isVerbose => _delegate.isVerbose; @override bool get hadErrorOutput => _delegate.hadErrorOutput; @override set hadErrorOutput(bool value) => _delegate.hadErrorOutput = value; @override bool get hadWarningOutput => _delegate.hadWarningOutput; @override set hadWarningOutput(bool value) => _delegate.hadWarningOutput = value; @override bool get fatalWarnings => _delegate.fatalWarnings; @override set fatalWarnings(bool value) => _delegate.fatalWarnings = value; @override void printError(String message, { StackTrace? stackTrace, bool? emphasis, TerminalColor? color, int? indent, int? hangingIndent, bool? wrap, }) { _delegate.printError( message, stackTrace: stackTrace, emphasis: emphasis, color: color, indent: indent, hangingIndent: hangingIndent, wrap: wrap, ); } @override void printWarning(String message, { bool? emphasis, TerminalColor? color, int? indent, int? hangingIndent, bool? wrap, bool fatal = true, }) { _delegate.printWarning( message, emphasis: emphasis, color: color, indent: indent, hangingIndent: hangingIndent, wrap: wrap, fatal: fatal, ); } @override void printStatus(String message, { bool? emphasis, TerminalColor? color, bool? newline, int? indent, int? hangingIndent, bool? wrap, }) { _delegate.printStatus(message, emphasis: emphasis, color: color, newline: newline, indent: indent, hangingIndent: hangingIndent, wrap: wrap, ); } @override void printBox(String message, { String? title, }) { _delegate.printBox(message, title: title); } @override void printTrace(String message) { _delegate.printTrace(message); } @override void sendEvent(String name, [Map<String, dynamic>? args]) { _delegate.sendEvent(name, args); } @override Status startProgress(String message, { String? progressId, int progressIndicatorPadding = kDefaultStatusPadding, }) { return _delegate.startProgress(message, progressId: progressId, progressIndicatorPadding: progressIndicatorPadding, ); } @override Status startSpinner({ VoidCallback? onFinish, Duration? timeout, SlowWarningCallback? slowWarningCallback, TerminalColor? warningColor, }) { return _delegate.startSpinner( onFinish: onFinish, timeout: timeout, slowWarningCallback: slowWarningCallback, warningColor: warningColor, ); } @override bool get supportsColor => _delegate.supportsColor; @override void clear() => _delegate.clear(); @override void checkForFatalLogs() => _delegate.checkForFatalLogs(); } /// If [logger] is a [DelegatingLogger], walks the delegate chain and returns /// the first delegate with the matching type. /// /// Throws a [StateError] if no matching delegate is found. @override T asLogger<T extends Logger>(Logger logger) { final Logger original = logger; while (true) { if (logger is T) { return logger; } else if (logger is DelegatingLogger) { logger = logger._delegate; } else { throw StateError('$original has no ancestor delegate of type $T'); } } } class StdoutLogger extends Logger { StdoutLogger({ required this.terminal, required Stdio stdio, required OutputPreferences outputPreferences, StopwatchFactory stopwatchFactory = const StopwatchFactory(), }) : _stdio = stdio, _outputPreferences = outputPreferences, _stopwatchFactory = stopwatchFactory; @override final Terminal terminal; @override final OutputPreferences _outputPreferences; final Stdio _stdio; final StopwatchFactory _stopwatchFactory; Status? _status; @override bool get isVerbose => false; @override bool get supportsColor => terminal.supportsColor && terminal.isCliAnimationEnabled; @override bool get hasTerminal => _stdio.stdinHasTerminal; @override void printError( String message, { StackTrace? stackTrace, bool? emphasis, TerminalColor? color, int? indent, int? hangingIndent, bool? wrap, }) { hadErrorOutput = true; _status?.pause(); message = wrapText(message, indent: indent, hangingIndent: hangingIndent, shouldWrap: wrap ?? _outputPreferences.wrapText, columnWidth: _outputPreferences.wrapColumn, ); if (emphasis ?? false) { message = terminal.bolden(message); } message = terminal.color(message, color ?? TerminalColor.red); writeToStdErr('$message\n'); if (stackTrace != null) { writeToStdErr('$stackTrace\n'); } _status?.resume(); } @override void printWarning( String message, { bool? emphasis, TerminalColor? color, int? indent, int? hangingIndent, bool? wrap, bool fatal = true, }) { hadWarningOutput = hadWarningOutput || fatal; _status?.pause(); message = wrapText(message, indent: indent, hangingIndent: hangingIndent, shouldWrap: wrap ?? _outputPreferences.wrapText, columnWidth: _outputPreferences.wrapColumn, ); if (emphasis ?? false) { message = terminal.bolden(message); } message = terminal.color(message, color ?? TerminalColor.cyan); writeToStdErr('$message\n'); _status?.resume(); } @override void printStatus( String message, { bool? emphasis, TerminalColor? color, bool? newline, int? indent, int? hangingIndent, bool? wrap, }) { _status?.pause(); message = wrapText(message, indent: indent, hangingIndent: hangingIndent, shouldWrap: wrap ?? _outputPreferences.wrapText, columnWidth: _outputPreferences.wrapColumn, ); if (emphasis ?? false) { message = terminal.bolden(message); } if (color != null) { message = terminal.color(message, color); } if (newline ?? true) { message = '$message\n'; } writeToStdOut(message); _status?.resume(); } @override void printBox(String message, { String? title, }) { _status?.pause(); _generateBox( title: title, message: message, wrapColumn: _outputPreferences.wrapColumn, terminal: terminal, write: writeToStdOut, ); _status?.resume(); } @protected void writeToStdOut(String message) => _stdio.stdoutWrite(message); @protected void writeToStdErr(String message) => _stdio.stderrWrite(message); @override void printTrace(String message) { } @override Status startProgress( String message, { String? progressId, int progressIndicatorPadding = kDefaultStatusPadding, }) { if (_status != null) { // Ignore nested progresses; return a no-op status object. return SilentStatus( stopwatch: _stopwatchFactory.createStopwatch(), )..start(); } if (supportsColor) { _status = SpinnerStatus( message: message, padding: progressIndicatorPadding, onFinish: _clearStatus, stdio: _stdio, stopwatch: _stopwatchFactory.createStopwatch(), terminal: terminal, )..start(); } else { _status = SummaryStatus( message: message, padding: progressIndicatorPadding, onFinish: _clearStatus, stdio: _stdio, stopwatch: _stopwatchFactory.createStopwatch(), )..start(); } return _status!; } @override Status startSpinner({ VoidCallback? onFinish, Duration? timeout, SlowWarningCallback? slowWarningCallback, TerminalColor? warningColor, }) { if (_status != null || !supportsColor) { return SilentStatus( onFinish: onFinish, stopwatch: _stopwatchFactory.createStopwatch(), )..start(); } _status = AnonymousSpinnerStatus( onFinish: () { if (onFinish != null) { onFinish(); } _clearStatus(); }, stdio: _stdio, stopwatch: _stopwatchFactory.createStopwatch(), terminal: terminal, timeout: timeout, slowWarningCallback: slowWarningCallback, warningColor: warningColor, )..start(); return _status!; } void _clearStatus() { _status = null; } @override void sendEvent(String name, [Map<String, dynamic>? args]) { } @override void clear() { _status?.pause(); writeToStdOut('${terminal.clearScreen()}\n'); _status?.resume(); } } typedef _Writer = void Function(String message); /// Wraps the message in a box, and writes the bytes by calling [write]. /// /// Example output: /// /// ┌─ [title] ─┐ /// │ [message] │ /// └───────────┘ /// /// When [title] is provided, the box will have a title above it. /// /// The box width never exceeds [wrapColumn]. /// /// If [wrapColumn] is not provided, the default value is 100. void _generateBox({ required String message, required int wrapColumn, required _Writer write, required Terminal terminal, String? title, }) { const int kPaddingLeftRight = 1; const int kEdges = 2; final int maxTextWidthPerLine = wrapColumn - kEdges - kPaddingLeftRight * 2; final List<String> lines = wrapText(message, shouldWrap: true, columnWidth: maxTextWidthPerLine).split('\n'); final List<int> lineWidth = lines.map((String line) => _getColumnSize(line)).toList(); final int maxColumnSize = lineWidth.reduce((int currLen, int maxLen) => max(currLen, maxLen)); final int textWidth = min(maxColumnSize, maxTextWidthPerLine); final int textWithPaddingWidth = textWidth + kPaddingLeftRight * 2; write('\n'); // Write `┌─ [title] ─┐`. write('┌'); write('─'); if (title == null) { write('─' * (textWithPaddingWidth - 1)); } else { write(' ${terminal.bolden(title)} '); write('─' * (textWithPaddingWidth - title.length - 3)); } write('┐'); write('\n'); // Write `│ [message] │`. for (int lineIdx = 0; lineIdx < lines.length; lineIdx++) { write('│'); write(' ' * kPaddingLeftRight); write(lines[lineIdx]); final int remainingSpacesToEnd = textWidth - lineWidth[lineIdx]; write(' ' * (remainingSpacesToEnd + kPaddingLeftRight)); write('│'); write('\n'); } // Write `└───────────┘`. write('└'); write('─' * textWithPaddingWidth); write('┘'); write('\n'); } final RegExp _ansiEscapePattern = RegExp('\x1B\\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]'); int _getColumnSize(String line) { // Remove ANSI escape characters from the string. return line.replaceAll(_ansiEscapePattern, '').length; } /// A [StdoutLogger] which replaces Unicode characters that cannot be printed to /// the Windows console with alternative symbols. /// /// By default, Windows uses either "Consolas" or "Lucida Console" as fonts to /// render text in the console. Both fonts only have a limited character set. /// Unicode characters, that are not available in either of the two default /// fonts, should be replaced by this class with printable symbols. Otherwise, /// they will show up as the unrepresentable character symbol '�'. class WindowsStdoutLogger extends StdoutLogger { WindowsStdoutLogger({ required super.terminal, required super.stdio, required super.outputPreferences, super.stopwatchFactory, }); @override void writeToStdOut(String message) { final String windowsMessage = terminal.supportsEmoji ? message : message.replaceAll('🔥', '') .replaceAll('🖼️', '') .replaceAll('✗', 'X') .replaceAll('✓', '√') .replaceAll('🔨', '') .replaceAll('💪', '') .replaceAll('⚠️', '!') .replaceAll('✏️', ''); _stdio.stdoutWrite(windowsMessage); } } class BufferLogger extends Logger { BufferLogger({ required this.terminal, required OutputPreferences outputPreferences, StopwatchFactory stopwatchFactory = const StopwatchFactory(), bool verbose = false, }) : _outputPreferences = outputPreferences, _stopwatchFactory = stopwatchFactory, _verbose = verbose; /// Create a [BufferLogger] with test preferences. BufferLogger.test({ Terminal? terminal, OutputPreferences? outputPreferences, bool verbose = false, }) : terminal = terminal ?? Terminal.test(), _outputPreferences = outputPreferences ?? OutputPreferences.test(), _stopwatchFactory = const StopwatchFactory(), _verbose = verbose; @override final OutputPreferences _outputPreferences; @override final Terminal terminal; final StopwatchFactory _stopwatchFactory; final bool _verbose; @override bool get isVerbose => _verbose; @override bool get supportsColor => terminal.supportsColor && terminal.isCliAnimationEnabled; final StringBuffer _error = StringBuffer(); final StringBuffer _warning = StringBuffer(); final StringBuffer _status = StringBuffer(); final StringBuffer _trace = StringBuffer(); final StringBuffer _events = StringBuffer(); String get errorText => _error.toString(); String get warningText => _warning.toString(); String get statusText => _status.toString(); String get traceText => _trace.toString(); String get eventText => _events.toString(); @override bool get hasTerminal => false; @override void printError( String message, { StackTrace? stackTrace, bool? emphasis, TerminalColor? color, int? indent, int? hangingIndent, bool? wrap, }) { hadErrorOutput = true; final StringBuffer errorMessage = StringBuffer(); errorMessage.write(message); if (stackTrace != null) { errorMessage.writeln(); errorMessage.write(stackTrace); } _error.writeln(terminal.color( wrapText(errorMessage.toString(), indent: indent, hangingIndent: hangingIndent, shouldWrap: wrap ?? _outputPreferences.wrapText, columnWidth: _outputPreferences.wrapColumn, ), color ?? TerminalColor.red, )); } @override void printWarning( String message, { bool? emphasis, TerminalColor? color, int? indent, int? hangingIndent, bool? wrap, bool fatal = true, }) { hadWarningOutput = hadWarningOutput || fatal; _warning.writeln(terminal.color( wrapText(message, indent: indent, hangingIndent: hangingIndent, shouldWrap: wrap ?? _outputPreferences.wrapText, columnWidth: _outputPreferences.wrapColumn, ), color ?? TerminalColor.cyan, )); } @override void printStatus( String message, { bool? emphasis, TerminalColor? color, bool? newline, int? indent, int? hangingIndent, bool? wrap, }) { if (newline ?? true) { _status.writeln(wrapText(message, indent: indent, hangingIndent: hangingIndent, shouldWrap: wrap ?? _outputPreferences.wrapText, columnWidth: _outputPreferences.wrapColumn, )); } else { _status.write(wrapText(message, indent: indent, hangingIndent: hangingIndent, shouldWrap: wrap ?? _outputPreferences.wrapText, columnWidth: _outputPreferences.wrapColumn, )); } } @override void printBox(String message, { String? title, }) { _generateBox( title: title, message: message, wrapColumn: _outputPreferences.wrapColumn, terminal: terminal, write: _status.write, ); } @override void printTrace(String message) => _trace.writeln(message); @override Status startProgress( String message, { String? progressId, int progressIndicatorPadding = kDefaultStatusPadding, }) { printStatus(message); return SilentStatus( stopwatch: _stopwatchFactory.createStopwatch(), )..start(); } @override Status startSpinner({ VoidCallback? onFinish, Duration? timeout, SlowWarningCallback? slowWarningCallback, TerminalColor? warningColor, }) { return SilentStatus( stopwatch: _stopwatchFactory.createStopwatch(), onFinish: onFinish, )..start(); } @override void clear() { _error.clear(); _status.clear(); _trace.clear(); _events.clear(); } @override void sendEvent(String name, [Map<String, dynamic>? args]) { _events.write(json.encode(<String, Object?>{ 'name': name, 'args': args, })); } } class VerboseLogger extends DelegatingLogger { VerboseLogger(super.parent, { StopwatchFactory stopwatchFactory = const StopwatchFactory() }) : _stopwatch = stopwatchFactory.createStopwatch(), _stopwatchFactory = stopwatchFactory { _stopwatch.start(); } final Stopwatch _stopwatch; final StopwatchFactory _stopwatchFactory; @override bool get isVerbose => true; @override void printError( String message, { StackTrace? stackTrace, bool? emphasis, TerminalColor? color, int? indent, int? hangingIndent, bool? wrap, }) { hadErrorOutput = true; _emit( _LogType.error, wrapText(message, indent: indent, hangingIndent: hangingIndent, shouldWrap: wrap ?? _outputPreferences.wrapText, columnWidth: _outputPreferences.wrapColumn, ), stackTrace, ); } @override void printWarning( String message, { StackTrace? stackTrace, bool? emphasis, TerminalColor? color, int? indent, int? hangingIndent, bool? wrap, bool fatal = true, }) { hadWarningOutput = true; _emit( _LogType.warning, wrapText(message, indent: indent, hangingIndent: hangingIndent, shouldWrap: wrap ?? _outputPreferences.wrapText, columnWidth: _outputPreferences.wrapColumn, ), stackTrace, ); } @override void printStatus( String message, { bool? emphasis, TerminalColor? color, bool? newline, int? indent, int? hangingIndent, bool? wrap, }) { _emit(_LogType.status, wrapText(message, indent: indent, hangingIndent: hangingIndent, shouldWrap: wrap ?? _outputPreferences.wrapText, columnWidth: _outputPreferences.wrapColumn, )); } @override void printBox(String message, { String? title, }) { String composedMessage = ''; _generateBox( title: title, message: message, wrapColumn: _outputPreferences.wrapColumn, terminal: terminal, write: (String line) { composedMessage += line; }, ); _emit(_LogType.status, composedMessage); } @override void printTrace(String message) { _emit(_LogType.trace, message); } @override Status startProgress( String message, { String? progressId, int progressIndicatorPadding = kDefaultStatusPadding, }) { printStatus(message); final Stopwatch timer = _stopwatchFactory.createStopwatch()..start(); return SilentStatus( // This is intentionally a different stopwatch than above. stopwatch: _stopwatchFactory.createStopwatch(), onFinish: () { String time; if (timer.elapsed.inSeconds > 2) { time = getElapsedAsSeconds(timer.elapsed); } else { time = getElapsedAsMilliseconds(timer.elapsed); } printTrace('$message (completed in $time)'); }, )..start(); } void _emit(_LogType type, String message, [ StackTrace? stackTrace ]) { if (message.trim().isEmpty) { return; } final int millis = _stopwatch.elapsedMilliseconds; _stopwatch.reset(); String prefix; const int prefixWidth = 8; if (millis == 0) { prefix = ''.padLeft(prefixWidth); } else { prefix = '+$millis ms'.padLeft(prefixWidth); if (millis >= 100) { prefix = terminal.bolden(prefix); } } prefix = '[$prefix] '; final String indent = ''.padLeft(prefix.length); final String indentMessage = message.replaceAll('\n', '\n$indent'); switch (type) { case _LogType.error: super.printError(prefix + terminal.bolden(indentMessage)); if (stackTrace != null) { super.printError(indent + stackTrace.toString().replaceAll('\n', '\n$indent')); } case _LogType.warning: super.printWarning(prefix + terminal.bolden(indentMessage)); case _LogType.status: super.printStatus(prefix + terminal.bolden(indentMessage)); case _LogType.trace: // This seems wrong, since there is a 'printTrace' to call on the // superclass, but it's actually the entire point of this logger: to // make things more verbose than they normally would be. super.printStatus(prefix + indentMessage); } } @override void sendEvent(String name, [Map<String, dynamic>? args]) { } } class PrefixedErrorLogger extends DelegatingLogger { PrefixedErrorLogger(super.parent); @override void printError( String message, { StackTrace? stackTrace, bool? emphasis, TerminalColor? color, int? indent, int? hangingIndent, bool? wrap, }) { hadErrorOutput = true; if (message.trim().isNotEmpty) { message = 'ERROR: $message'; } super.printError( message, stackTrace: stackTrace, emphasis: emphasis, color: color, indent: indent, hangingIndent: hangingIndent, wrap: wrap, ); } } enum _LogType { error, warning, status, trace } typedef SlowWarningCallback = String Function(); /// A [Status] class begins when start is called, and may produce progress /// information asynchronously. /// /// The [SilentStatus] class never has any output. /// /// The [SpinnerStatus] subclass shows a message with a spinner, and replaces it /// with timing information when stopped. When canceled, the information isn't /// shown. In either case, a newline is printed. /// /// The [AnonymousSpinnerStatus] subclass just shows a spinner. /// /// The [SummaryStatus] subclass shows only a static message (without an /// indicator), then updates it when the operation ends. /// /// Generally, consider `logger.startProgress` instead of directly creating /// a [Status] or one of its subclasses. abstract class Status { Status({ this.onFinish, required Stopwatch stopwatch, this.timeout, }) : _stopwatch = stopwatch; final VoidCallback? onFinish; final Duration? timeout; @protected final Stopwatch _stopwatch; @protected String get elapsedTime { if (_stopwatch.elapsed.inSeconds > 2) { return getElapsedAsSeconds(_stopwatch.elapsed); } return getElapsedAsMilliseconds(_stopwatch.elapsed); } @visibleForTesting bool get seemsSlow => timeout != null && _stopwatch.elapsed > timeout!; /// Call to start spinning. void start() { assert(!_stopwatch.isRunning); _stopwatch.start(); } /// Call to stop spinning after success. void stop() { finish(); } /// Call to cancel the spinner after failure or cancellation. void cancel() { finish(); } /// Call to clear the current line but not end the progress. void pause() { } /// Call to resume after a pause. void resume() { } @protected void finish() { assert(_stopwatch.isRunning); _stopwatch.stop(); onFinish?.call(); } } /// A [Status] that shows nothing. class SilentStatus extends Status { SilentStatus({ required super.stopwatch, super.onFinish, }); @override void finish() { onFinish?.call(); } } const int _kTimePadding = 8; // should fit "99,999ms" /// Constructor writes [message] to [stdout]. On [cancel] or [stop], will call /// [onFinish]. On [stop], will additionally print out summary information. class SummaryStatus extends Status { SummaryStatus({ this.message = '', required super.stopwatch, this.padding = kDefaultStatusPadding, super.onFinish, required Stdio stdio, }) : _stdio = stdio; final String message; final int padding; final Stdio _stdio; bool _messageShowingOnCurrentLine = false; @override void start() { _printMessage(); super.start(); } void _writeToStdOut(String message) => _stdio.stdoutWrite(message); void _printMessage() { assert(!_messageShowingOnCurrentLine); _writeToStdOut('${message.padRight(padding)} '); _messageShowingOnCurrentLine = true; } @override void stop() { if (!_messageShowingOnCurrentLine) { _printMessage(); } super.stop(); assert(_messageShowingOnCurrentLine); _writeToStdOut(elapsedTime.padLeft(_kTimePadding)); _writeToStdOut('\n'); } @override void cancel() { super.cancel(); if (_messageShowingOnCurrentLine) { _writeToStdOut('\n'); } } @override void pause() { super.pause(); if (_messageShowingOnCurrentLine) { _writeToStdOut('\n'); _messageShowingOnCurrentLine = false; } } } /// A kind of animated [Status] that has no message. /// /// Call [pause] before outputting any text while this is running. class AnonymousSpinnerStatus extends Status { AnonymousSpinnerStatus({ super.onFinish, required super.stopwatch, required Stdio stdio, required Terminal terminal, this.slowWarningCallback, this.warningColor, super.timeout, }) : _stdio = stdio, _terminal = terminal, _animation = _selectAnimation(terminal); final Stdio _stdio; final Terminal _terminal; String _slowWarning = ''; final SlowWarningCallback? slowWarningCallback; final TerminalColor? warningColor; static const String _backspaceChar = '\b'; static const String _clearChar = ' '; static const List<String> _emojiAnimations = <String>[ '⣾⣽⣻⢿⡿⣟⣯⣷', // counter-clockwise '⣾⣷⣯⣟⡿⢿⣻⣽', // clockwise '⣾⣷⣯⣟⡿⢿⣻⣽⣷⣾⣽⣻⢿⡿⣟⣯⣷', // bouncing clockwise and counter-clockwise '⣾⣷⣯⣽⣻⣟⡿⢿⣻⣟⣯⣽', // snaking '⣾⣽⣻⢿⣿⣷⣯⣟⡿⣿', // alternating rain '⣀⣠⣤⣦⣶⣾⣿⡿⠿⠻⠛⠋⠉⠙⠛⠟⠿⢿⣿⣷⣶⣴⣤⣄', // crawl up and down, large '⠙⠚⠖⠦⢤⣠⣄⡤⠴⠲⠓⠋', // crawl up and down, small '⣀⡠⠤⠔⠒⠊⠉⠑⠒⠢⠤⢄', // crawl up and down, tiny '⡀⣄⣦⢷⠻⠙⠈⠀⠁⠋⠟⡾⣴⣠⢀⠀', // slide up and down '⠙⠸⢰⣠⣄⡆⠇⠋', // clockwise line '⠁⠈⠐⠠⢀⡀⠄⠂', // clockwise dot '⢇⢣⢱⡸⡜⡎', // vertical wobble up '⡇⡎⡜⡸⢸⢱⢣⢇', // vertical wobble down '⡀⣀⣐⣒⣖⣶⣾⣿⢿⠿⠯⠭⠩⠉⠁⠀', // swirl '⠁⠐⠄⢀⢈⢂⢠⣀⣁⣐⣄⣌⣆⣤⣥⣴⣼⣶⣷⣿⣾⣶⣦⣤⣠⣀⡀⠀⠀', // snowing and melting '⠁⠋⠞⡴⣠⢀⠀⠈⠙⠻⢷⣦⣄⡀⠀⠉⠛⠲⢤⢀⠀', // falling water '⠄⡢⢑⠈⠀⢀⣠⣤⡶⠞⠋⠁⠀⠈⠙⠳⣆⡀⠀⠆⡷⣹⢈⠀⠐⠪⢅⡀⠀', // fireworks '⠐⢐⢒⣒⣲⣶⣷⣿⡿⡷⡧⠧⠇⠃⠁⠀⡀⡠⡡⡱⣱⣳⣷⣿⢿⢯⢧⠧⠣⠃⠂⠀⠈⠨⠸⠺⡺⡾⡿⣿⡿⡷⡗⡇⡅⡄⠄⠀⡀⡐⣐⣒⣓⣳⣻⣿⣾⣼⡼⡸⡘⡈⠈⠀', // fade '⢸⡯⠭⠅⢸⣇⣀⡀⢸⣇⣸⡇⠈⢹⡏⠁⠈⢹⡏⠁⢸⣯⣭⡅⢸⡯⢕⡂⠀⠀', // text crawl ]; static const List<String> _asciiAnimations = <String>[ r'-\|/', ]; static List<String> _selectAnimation(Terminal terminal) { final List<String> animations = terminal.supportsEmoji ? _emojiAnimations : _asciiAnimations; return animations[terminal.preferredStyle % animations.length] .runes .map<String>((int scalar) => String.fromCharCode(scalar)) .toList(); } final List<String> _animation; Timer? timer; int ticks = 0; int _lastAnimationFrameLength = 0; bool timedOut = false; String get _currentAnimationFrame => _animation[ticks % _animation.length]; int get _currentLineLength => _lastAnimationFrameLength + _slowWarning.length; void _writeToStdOut(String message) => _stdio.stdoutWrite(message); void _clear(int length) { _writeToStdOut( '${_backspaceChar * length}' '${_clearChar * length}' '${_backspaceChar * length}' ); } @override void start() { super.start(); assert(timer == null); _startSpinner(); } void _startSpinner() { timer = Timer.periodic(const Duration(milliseconds: 100), _callback); _callback(timer!); } void _callback(Timer timer) { assert(this.timer == timer); assert(timer.isActive); _writeToStdOut(_backspaceChar * _lastAnimationFrameLength); ticks += 1; if (seemsSlow) { if (!timedOut) { timedOut = true; if (_currentLineLength > _lastAnimationFrameLength) { _clear(_currentLineLength - _lastAnimationFrameLength); } } final SlowWarningCallback? callback = slowWarningCallback; if (_slowWarning.isEmpty && callback != null) { final TerminalColor? color = warningColor; if (color != null) { _slowWarning = _terminal.color(callback(), color); } else { _slowWarning = callback(); } _writeToStdOut(_slowWarning); } } final String newFrame = _currentAnimationFrame; _lastAnimationFrameLength = newFrame.runes.length; _writeToStdOut(newFrame); } @override void pause() { assert(timer != null); assert(timer!.isActive); if (_terminal.supportsColor) { _writeToStdOut('\r\x1B[K'); // go to start of line and clear line } else { _clear(_currentLineLength); } _lastAnimationFrameLength = 0; timer?.cancel(); } @override void resume() { assert(timer != null); assert(!timer!.isActive); _startSpinner(); } @override void finish() { assert(timer != null); assert(timer!.isActive); timer?.cancel(); timer = null; _clear(_lastAnimationFrameLength + _slowWarning.length); _slowWarning = ''; _lastAnimationFrameLength = 0; super.finish(); } } /// An animated version of [Status]. /// /// The constructor writes [message] to [stdout] with padding, then starts an /// indeterminate progress indicator animation. /// /// On [cancel] or [stop], will call [onFinish]. On [stop], will /// additionally print out summary information. /// /// Call [pause] before outputting any text while this is running. class SpinnerStatus extends AnonymousSpinnerStatus { SpinnerStatus({ required this.message, this.padding = kDefaultStatusPadding, super.onFinish, required super.stopwatch, required super.stdio, required super.terminal, }); final String message; final int padding; static final String _margin = AnonymousSpinnerStatus._clearChar * (5 + _kTimePadding - 1); int _totalMessageLength = 0; @override int get _currentLineLength => _totalMessageLength + super._currentLineLength; @override void start() { _printStatus(); super.start(); } void _printStatus() { final String line = '${message.padRight(padding)}$_margin'; _totalMessageLength = line.length; _writeToStdOut(line); } @override void pause() { super.pause(); _totalMessageLength = 0; } @override void resume() { _printStatus(); super.resume(); } @override void stop() { super.stop(); // calls finish, which clears the spinner assert(_totalMessageLength > _kTimePadding); _writeToStdOut(AnonymousSpinnerStatus._backspaceChar * (_kTimePadding - 1)); _writeToStdOut(elapsedTime.padLeft(_kTimePadding)); _writeToStdOut('\n'); } @override void cancel() { super.cancel(); // calls finish, which clears the spinner assert(_totalMessageLength > 0); _writeToStdOut('\n'); } }
flutter/packages/flutter_tools/lib/src/base/logger.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/base/logger.dart", "repo_id": "flutter", "token_count": 15087 }
748
// 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:package_config/package_config_types.dart'; import 'artifacts.dart'; import 'base/config.dart'; import 'base/file_system.dart'; import 'base/logger.dart'; import 'base/os.dart'; import 'base/utils.dart'; import 'convert.dart'; import 'globals.dart' as globals; /// Whether icon font subsetting is enabled by default. const bool kIconTreeShakerEnabledDefault = true; /// Information about a build to be performed or used. class BuildInfo { const BuildInfo( this.mode, this.flavor, { this.trackWidgetCreation = false, this.frontendServerStarterPath, List<String>? extraFrontEndOptions, List<String>? extraGenSnapshotOptions, List<String>? fileSystemRoots, this.androidProjectArgs = const <String>[], this.fileSystemScheme, this.buildNumber, this.buildName, this.splitDebugInfoPath, this.dartObfuscation = false, List<String>? dartDefines, this.bundleSkSLPath, List<String>? dartExperiments, required this.treeShakeIcons, this.performanceMeasurementFile, this.packagesPath = '.dart_tool/package_config.json', // TODO(zanderso): make this required and remove the default. this.nullSafetyMode = NullSafetyMode.sound, this.codeSizeDirectory, this.androidGradleDaemon = true, this.androidSkipBuildDependencyValidation = false, this.packageConfig = PackageConfig.empty, this.initializeFromDill, this.assumeInitializeFromDillUpToDate = false, this.buildNativeAssets = true, }) : extraFrontEndOptions = extraFrontEndOptions ?? const <String>[], extraGenSnapshotOptions = extraGenSnapshotOptions ?? const <String>[], fileSystemRoots = fileSystemRoots ?? const <String>[], dartDefines = dartDefines ?? const <String>[], dartExperiments = dartExperiments ?? const <String>[]; final BuildMode mode; /// The null safety mode the application should be run in. /// /// If not provided, defaults to [NullSafetyMode.autodetect]. final NullSafetyMode nullSafetyMode; /// Whether the build should subset icon fonts. final bool treeShakeIcons; /// Represents a custom Android product flavor or an Xcode scheme, null for /// using the default. /// /// If not null, the Gradle build task will be `assembleFlavorMode` (e.g. /// `assemblePaidRelease`), and the Xcode build configuration will be /// Mode-Flavor (e.g. Release-Paid). final String? flavor; /// The path to the package configuration file to use for compilation. /// /// This is used by package:package_config to locate the actual package_config.json /// file. If not provided, defaults to `.dart_tool/package_config.json`. final String packagesPath; final List<String> fileSystemRoots; final String? fileSystemScheme; /// Whether the build should track widget creation locations. final bool trackWidgetCreation; /// If provided, the frontend server will be started in JIT mode from this /// file. final String? frontendServerStarterPath; /// Extra command-line options for front-end. final List<String> extraFrontEndOptions; /// Extra command-line options for gen_snapshot. final List<String> extraGenSnapshotOptions; /// Internal version number (not displayed to users). /// Each build must have a unique number to differentiate it from previous builds. /// It is used to determine whether one build is more recent than another, with higher numbers indicating more recent build. /// On Android it is used as versionCode. /// On Xcode builds it is used as CFBundleVersion. /// On Windows it is used as the build suffix for the product and file versions. final String? buildNumber; /// A "x.y.z" string used as the version number shown to users. /// For each new version of your app, you will provide a version number to differentiate it from previous versions. /// On Android it is used as versionName. /// On Xcode builds it is used as CFBundleShortVersionString. /// On Windows it is used as the major, minor, and patch parts of the product and file versions. final String? buildName; /// An optional directory path to save debugging information from dwarf stack /// traces. If null, stack trace information is not stripped from the /// executable. final String? splitDebugInfoPath; /// Whether to apply dart source code obfuscation. final bool dartObfuscation; /// An optional path to a JSON containing object SkSL shaders. /// /// Currently this is only supported for Android builds. final String? bundleSkSLPath; /// Additional constant values to be made available in the Dart program. /// /// These values can be used with the const `fromEnvironment` constructors of /// [bool], [String], [int], and [double]. final List<String> dartDefines; /// A list of Dart experiments. final List<String> dartExperiments; /// The name of a file where flutter assemble will output performance /// information in a JSON format. /// /// This is not considered a build input and will not force assemble to /// rerun tasks. final String? performanceMeasurementFile; /// If provided, an output directory where one or more v8-style heap snapshots /// will be written for code size profiling. final String? codeSizeDirectory; /// Whether to enable the Gradle daemon when performing an Android build. /// /// Starting the daemon is the default behavior of the gradle wrapper script created /// in a Flutter project. Setting this value to false will cause the tool to pass /// `--no-daemon` to the gradle wrapper script, preventing it from spawning a daemon /// process. /// /// For one-off builds or CI systems, preventing the daemon from spawning will /// reduce system resource usage, at the cost of any subsequent builds starting /// up slightly slower. /// /// The Gradle daemon may also be disabled in the Android application's properties file. final bool androidGradleDaemon; /// Whether to skip checking of individual versions of our Android build time /// dependencies. final bool androidSkipBuildDependencyValidation; /// Additional key value pairs that are passed directly to the gradle project via the `-P` /// flag. final List<String> androidProjectArgs; /// The package configuration for the loaded application. /// /// This is captured once during startup, but the actual package configuration /// may change during a 'flutter run` workflow. final PackageConfig packageConfig; /// The kernel file that the resident compiler will be initialized with. /// /// If this is null, it will be initialized from the default cached location. final String? initializeFromDill; /// If set, assumes that the file passed in [initializeFromDill] is up to date /// and skips the check and potential invalidation of files. final bool assumeInitializeFromDillUpToDate; /// If set, builds native assets with `build.dart` from all packages. final bool buildNativeAssets; static const BuildInfo debug = BuildInfo(BuildMode.debug, null, trackWidgetCreation: true, treeShakeIcons: false); static const BuildInfo profile = BuildInfo(BuildMode.profile, null, treeShakeIcons: kIconTreeShakerEnabledDefault); static const BuildInfo jitRelease = BuildInfo(BuildMode.jitRelease, null, treeShakeIcons: kIconTreeShakerEnabledDefault); static const BuildInfo release = BuildInfo(BuildMode.release, null, treeShakeIcons: kIconTreeShakerEnabledDefault); /// Returns whether a debug build is requested. /// /// Exactly one of [isDebug], [isProfile], or [isRelease] is true. bool get isDebug => mode == BuildMode.debug; /// Returns whether a profile build is requested. /// /// Exactly one of [isDebug], [isProfile], [isJitRelease], /// or [isRelease] is true. bool get isProfile => mode == BuildMode.profile; /// Returns whether a release build is requested. /// /// Exactly one of [isDebug], [isProfile], [isJitRelease], /// or [isRelease] is true. bool get isRelease => mode == BuildMode.release; /// Returns whether a JIT release build is requested. /// /// Exactly one of [isDebug], [isProfile], [isJitRelease], /// or [isRelease] is true. bool get isJitRelease => mode == BuildMode.jitRelease; bool get usesAot => isAotBuildMode(mode); bool get supportsEmulator => isEmulatorBuildMode(mode); bool get supportsSimulator => isEmulatorBuildMode(mode); String get modeName => mode.cliName; String get friendlyModeName => getFriendlyModeName(mode); /// the flavor name in the output apk files is lower-cased (see Flutter Gradle Plugin), /// so the lower cased flavor name is used to compute the output file name String? get lowerCasedFlavor => flavor?.toLowerCase(); /// the flavor name in the output bundle files has the first character lower-cased, /// so the uncapitalized flavor name is used to compute the output file name String? get uncapitalizedFlavor => _uncapitalize(flavor); /// The module system DDC is targeting, or null if not using DDC. // TODO(markzipan): delete this when DDC's AMD module system is deprecated, https://github.com/flutter/flutter/issues/142060. DdcModuleFormat? get ddcModuleFormat => _ddcModuleFormatFromFrontEndArgs(extraFrontEndOptions); /// Convert to a structured string encoded structure appropriate for usage /// in build system [Environment.defines]. /// /// Fields that are `null` are excluded from this configuration. Map<String, String> toBuildSystemEnvironment() { // packagesPath and performanceMeasurementFile are not passed into // the Environment map. return <String, String>{ kBuildMode: mode.cliName, if (dartDefines.isNotEmpty) kDartDefines: encodeDartDefines(dartDefines), kDartObfuscation: dartObfuscation.toString(), if (frontendServerStarterPath != null) kFrontendServerStarterPath: frontendServerStarterPath!, if (extraFrontEndOptions.isNotEmpty) kExtraFrontEndOptions: extraFrontEndOptions.join(','), if (extraGenSnapshotOptions.isNotEmpty) kExtraGenSnapshotOptions: extraGenSnapshotOptions.join(','), if (splitDebugInfoPath != null) kSplitDebugInfo: splitDebugInfoPath!, kTrackWidgetCreation: trackWidgetCreation.toString(), kIconTreeShakerFlag: treeShakeIcons.toString(), if (bundleSkSLPath != null) kBundleSkSLPath: bundleSkSLPath!, if (codeSizeDirectory != null) kCodeSizeDirectory: codeSizeDirectory!, if (fileSystemRoots.isNotEmpty) kFileSystemRoots: fileSystemRoots.join(','), if (fileSystemScheme != null) kFileSystemScheme: fileSystemScheme!, if (buildName != null) kBuildName: buildName!, if (buildNumber != null) kBuildNumber: buildNumber!, }; } /// Convert to a structured string encoded structure appropriate for usage as /// environment variables or to embed in other scripts. /// /// Fields that are `null` are excluded from this configuration. Map<String, String> toEnvironmentConfig() { return <String, String>{ if (dartDefines.isNotEmpty) 'DART_DEFINES': encodeDartDefines(dartDefines), 'DART_OBFUSCATION': dartObfuscation.toString(), if (frontendServerStarterPath != null) 'FRONTEND_SERVER_STARTER_PATH': frontendServerStarterPath!, if (extraFrontEndOptions.isNotEmpty) 'EXTRA_FRONT_END_OPTIONS': extraFrontEndOptions.join(','), if (extraGenSnapshotOptions.isNotEmpty) 'EXTRA_GEN_SNAPSHOT_OPTIONS': extraGenSnapshotOptions.join(','), if (splitDebugInfoPath != null) 'SPLIT_DEBUG_INFO': splitDebugInfoPath!, 'TRACK_WIDGET_CREATION': trackWidgetCreation.toString(), 'TREE_SHAKE_ICONS': treeShakeIcons.toString(), if (performanceMeasurementFile != null) 'PERFORMANCE_MEASUREMENT_FILE': performanceMeasurementFile!, if (bundleSkSLPath != null) 'BUNDLE_SKSL_PATH': bundleSkSLPath!, 'PACKAGE_CONFIG': packagesPath, if (codeSizeDirectory != null) 'CODE_SIZE_DIRECTORY': codeSizeDirectory!, if (flavor != null) 'FLAVOR': flavor!, }; } /// Convert this config to a series of project level arguments to be passed /// on the command line to gradle. List<String> toGradleConfig() { // PACKAGE_CONFIG not currently supported. return <String>[ if (dartDefines.isNotEmpty) '-Pdart-defines=${encodeDartDefines(dartDefines)}', '-Pdart-obfuscation=$dartObfuscation', if (frontendServerStarterPath != null) '-Pfrontend-server-starter-path=$frontendServerStarterPath', if (extraFrontEndOptions.isNotEmpty) '-Pextra-front-end-options=${extraFrontEndOptions.join(',')}', if (extraGenSnapshotOptions.isNotEmpty) '-Pextra-gen-snapshot-options=${extraGenSnapshotOptions.join(',')}', if (splitDebugInfoPath != null) '-Psplit-debug-info=$splitDebugInfoPath', '-Ptrack-widget-creation=$trackWidgetCreation', '-Ptree-shake-icons=$treeShakeIcons', if (performanceMeasurementFile != null) '-Pperformance-measurement-file=$performanceMeasurementFile', if (bundleSkSLPath != null) '-Pbundle-sksl-path=$bundleSkSLPath', if (codeSizeDirectory != null) '-Pcode-size-directory=$codeSizeDirectory', for (final String projectArg in androidProjectArgs) '-P$projectArg', ]; } } /// Information about an Android build to be performed or used. class AndroidBuildInfo { const AndroidBuildInfo( this.buildInfo, { this.targetArchs = const <AndroidArch>[ AndroidArch.armeabi_v7a, AndroidArch.arm64_v8a, AndroidArch.x86_64, ], this.splitPerAbi = false, this.fastStart = false, }); // The build info containing the mode and flavor. final BuildInfo buildInfo; /// Whether to split the shared library per ABI. /// /// When this is false, multiple ABIs will be contained within one primary /// build artifact. When this is true, multiple build artifacts (one per ABI) /// will be produced. final bool splitPerAbi; /// The target platforms for the build. final Iterable<AndroidArch> targetArchs; /// Whether to bootstrap an empty application. final bool fastStart; } /// A summary of the compilation strategy used for Dart. enum BuildMode { /// Built in JIT mode with no optimizations, enabled asserts, and a VM service. debug, /// Built in AOT mode with some optimizations and a VM service. profile, /// Built in AOT mode with all optimizations and no VM service. release, /// Built in JIT mode with all optimizations and no VM service. jitRelease; factory BuildMode.fromCliName(String value) => values.singleWhere( (BuildMode element) => element.cliName == value, orElse: () => throw ArgumentError('$value is not a supported build mode'), ); static const Set<BuildMode> releaseModes = <BuildMode>{ release, jitRelease, }; static const Set<BuildMode> jitModes = <BuildMode>{ debug, jitRelease, }; /// Whether this mode is considered release. /// /// Useful for determining whether we should enable/disable asserts or /// other development features. bool get isRelease => releaseModes.contains(this); /// Whether this mode is using the JIT runtime. bool get isJit => jitModes.contains(this); /// Whether this mode is using the precompiled runtime. bool get isPrecompiled => !isJit; String get cliName => snakeCase(name); @override String toString() => cliName; } /// Environment type of the target device. enum EnvironmentType { physical, simulator, } String? validatedBuildNumberForPlatform(TargetPlatform targetPlatform, String? buildNumber, Logger logger) { if (buildNumber == null) { return null; } if (targetPlatform == TargetPlatform.ios || targetPlatform == TargetPlatform.darwin) { // See CFBundleVersion at https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html final RegExp disallowed = RegExp(r'[^\d\.]'); String tmpBuildNumber = buildNumber.replaceAll(disallowed, ''); if (tmpBuildNumber.isEmpty) { return null; } final List<String> segments = tmpBuildNumber .split('.') .where((String segment) => segment.isNotEmpty) .toList(); if (segments.isEmpty) { segments.add('0'); } tmpBuildNumber = segments.join('.'); if (tmpBuildNumber != buildNumber) { logger.printTrace('Invalid build-number: $buildNumber for iOS/macOS, overridden by $tmpBuildNumber.\n' 'See CFBundleVersion at https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html'); } return tmpBuildNumber; } if (targetPlatform == TargetPlatform.android_arm || targetPlatform == TargetPlatform.android_arm64 || targetPlatform == TargetPlatform.android_x64 || targetPlatform == TargetPlatform.android_x86) { // See versionCode at https://developer.android.com/studio/publish/versioning final RegExp disallowed = RegExp(r'[^\d]'); String tmpBuildNumberStr = buildNumber.replaceAll(disallowed, ''); int tmpBuildNumberInt = int.tryParse(tmpBuildNumberStr) ?? 0; if (tmpBuildNumberInt < 1) { tmpBuildNumberInt = 1; } tmpBuildNumberStr = tmpBuildNumberInt.toString(); if (tmpBuildNumberStr != buildNumber) { logger.printTrace('Invalid build-number: $buildNumber for Android, overridden by $tmpBuildNumberStr.\n' 'See versionCode at https://developer.android.com/studio/publish/versioning'); } return tmpBuildNumberStr; } return buildNumber; } String? validatedBuildNameForPlatform(TargetPlatform targetPlatform, String? buildName, Logger logger) { if (buildName == null) { return null; } if (targetPlatform == TargetPlatform.ios || targetPlatform == TargetPlatform.darwin) { // See CFBundleShortVersionString at https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html final RegExp disallowed = RegExp(r'[^\d\.]'); String tmpBuildName = buildName.replaceAll(disallowed, ''); if (tmpBuildName.isEmpty) { return null; } final List<String> segments = tmpBuildName .split('.') .where((String segment) => segment.isNotEmpty) .toList(); while (segments.length < 3) { segments.add('0'); } tmpBuildName = segments.join('.'); if (tmpBuildName != buildName) { logger.printTrace('Invalid build-name: $buildName for iOS/macOS, overridden by $tmpBuildName.\n' 'See CFBundleShortVersionString at https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html'); } return tmpBuildName; } if (targetPlatform == TargetPlatform.android || targetPlatform == TargetPlatform.android_arm || targetPlatform == TargetPlatform.android_arm64 || targetPlatform == TargetPlatform.android_x64 || targetPlatform == TargetPlatform.android_x86) { // See versionName at https://developer.android.com/studio/publish/versioning return buildName; } return buildName; } String getFriendlyModeName(BuildMode mode) { return snakeCase(mode.cliName).replaceAll('_', ' '); } // Returns true if the selected build mode uses ahead-of-time compilation. bool isAotBuildMode(BuildMode mode) { return mode == BuildMode.profile || mode == BuildMode.release; } // Returns true if the given build mode can be used on emulators / simulators. bool isEmulatorBuildMode(BuildMode mode) { return mode == BuildMode.debug; } enum TargetPlatform { android, ios, darwin, linux_x64, linux_arm64, windows_x64, windows_arm64, fuchsia_arm64, fuchsia_x64, tester, web_javascript, // The arch specific android target platforms are soft-deprecated. // Instead of using TargetPlatform as a combination arch + platform // the code will be updated to carry arch information in [DarwinArch] // and [AndroidArch]. android_arm, android_arm64, android_x64, android_x86; String get fuchsiaArchForTargetPlatform { switch (this) { case TargetPlatform.fuchsia_arm64: return 'arm64'; case TargetPlatform.fuchsia_x64: return 'x64'; case TargetPlatform.android: case TargetPlatform.android_arm: case TargetPlatform.android_arm64: case TargetPlatform.android_x64: case TargetPlatform.android_x86: case TargetPlatform.darwin: case TargetPlatform.ios: case TargetPlatform.linux_arm64: case TargetPlatform.linux_x64: case TargetPlatform.tester: case TargetPlatform.web_javascript: case TargetPlatform.windows_x64: case TargetPlatform.windows_arm64: throw UnsupportedError('Unexpected Fuchsia platform $this'); } } String get simpleName { switch (this) { case TargetPlatform.linux_x64: case TargetPlatform.darwin: case TargetPlatform.windows_x64: return 'x64'; case TargetPlatform.linux_arm64: case TargetPlatform.windows_arm64: return 'arm64'; case TargetPlatform.android: case TargetPlatform.android_arm: case TargetPlatform.android_arm64: case TargetPlatform.android_x64: case TargetPlatform.android_x86: case TargetPlatform.fuchsia_arm64: case TargetPlatform.fuchsia_x64: case TargetPlatform.ios: case TargetPlatform.tester: case TargetPlatform.web_javascript: throw UnsupportedError('Unexpected target platform $this'); } } } /// iOS and macOS target device architecture. // // TODO(cbracken): split TargetPlatform.ios into ios_armv7, ios_arm64. enum DarwinArch { armv7, // Deprecated. Used to display 32-bit unsupported devices. arm64, x86_64; /// Returns the Dart SDK's name for the specified target architecture. /// /// When building for Darwin platforms, the tool invokes architecture-specific /// variants of `gen_snapshot`, one for each target architecture. The output /// instructions are then built into architecture-specific binaries, which are /// merged into a universal binary using the `lipo` tool. String get dartName { return switch (this) { DarwinArch.armv7 => 'armv7', DarwinArch.arm64 => 'arm64', DarwinArch.x86_64 => 'x64' }; } } // TODO(zanderso): replace all android TargetPlatform usage with AndroidArch. enum AndroidArch { armeabi_v7a, arm64_v8a, x86, x86_64; String get archName { return switch (this) { AndroidArch.armeabi_v7a => 'armeabi-v7a', AndroidArch.arm64_v8a => 'arm64-v8a', AndroidArch.x86_64 => 'x86_64', AndroidArch.x86 => 'x86' }; } String get platformName { return switch (this) { AndroidArch.armeabi_v7a => 'android-arm', AndroidArch.arm64_v8a => 'android-arm64', AndroidArch.x86_64 => 'android-x64', AndroidArch.x86 => 'android-x86' }; } } /// The default set of iOS device architectures to build for. List<DarwinArch> defaultIOSArchsForEnvironment( EnvironmentType environmentType, Artifacts artifacts, ) { // Handle single-arch local engines. final LocalEngineInfo? localEngineInfo = artifacts.localEngineInfo; if (localEngineInfo != null) { final String localEngineName = localEngineInfo.localTargetName; if (localEngineName.contains('_arm64')) { return <DarwinArch>[ DarwinArch.arm64 ]; } if (localEngineName.contains('_sim')) { return <DarwinArch>[ DarwinArch.x86_64 ]; } } else if (environmentType == EnvironmentType.simulator) { return <DarwinArch>[ DarwinArch.x86_64, DarwinArch.arm64, ]; } return <DarwinArch>[ DarwinArch.arm64, ]; } /// The default set of macOS device architectures to build for. List<DarwinArch> defaultMacOSArchsForEnvironment(Artifacts artifacts) { // Handle single-arch local engines. final LocalEngineInfo? localEngineInfo = artifacts.localEngineInfo; if (localEngineInfo != null) { if (localEngineInfo.localTargetName.contains('_arm64')) { return <DarwinArch>[ DarwinArch.arm64 ]; } return <DarwinArch>[ DarwinArch.x86_64 ]; } return <DarwinArch>[ DarwinArch.x86_64, DarwinArch.arm64, ]; } DarwinArch getIOSArchForName(String arch) { switch (arch) { case 'armv7': case 'armv7f': // iPhone 4S. case 'armv7s': // iPad 4. return DarwinArch.armv7; case 'arm64': case 'arm64e': // iPhone XS/XS Max/XR and higher. arm64 runs on arm64e devices. return DarwinArch.arm64; case 'x86_64': return DarwinArch.x86_64; } throw Exception('Unsupported iOS arch name "$arch"'); } DarwinArch getDarwinArchForName(String arch) { switch (arch) { case 'arm64': return DarwinArch.arm64; case 'x86_64': return DarwinArch.x86_64; } throw Exception('Unsupported MacOS arch name "$arch"'); } String getNameForTargetPlatform(TargetPlatform platform, {DarwinArch? darwinArch}) { switch (platform) { case TargetPlatform.android_arm: return 'android-arm'; case TargetPlatform.android_arm64: return 'android-arm64'; case TargetPlatform.android_x64: return 'android-x64'; case TargetPlatform.android_x86: return 'android-x86'; case TargetPlatform.ios: if (darwinArch != null) { return 'ios-${darwinArch.name}'; } return 'ios'; case TargetPlatform.darwin: if (darwinArch != null) { return 'darwin-${darwinArch.name}'; } return 'darwin'; case TargetPlatform.linux_x64: return 'linux-x64'; case TargetPlatform.linux_arm64: return 'linux-arm64'; case TargetPlatform.windows_x64: return 'windows-x64'; case TargetPlatform.windows_arm64: return 'windows-arm64'; case TargetPlatform.fuchsia_arm64: return 'fuchsia-arm64'; case TargetPlatform.fuchsia_x64: return 'fuchsia-x64'; case TargetPlatform.tester: return 'flutter-tester'; case TargetPlatform.web_javascript: return 'web-javascript'; case TargetPlatform.android: return 'android'; } } TargetPlatform getTargetPlatformForName(String platform) { switch (platform) { case 'android': return TargetPlatform.android; case 'android-arm': return TargetPlatform.android_arm; case 'android-arm64': return TargetPlatform.android_arm64; case 'android-x64': return TargetPlatform.android_x64; case 'android-x86': return TargetPlatform.android_x86; case 'fuchsia-arm64': return TargetPlatform.fuchsia_arm64; case 'fuchsia-x64': return TargetPlatform.fuchsia_x64; case 'ios': return TargetPlatform.ios; case 'darwin': // For backward-compatibility and also for Tester, where it must match // host platform name (HostPlatform.darwin_x64) case 'darwin-x64': case 'darwin-arm64': return TargetPlatform.darwin; case 'linux-x64': return TargetPlatform.linux_x64; case 'linux-arm64': return TargetPlatform.linux_arm64; case 'windows-x64': return TargetPlatform.windows_x64; case 'windows-arm64': return TargetPlatform.windows_arm64; case 'web-javascript': return TargetPlatform.web_javascript; case 'flutter-tester': return TargetPlatform.tester; } throw Exception('Unsupported platform name "$platform"'); } AndroidArch getAndroidArchForName(String platform) { switch (platform) { case 'android-arm': return AndroidArch.armeabi_v7a; case 'android-arm64': return AndroidArch.arm64_v8a; case 'android-x64': return AndroidArch.x86_64; case 'android-x86': return AndroidArch.x86; } throw Exception('Unsupported Android arch name "$platform"'); } HostPlatform getCurrentHostPlatform() { if (globals.platform.isMacOS) { return HostPlatform.darwin_x64; } if (globals.platform.isLinux) { // support x64 and arm64 architecture. return globals.os.hostPlatform; } if (globals.platform.isWindows) { return HostPlatform.windows_x64; } globals.printWarning('Unsupported host platform, defaulting to Linux'); return HostPlatform.linux_x64; } /// Returns the top-level build output directory. String getBuildDirectory([Config? config, FileSystem? fileSystem]) { // TODO(andrewkolos): Prefer required parameters instead of falling back to globals. // TODO(johnmccutchan): Stop calling this function as part of setting // up command line argument processing. final Config localConfig = config ?? globals.config; final FileSystem localFilesystem = fileSystem ?? globals.fs; final String buildDir = localConfig.getValue('build-dir') as String? ?? 'build'; if (localFilesystem.path.isAbsolute(buildDir)) { throw Exception( 'build-dir config setting in ${globals.config.configPath} must be relative'); } return buildDir; } /// Returns the Android build output directory. String getAndroidBuildDirectory() { // TODO(cbracken): move to android subdir. return getBuildDirectory(); } /// Returns the AOT build output directory. String getAotBuildDirectory() { return globals.fs.path.join(getBuildDirectory(), 'aot'); } /// Returns the asset build output directory. String getAssetBuildDirectory([Config? config, FileSystem? fileSystem]) { return (fileSystem ?? globals.fs) .path.join(getBuildDirectory(config, fileSystem), 'flutter_assets'); } /// Returns the iOS build output directory. String getIosBuildDirectory() { return globals.fs.path.join(getBuildDirectory(), 'ios'); } /// Returns the macOS build output directory. String getMacOSBuildDirectory() { return globals.fs.path.join(getBuildDirectory(), 'macos'); } /// Returns the web build output directory. String getWebBuildDirectory() { return globals.fs.path.join(getBuildDirectory(), 'web'); } /// Returns the Linux build output directory. String getLinuxBuildDirectory([TargetPlatform? targetPlatform]) { final String arch = (targetPlatform == null) ? _getCurrentHostPlatformArchName() : targetPlatform.simpleName; final String subDirs = 'linux/$arch'; return globals.fs.path.join(getBuildDirectory(), subDirs); } /// Returns the Windows build output directory. String getWindowsBuildDirectory(TargetPlatform targetPlatform) { final String arch = targetPlatform.simpleName; return globals.fs.path.join(getBuildDirectory(), 'windows', arch); } /// Returns the Fuchsia build output directory. String getFuchsiaBuildDirectory() { return globals.fs.path.join(getBuildDirectory(), 'fuchsia'); } /// Defines specified via the `--dart-define` command-line option. /// /// These values are URI-encoded and then combined into a comma-separated string. const String kDartDefines = 'DartDefines'; /// The define to pass a [BuildMode]. const String kBuildMode = 'BuildMode'; /// The define to pass whether we compile 64-bit android-arm code. const String kTargetPlatform = 'TargetPlatform'; /// The define to control what target file is used. const String kTargetFile = 'TargetFile'; /// Whether to enable or disable track widget creation. const String kTrackWidgetCreation = 'TrackWidgetCreation'; /// If provided, the frontend server will be started in JIT mode from this file. const String kFrontendServerStarterPath = 'FrontendServerStarterPath'; /// Additional configuration passed to the dart front end. /// /// This is expected to be a comma separated list of strings. const String kExtraFrontEndOptions = 'ExtraFrontEndOptions'; /// Additional configuration passed to gen_snapshot. /// /// This is expected to be a comma separated list of strings. const String kExtraGenSnapshotOptions = 'ExtraGenSnapshotOptions'; /// Whether the build should run gen_snapshot as a split aot build for deferred /// components. const String kDeferredComponents = 'DeferredComponents'; /// Whether to strip source code information out of release builds and where to save it. const String kSplitDebugInfo = 'SplitDebugInfo'; /// Alternative scheme for file URIs. /// /// May be used along with [kFileSystemRoots] to support a multi-root /// filesystem. const String kFileSystemScheme = 'FileSystemScheme'; /// Additional filesystem roots. /// /// If provided, must be used along with [kFileSystemScheme]. const String kFileSystemRoots = 'FileSystemRoots'; /// The define to control what iOS architectures are built for. /// /// This is expected to be a space-delimited list of architectures. If not /// provided, defaults to arm64. const String kIosArchs = 'IosArchs'; /// The define to control what macOS architectures are built for. /// /// This is expected to be a space-delimited list of architectures. If not /// provided, defaults to x86_64 and arm64. /// /// Supported values are x86_64 and arm64. const String kDarwinArchs = 'DarwinArchs'; /// The define to control what Android architectures are built for. /// /// This is expected to be a space-delimited list of architectures. const String kAndroidArchs = 'AndroidArchs'; /// The define to control what min Android SDK version is built for. /// /// This is expected to be int. /// /// If not provided, defaults to `minSdkVersion` from gradle_utils.dart. /// /// This is passed in by flutter.groovy's invocation of `flutter assemble`. /// /// For more info, see: /// https://developer.android.com/ndk/guides/sdk-versions#minsdkversion /// https://developer.android.com/ndk/guides/other_build_systems#overview const String kMinSdkVersion = 'MinSdkVersion'; /// Path to the SDK root to be used as the isysroot. const String kSdkRoot = 'SdkRoot'; /// Whether to enable Dart obfuscation and where to save the symbol map. const String kDartObfuscation = 'DartObfuscation'; /// Whether to enable Native Assets. /// /// If true, native assets are built and the mapping for native assets lookup /// at runtime is embedded in the kernel file. /// /// If false, native assets are not built, and an empty mapping is embedded in /// the kernel file. Used for targets that trigger kernel builds but /// are not OS/architecture specific. /// /// Supported values are 'true' and 'false'. /// /// Defaults to 'true'. const String kNativeAssets = 'NativeAssets'; /// An output directory where one or more code-size measurements may be written. const String kCodeSizeDirectory = 'CodeSizeDirectory'; /// SHA identifier of the Apple developer code signing identity. /// /// Same as EXPANDED_CODE_SIGN_IDENTITY Xcode build setting. /// Also discoverable via `security find-identity -p codesigning`. const String kCodesignIdentity = 'CodesignIdentity'; /// The build define controlling whether icon fonts should be stripped down to /// only the glyphs used by the application. const String kIconTreeShakerFlag = 'TreeShakeIcons'; /// The input key for an SkSL bundle path. const String kBundleSkSLPath = 'BundleSkSLPath'; /// The define to pass build name const String kBuildName = 'BuildName'; /// The app flavor to build. const String kFlavor = 'Flavor'; /// The define to pass build number const String kBuildNumber = 'BuildNumber'; /// The action Xcode is taking. /// /// Will be "build" when building and "install" when archiving. const String kXcodeAction = 'Action'; final Converter<String, String> _defineEncoder = utf8.encoder.fuse(base64.encoder); final Converter<String, String> _defineDecoder = base64.decoder.fuse(utf8.decoder); /// Encode a List of dart defines in a base64 string. /// /// This encoding does not include `,`, which is used to distinguish /// the individual entries, nor does it include `%` which is often a /// control character on windows command lines. /// /// When decoding this string, it can be safely split on commas, since any /// user provided commands will still be encoded. /// /// If the presence of the `/` character ends up being an issue, this can /// be changed to use base32 instead. String encodeDartDefines(List<String> defines) { return defines.map(_defineEncoder.convert).join(','); } List<String> decodeCommaSeparated(Map<String, String> environmentDefines, String key) { if (!environmentDefines.containsKey(key) || environmentDefines[key]!.isEmpty) { return <String>[]; } return environmentDefines[key]! .split(',') .cast<String>() .toList(); } /// Dart defines are encoded inside [environmentDefines] as a comma-separated list. List<String> decodeDartDefines(Map<String, String> environmentDefines, String key) { if (!environmentDefines.containsKey(key) || environmentDefines[key]!.isEmpty) { return <String>[]; } return environmentDefines[key]! .split(',') .map<Object>(_defineDecoder.convert) .cast<String>() .toList(); } /// The null safety runtime mode the app should be built in. enum NullSafetyMode { sound, unsound, /// The null safety mode was not detected. Only supported for 'flutter test'. autodetect, } /// Indicates the module system DDC is targeting. enum DdcModuleFormat { amd, ddc, } // TODO(markzipan): delete this when DDC's AMD module system is deprecated, https://github.com/flutter/flutter/issues/142060. DdcModuleFormat? _ddcModuleFormatFromFrontEndArgs(List<String>? extraFrontEndArgs) { if (extraFrontEndArgs == null) { return null; } const String ddcModuleFormatString = '--dartdevc-module-format='; for (final String flag in extraFrontEndArgs) { if (flag.startsWith(ddcModuleFormatString)) { final String moduleFormatString = flag .substring(ddcModuleFormatString.length, flag.length); return DdcModuleFormat.values.byName(moduleFormatString); } } return null; } String _getCurrentHostPlatformArchName() { final HostPlatform hostPlatform = getCurrentHostPlatform(); return hostPlatform.platformName; } String? _uncapitalize(String? s) { if (s == null || s.isEmpty) { return s; } return s.substring(0, 1).toLowerCase() + s.substring(1); }
flutter/packages/flutter_tools/lib/src/build_info.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/build_info.dart", "repo_id": "flutter", "token_count": 12342 }
749
// 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 '../../convert.dart'; import '../../devfs.dart'; import '../../project.dart'; import '../build_system.dart'; import '../depfile.dart'; import '../exceptions.dart'; import 'assets.dart'; import 'common.dart'; import 'desktop.dart'; import 'icon_tree_shaker.dart'; /// The only files/subdirectories we care out. const List<String> _kLinuxArtifacts = <String>[ 'libflutter_linux_gtk.so', ]; const String _kLinuxDepfile = 'linux_engine_sources.d'; /// Copies the Linux desktop embedding files to the copy directory. class UnpackLinux extends Target { const UnpackLinux(this.targetPlatform); final TargetPlatform targetPlatform; @override String get name => 'unpack_linux'; @override List<Source> get inputs => const <Source>[ Source.pattern('{FLUTTER_ROOT}/packages/flutter_tools/lib/src/build_system/targets/linux.dart'), ]; @override List<Source> get outputs => const <Source>[]; @override List<String> get depfiles => const <String>[_kLinuxDepfile]; @override List<Target> get dependencies => <Target>[]; @override Future<void> build(Environment environment) async { final String? buildModeEnvironment = environment.defines[kBuildMode]; if (buildModeEnvironment == null) { throw MissingDefineException(kBuildMode, name); } final BuildMode buildMode = BuildMode.fromCliName(buildModeEnvironment); final String engineSourcePath = environment.artifacts .getArtifactPath( Artifact.linuxDesktopPath, mode: buildMode, platform: targetPlatform, ); final String headersPath = environment.artifacts .getArtifactPath( Artifact.linuxHeaders, mode: buildMode, platform: targetPlatform, ); final Directory outputDirectory = environment.fileSystem.directory( environment.fileSystem.path.join( environment.projectDir.path, 'linux', 'flutter', 'ephemeral', )); final Depfile depfile = unpackDesktopArtifacts( fileSystem: environment.fileSystem, engineSourcePath: engineSourcePath, outputDirectory: outputDirectory, artifacts: _kLinuxArtifacts, clientSourcePaths: <String>[headersPath], icuDataPath: environment.artifacts.getArtifactPath( Artifact.icuData, platform: targetPlatform, ) ); environment.depFileService.writeToFile( depfile, environment.buildDir.childFile(_kLinuxDepfile), ); } } /// Creates a bundle for the Linux desktop target. abstract class BundleLinuxAssets extends Target { const BundleLinuxAssets(this.targetPlatform); final TargetPlatform targetPlatform; @override List<Target> get dependencies => <Target>[ const KernelSnapshot(), UnpackLinux(targetPlatform), ]; @override List<Source> get inputs => const <Source>[ Source.pattern('{FLUTTER_ROOT}/packages/flutter_tools/lib/src/build_system/targets/linux.dart'), Source.pattern('{PROJECT_DIR}/pubspec.yaml'), ...IconTreeShaker.inputs, ]; @override List<String> get depfiles => const <String>[ 'flutter_assets.d', ]; @override Future<void> build(Environment environment) async { final String? buildModeEnvironment = environment.defines[kBuildMode]; if (buildModeEnvironment == null) { throw MissingDefineException(kBuildMode, 'bundle_linux_assets'); } final BuildMode buildMode = BuildMode.fromCliName(buildModeEnvironment); final Directory outputDirectory = environment.outputDir .childDirectory('flutter_assets'); if (!outputDirectory.existsSync()) { outputDirectory.createSync(); } // Only copy the kernel blob in debug mode. if (buildMode == BuildMode.debug) { environment.buildDir.childFile('app.dill') .copySync(outputDirectory.childFile('kernel_blob.bin').path); } final String versionInfo = getVersionInfo(environment.defines); final Depfile depfile = await copyAssets( environment, outputDirectory, targetPlatform: targetPlatform, additionalContent: <String, DevFSContent>{ 'version.json': DevFSStringContent(versionInfo), }, ); environment.depFileService.writeToFile( depfile, environment.buildDir.childFile('flutter_assets.d'), ); } /// Return json encoded string that contains data about version for package_info String getVersionInfo(Map<String, String> defines) { final Map<String, dynamic> versionInfo = jsonDecode(FlutterProject.current().getVersionInfo()) as Map<String, dynamic>; if (defines.containsKey(kBuildNumber)) { versionInfo['build_number'] = defines[kBuildNumber]; } if (defines.containsKey(kBuildName)) { versionInfo['version'] = defines[kBuildName]; } return jsonEncode(versionInfo); } } /// A wrapper for AOT compilation that copies app.so into the output directory. class LinuxAotBundle extends Target { /// Create a [LinuxAotBundle] wrapper for [aotTarget]. const LinuxAotBundle(this.aotTarget); /// The [AotElfBase] subclass that produces the app.so. final AotElfBase aotTarget; @override String get name => 'linux_aot_bundle'; @override List<Source> get inputs => const <Source>[ Source.pattern('{BUILD_DIR}/app.so'), ]; @override List<Source> get outputs => const <Source>[ Source.pattern('{OUTPUT_DIR}/lib/libapp.so'), ]; @override List<Target> get dependencies => <Target>[ aotTarget, ]; @override Future<void> build(Environment environment) async { final File outputFile = environment.buildDir.childFile('app.so'); final Directory outputDirectory = environment.outputDir.childDirectory('lib'); if (!outputDirectory.existsSync()) { outputDirectory.createSync(recursive: true); } outputFile.copySync(outputDirectory.childFile('libapp.so').path); } } class DebugBundleLinuxAssets extends BundleLinuxAssets { const DebugBundleLinuxAssets(super.targetPlatform); @override String get name => 'debug_bundle_${getNameForTargetPlatform(targetPlatform)}_assets'; @override List<Source> get inputs => <Source>[ const Source.pattern('{BUILD_DIR}/app.dill'), ]; @override List<Source> get outputs => <Source>[ const Source.pattern('{OUTPUT_DIR}/flutter_assets/kernel_blob.bin'), ]; } class ProfileBundleLinuxAssets extends BundleLinuxAssets { const ProfileBundleLinuxAssets(super.targetPlatform); @override String get name => 'profile_bundle_${getNameForTargetPlatform(targetPlatform)}_assets'; @override List<Source> get outputs => const <Source>[]; @override List<Target> get dependencies => <Target>[ ...super.dependencies, LinuxAotBundle(AotElfProfile(targetPlatform)), ]; } class ReleaseBundleLinuxAssets extends BundleLinuxAssets { const ReleaseBundleLinuxAssets(super.targetPlatform); @override String get name => 'release_bundle_${getNameForTargetPlatform(targetPlatform)}_assets'; @override List<Source> get outputs => const <Source>[]; @override List<Target> get dependencies => <Target>[ ...super.dependencies, LinuxAotBundle(AotElfRelease(targetPlatform)), ]; }
flutter/packages/flutter_tools/lib/src/build_system/targets/linux.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/build_system/targets/linux.dart", "repo_id": "flutter", "token_count": 2509 }
750
// 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/file_system.dart'; import '../base/io.dart'; import '../base/logger.dart'; import '../dart/analysis.dart'; import 'analyze_base.dart'; class AnalyzeContinuously extends AnalyzeBase { AnalyzeContinuously( super.argResults, List<Directory> repoPackages, { required super.fileSystem, required super.logger, required super.terminal, required super.platform, required super.processManager, required super.artifacts, required super.suppressAnalytics, }) : super( repoPackages: repoPackages, ); String? analysisTarget; bool firstAnalysis = true; Set<String> analyzedPaths = <String>{}; Map<String, List<AnalysisError>> analysisErrors = <String, List<AnalysisError>>{}; final Stopwatch analysisTimer = Stopwatch(); int lastErrorCount = 0; Status? analysisStatus; @override Future<void> analyze() async { List<String> directories; if (isFlutterRepo) { final PackageDependencyTracker dependencies = PackageDependencyTracker(); dependencies.checkForConflictingDependencies(repoPackages, dependencies); directories = <String>[flutterRoot]; analysisTarget = 'Flutter repository'; logger.printTrace('Analyzing Flutter repository:'); } else { directories = <String>[fileSystem.currentDirectory.path]; analysisTarget = fileSystem.currentDirectory.path; } final AnalysisServer server = AnalysisServer( sdkPath, directories, fileSystem: fileSystem, logger: logger, platform: platform, processManager: processManager, terminal: terminal, protocolTrafficLog: protocolTrafficLog, suppressAnalytics: suppressAnalytics, ); server.onAnalyzing.listen((bool isAnalyzing) => _handleAnalysisStatus(server, isAnalyzing)); server.onErrors.listen(_handleAnalysisErrors); await server.start(); final int? exitCode = await server.onExit; final String message = 'Analysis server exited with code $exitCode.'; if (exitCode != 0) { throwToolExit(message, exitCode: exitCode); } logger.printStatus(message); if (server.didServerErrorOccur) { throwToolExit('Server error(s) occurred.'); } } void _handleAnalysisStatus(AnalysisServer server, bool isAnalyzing) { if (isAnalyzing) { analysisStatus?.cancel(); if (!firstAnalysis) { logger.printStatus('\n'); } analysisStatus = logger.startProgress('Analyzing $analysisTarget...'); analyzedPaths.clear(); analysisTimer.start(); } else { analysisStatus?.stop(); analysisStatus = null; analysisTimer.stop(); logger.printStatus(terminal.clearScreen(), newline: false); // Remove errors for deleted files, sort, and print errors. final List<AnalysisError> sortedErrors = <AnalysisError>[]; final List<String> pathsToRemove = <String>[]; analysisErrors.forEach((String path, List<AnalysisError> errors) { if (fileSystem.isFileSync(path)) { sortedErrors.addAll(errors); } else { pathsToRemove.add(path); } }); analysisErrors.removeWhere((String path, _) => pathsToRemove.contains(path)); sortedErrors.sort(); for (final AnalysisError error in sortedErrors) { logger.printStatus(error.toString()); logger.printTrace('error code: ${error.code}'); } dumpErrors(sortedErrors.map<String>((AnalysisError error) => error.toLegacyString())); final int issueCount = sortedErrors.length; final int issueDiff = issueCount - lastErrorCount; lastErrorCount = issueCount; final String seconds = (analysisTimer.elapsedMilliseconds / 1000.0).toStringAsFixed(2); final String errorsMessage = AnalyzeBase.generateErrorsMessage( issueCount: issueCount, issueDiff: issueDiff, files: analyzedPaths.length, seconds: seconds, ); logger.printStatus(errorsMessage); if (firstAnalysis && isBenchmarking) { writeBenchmark(analysisTimer, issueCount); server.dispose().whenComplete(() { exit(issueCount > 0 ? 1 : 0); }); } firstAnalysis = false; } } void _handleAnalysisErrors(FileAnalysisErrors fileErrors) { fileErrors.errors.removeWhere((AnalysisError error) => error.type == 'TODO'); analyzedPaths.add(fileErrors.file); analysisErrors[fileErrors.file] = fileErrors.errors; } }
flutter/packages/flutter_tools/lib/src/commands/analyze_continuously.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/commands/analyze_continuously.dart", "repo_id": "flutter", "token_count": 1655 }
751
// 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/file_system.dart'; import '../base/utils.dart'; import '../build_info.dart'; import '../features.dart'; import '../globals.dart' as globals; import '../project.dart'; import '../runner/flutter_command.dart' show DevelopmentArtifact, FlutterCommandResult, FlutterOptions; import '../web/compile.dart'; import '../web/file_generators/flutter_service_worker_js.dart'; import '../web/web_constants.dart'; import '../web_template.dart'; import 'build.dart'; class BuildWebCommand extends BuildSubCommand { BuildWebCommand({ required super.logger, required FileSystem fileSystem, required bool verboseHelp, }) : _fileSystem = fileSystem, super(verboseHelp: verboseHelp) { addTreeShakeIconsFlag(); usesTargetOption(); usesOutputDir(); usesPubOption(); usesBuildNumberOption(); usesBuildNameOption(); addBuildModeFlags(verboseHelp: verboseHelp, excludeDebug: true); usesDartDefineOption(); addEnableExperimentation(hide: !verboseHelp); addNullSafetyModeOptions(hide: !verboseHelp); addNativeNullAssertions(); // // Flutter web-specific options // argParser.addSeparator('Flutter web options'); argParser.addOption('base-href', help: 'Overrides the href attribute of the <base> tag in web/index.html. ' 'No change is done to web/index.html file if this flag is not provided. ' 'The value has to start and end with a slash "/". ' 'For more information: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base' ); argParser.addOption( 'pwa-strategy', defaultsTo: ServiceWorkerStrategy.offlineFirst.cliName, help: 'The caching strategy to be used by the PWA service worker.', allowed: ServiceWorkerStrategy.values.map((ServiceWorkerStrategy e) => e.cliName), allowedHelp: CliEnum.allowedHelp(ServiceWorkerStrategy.values), ); usesWebRendererOption(); usesWebResourcesCdnFlag(); // // Common compilation options among JavaScript and Wasm // argParser.addOption( 'optimization-level', abbr: 'O', help: 'Sets the optimization level used for Dart compilation to JavaScript/Wasm.', defaultsTo: '${WebCompilerConfig.kDefaultOptimizationLevel}', allowed: const <String>['1', '2', '3', '4'], ); // // JavaScript compilation options // argParser.addSeparator('JavaScript compilation options'); argParser.addFlag('csp', negatable: false, help: 'Disable dynamic generation of code in the generated output. ' 'This is necessary to satisfy CSP restrictions (see http://www.w3.org/TR/CSP/).' ); argParser.addFlag( 'source-maps', help: 'Generate a sourcemap file. These can be used by browsers ' 'to view and debug the original source code of a compiled and minified Dart ' 'application.' ); argParser.addOption('dart2js-optimization', help: 'Sets the optimization level used for Dart compilation to JavaScript. ' 'Deprecated: Please use "-O=<level>" / "--optimization-level=<level>".', allowed: const <String>['O1', 'O2', 'O3', 'O4'], ); argParser.addFlag('dump-info', negatable: false, help: 'Passes "--dump-info" to the Javascript compiler which generates ' 'information about the generated code is a .js.info.json file.' ); argParser.addFlag('no-frequency-based-minification', negatable: false, help: 'Disables the frequency based minifier. ' 'Useful for comparing the output between builds.' ); // // Experimental options // if (featureFlags.isFlutterWebWasmEnabled) { argParser.addSeparator('Experimental options'); } argParser.addFlag( FlutterOptions.kWebWasmFlag, help: 'Compile to WebAssembly rather than JavaScript.\n$kWasmMoreInfo', negatable: false, hide: !featureFlags.isFlutterWebWasmEnabled, ); argParser.addFlag( 'strip-wasm', help: 'Whether to strip the resulting wasm file of static symbol names.', defaultsTo: true, hide: !featureFlags.isFlutterWebWasmEnabled, ); } final FileSystem _fileSystem; @override Future<Set<DevelopmentArtifact>> get requiredArtifacts async => const <DevelopmentArtifact>{ DevelopmentArtifact.web, }; @override final String name = 'web'; @override bool get hidden => !featureFlags.isWebEnabled; @override final String description = 'Build a web application bundle.'; @override Future<FlutterCommandResult> runCommand() async { if (!featureFlags.isWebEnabled) { throwToolExit('"build web" is not currently supported. To enable, run "flutter config --enable-web".'); } final int optimizationLevel = int.parse(stringArg('optimization-level')!); final String? dart2jsOptimizationLevelValue = stringArg('dart2js-optimization'); final int jsOptimizationLevel = dart2jsOptimizationLevelValue != null ? int.parse(dart2jsOptimizationLevelValue.substring(1)) : optimizationLevel; final List<WebCompilerConfig> compilerConfigs; if (boolArg('wasm')) { if (!featureFlags.isFlutterWebWasmEnabled) { throwToolExit('Compiling to WebAssembly (wasm) is only available on the beta and master channels.'); } if (stringArg(FlutterOptions.kWebRendererFlag) != argParser.defaultFor(FlutterOptions.kWebRendererFlag)) { throwToolExit('"--${FlutterOptions.kWebRendererFlag}" cannot be combined with "--${FlutterOptions.kWebWasmFlag}"'); } globals.logger.printBox( title: 'Experimental feature', ''' WebAssembly compilation is experimental. $kWasmMoreInfo''', ); compilerConfigs = <WebCompilerConfig>[ WasmCompilerConfig( optimizationLevel: optimizationLevel, stripWasm: boolArg('strip-wasm'), renderer: WebRendererMode.skwasm, ), JsCompilerConfig( csp: boolArg('csp'), optimizationLevel: jsOptimizationLevel, dumpInfo: boolArg('dump-info'), nativeNullAssertions: boolArg('native-null-assertions'), noFrequencyBasedMinification: boolArg('no-frequency-based-minification'), sourceMaps: boolArg('source-maps'), renderer: WebRendererMode.canvaskit, )]; } else { WebRendererMode webRenderer = WebRendererMode.auto; if (argParser.options.containsKey(FlutterOptions.kWebRendererFlag)) { webRenderer = WebRendererMode.values.byName(stringArg(FlutterOptions.kWebRendererFlag)!); } compilerConfigs = <WebCompilerConfig>[JsCompilerConfig( csp: boolArg('csp'), optimizationLevel: jsOptimizationLevel, dumpInfo: boolArg('dump-info'), nativeNullAssertions: boolArg('native-null-assertions'), noFrequencyBasedMinification: boolArg('no-frequency-based-minification'), sourceMaps: boolArg('source-maps'), renderer: webRenderer, )]; } final FlutterProject flutterProject = FlutterProject.current(); final String target = stringArg('target')!; final BuildInfo buildInfo = await getBuildInfo(); if (buildInfo.isDebug) { throwToolExit('debug builds cannot be built directly for the web. Try using "flutter run"'); } final String? baseHref = stringArg('base-href'); if (baseHref != null && !(baseHref.startsWith('/') && baseHref.endsWith('/'))) { throwToolExit( 'Received a --base-href value of "$baseHref"\n' '--base-href should start and end with /', ); } if (!flutterProject.web.existsSync()) { throwToolExit('Missing index.html.'); } if (!_fileSystem.currentDirectory .childDirectory('web') .childFile('index.html') .readAsStringSync() .contains(kBaseHrefPlaceholder) && baseHref != null) { throwToolExit( "Couldn't find the placeholder for base href. " 'Please add `<base href="$kBaseHrefPlaceholder">` to web/index.html' ); } // Currently supporting options [output-dir] and [output] as // valid approaches for setting output directory of build artifacts final String? outputDirectoryPath = stringArg('output'); displayNullSafetyMode(buildInfo); final WebBuilder webBuilder = WebBuilder( logger: globals.logger, processManager: globals.processManager, buildSystem: globals.buildSystem, fileSystem: globals.fs, flutterVersion: globals.flutterVersion, usage: globals.flutterUsage, analytics: globals.analytics, ); await webBuilder.buildWeb( flutterProject, target, buildInfo, ServiceWorkerStrategy.fromCliName(stringArg('pwa-strategy')), compilerConfigs: compilerConfigs, baseHref: baseHref, outputDirectoryPath: outputDirectoryPath, ); return FlutterCommandResult.success(); } }
flutter/packages/flutter_tools/lib/src/commands/build_web.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/commands/build_web.dart", "repo_id": "flutter", "token_count": 3433 }
752
// 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:process/process.dart'; import '../artifacts.dart'; import '../base/common.dart'; import '../base/file_system.dart'; import '../base/logger.dart'; import '../localizations/gen_l10n.dart'; import '../localizations/localizations_utils.dart'; import '../runner/flutter_command.dart'; /// A command to generate localizations source files for a Flutter project. /// /// It generates Dart localization source files from arb files. /// /// For a more comprehensive tutorial on the tool, please see the /// [internationalization user guide](flutter.dev/go/i18n-user-guide). class GenerateLocalizationsCommand extends FlutterCommand { GenerateLocalizationsCommand({ required FileSystem fileSystem, required Logger logger, required Artifacts artifacts, required ProcessManager processManager, }) : _fileSystem = fileSystem, _logger = logger, _artifacts = artifacts, _processManager = processManager { argParser.addOption( 'arb-dir', help: 'The directory where the template and translated arb files are located.', ); argParser.addOption( 'output-dir', help: 'The directory where the generated localization classes will be written ' 'if the synthetic-package flag is set to false.\n' '\n' 'If output-dir is specified and the synthetic-package flag is enabled, ' 'this option will be ignored by the tool.\n' '\n' 'The app must import the file specified in the "--output-localization-file" ' 'option from this directory. If unspecified, this defaults to the same ' 'directory as the input directory specified in "--arb-dir".', ); argParser.addOption( 'template-arb-file', help: 'The template arb file that will be used as the basis for ' 'generating the Dart localization and messages files.', ); argParser.addOption( 'output-localization-file', help: 'The filename for the output localization and localizations ' 'delegate classes.', ); argParser.addOption( 'untranslated-messages-file', help: 'The location of a file that describes the localization ' 'messages have not been translated yet. Using this option will create ' 'a JSON file at the target location, in the following format:\n' '\n' ' "locale": ["message_1", "message_2" ... "message_n"]\n' '\n' 'If this option is not specified, a summary of the messages that ' 'have not been translated will be printed on the command line.', ); argParser.addOption( 'output-class', defaultsTo: 'AppLocalizations', help: 'The Dart class name to use for the output localization and ' 'localizations delegate classes.', ); argParser.addMultiOption( 'preferred-supported-locales', valueHelp: 'locale', help: 'The list of preferred supported locales for the application. ' 'By default, the tool will generate the supported locales list in ' 'alphabetical order. Use this flag if you would like to default to ' 'a different locale. ' 'For example, pass in "en_US" if you would like your app to ' 'default to American English on devices that support it. ' 'Pass this option multiple times to define multiple items.', ); argParser.addOption( 'header', help: 'The header to prepend to the generated Dart localizations ' 'files. This option takes in a string.\n' '\n' 'For example, pass in "/// All localized files." if you would ' 'like this string prepended to the generated Dart file.\n' '\n' 'Alternatively, see the "--header-file" option to pass in a text ' 'file for longer headers.' ); argParser.addOption( 'header-file', help: 'The header to prepend to the generated Dart localizations ' 'files. The value of this option is the name of the file that ' 'contains the header text which will be inserted at the top ' 'of each generated Dart file.\n' '\n' 'Alternatively, see the "--header" option to pass in a string ' 'for a simpler header.\n' '\n' 'This file should be placed in the directory specified in "--arb-dir".' ); argParser.addFlag( 'use-deferred-loading', help: 'Whether to generate the Dart localization file with locales imported ' 'as deferred, allowing for lazy loading of each locale in Flutter web.\n' '\n' 'This can reduce a web app’s initial startup time by decreasing the ' 'size of the JavaScript bundle. When this flag is set to true, the ' 'messages for a particular locale are only downloaded and loaded by the ' 'Flutter app as they are needed. For projects with a lot of different ' 'locales and many localization strings, it can be an performance ' 'improvement to have deferred loading. For projects with a small number ' 'of locales, the difference is negligible, and might slow down the start ' 'up compared to bundling the localizations with the rest of the ' 'application.\n' '\n' 'This flag does not affect other platforms such as mobile or desktop.', ); argParser.addOption( 'gen-inputs-and-outputs-list', valueHelp: 'path-to-output-directory', help: 'When specified, the tool generates a JSON file containing the ' "tool's inputs and outputs named gen_l10n_inputs_and_outputs.json.\n" '\n' 'This can be useful for keeping track of which files of the Flutter ' 'project were used when generating the latest set of localizations. ' "For example, the Flutter tool's build system uses this file to " 'keep track of when to call gen_l10n during hot reload.\n' '\n' 'The value of this option is the directory where the JSON file will be ' 'generated.\n' '\n' 'When null, the JSON file will not be generated.' ); argParser.addFlag( 'synthetic-package', defaultsTo: true, help: 'Determines whether or not the generated output files will be ' 'generated as a synthetic package or at a specified directory in ' 'the Flutter project.\n' '\n' 'This flag is set to true by default.\n' '\n' 'When synthetic-package is set to false, it will generate the ' 'localizations files in the directory specified by arb-dir by default.\n' '\n' 'If output-dir is specified, files will be generated there.', ); argParser.addOption( 'project-dir', valueHelp: 'absolute/path/to/flutter/project', help: 'When specified, the tool uses the path passed into this option ' 'as the directory of the root Flutter project.\n' '\n' 'When null, the relative path to the present working directory will be used.' ); argParser.addFlag( 'required-resource-attributes', help: 'Requires all resource ids to contain a corresponding resource attribute.\n' '\n' 'By default, simple messages will not require metadata, but it is highly ' 'recommended as this provides context for the meaning of a message to ' 'readers.\n' '\n' 'Resource attributes are still required for plural messages.' ); argParser.addFlag( 'nullable-getter', defaultsTo: true, help: 'Whether or not the localizations class getter is nullable.\n' '\n' 'By default, this value is set to true so that ' 'Localizations.of(context) returns a nullable value ' 'for backwards compatibility. If this value is set to false, then ' 'a null check is performed on the returned value of ' 'Localizations.of(context), removing the need for null checking in ' 'user code.' ); argParser.addFlag( 'format', help: 'When specified, the "dart format" command is run after generating the localization files.' ); argParser.addFlag( 'use-escaping', help: 'Whether or not to use escaping for messages.\n' '\n' 'By default, this value is set to false for backwards compatibility. ' 'Turning this flag on will cause the parser to treat any special characters ' 'contained within pairs of single quotes as normal strings and treat all ' 'consecutive pairs of single quotes as a single quote character.', ); argParser.addFlag( 'suppress-warnings', help: 'When specified, all warnings will be suppressed.\n' ); argParser.addFlag( 'relax-syntax', help: 'When specified, the syntax will be relaxed so that the special character ' '"{" is treated as a string if it is not followed by a valid placeholder ' 'and "}" is treated as a string if it does not close any previous "{" ' 'that is treated as a special character.', ); argParser.addFlag( 'use-named-parameters', help: 'Whether or not to use named parameters for the generated localization methods.', ); } final FileSystem _fileSystem; final Logger _logger; final Artifacts _artifacts; final ProcessManager _processManager; @override String get description => 'Generate localizations for the current project.'; @override String get name => 'gen-l10n'; @override String get category => FlutterCommandCategory.project; @override Future<FlutterCommandResult> runCommand() async { // Validate the rest of the args. if (argResults!.rest.isNotEmpty) { throwToolExit('Unexpected positional argument "${argResults!.rest.first}".'); } // Keep in mind that this is also defined in the following locations: // 1. flutter_tools/lib/src/build_system/targets/localizations.dart // 2. flutter_tools/test/general.shard/build_system/targets/localizations_test.dart // Keep the value consistent in all three locations to ensure behavior is the // same across "flutter gen-l10n" and "flutter run". final String defaultArbDir = _fileSystem.path.join('lib', 'l10n'); // Get all options associated with gen-l10n. final LocalizationOptions options; if (_fileSystem.file('l10n.yaml').existsSync()) { options = parseLocalizationsOptionsFromYAML( file: _fileSystem.file('l10n.yaml'), logger: _logger, defaultArbDir: defaultArbDir, ); _logger.printStatus( 'Because l10n.yaml exists, the options defined there will be used ' 'instead.\n' 'To use the command line arguments, delete the l10n.yaml file in the ' 'Flutter project.\n\n' ); } else { options = parseLocalizationsOptionsFromCommand( command: this, defaultArbDir: defaultArbDir ); } // Run the localizations generator. await generateLocalizations( logger: _logger, options: options, projectDir: _fileSystem.currentDirectory, fileSystem: _fileSystem, artifacts: _artifacts, processManager: _processManager, ); return FlutterCommandResult.success(); } }
flutter/packages/flutter_tools/lib/src/commands/generate_localizations.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/commands/generate_localizations.dart", "repo_id": "flutter", "token_count": 4446 }
753
// 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 'package:package_config/package_config.dart'; import 'package:process/process.dart'; import 'package:usage/uuid/uuid.dart'; import 'artifacts.dart'; import 'base/common.dart'; import 'base/file_system.dart'; import 'base/io.dart'; import 'base/logger.dart'; import 'base/platform.dart'; import 'build_info.dart'; import 'convert.dart'; /// Opt-in changes to the dart compilers. const List<String> kDartCompilerExperiments = <String>[ ]; /// The target model describes the set of core libraries that are available within /// the SDK. class TargetModel { /// Parse a [TargetModel] from a raw string. /// /// Throws an exception if passed a value other than 'flutter', /// 'flutter_runner', 'vm', or 'dartdevc'. factory TargetModel(String rawValue) { switch (rawValue) { case 'flutter': return flutter; case 'flutter_runner': return flutterRunner; case 'vm': return vm; case 'dartdevc': return dartdevc; } throw Exception('Unexpected target model $rawValue'); } const TargetModel._(this._value); /// The Flutter patched Dart SDK. static const TargetModel flutter = TargetModel._('flutter'); /// The Fuchsia patched SDK. static const TargetModel flutterRunner = TargetModel._('flutter_runner'); /// The Dart VM. static const TargetModel vm = TargetModel._('vm'); /// The development compiler for JavaScript. static const TargetModel dartdevc = TargetModel._('dartdevc'); final String _value; @override String toString() => _value; } class CompilerOutput { const CompilerOutput(this.outputFilename, this.errorCount, this.sources, {this.expressionData}); final String outputFilename; final int errorCount; final List<Uri> sources; /// This field is only non-null for expression compilation requests. final Uint8List? expressionData; } enum StdoutState { CollectDiagnostic, CollectDependencies } /// Handles stdin/stdout communication with the frontend server. class StdoutHandler { StdoutHandler({ required Logger logger, required FileSystem fileSystem, }) : _logger = logger, _fileSystem = fileSystem { reset(); } final Logger _logger; final FileSystem _fileSystem; String? boundaryKey; StdoutState state = StdoutState.CollectDiagnostic; Completer<CompilerOutput?>? compilerOutput; final List<Uri> sources = <Uri>[]; bool _suppressCompilerMessages = false; bool _expectSources = true; bool _readFile = false; void handler(String message) { const String kResultPrefix = 'result '; if (boundaryKey == null && message.startsWith(kResultPrefix)) { boundaryKey = message.substring(kResultPrefix.length); return; } final String? messageBoundaryKey = boundaryKey; if (messageBoundaryKey != null && message.startsWith(messageBoundaryKey)) { if (_expectSources) { if (state == StdoutState.CollectDiagnostic) { state = StdoutState.CollectDependencies; return; } } if (message.length <= messageBoundaryKey.length) { compilerOutput?.complete(); return; } final int spaceDelimiter = message.lastIndexOf(' '); final String fileName = message.substring(messageBoundaryKey.length + 1, spaceDelimiter); final int errorCount = int.parse(message.substring(spaceDelimiter + 1).trim()); Uint8List? expressionData; if (_readFile) { expressionData = _fileSystem.file(fileName).readAsBytesSync(); } final CompilerOutput output = CompilerOutput( fileName, errorCount, sources, expressionData: expressionData, ); compilerOutput?.complete(output); return; } switch (state) { case StdoutState.CollectDiagnostic when _suppressCompilerMessages: _logger.printTrace(message); case StdoutState.CollectDiagnostic: _logger.printError(message); case StdoutState.CollectDependencies: switch (message[0]) { case '+': sources.add(Uri.parse(message.substring(1))); case '-': sources.remove(Uri.parse(message.substring(1))); default: _logger.printTrace('Unexpected prefix for $message uri - ignoring'); } } } // This is needed to get ready to process next compilation result output, // with its own boundary key and new completer. void reset({ bool suppressCompilerMessages = false, bool expectSources = true, bool readFile = false }) { boundaryKey = null; compilerOutput = Completer<CompilerOutput?>(); _suppressCompilerMessages = suppressCompilerMessages; _expectSources = expectSources; _readFile = readFile; state = StdoutState.CollectDiagnostic; } } /// List the preconfigured build options for a given build mode. List<String> buildModeOptions(BuildMode mode, List<String> dartDefines) => switch (mode) { BuildMode.debug => <String>[ // These checks allow the CLI to override the value of this define for unit // testing the framework. if (!dartDefines.any((String define) => define.startsWith('dart.vm.profile'))) '-Ddart.vm.profile=false', if (!dartDefines.any((String define) => define.startsWith('dart.vm.product'))) '-Ddart.vm.product=false', '--enable-asserts', ], BuildMode.profile => <String>[ // These checks allow the CLI to override the value of this define for // benchmarks with most timeline traces disabled. if (!dartDefines.any((String define) => define.startsWith('dart.vm.profile'))) '-Ddart.vm.profile=true', if (!dartDefines.any((String define) => define.startsWith('dart.vm.product'))) '-Ddart.vm.product=false', '--delete-tostring-package-uri=dart:ui', '--delete-tostring-package-uri=package:flutter', ...kDartCompilerExperiments, ], BuildMode.release => <String>[ '-Ddart.vm.profile=false', '-Ddart.vm.product=true', '--delete-tostring-package-uri=dart:ui', '--delete-tostring-package-uri=package:flutter', ...kDartCompilerExperiments, ], _ => throw Exception('Unknown BuildMode: $mode') }; /// A compiler interface for producing single (non-incremental) kernel files. class KernelCompiler { KernelCompiler({ required FileSystem fileSystem, required Logger logger, required ProcessManager processManager, required Artifacts artifacts, required List<String> fileSystemRoots, String? fileSystemScheme, @visibleForTesting StdoutHandler? stdoutHandler, }) : _logger = logger, _fileSystem = fileSystem, _artifacts = artifacts, _processManager = processManager, _fileSystemScheme = fileSystemScheme, _fileSystemRoots = fileSystemRoots, _stdoutHandler = stdoutHandler ?? StdoutHandler(logger: logger, fileSystem: fileSystem); final FileSystem _fileSystem; final Artifacts _artifacts; final ProcessManager _processManager; final Logger _logger; final String? _fileSystemScheme; final List<String> _fileSystemRoots; final StdoutHandler _stdoutHandler; Future<CompilerOutput?> compile({ required String sdkRoot, String? mainPath, String? outputFilePath, String? depFilePath, TargetModel targetModel = TargetModel.flutter, bool linkPlatformKernelIn = false, bool aot = false, String? frontendServerStarterPath, List<String>? extraFrontEndOptions, List<String>? fileSystemRoots, String? fileSystemScheme, String? initializeFromDill, String? platformDill, Directory? buildDir, String? targetOS, bool checkDartPluginRegistry = false, required String? packagesPath, required BuildMode buildMode, required bool trackWidgetCreation, required List<String> dartDefines, required PackageConfig packageConfig, String? nativeAssets, }) async { final TargetPlatform? platform = targetModel == TargetModel.dartdevc ? TargetPlatform.web_javascript : null; // This is a URI, not a file path, so the forward slash is correct even on Windows. if (!sdkRoot.endsWith('/')) { sdkRoot = '$sdkRoot/'; } String? mainUri; final File mainFile = _fileSystem.file(mainPath); final Uri mainFileUri = mainFile.uri; if (packagesPath != null) { mainUri = packageConfig.toPackageUri(mainFileUri)?.toString(); } mainUri ??= toMultiRootPath(mainFileUri, _fileSystemScheme, _fileSystemRoots, _fileSystem.path.separator == r'\'); if (outputFilePath != null && !_fileSystem.isFileSync(outputFilePath)) { _fileSystem.file(outputFilePath).createSync(recursive: true); } // Check if there's a Dart plugin registrant. // This is contained in the file `dart_plugin_registrant.dart` under `.dart_tools/flutter_build/`. final File? dartPluginRegistrant = checkDartPluginRegistry ? buildDir?.parent.childFile('dart_plugin_registrant.dart') : null; String? dartPluginRegistrantUri; if (dartPluginRegistrant != null && dartPluginRegistrant.existsSync()) { final Uri dartPluginRegistrantFileUri = dartPluginRegistrant.uri; dartPluginRegistrantUri = packageConfig.toPackageUri(dartPluginRegistrantFileUri)?.toString() ?? toMultiRootPath(dartPluginRegistrantFileUri, _fileSystemScheme, _fileSystemRoots, _fileSystem.path.separator == r'\'); } final List<String> commandToStartFrontendServer; if (frontendServerStarterPath != null && frontendServerStarterPath.isNotEmpty) { final String engineDartPath = _artifacts.getArtifactPath(Artifact.engineDartBinary, platform: platform); if (!_processManager.canRun(engineDartPath)) { throwToolExit('Unable to find Dart binary at $engineDartPath'); } commandToStartFrontendServer = <String>[ engineDartPath, '--disable-dart-dev', frontendServerStarterPath, ]; } else { final String engineDartAotRuntimePath = _artifacts.getArtifactPath(Artifact.engineDartAotRuntime, platform: platform); if (!_processManager.canRun(engineDartAotRuntimePath)) { throwToolExit('Unable to find dartaotruntime binary at $engineDartAotRuntimePath'); } commandToStartFrontendServer = <String>[ engineDartAotRuntimePath, '--disable-dart-dev', _artifacts.getArtifactPath( Artifact.frontendServerSnapshotForEngineDartSdk, platform: platform, ), ]; } final List<String> command = commandToStartFrontendServer + <String>[ '--sdk-root', sdkRoot, '--target=$targetModel', '--no-print-incremental-dependencies', for (final Object dartDefine in dartDefines) '-D$dartDefine', ...buildModeOptions(buildMode, dartDefines), if (trackWidgetCreation) '--track-widget-creation', if (!linkPlatformKernelIn) '--no-link-platform', if (aot) ...<String>[ '--aot', '--tfa', // The --target-os flag only makes sense for whole program compilation. if (targetOS != null) ...<String>[ '--target-os', targetOS, ], ], if (packagesPath != null) ...<String>[ '--packages', packagesPath, ], if (outputFilePath != null) ...<String>[ '--output-dill', outputFilePath, ], if (depFilePath != null && (fileSystemRoots == null || fileSystemRoots.isEmpty)) ...<String>[ '--depfile', depFilePath, ], if (fileSystemRoots != null) for (final String root in fileSystemRoots) ...<String>[ '--filesystem-root', root, ], if (fileSystemScheme != null) ...<String>[ '--filesystem-scheme', fileSystemScheme, ], if (initializeFromDill != null) ...<String>[ '--incremental', '--initialize-from-dill', initializeFromDill, ], if (platformDill != null) ...<String>[ '--platform', platformDill, ], if (dartPluginRegistrantUri != null) ...<String>[ '--source', dartPluginRegistrantUri, '--source', 'package:flutter/src/dart_plugin_registrant.dart', '-Dflutter.dart_plugin_registrant=$dartPluginRegistrantUri', ], if (nativeAssets != null) ...<String>[ '--native-assets', nativeAssets, ], // See: https://github.com/flutter/flutter/issues/103994 '--verbosity=error', ...?extraFrontEndOptions, mainUri, ]; _logger.printTrace(command.join(' ')); final Process server = await _processManager.start(command); server.stderr .transform<String>(utf8.decoder) .listen(_logger.printError); server.stdout .transform<String>(utf8.decoder) .transform<String>(const LineSplitter()) .listen(_stdoutHandler.handler); final int exitCode = await server.exitCode; if (exitCode == 0) { return _stdoutHandler.compilerOutput?.future; } return null; } } /// Class that allows to serialize compilation requests to the compiler. abstract class _CompilationRequest { _CompilationRequest(this.completer); Completer<CompilerOutput?> completer; Future<CompilerOutput?> _run(DefaultResidentCompiler compiler); Future<void> run(DefaultResidentCompiler compiler) async { completer.complete(await _run(compiler)); } } class _RecompileRequest extends _CompilationRequest { _RecompileRequest( super.completer, this.mainUri, this.invalidatedFiles, this.outputPath, this.packageConfig, this.suppressErrors, { this.additionalSourceUri, this.nativeAssetsYamlUri, }); Uri mainUri; List<Uri>? invalidatedFiles; String outputPath; PackageConfig packageConfig; bool suppressErrors; final Uri? additionalSourceUri; final Uri? nativeAssetsYamlUri; @override Future<CompilerOutput?> _run(DefaultResidentCompiler compiler) async => compiler._recompile(this); } class _CompileExpressionRequest extends _CompilationRequest { _CompileExpressionRequest( super.completer, this.expression, this.definitions, this.definitionTypes, this.typeDefinitions, this.typeBounds, this.typeDefaults, this.libraryUri, this.klass, this.method, this.isStatic, ); String expression; List<String>? definitions; List<String>? definitionTypes; List<String>? typeDefinitions; List<String>? typeBounds; List<String>? typeDefaults; String? libraryUri; String? klass; String? method; bool isStatic; @override Future<CompilerOutput?> _run(DefaultResidentCompiler compiler) async => compiler._compileExpression(this); } class _CompileExpressionToJsRequest extends _CompilationRequest { _CompileExpressionToJsRequest( super.completer, this.libraryUri, this.line, this.column, this.jsModules, this.jsFrameValues, this.moduleName, this.expression, ); final String? libraryUri; final int line; final int column; final Map<String, String>? jsModules; final Map<String, String>? jsFrameValues; final String? moduleName; final String? expression; @override Future<CompilerOutput?> _run(DefaultResidentCompiler compiler) async => compiler._compileExpressionToJs(this); } class _RejectRequest extends _CompilationRequest { _RejectRequest(super.completer); @override Future<CompilerOutput?> _run(DefaultResidentCompiler compiler) async => compiler._reject(); } /// Wrapper around incremental frontend server compiler, that communicates with /// server via stdin/stdout. /// /// The wrapper is intended to stay resident in memory as user changes, reloads, /// restarts the Flutter app. abstract class ResidentCompiler { factory ResidentCompiler(String sdkRoot, { required BuildMode buildMode, required Logger logger, required ProcessManager processManager, required Artifacts artifacts, required Platform platform, required FileSystem fileSystem, bool testCompilation, bool trackWidgetCreation, String packagesPath, List<String> fileSystemRoots, String? fileSystemScheme, String initializeFromDill, bool assumeInitializeFromDillUpToDate, TargetModel targetModel, bool unsafePackageSerialization, String? frontendServerStarterPath, List<String> extraFrontEndOptions, String platformDill, List<String>? dartDefines, String librariesSpec, }) = DefaultResidentCompiler; // TODO(zanderso): find a better way to configure additional file system // roots from the runner. // See: https://github.com/flutter/flutter/issues/50494 void addFileSystemRoot(String root); /// If invoked for the first time, it compiles Dart script identified by /// [mainPath], [invalidatedFiles] list is ignored. /// On successive runs [invalidatedFiles] indicates which files need to be /// recompiled. If [mainPath] is [null], previously used [mainPath] entry /// point that is used for recompilation. /// Binary file name is returned if compilation was successful, otherwise /// null is returned. /// /// If [checkDartPluginRegistry] is true, it is the caller's responsibility /// to ensure that the generated registrant file has been updated such that /// it is wrapping [mainUri]. Future<CompilerOutput?> recompile( Uri mainUri, List<Uri>? invalidatedFiles, { required String outputPath, required PackageConfig packageConfig, required FileSystem fs, String? projectRootPath, bool suppressErrors = false, bool checkDartPluginRegistry = false, File? dartPluginRegistrant, Uri? nativeAssetsYaml, }); Future<CompilerOutput?> compileExpression( String expression, List<String>? definitions, List<String>? definitionTypes, List<String>? typeDefinitions, List<String>? typeBounds, List<String>? typeDefaults, String? libraryUri, String? klass, String? method, bool isStatic, ); /// Compiles [expression] in [libraryUri] at [line]:[column] to JavaScript /// in [moduleName]. /// /// Values listed in [jsFrameValues] are substituted for their names in the /// [expression]. /// /// Ensures that all [jsModules] are loaded and accessible inside the /// expression. /// /// Example values of parameters: /// [moduleName] is of the form '/packages/hello_world_main.dart' /// [jsFrameValues] is a map from js variable name to its primitive value /// or another variable name, for example /// { 'x': '1', 'y': 'y', 'o': 'null' } /// [jsModules] is a map from variable name to the module name, where /// variable name is the name originally used in JavaScript to contain the /// module object, for example: /// { 'dart':'dart_sdk', 'main': '/packages/hello_world_main.dart' } /// Returns a [CompilerOutput] including the name of the file containing the /// compilation result and a number of errors. Future<CompilerOutput?> compileExpressionToJs( String libraryUri, int line, int column, Map<String, String> jsModules, Map<String, String> jsFrameValues, String moduleName, String expression, ); /// Should be invoked when results of compilation are accepted by the client. /// /// Either [accept] or [reject] should be called after every [recompile] call. void accept(); /// Should be invoked when results of compilation are rejected by the client. /// /// Either [accept] or [reject] should be called after every [recompile] call. Future<CompilerOutput?> reject(); /// Should be invoked when frontend server compiler should forget what was /// accepted previously so that next call to [recompile] produces complete /// kernel file. void reset(); Future<Object> shutdown(); } @visibleForTesting class DefaultResidentCompiler implements ResidentCompiler { DefaultResidentCompiler( String sdkRoot, { required this.buildMode, required Logger logger, required ProcessManager processManager, required this.artifacts, required Platform platform, required FileSystem fileSystem, this.testCompilation = false, this.trackWidgetCreation = true, this.packagesPath, List<String> fileSystemRoots = const <String>[], this.fileSystemScheme, this.initializeFromDill, this.assumeInitializeFromDillUpToDate = false, this.targetModel = TargetModel.flutter, this.unsafePackageSerialization = false, this.frontendServerStarterPath, this.extraFrontEndOptions, this.platformDill, List<String>? dartDefines, this.librariesSpec, @visibleForTesting StdoutHandler? stdoutHandler, }) : _logger = logger, _processManager = processManager, _stdoutHandler = stdoutHandler ?? StdoutHandler(logger: logger, fileSystem: fileSystem), _platform = platform, dartDefines = dartDefines ?? const <String>[], // This is a URI, not a file path, so the forward slash is correct even on Windows. sdkRoot = sdkRoot.endsWith('/') ? sdkRoot : '$sdkRoot/', // Make a copy, we might need to modify it later. fileSystemRoots = List<String>.from(fileSystemRoots); final Logger _logger; final ProcessManager _processManager; final Artifacts artifacts; final Platform _platform; final bool testCompilation; final BuildMode buildMode; final bool trackWidgetCreation; final String? packagesPath; final TargetModel targetModel; final List<String> fileSystemRoots; final String? fileSystemScheme; final String? initializeFromDill; final bool assumeInitializeFromDillUpToDate; final bool unsafePackageSerialization; final String? frontendServerStarterPath; final List<String>? extraFrontEndOptions; final List<String> dartDefines; final String? librariesSpec; @override void addFileSystemRoot(String root) { fileSystemRoots.add(root); } /// The path to the root of the Dart SDK used to compile. /// /// This is used to resolve the [platformDill]. final String sdkRoot; /// The path to the platform dill file. /// /// This does not need to be provided for the normal Flutter workflow. final String? platformDill; Process? _server; final StdoutHandler _stdoutHandler; bool _compileRequestNeedsConfirmation = false; final StreamController<_CompilationRequest> _controller = StreamController<_CompilationRequest>(); @override Future<CompilerOutput?> recompile( Uri mainUri, List<Uri>? invalidatedFiles, { required String outputPath, required PackageConfig packageConfig, bool suppressErrors = false, bool checkDartPluginRegistry = false, File? dartPluginRegistrant, String? projectRootPath, FileSystem? fs, Uri? nativeAssetsYaml, }) async { if (!_controller.hasListener) { _controller.stream.listen(_handleCompilationRequest); } Uri? additionalSourceUri; // `dart_plugin_registrant.dart` contains the Dart plugin registry. if (checkDartPluginRegistry && dartPluginRegistrant != null && dartPluginRegistrant.existsSync()) { additionalSourceUri = dartPluginRegistrant.uri; } final Completer<CompilerOutput?> completer = Completer<CompilerOutput?>(); _controller.add(_RecompileRequest( completer, mainUri, invalidatedFiles, outputPath, packageConfig, suppressErrors, additionalSourceUri: additionalSourceUri, nativeAssetsYamlUri: nativeAssetsYaml, )); return completer.future; } Future<CompilerOutput?> _recompile(_RecompileRequest request) async { _stdoutHandler.reset(); _compileRequestNeedsConfirmation = true; _stdoutHandler._suppressCompilerMessages = request.suppressErrors; final String mainUri = request.packageConfig.toPackageUri(request.mainUri)?.toString() ?? toMultiRootPath(request.mainUri, fileSystemScheme, fileSystemRoots, _platform.isWindows); String? additionalSourceUri; if (request.additionalSourceUri != null) { additionalSourceUri = request.packageConfig.toPackageUri(request.additionalSourceUri!)?.toString() ?? toMultiRootPath(request.additionalSourceUri!, fileSystemScheme, fileSystemRoots, _platform.isWindows); } final String? nativeAssets = request.nativeAssetsYamlUri?.toString(); final Process? server = _server; if (server == null) { return _compile( mainUri, request.outputPath, additionalSourceUri: additionalSourceUri, nativeAssetsUri: nativeAssets, ); } final String inputKey = Uuid().generateV4(); if (nativeAssets != null && nativeAssets.isNotEmpty) { server.stdin.writeln('native-assets $nativeAssets'); _logger.printTrace('<- native-assets $nativeAssets'); } server.stdin.writeln('recompile $mainUri $inputKey'); _logger.printTrace('<- recompile $mainUri $inputKey'); final List<Uri>? invalidatedFiles = request.invalidatedFiles; if (invalidatedFiles != null) { for (final Uri fileUri in invalidatedFiles) { String message; if (fileUri.scheme == 'package') { message = fileUri.toString(); } else { message = request.packageConfig.toPackageUri(fileUri)?.toString() ?? toMultiRootPath(fileUri, fileSystemScheme, fileSystemRoots, _platform.isWindows); } server.stdin.writeln(message); _logger.printTrace(message); } } server.stdin.writeln(inputKey); _logger.printTrace('<- $inputKey'); return _stdoutHandler.compilerOutput?.future; } final List<_CompilationRequest> _compilationQueue = <_CompilationRequest>[]; Future<void> _handleCompilationRequest(_CompilationRequest request) async { final bool isEmpty = _compilationQueue.isEmpty; _compilationQueue.add(request); // Only trigger processing if queue was empty - i.e. no other requests // are currently being processed. This effectively enforces "one // compilation request at a time". if (isEmpty) { while (_compilationQueue.isNotEmpty) { final _CompilationRequest request = _compilationQueue.first; await request.run(this); _compilationQueue.removeAt(0); } } } Future<CompilerOutput?> _compile( String scriptUri, String? outputPath, { String? additionalSourceUri, String? nativeAssetsUri, }) async { final TargetPlatform? platform = (targetModel == TargetModel.dartdevc) ? TargetPlatform.web_javascript : null; late final List<String> commandToStartFrontendServer; if (frontendServerStarterPath != null && frontendServerStarterPath!.isNotEmpty) { commandToStartFrontendServer = <String>[ artifacts.getArtifactPath(Artifact.engineDartBinary, platform: platform), '--disable-dart-dev', frontendServerStarterPath!, ]; } else { commandToStartFrontendServer = <String>[ artifacts.getArtifactPath(Artifact.engineDartAotRuntime, platform: platform), '--disable-dart-dev', artifacts.getArtifactPath( Artifact.frontendServerSnapshotForEngineDartSdk, platform: platform, ), ]; } final List<String> command = commandToStartFrontendServer + <String>[ '--sdk-root', sdkRoot, '--incremental', if (testCompilation) '--no-print-incremental-dependencies', '--target=$targetModel', // TODO(annagrin): remove once this becomes the default behavior // in the frontend_server. // https://github.com/flutter/flutter/issues/59902 '--experimental-emit-debug-metadata', for (final Object dartDefine in dartDefines) '-D$dartDefine', if (outputPath != null) ...<String>[ '--output-dill', outputPath, ], // If we have a platform dill, we don't need to pass the libraries spec, // since the information is embedded in the .dill file. if (librariesSpec != null && platformDill == null) ...<String>[ '--libraries-spec', librariesSpec!, ], if (packagesPath != null) ...<String>[ '--packages', packagesPath!, ], ...buildModeOptions(buildMode, dartDefines), if (trackWidgetCreation) '--track-widget-creation', for (final String root in fileSystemRoots) ...<String>[ '--filesystem-root', root, ], if (fileSystemScheme != null) ...<String>[ '--filesystem-scheme', fileSystemScheme!, ], if (initializeFromDill != null) ...<String>[ '--initialize-from-dill', initializeFromDill!, ], if (assumeInitializeFromDillUpToDate) '--assume-initialize-from-dill-up-to-date', if (additionalSourceUri != null) ...<String>[ '--source', additionalSourceUri, '--source', 'package:flutter/src/dart_plugin_registrant.dart', '-Dflutter.dart_plugin_registrant=$additionalSourceUri', ], if (nativeAssetsUri != null) ...<String>[ '--native-assets', nativeAssetsUri, ], if (platformDill != null) ...<String>[ '--platform', platformDill!, ], if (unsafePackageSerialization) '--unsafe-package-serialization', // See: https://github.com/flutter/flutter/issues/103994 '--verbosity=error', ...?extraFrontEndOptions, ]; _logger.printTrace(command.join(' ')); _server = await _processManager.start(command); _server?.stdout .transform<String>(utf8.decoder) .transform<String>(const LineSplitter()) .listen( _stdoutHandler.handler, onDone: () { // when outputFilename future is not completed, but stdout is closed // process has died unexpectedly. if (_stdoutHandler.compilerOutput?.isCompleted == false) { _stdoutHandler.compilerOutput?.complete(); throwToolExit('the Dart compiler exited unexpectedly.'); } }); _server?.stderr .transform<String>(utf8.decoder) .transform<String>(const LineSplitter()) .listen(_logger.printError); unawaited(_server?.exitCode.then((int code) { if (code != 0) { throwToolExit('the Dart compiler exited unexpectedly.'); } })); if (nativeAssetsUri != null && nativeAssetsUri.isNotEmpty) { _server?.stdin.writeln('native-assets $nativeAssetsUri'); _logger.printTrace('<- native-assets $nativeAssetsUri'); } _server?.stdin.writeln('compile $scriptUri'); _logger.printTrace('<- compile $scriptUri'); return _stdoutHandler.compilerOutput?.future; } @override Future<CompilerOutput?> compileExpression( String expression, List<String>? definitions, List<String>? definitionTypes, List<String>? typeDefinitions, List<String>? typeBounds, List<String>? typeDefaults, String? libraryUri, String? klass, String? method, bool isStatic, ) async { if (!_controller.hasListener) { _controller.stream.listen(_handleCompilationRequest); } final Completer<CompilerOutput?> completer = Completer<CompilerOutput?>(); final _CompileExpressionRequest request = _CompileExpressionRequest( completer, expression, definitions, definitionTypes, typeDefinitions, typeBounds, typeDefaults, libraryUri, klass, method, isStatic); _controller.add(request); return completer.future; } Future<CompilerOutput?> _compileExpression(_CompileExpressionRequest request) async { _stdoutHandler.reset(suppressCompilerMessages: true, expectSources: false, readFile: true); // 'compile-expression' should be invoked after compiler has been started, // program was compiled. final Process? server = _server; if (server == null) { return null; } final String inputKey = Uuid().generateV4(); server.stdin ..writeln('compile-expression $inputKey') ..writeln(request.expression); request.definitions?.forEach(server.stdin.writeln); server.stdin.writeln(inputKey); request.definitionTypes?.forEach(server.stdin.writeln); server.stdin.writeln(inputKey); request.typeDefinitions?.forEach(server.stdin.writeln); server.stdin.writeln(inputKey); request.typeBounds?.forEach(server.stdin.writeln); server.stdin.writeln(inputKey); request.typeDefaults?.forEach(server.stdin.writeln); server.stdin ..writeln(inputKey) ..writeln(request.libraryUri ?? '') ..writeln(request.klass ?? '') ..writeln(request.method ?? '') ..writeln(request.isStatic); return _stdoutHandler.compilerOutput?.future; } @override Future<CompilerOutput?> compileExpressionToJs( String libraryUri, int line, int column, Map<String, String> jsModules, Map<String, String> jsFrameValues, String moduleName, String expression, ) { if (!_controller.hasListener) { _controller.stream.listen(_handleCompilationRequest); } final Completer<CompilerOutput?> completer = Completer<CompilerOutput?>(); _controller.add( _CompileExpressionToJsRequest( completer, libraryUri, line, column, jsModules, jsFrameValues, moduleName, expression) ); return completer.future; } Future<CompilerOutput?> _compileExpressionToJs(_CompileExpressionToJsRequest request) async { _stdoutHandler.reset(suppressCompilerMessages: true, expectSources: false); // 'compile-expression-to-js' should be invoked after compiler has been started, // program was compiled. final Process? server = _server; if (server == null) { return null; } final String inputKey = Uuid().generateV4(); server.stdin ..writeln('compile-expression-to-js $inputKey') ..writeln(request.libraryUri ?? '') ..writeln(request.line) ..writeln(request.column); request.jsModules?.forEach((String k, String v) { server.stdin.writeln('$k:$v'); }); server.stdin.writeln(inputKey); request.jsFrameValues?.forEach((String k, String v) { server.stdin.writeln('$k:$v'); }); server.stdin ..writeln(inputKey) ..writeln(request.moduleName ?? '') ..writeln(request.expression ?? ''); return _stdoutHandler.compilerOutput?.future; } @override void accept() { if (_compileRequestNeedsConfirmation) { _server?.stdin.writeln('accept'); _logger.printTrace('<- accept'); } _compileRequestNeedsConfirmation = false; } @override Future<CompilerOutput?> reject() { if (!_controller.hasListener) { _controller.stream.listen(_handleCompilationRequest); } final Completer<CompilerOutput?> completer = Completer<CompilerOutput?>(); _controller.add(_RejectRequest(completer)); return completer.future; } Future<CompilerOutput?> _reject() async { if (!_compileRequestNeedsConfirmation) { return Future<CompilerOutput?>.value(); } _stdoutHandler.reset(expectSources: false); _server?.stdin.writeln('reject'); _logger.printTrace('<- reject'); _compileRequestNeedsConfirmation = false; return _stdoutHandler.compilerOutput?.future; } @override void reset() { _server?.stdin.writeln('reset'); _logger.printTrace('<- reset'); } @override Future<Object> shutdown() async { // Server was never successfully created. final Process? server = _server; if (server == null) { return 0; } _logger.printTrace('killing pid ${server.pid}'); server.kill(); return server.exitCode; } } /// Convert a file URI into a multi-root scheme URI if provided, otherwise /// return unmodified. @visibleForTesting String toMultiRootPath(Uri fileUri, String? scheme, List<String> fileSystemRoots, bool windows) { if (scheme == null || fileSystemRoots.isEmpty || fileUri.scheme != 'file') { return fileUri.toString(); } final String filePath = fileUri.toFilePath(windows: windows); for (final String fileSystemRoot in fileSystemRoots) { if (filePath.startsWith(fileSystemRoot)) { return '$scheme://${filePath.substring(fileSystemRoot.length)}'; } } return fileUri.toString(); }
flutter/packages/flutter_tools/lib/src/compile.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/compile.dart", "repo_id": "flutter", "token_count": 13408 }
754
// 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:dds/dap.dart' hide PidTracker; import 'package:vm_service/vm_service.dart' as vm; import '../base/io.dart'; import '../cache.dart'; import '../convert.dart'; import '../globals.dart' as globals show fs; import 'error_formatter.dart'; import 'flutter_adapter_args.dart'; import 'flutter_base_adapter.dart'; /// A DAP Debug Adapter for running and debugging Flutter applications. class FlutterDebugAdapter extends FlutterBaseDebugAdapter with VmServiceInfoFileUtils { FlutterDebugAdapter( super.channel, { required super.fileSystem, required super.platform, super.ipv6, super.enableFlutterDds = true, super.enableAuthCodes, super.logger, super.onError, }); /// A completer that completes when the app.started event has been received. final Completer<void> _appStartedCompleter = Completer<void>(); /// Whether or not the app.started event has been received. bool get _receivedAppStarted => _appStartedCompleter.isCompleted; /// The appId of the current running Flutter app. String? _appId; /// A progress reporter for the applications launch progress. /// /// `null` if a launch is not in progress (or has completed). DapProgressReporter? launchProgress; /// The ID to use for the next request sent to the Flutter run daemon. int _flutterRequestId = 1; /// Outstanding requests that have been sent to the Flutter run daemon and /// their handlers. final Map<int, Completer<Object?>> _flutterRequestCompleters = <int, Completer<Object?>>{}; /// A list of reverse-requests from `flutter run --machine` that should be forwarded to the client. static const Set<String> _requestsToForwardToClient = <String>{ // The 'app.exposeUrl' request is sent by Flutter to request the client // exposes a URL to the user and return the public version of that URL. // // This supports some web scenarios where the `flutter` tool may be running // on a different machine to the user (for example a cloud IDE or in VS Code // remote workspace) so we cannot just use the raw URL because the hostname // and/or port might not be available to the machine the user is using. // Instead, the IDE/infrastructure can set up port forwarding/proxying and // return a user-facing URL that will map to the original (localhost) URL // Flutter provided. 'app.exposeUrl', }; /// A list of events from `flutter run --machine` that should be forwarded to the client. static const Set<String> _eventsToForwardToClient = <String>{ // The 'app.webLaunchUrl' event is sent to the client to tell it about a URL // that should be launched (including a flag for whether it has been // launched by the tool or needs launching by the editor). 'app.webLaunchUrl', }; /// Completers for reverse requests from Flutter that may need to be handled by the client. final Map<Object, Completer<Object?>> _reverseRequestCompleters = <Object, Completer<Object?>>{}; /// Whether or not the user requested debugging be enabled. /// /// For debugging to be enabled, the user must have chosen "Debug" (and not /// "Run") in the editor (which maps to the DAP `noDebug` field) _and_ must /// not have requested to run in Profile or Release mode. Profile/Release /// modes will always disable debugging. /// /// This is always `true` for attach requests. /// /// When not debugging, we will not connect to the VM Service so some /// functionality (breakpoints, evaluation, etc.) will not be available. /// Functionality provided via the daemon (hot reload/restart) will still be /// available. @override bool get enableDebugger => super.enableDebugger && !profileMode && !releaseMode; /// Whether the launch configuration arguments specify `--profile`. /// /// Always `false` for attach requests. bool get profileMode { final DartCommonLaunchAttachRequestArguments args = this.args; if (args is FlutterLaunchRequestArguments) { return args.toolArgs?.contains('--profile') ?? false; } // Otherwise (attach), always false. return false; } /// Whether the launch configuration arguments specify `--release`. /// /// Always `false` for attach requests. bool get releaseMode { final DartCommonLaunchAttachRequestArguments args = this.args; if (args is FlutterLaunchRequestArguments) { return args.toolArgs?.contains('--release') ?? false; } // Otherwise (attach), always false. return false; } /// Called by [attachRequest] to request that we actually connect to the app to be debugged. @override Future<void> attachImpl() async { final FlutterAttachRequestArguments args = this.args as FlutterAttachRequestArguments; String? vmServiceUri = args.vmServiceUri; final String? vmServiceInfoFile = args.vmServiceInfoFile; if (vmServiceUri != null && vmServiceInfoFile != null) { sendConsoleOutput( 'To attach, provide only one (or neither) of vmServiceUri/vmServiceInfoFile', ); handleSessionTerminate(); return; } launchProgress = startProgressNotification( 'launch', 'Flutter', message: 'Attaching…', ); if (vmServiceUri == null && vmServiceInfoFile != null) { final Uri uriFromFile = await waitForVmServiceInfoFile(logger, globals.fs.file(vmServiceInfoFile)); vmServiceUri = uriFromFile.toString(); } final List<String> toolArgs = <String>[ 'attach', '--machine', if (!enableFlutterDds) '--no-dds', if (vmServiceUri != null) ...<String>['--debug-uri', vmServiceUri], ]; await _startProcess( toolArgs: toolArgs, customTool: args.customTool, customToolReplacesArgs: args.customToolReplacesArgs, userToolArgs: args.toolArgs, targetProgram: args.program, ); } /// [customRequest] handles any messages that do not match standard messages in the spec. /// /// This is used to allow a client/DA to have custom methods outside of the /// spec. It is up to the client/DA to negotiate which custom messages are /// allowed. /// /// [sendResponse] must be called when handling a message, even if it is with /// a null response. Otherwise the client will never be informed that the /// request has completed. /// /// Any requests not handled must call super which will respond with an error /// that the message was not supported. /// /// Unless they start with _ to indicate they are private, custom messages /// should not change in breaking ways if client IDEs/editors may be calling /// them. @override Future<void> customRequest( Request request, RawRequestArguments? args, void Function(Object?) sendResponse, ) async { switch (request.command) { case 'hotRestart': case 'hotReload': // This convention is for the internal IDE client. case r'$/hotReload': final bool isFullRestart = request.command == 'hotRestart'; await _performRestart(isFullRestart, args?.args['reason'] as String?); sendResponse(null); // Handle requests (from the client) that provide responses to reverse-requests // that we forwarded from `flutter run --machine`. case 'flutter.sendForwardedRequestResponse': _handleForwardedResponse(args); sendResponse(null); default: await super.customRequest(request, args, sendResponse); } } @override Future<void> handleExtensionEvent(vm.Event event) async { await super.handleExtensionEvent(event); switch (event.kind) { case vm.EventKind.kExtension: switch (event.extensionKind) { case 'Flutter.ServiceExtensionStateChanged': _sendServiceExtensionStateChanged(event.extensionData); case 'Flutter.Error': _handleFlutterErrorEvent(event.extensionData); } } } /// Sends OutputEvents to the client for a Flutter.Error event. void _handleFlutterErrorEvent(vm.ExtensionData? data) { final Map<String, Object?>? errorData = data?.data; if (errorData == null) { return; } FlutterErrorFormatter() ..formatError(errorData) ..sendOutput(sendOutput); } /// Called by [launchRequest] to request that we actually start the app to be run/debugged. /// /// For debugging, this should start paused, connect to the VM Service, set /// breakpoints, and resume. @override Future<void> launchImpl() async { final FlutterLaunchRequestArguments args = this.args as FlutterLaunchRequestArguments; launchProgress = startProgressNotification( 'launch', 'Flutter', message: 'Launching…', ); final List<String> toolArgs = <String>[ 'run', '--machine', if (!enableFlutterDds) '--no-dds', if (enableDebugger) '--start-paused', // Structured errors are enabled by default, but since we don't connect // the VM Service for noDebug, we need to disable them so that error text // is sent to stderr. Otherwise the user will not see any exception text // (because nobody is listening for Flutter.Error events). if (!enableDebugger) '--dart-define=flutter.inspector.structuredErrors=false', ]; await _startProcess( toolArgs: toolArgs, customTool: args.customTool, customToolReplacesArgs: args.customToolReplacesArgs, targetProgram: args.program, userToolArgs: args.toolArgs, userArgs: args.args, ); } /// Starts the `flutter` process to run/attach to the required app. Future<void> _startProcess({ required String? customTool, required int? customToolReplacesArgs, required List<String> toolArgs, required List<String>? userToolArgs, String? targetProgram, List<String>? userArgs, }) async { // Handle customTool and deletion of any arguments for it. final String executable = customTool ?? fileSystem.path.join(Cache.flutterRoot!, 'bin', platform.isWindows ? 'flutter.bat' : 'flutter'); final int? removeArgs = customToolReplacesArgs; if (customTool != null && removeArgs != null) { toolArgs.removeRange(0, math.min(removeArgs, toolArgs.length)); } final List<String> processArgs = <String>[ ...toolArgs, ...?userToolArgs, if (targetProgram != null) ...<String>[ '--target', targetProgram, ], ...?userArgs, ]; await launchAsProcess( executable: executable, processArgs: processArgs, env: args.env, ); } /// restart is called by the client when the user invokes a restart (for example with the button on the debug toolbar). /// /// For Flutter, we handle this ourselves be sending a Hot Restart request /// to the running app. @override Future<void> restartRequest( Request request, RestartArguments? args, void Function() sendResponse, ) async { await _performRestart(true); sendResponse(); } /// Sends a request to the Flutter run daemon that is running/attaching to the app and waits for a response. /// /// If there is no process, the message will be silently ignored (this is /// common during the application being stopped, where async messages may be /// processed). Future<Object?> sendFlutterRequest( String method, Map<String, Object?>? params, ) async { final Completer<Object?> completer = Completer<Object?>(); final int id = _flutterRequestId++; _flutterRequestCompleters[id] = completer; sendFlutterMessage(<String, Object?>{ 'id': id, 'method': method, 'params': params, }); return completer.future; } /// Sends a message to the Flutter run daemon. /// /// Throws `DebugAdapterException` if a Flutter process is not yet running. void sendFlutterMessage(Map<String, Object?> message) { final Process? process = this.process; if (process == null) { throw DebugAdapterException('Flutter process has not yet started'); } final String messageString = jsonEncode(message); // Flutter requests are always wrapped in brackets as an array. final String payload = '[$messageString]\n'; _logTraffic('==> [Flutter] $payload'); process.stdin.writeln(payload); } /// Called by [terminateRequest] to request that we gracefully shut down the app being run (or in the case of an attach, disconnect). @override Future<void> terminateImpl() async { if (isAttach) { await handleDetach(); } // Send a request to stop/detach to give Flutter chance to do some cleanup. // It's possible the Flutter process will terminate before we process the // response, so accept either a response or the process exiting. if (_appId != null) { final String method = isAttach ? 'app.detach' : 'app.stop'; await Future.any<void>(<Future<void>>[ sendFlutterRequest(method, <String, Object?>{'appId': _appId}), process?.exitCode ?? Future<void>.value(), ]); } terminatePids(ProcessSignal.sigterm); await process?.exitCode; } /// Connects to the VM Service if the app.started event has fired, and a VM Service URI is available. Future<void> _connectDebugger(Uri vmServiceUri) async { if (enableDebugger) { await connectDebugger(vmServiceUri); } else { // Usually, `connectDebugger` (in the base Dart adapter) will send this // event when it connects a debugger. Since we're not connecting a // debugger we send this ourselves, to allow clients to connect to the // VM Service for things like starting DevTools, even if debugging is // not available. // TODO(dantup): Switch this to call `sendDebuggerUris()` on the base // adapter once rolled into Flutter. sendEvent( RawEventBody(<String, Object?>{ 'vmServiceUri': vmServiceUri.toString(), }), eventType: 'dart.debuggerUris', ); } } /// Handles the app.start event from Flutter. void _handleAppStart(Map<String, Object?> params) { _appId = params['appId'] as String?; if (_appId == null) { throw DebugAdapterException('Unexpected null `appId` in app.start event'); } // Notify the client whether it can call 'restartRequest' when the user // clicks restart, instead of terminating and re-starting its own debug // session (which is much slower, but required for profile/release mode). final bool supportsRestart = (params['supportsRestart'] as bool?) ?? false; sendEvent(CapabilitiesEventBody(capabilities: Capabilities(supportsRestartRequest: supportsRestart))); // Send a custom event so the editor has info about the app starting. // // This message contains things like the `deviceId` and `mode` that the // client might not know about if they were inferred or set by users custom // args. sendEvent( RawEventBody(params), eventType: 'flutter.appStart', ); } /// Handles any app.progress event from Flutter. void _handleAppProgress(Map<String, Object?> params) { // If this is a new progress starting (and we're still launching), update // the progress notification. // // We ignore finished status because we have a limited API - the next // item will replace it (or the launch progress will be completed by // _handleAppStarted). if (params case {'message': final String message, 'finished': false}) { launchProgress?.update(message: message); } } /// Handles the app.started event from Flutter. Future<void> _handleAppStarted() async { launchProgress?.end(); launchProgress = null; _appStartedCompleter.complete(); // Send a custom event so the editor knows the app has started. // // This may be useful when there's no VM Service (for example Profile mode) // but the editor still wants to know that startup has finished. if (enableDebugger) { await debuggerInitialized; // Ensure we're fully initialized before sending. } sendEvent( RawEventBody(<String, Object?>{}), eventType: 'flutter.appStarted', ); } /// Handles the daemon.connected event, recording the pid of the flutter_tools process. void _handleDaemonConnected(Map<String, Object?> params) { // On Windows, the pid from the process we spawn is the shell running // flutter.bat and terminating it may not be reliable, so we also take the // pid provided from the VM running flutter_tools. final int? pid = params['pid'] as int?; if (pid != null) { pidsToTerminate.add(pid); } } /// Handles the app.debugPort event from Flutter, connecting to the VM Service if everything else is ready. Future<void> _handleDebugPort(Map<String, Object?> params) async { // Capture the VM Service URL which we'll connect to when we get app.started. final String? wsUri = params['wsUri'] as String?; if (wsUri != null) { final Uri vmServiceUri = Uri.parse(wsUri); // Also wait for app.started before we connect, to ensure Flutter's // initialization is all complete. await _appStartedCompleter.future; await _connectDebugger(vmServiceUri); } } /// Handles the Flutter process exiting, terminating the debug session if it has not already begun terminating. @override void handleExitCode(int code) { final String codeSuffix = code == 0 ? '' : ' ($code)'; _logTraffic('<== [Flutter] Process exited ($code)'); handleSessionTerminate(codeSuffix); } /// Handles incoming JSON events from `flutter run --machine`. void handleJsonEvent(String event, Map<String, Object?>? params) { params ??= <String, Object?>{}; switch (event) { case 'daemon.connected': _handleDaemonConnected(params); case 'app.debugPort': _handleDebugPort(params); case 'app.start': _handleAppStart(params); case 'app.progress': _handleAppProgress(params); case 'app.started': _handleAppStarted(); } if (_eventsToForwardToClient.contains(event)) { // Forward the event to the client. sendEvent( RawEventBody(<String, Object?>{ 'event': event, 'params': params, }), eventType: 'flutter.forwardedEvent', ); } } /// Handles incoming reverse requests from `flutter run --machine`. /// /// These requests are usually just forwarded to the client via an event /// (`flutter.forwardedRequest`) and responses are provided by the client in a /// custom event (`flutter.forwardedRequestResponse`). void _handleJsonRequest( Object id, String method, Map<String, Object?>? params, ) { /// A helper to send a client response to Flutter. void sendResponseToFlutter(Object? id, Object? value, { bool error = false }) { sendFlutterMessage(<String, Object?>{ 'id': id, if (error) 'error': value else 'result': value }); } // Set up a completer to forward the response back to `flutter` when it arrives. final Completer<Object?> completer = Completer<Object?>(); _reverseRequestCompleters[id] = completer; completer.future .then( (Object? value) => sendResponseToFlutter(id, value), onError: (Object? e) => sendResponseToFlutter(id, e.toString(), error: true), ); if (_requestsToForwardToClient.contains(method)) { // Forward the request to the client in an event. sendEvent( RawEventBody(<String, Object?>{ 'id': id, 'method': method, 'params': params, }), eventType: 'flutter.forwardedRequest', ); } else { completer.completeError(ArgumentError.value(method, 'Unknown request method.')); } } /// Handles client responses to reverse-requests that were forwarded from Flutter. void _handleForwardedResponse(RawRequestArguments? args) { final Object? id = args?.args['id']; final Object? result = args?.args['result']; final Object? error = args?.args['error']; final Completer<Object?>? completer = _reverseRequestCompleters[id]; if (error != null) { completer?.completeError(DebugAdapterException('Client reported an error handling reverse-request $error')); } else { completer?.complete(result); } } /// Handles incoming JSON messages from `flutter run --machine` that are responses to requests that we sent. void _handleJsonResponse(int id, Map<String, Object?> response) { final Completer<Object?>? handler = _flutterRequestCompleters.remove(id); if (handler == null) { logger?.call( 'Received response from Flutter run daemon with ID $id ' 'but had not matching handler', ); return; } final Object? error = response['error']; final Object? result = response['result']; if (error != null) { handler.completeError(DebugAdapterException('$error')); } else { handler.complete(result); } } @override void handleStderr(List<int> data) { _logTraffic('<== [Flutter] [stderr] $data'); sendOutput('stderr', utf8.decode(data)); } /// Handles stdout from the `flutter run --machine` process, decoding the JSON and calling the appropriate handlers. @override void handleStdout(String data) { // Output intended for us to parse is JSON wrapped in brackets: // [{"event":"app.foo","params":{"bar":"baz"}}] // However, it's also possible a user printed things that look a little like // this so try to detect only things we're interested in: // - parses as JSON // - is a List of only a single item that is a Map<String, Object?> // - the item has an "event" field that is a String // - the item has a "params" field that is a Map<String, Object?>? _logTraffic('<== [Flutter] $data'); // Output is sent as console (eg. output from tooling) until the app has // started, then stdout (users output). This is so info like // "Launching lib/main.dart on Device foo" is formatted differently to // general output printed by the user. final String outputCategory = _receivedAppStarted ? 'stdout' : 'console'; // Output in stdout can include both user output (eg. print) and Flutter // daemon output. Since it's not uncommon for users to print JSON while // debugging, we must try to detect which messages are likely Flutter // messages as reliably as possible, as trying to process users output // as a Flutter message may result in an unhandled error that will // terminate the debug adapter in a way that does not provide feedback // because the standard crash violates the DAP protocol. Object? jsonData; try { jsonData = jsonDecode(data); } on FormatException { // If the output wasn't valid JSON, it was standard stdout that should // be passed through to the user. sendOutput(outputCategory, data); // Detect if the output contains a prompt about using the Dart Debug // extension and also update the progress notification to make it clearer // we're waiting for the user to do something. if (data.contains('Waiting for connection from Dart debug extension')) { launchProgress?.update( message: 'Please click the Dart Debug extension button in the spawned browser window', ); } return; } final Map<String, Object?>? payload = jsonData is List && jsonData.length == 1 && jsonData.first is Map<String, Object?> ? jsonData.first as Map<String, Object?> : null; if (payload == null) { // JSON didn't match expected format for Flutter responses, so treat as // standard user output. sendOutput(outputCategory, data); return; } final Object? event = payload['event']; final Object? method = payload['method']; final Object? params = payload['params']; final Object? id = payload['id']; if (event is String && params is Map<String, Object?>?) { handleJsonEvent(event, params); } else if (id != null && method is String && params is Map<String, Object?>?) { _handleJsonRequest(id, method, params); } else if (id is int && _flutterRequestCompleters.containsKey(id)) { _handleJsonResponse(id, payload); } else { // If it wasn't processed above, sendOutput(outputCategory, data); } } /// Logs JSON traffic to aid debugging. /// /// If `sendLogsToClient` was `true` in the launch/attach config, logs will /// also be sent back to the client in a "dart.log" event to simplify /// capturing logs from the IDE (such as using the **Dart: Capture Logs** /// command in VS Code). void _logTraffic(String message) { logger?.call(message); if (sendLogsToClient) { sendEvent( RawEventBody(<String, String>{'message': message}), eventType: 'dart.log', ); } } /// Performs a restart/reload by sending the `app.restart` message to the `flutter run --machine` process. Future<void> _performRestart( bool fullRestart, [ String? reason, ]) async { // Don't do anything if the app hasn't started yet, as restarts and reloads // can only operate on a running app. if (_appId == null) { return; } final String progressId = fullRestart ? 'hotRestart' : 'hotReload'; final String progressMessage = fullRestart ? 'Hot restarting…' : 'Hot reloading…'; final DapProgressReporter progress = startProgressNotification( progressId, 'Flutter', message: progressMessage, ); try { await sendFlutterRequest('app.restart', <String, Object?>{ 'appId': _appId, 'fullRestart': fullRestart, 'pause': enableDebugger, 'reason': reason, 'debounce': true, }); } on DebugAdapterException catch (error) { final String action = fullRestart ? 'Hot Restart' : 'Hot Reload'; sendOutput('console', 'Failed to $action: $error'); } finally { progress.end(); } } void _sendServiceExtensionStateChanged(vm.ExtensionData? extensionData) { final Map<String, dynamic>? data = extensionData?.data; if (data != null) { sendEvent( RawEventBody(data), eventType: 'flutter.serviceExtensionStateChanged', ); } } }
flutter/packages/flutter_tools/lib/src/debug_adapters/flutter_adapter.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/debug_adapters/flutter_adapter.dart", "repo_id": "flutter", "token_count": 9037 }
755
// 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/context.dart'; /// The current [FeatureFlags] implementation. FeatureFlags get featureFlags => context.get<FeatureFlags>()!; /// The interface used to determine if a particular [Feature] is enabled. /// /// The rest of the tools code should use this class instead of looking up /// features directly. To facilitate rolls to google3 and other clients, all /// flags should be provided with a default implementation here. Clients that /// use this class should extent instead of implement, so that new flags are /// picked up automatically. abstract class FeatureFlags { /// const constructor so that subclasses can be const. const FeatureFlags(); /// Whether flutter desktop for linux is enabled. bool get isLinuxEnabled => false; /// Whether flutter desktop for macOS is enabled. bool get isMacOSEnabled => false; /// Whether flutter web is enabled. bool get isWebEnabled => false; /// Whether flutter desktop for Windows is enabled. bool get isWindowsEnabled => false; /// Whether android is enabled. bool get isAndroidEnabled => true; /// Whether iOS is enabled. bool get isIOSEnabled => true; /// Whether fuchsia is enabled. bool get isFuchsiaEnabled => true; /// Whether custom devices are enabled. bool get areCustomDevicesEnabled => false; /// Whether WebAssembly compilation for Flutter Web is enabled. bool get isFlutterWebWasmEnabled => false; /// Whether animations are used in the command line interface. bool get isCliAnimationEnabled => true; /// Whether native assets compilation and bundling is enabled. bool get isNativeAssetsEnabled => false; /// Whether native assets compilation and bundling is enabled. bool get isPreviewDeviceEnabled => true; /// Whether a particular feature is enabled for the current channel. /// /// Prefer using one of the specific getters above instead of this API. bool isEnabled(Feature feature); } /// All current Flutter feature flags. const List<Feature> allFeatures = <Feature>[ flutterWebFeature, flutterLinuxDesktopFeature, flutterMacOSDesktopFeature, flutterWindowsDesktopFeature, flutterAndroidFeature, flutterIOSFeature, flutterFuchsiaFeature, flutterCustomDevicesFeature, flutterWebWasm, cliAnimation, nativeAssets, previewDevice, ]; /// All current Flutter feature flags that can be configured. /// /// [Feature.configSetting] is not `null`. Iterable<Feature> get allConfigurableFeatures => allFeatures.where((Feature feature) => feature.configSetting != null); /// The [Feature] for flutter web. const Feature flutterWebFeature = Feature.fullyEnabled( name: 'Flutter for web', configSetting: 'enable-web', environmentOverride: 'FLUTTER_WEB', ); /// The [Feature] for macOS desktop. const Feature flutterMacOSDesktopFeature = Feature.fullyEnabled( name: 'support for desktop on macOS', configSetting: 'enable-macos-desktop', environmentOverride: 'FLUTTER_MACOS', ); /// The [Feature] for Linux desktop. const Feature flutterLinuxDesktopFeature = Feature.fullyEnabled( name: 'support for desktop on Linux', configSetting: 'enable-linux-desktop', environmentOverride: 'FLUTTER_LINUX', ); /// The [Feature] for Windows desktop. const Feature flutterWindowsDesktopFeature = Feature.fullyEnabled( name: 'support for desktop on Windows', configSetting: 'enable-windows-desktop', environmentOverride: 'FLUTTER_WINDOWS', ); /// The [Feature] for Android devices. const Feature flutterAndroidFeature = Feature.fullyEnabled( name: 'Flutter for Android', configSetting: 'enable-android', ); /// The [Feature] for iOS devices. const Feature flutterIOSFeature = Feature.fullyEnabled( name: 'Flutter for iOS', configSetting: 'enable-ios', ); /// The [Feature] for Fuchsia support. const Feature flutterFuchsiaFeature = Feature( name: 'Flutter for Fuchsia', configSetting: 'enable-fuchsia', environmentOverride: 'FLUTTER_FUCHSIA', master: FeatureChannelSetting( available: true, ), ); const Feature flutterCustomDevicesFeature = Feature( name: 'early support for custom device types', configSetting: 'enable-custom-devices', environmentOverride: 'FLUTTER_CUSTOM_DEVICES', master: FeatureChannelSetting( available: true, ), beta: FeatureChannelSetting( available: true, ), stable: FeatureChannelSetting( available: true, ), ); /// Enabling WebAssembly compilation from `flutter build web` const Feature flutterWebWasm = Feature( name: 'WebAssembly compilation from flutter build web', environmentOverride: 'FLUTTER_WEB_WASM', beta: FeatureChannelSetting( available: true, enabledByDefault: true, ), master: FeatureChannelSetting( available: true, enabledByDefault: true, ), ); const String kCliAnimationsFeatureName = 'cli-animations'; /// The [Feature] for CLI animations. /// /// The TERM environment variable set to "dumb" turns this off. const Feature cliAnimation = Feature.fullyEnabled( name: 'animations in the command line interface', configSetting: kCliAnimationsFeatureName, ); /// Enable native assets compilation and bundling. const Feature nativeAssets = Feature( name: 'native assets compilation and bundling', configSetting: 'enable-native-assets', environmentOverride: 'FLUTTER_NATIVE_ASSETS', master: FeatureChannelSetting( available: true, ), ); /// Enable Flutter preview prebuilt device. const Feature previewDevice = Feature( name: 'Flutter preview prebuilt device', configSetting: 'enable-flutter-preview', environmentOverride: 'FLUTTER_PREVIEW_DEVICE', master: FeatureChannelSetting( available: true, ), beta: FeatureChannelSetting( available: true, ), ); /// A [Feature] is a process for conditionally enabling tool features. /// /// All settings are optional, and if not provided will generally default to /// a "safe" value, such as being off. /// /// The top level feature settings can be provided to apply to all channels. /// Otherwise, more specific settings take precedence over higher level /// settings. class Feature { /// Creates a [Feature]. const Feature({ required this.name, this.environmentOverride, this.configSetting, this.extraHelpText, this.master = const FeatureChannelSetting(), this.beta = const FeatureChannelSetting(), this.stable = const FeatureChannelSetting() }); /// Creates a [Feature] that is fully enabled across channels. const Feature.fullyEnabled( {required this.name, this.environmentOverride, this.configSetting, this.extraHelpText}) : master = const FeatureChannelSetting( available: true, enabledByDefault: true, ), beta = const FeatureChannelSetting( available: true, enabledByDefault: true, ), stable = const FeatureChannelSetting( available: true, enabledByDefault: true, ); /// The user visible name for this feature. final String name; /// The settings for the master branch and other unknown channels. final FeatureChannelSetting master; /// The settings for the beta branch. final FeatureChannelSetting beta; /// The settings for the stable branch. final FeatureChannelSetting stable; /// The name of an environment variable that can override the setting. /// /// The environment variable needs to be set to the value 'true'. This is /// only intended for usage by CI and not as an advertised method to enable /// a feature. /// /// If not provided, defaults to `null` meaning there is no override. final String? environmentOverride; /// The name of a setting that can be used to enable this feature. /// /// If not provided, defaults to `null` meaning there is no config setting. final String? configSetting; /// Additional text to add to the end of the help message. /// /// If not provided, defaults to `null` meaning there is no additional text. final String? extraHelpText; /// A help message for the `flutter config` command, or null if unsupported. String? generateHelpMessage() { if (configSetting == null) { return null; } final StringBuffer buffer = StringBuffer('Enable or disable $name.'); final List<String> channels = <String>[ if (master.available) 'master', if (beta.available) 'beta', if (stable.available) 'stable', ]; // Add channel info for settings only on some channels. if (channels.length == 1) { buffer.write('\nThis setting applies only to the ${channels.single} channel.'); } else if (channels.length == 2) { buffer.write('\nThis setting applies only to the ${channels.join(' and ')} channels.'); } if (extraHelpText != null) { buffer.write(' $extraHelpText'); } return buffer.toString(); } /// Retrieve the correct setting for the provided `channel`. FeatureChannelSetting getSettingForChannel(String channel) { switch (channel) { case 'stable': return stable; case 'beta': return beta; case 'master': default: return master; } } } /// A description of the conditions to enable a feature for a particular channel. class FeatureChannelSetting { const FeatureChannelSetting({ this.available = false, this.enabledByDefault = false, }); /// Whether the feature is available on this channel. /// /// If not provided, defaults to `false`. This implies that the feature /// cannot be enabled even by the settings below. final bool available; /// Whether the feature is enabled by default. /// /// If not provided, defaults to `false`. final bool enabledByDefault; }
flutter/packages/flutter_tools/lib/src/features.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/features.dart", "repo_id": "flutter", "token_count": 2822 }
756
// 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:process/process.dart'; import 'package:unified_analytics/unified_analytics.dart'; import 'android/android_sdk.dart'; import 'android/android_studio.dart'; import 'android/gradle_utils.dart'; import 'android/java.dart'; import 'artifacts.dart'; import 'base/bot_detector.dart'; import 'base/config.dart'; import 'base/context.dart'; import 'base/error_handling_io.dart'; import 'base/file_system.dart'; import 'base/io.dart'; import 'base/logger.dart'; import 'base/net.dart'; import 'base/os.dart'; import 'base/platform.dart'; import 'base/process.dart'; import 'base/signals.dart'; import 'base/template.dart'; import 'base/terminal.dart'; import 'base/time.dart'; import 'base/user_messages.dart'; import 'build_system/build_system.dart'; import 'build_system/build_targets.dart'; import 'cache.dart'; import 'custom_devices/custom_devices_config.dart'; import 'device.dart'; import 'doctor.dart'; import 'fuchsia/fuchsia_sdk.dart'; import 'ios/ios_workflow.dart'; import 'ios/plist_parser.dart'; import 'ios/simulators.dart'; import 'ios/xcodeproj.dart'; import 'macos/cocoapods.dart'; import 'macos/cocoapods_validator.dart'; import 'macos/xcdevice.dart'; import 'macos/xcode.dart'; import 'persistent_tool_state.dart'; import 'pre_run_validator.dart'; import 'project.dart'; import 'reporting/crash_reporting.dart'; import 'reporting/reporting.dart'; import 'runner/flutter_command.dart'; import 'runner/local_engine.dart'; import 'version.dart'; // TODO(ianh): We should remove all the global variables and replace them with // arguments (to constructors, methods, etc, as appropriate). Artifacts? get artifacts => context.get<Artifacts>(); BuildSystem get buildSystem => context.get<BuildSystem>()!; BuildTargets get buildTargets => context.get<BuildTargets>()!; Cache get cache => context.get<Cache>()!; CocoaPodsValidator? get cocoapodsValidator => context.get<CocoaPodsValidator>(); Config get config => context.get<Config>()!; CrashReporter? get crashReporter => context.get<CrashReporter>(); DeviceManager? get deviceManager => context.get<DeviceManager>(); Doctor? get doctor => context.get<Doctor>(); HttpClientFactory? get httpClientFactory => context.get<HttpClientFactory>(); IOSSimulatorUtils? get iosSimulatorUtils => context.get<IOSSimulatorUtils>(); Logger get logger => context.get<Logger>()!; OperatingSystemUtils get os => context.get<OperatingSystemUtils>()!; Signals get signals => context.get<Signals>() ?? LocalSignals.instance; AndroidStudio? get androidStudio => context.get<AndroidStudio>(); AndroidSdk? get androidSdk => context.get<AndroidSdk>(); FlutterVersion get flutterVersion => context.get<FlutterVersion>()!; FuchsiaArtifacts? get fuchsiaArtifacts => context.get<FuchsiaArtifacts>(); FuchsiaSdk? get fuchsiaSdk => context.get<FuchsiaSdk>(); Usage get flutterUsage => context.get<Usage>()!; XcodeProjectInterpreter? get xcodeProjectInterpreter => context.get<XcodeProjectInterpreter>(); XCDevice? get xcdevice => context.get<XCDevice>(); Xcode? get xcode => context.get<Xcode>(); IOSWorkflow? get iosWorkflow => context.get<IOSWorkflow>(); LocalEngineLocator? get localEngineLocator => context.get<LocalEngineLocator>(); PersistentToolState? get persistentToolState => PersistentToolState.instance; BotDetector get botDetector => context.get<BotDetector>() ?? _defaultBotDetector; final BotDetector _defaultBotDetector = BotDetector( httpClientFactory: context.get<HttpClientFactory>() ?? () => HttpClient(), platform: platform, persistentToolState: persistentToolState ?? PersistentToolState( fileSystem: fs, logger: logger, platform: platform, ), ); Future<bool> get isRunningOnBot => botDetector.isRunningOnBot; // Analytics instance for package:unified_analytics for analytics // reporting for all Flutter and Dart related tooling Analytics get analytics => context.get<Analytics>()!; /// Currently active implementation of the file system. /// /// By default it uses local disk-based implementation. Override this in tests /// with [MemoryFileSystem]. FileSystem get fs => ErrorHandlingFileSystem( delegate: context.get<FileSystem>() ?? localFileSystem, platform: platform, ); FileSystemUtils get fsUtils => context.get<FileSystemUtils>() ?? FileSystemUtils( fileSystem: fs, platform: platform, ); const ProcessManager _kLocalProcessManager = LocalProcessManager(); /// The active process manager. ProcessManager get processManager => context.get<ProcessManager>() ?? _kLocalProcessManager; ProcessUtils get processUtils => context.get<ProcessUtils>()!; const Platform _kLocalPlatform = LocalPlatform(); Platform get platform => context.get<Platform>() ?? _kLocalPlatform; UserMessages get userMessages => context.get<UserMessages>()!; final OutputPreferences _default = OutputPreferences( wrapText: stdio.hasTerminal, showColor: platform.stdoutSupportsAnsi, stdio: stdio, ); OutputPreferences get outputPreferences => context.get<OutputPreferences>() ?? _default; /// The current system clock instance. SystemClock get systemClock => context.get<SystemClock>() ?? _systemClock; SystemClock _systemClock = const SystemClock(); ProcessInfo get processInfo => context.get<ProcessInfo>()!; /// Display an error level message to the user. Commands should use this if they /// fail in some way. /// /// Set [emphasis] to true to make the output bold if it's supported. /// Set [color] to a [TerminalColor] to color the output, if the logger /// supports it. The [color] defaults to [TerminalColor.red]. void printError( String message, { StackTrace? stackTrace, bool? emphasis, TerminalColor? color, int? indent, int? hangingIndent, bool? wrap, }) { logger.printError( message, stackTrace: stackTrace, emphasis: emphasis ?? false, color: color, indent: indent, hangingIndent: hangingIndent, wrap: wrap, ); } /// Display a warning level message to the user. Commands should use this if they /// have important warnings to convey that aren't fatal. /// /// Set [emphasis] to true to make the output bold if it's supported. /// Set [color] to a [TerminalColor] to color the output, if the logger /// supports it. The [color] defaults to [TerminalColor.cyan]. void printWarning( String message, { bool? emphasis, TerminalColor? color, int? indent, int? hangingIndent, bool? wrap, }) { logger.printWarning( message, emphasis: emphasis ?? false, color: color, indent: indent, hangingIndent: hangingIndent, wrap: wrap, ); } /// Display normal output of the command. This should be used for things like /// progress messages, success messages, or just normal command output. /// /// Set `emphasis` to true to make the output bold if it's supported. /// /// Set `newline` to false to skip the trailing linefeed. /// /// If `indent` is provided, each line of the message will be prepended by the /// specified number of whitespaces. void printStatus( String message, { bool? emphasis, bool? newline, TerminalColor? color, int? indent, int? hangingIndent, bool? wrap, }) { logger.printStatus( message, emphasis: emphasis ?? false, color: color, newline: newline ?? true, indent: indent, hangingIndent: hangingIndent, wrap: wrap, ); } /// Display the [message] inside a box. /// /// For example, this is the generated output: /// /// ┌─ [title] ─┐ /// │ [message] │ /// └───────────┘ /// /// If a terminal is attached, the lines in [message] are automatically wrapped based on /// the available columns. void printBox(String message, { String? title, }) { logger.printBox(message, title: title); } /// Use this for verbose tracing output. Users can turn this output on in order /// to help diagnose issues with the toolchain or with their setup. void printTrace(String message) => logger.printTrace(message); AnsiTerminal get terminal { return context.get<AnsiTerminal>() ?? _defaultAnsiTerminal; } final AnsiTerminal _defaultAnsiTerminal = AnsiTerminal( stdio: stdio, platform: platform, now: DateTime.now(), ); /// The global Stdio wrapper. Stdio get stdio => context.get<Stdio>() ?? (_stdioInstance ??= Stdio()); Stdio? _stdioInstance; PlistParser get plistParser => context.get<PlistParser>() ?? ( _plistInstance ??= PlistParser( fileSystem: fs, processManager: processManager, logger: logger, )); PlistParser? _plistInstance; /// The global template renderer. TemplateRenderer get templateRenderer => context.get<TemplateRenderer>()!; /// Global [ShutdownHooks] that should be run before the tool process exits. /// /// This is depended on by [localFileSystem] which is called before any /// [Context] is set up, and thus this cannot be a Context getter. final ShutdownHooks shutdownHooks = ShutdownHooks(); // Unless we're in a test of this class's signal handling features, we must // have only one instance created with the singleton LocalSignals instance // and the catchable signals it considers to be fatal. LocalFileSystem? _instance; LocalFileSystem get localFileSystem => _instance ??= LocalFileSystem( LocalSignals.instance, Signals.defaultExitSignals, shutdownHooks, ); /// Gradle utils in the current [AppContext]. GradleUtils? get gradleUtils => context.get<GradleUtils>(); CocoaPods? get cocoaPods => context.get<CocoaPods>(); FlutterProjectFactory get projectFactory { return context.get<FlutterProjectFactory>() ?? FlutterProjectFactory( logger: logger, fileSystem: fs, ); } CustomDevicesConfig get customDevicesConfig => context.get<CustomDevicesConfig>()!; PreRunValidator get preRunValidator => context.get<PreRunValidator>() ?? const NoOpPreRunValidator(); // Used to build RegExp instances which can detect the VM service message. final RegExp kVMServiceMessageRegExp = RegExp(r'The Dart VM service is listening on ((http|//)[a-zA-Z0-9:/=_\-\.\[\]]+)'); // The official tool no longer allows non-null safe builds. This can be // overridden in other clients. NonNullSafeBuilds get nonNullSafeBuilds => context.get<NonNullSafeBuilds>() ?? NonNullSafeBuilds.notAllowed; /// Contains information about the JRE/JDK to use for Java-dependent operations. /// /// A value of [null] indicates that no installation of java could be found on /// the host machine. Java? get java => context.get<Java>();
flutter/packages/flutter_tools/lib/src/globals.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/globals.dart", "repo_id": "flutter", "token_count": 3348 }
757
// 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/file_system.dart'; import '../../base/project_migrator.dart'; import '../../xcode_project.dart'; // Update the xcodeproj build location. Legacy build location does not work with Swift Packages. class ProjectBuildLocationMigration extends ProjectMigrator { ProjectBuildLocationMigration( IosProject project, super.logger, ) : _xcodeProjectWorkspaceData = project.xcodeProjectWorkspaceData; final File _xcodeProjectWorkspaceData; @override void migrate() { if (!_xcodeProjectWorkspaceData.existsSync()) { logger.printTrace('Xcode project workspace data not found, skipping build location migration.'); return; } processFileLines(_xcodeProjectWorkspaceData); } @override String migrateLine(String line) { const String legacyBuildLocation = 'location = "group:Runner.xcodeproj"'; const String defaultBuildLocation = 'location = "self:"'; return line.replaceAll(legacyBuildLocation, defaultBuildLocation); } @override String migrateFileContents(String fileContents) { const String podLocation = ''' <FileRef location = "group:Pods/Pods.xcodeproj"> </FileRef> '''; return fileContents.replaceAll(podLocation, ''); } }
flutter/packages/flutter_tools/lib/src/ios/migrations/project_build_location_migration.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/ios/migrations/project_build_location_migration.dart", "repo_id": "flutter", "token_count": 436 }
758
// 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' hide BuildMode; import '../../../base/common.dart'; import '../../../base/file_system.dart'; import '../../../base/io.dart'; import '../../../build_info.dart'; import '../../../globals.dart' as globals; 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?> dryRunNativeAssetsLinux({ required NativeAssetsBuildRunner buildRunner, required Uri projectUri, bool flutterTester = false, required FileSystem fileSystem, }) { return dryRunNativeAssetsSingleArchitecture( buildRunner: buildRunner, projectUri: projectUri, flutterTester: flutterTester, fileSystem: fileSystem, os: OS.linux, ); } Future<Iterable<KernelAsset>> dryRunNativeAssetsLinuxInternal( FileSystem fileSystem, Uri projectUri, bool flutterTester, NativeAssetsBuildRunner buildRunner, ) { return dryRunNativeAssetsSingleArchitectureInternal( fileSystem, projectUri, flutterTester, buildRunner, OS.linux, ); } Future<(Uri? nativeAssetsYaml, List<Uri> dependencies)> buildNativeAssetsLinux({ 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, ); } /// Flutter expects `clang++` to be on the path on Linux hosts. /// /// Search for the accompanying `clang`, `ar`, and `ld`. Future<CCompilerConfig> cCompilerConfigLinux() async { const String kClangPlusPlusBinary = 'clang++'; const String kClangBinary = 'clang'; const String kArBinary = 'llvm-ar'; const String kLdBinary = 'ld.lld'; final ProcessResult whichResult = await globals.processManager.run(<String>['which', kClangPlusPlusBinary]); if (whichResult.exitCode != 0) { throwToolExit('Failed to find $kClangPlusPlusBinary on PATH.'); } File clangPpFile = globals.fs.file((whichResult.stdout as String).trim()); clangPpFile = globals.fs.file(await clangPpFile.resolveSymbolicLinks()); final Directory clangDir = clangPpFile.parent; final Map<String, Uri> binaryPaths = <String, Uri>{}; for (final String binary in <String>[kClangBinary, kArBinary, kLdBinary]) { final File binaryFile = clangDir.childFile(binary); if (!await binaryFile.exists()) { throwToolExit("Failed to find $binary relative to $clangPpFile: $binaryFile doesn't exist."); } binaryPaths[binary] = binaryFile.uri; } return CCompilerConfig( ar: binaryPaths[kArBinary], cc: binaryPaths[kClangBinary], ld: binaryPaths[kLdBinary], ); }
flutter/packages/flutter_tools/lib/src/isolated/native_assets/linux/native_assets.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/isolated/native_assets/linux/native_assets.dart", "repo_id": "flutter", "token_count": 1120 }
759
// 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/user_messages.dart'; import '../base/version.dart'; import '../build_info.dart'; import '../doctor_validator.dart'; import '../ios/simulators.dart'; import 'xcode.dart'; String _iOSSimulatorMissing(String version) => ''' iOS $version Simulator not installed; this may be necessary for iOS and macOS development. To download and install the platform, open Xcode, select Xcode > Settings > Platforms, and click the GET button for the required platform. For more information, please visit: https://developer.apple.com/documentation/xcode/installing-additional-simulator-runtimes'''; class XcodeValidator extends DoctorValidator { XcodeValidator({ required Xcode xcode, required IOSSimulatorUtils iosSimulatorUtils, required UserMessages userMessages, }) : _xcode = xcode, _iosSimulatorUtils = iosSimulatorUtils, _userMessages = userMessages, super('Xcode - develop for iOS and macOS'); final Xcode _xcode; final IOSSimulatorUtils _iosSimulatorUtils; final UserMessages _userMessages; @override Future<ValidationResult> validate() async { final List<ValidationMessage> messages = <ValidationMessage>[]; ValidationType xcodeStatus = ValidationType.missing; String? xcodeVersionInfo; final String? xcodeSelectPath = _xcode.xcodeSelectPath; if (_xcode.isInstalled) { xcodeStatus = ValidationType.success; if (xcodeSelectPath != null) { messages.add(ValidationMessage(_userMessages.xcodeLocation(xcodeSelectPath))); } final String? versionText = _xcode.versionText; if (versionText != null) { xcodeVersionInfo = versionText; if (xcodeVersionInfo.contains(',')) { xcodeVersionInfo = xcodeVersionInfo.substring(0, xcodeVersionInfo.indexOf(',')); } } if (_xcode.buildVersion != null) { messages.add(ValidationMessage('Build ${_xcode.buildVersion}')); } if (!_xcode.isInstalledAndMeetsVersionCheck) { xcodeStatus = ValidationType.partial; messages.add(ValidationMessage.error(_userMessages.xcodeOutdated(xcodeRequiredVersion.toString()))); } else if (!_xcode.isRecommendedVersionSatisfactory) { xcodeStatus = ValidationType.partial; messages.add(ValidationMessage.hint(_userMessages.xcodeRecommended(xcodeRecommendedVersion.toString()))); } if (!_xcode.eulaSigned) { xcodeStatus = ValidationType.partial; messages.add(ValidationMessage.error(_userMessages.xcodeEula)); } if (!_xcode.isSimctlInstalled) { xcodeStatus = ValidationType.partial; messages.add(ValidationMessage.error(_userMessages.xcodeMissingSimct)); } final ValidationMessage? missingSimulatorMessage = await _validateSimulatorRuntimeInstalled(); if (missingSimulatorMessage != null) { xcodeStatus = ValidationType.partial; messages.add(missingSimulatorMessage); } } else { xcodeStatus = ValidationType.missing; if (xcodeSelectPath == null || xcodeSelectPath.isEmpty) { messages.add(ValidationMessage.error(_userMessages.xcodeMissing)); } else { messages.add(ValidationMessage.error(_userMessages.xcodeIncomplete)); } } return ValidationResult(xcodeStatus, messages, statusInfo: xcodeVersionInfo); } /// Validate the Xcode-installed iOS simulator SDK has a corresponding iOS /// simulator runtime installed. /// /// Starting with Xcode 15, the iOS simulator runtime is no longer downloaded /// with Xcode and must be downloaded and installed separately. /// iOS applications cannot be run without it. Future<ValidationMessage?> _validateSimulatorRuntimeInstalled() async { // Skip this validation if Xcode is not installed, Xcode is a version less // than 15, simctl is not installed, or if the EULA is not signed. if (!_xcode.isInstalled || _xcode.currentVersion == null || _xcode.currentVersion!.major < 15 || !_xcode.isSimctlInstalled || !_xcode.eulaSigned) { return null; } final Version? platformSDKVersion = await _xcode.sdkPlatformVersion(EnvironmentType.simulator); if (platformSDKVersion == null) { return const ValidationMessage.error('Unable to find the iPhone Simulator SDK.'); } final List<IOSSimulatorRuntime> runtimes = await _iosSimulatorUtils.getAvailableIOSRuntimes(); if (runtimes.isEmpty) { return const ValidationMessage.error('Unable to get list of installed Simulator runtimes.'); } // Verify there is a simulator runtime installed matching the // iphonesimulator SDK major version. try { runtimes.firstWhere( (IOSSimulatorRuntime runtime) => runtime.version?.major == platformSDKVersion.major, ); } on StateError { return ValidationMessage.hint(_iOSSimulatorMissing(platformSDKVersion.toString())); } return null; } }
flutter/packages/flutter_tools/lib/src/macos/xcode_validator.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/macos/xcode_validator.dart", "repo_id": "flutter", "token_count": 1789 }
760
// 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 List<ProjectValidatorResult> result = <ProjectValidatorResult>[]; result.add(ProjectValidatorResult( name: 'FlutterProject.directory', value: _toJsonValue(project.directory.absolute.path), status: StatusProjectValidator.info, )); result.add(ProjectValidatorResult( name: 'FlutterProject.metadataFile', value: _toJsonValue(project.metadataFile.absolute.path), status: StatusProjectValidator.info, )); result.add(ProjectValidatorResult( name: 'FlutterProject.android.exists', value: _toJsonValue(project.android.existsSync()), status: StatusProjectValidator.info, )); result.add(ProjectValidatorResult( name: 'FlutterProject.ios.exists', value: _toJsonValue(project.ios.exists), status: StatusProjectValidator.info, )); result.add(ProjectValidatorResult( name: 'FlutterProject.web.exists', value: _toJsonValue(project.web.existsSync()), status: StatusProjectValidator.info, )); result.add(ProjectValidatorResult( name: 'FlutterProject.macos.exists', value: _toJsonValue(project.macos.existsSync()), status: StatusProjectValidator.info, )); result.add(ProjectValidatorResult( name: 'FlutterProject.linux.exists', value: _toJsonValue(project.linux.existsSync()), status: StatusProjectValidator.info, )); result.add(ProjectValidatorResult( name: 'FlutterProject.windows.exists', value: _toJsonValue(project.windows.existsSync()), status: StatusProjectValidator.info, )); result.add(ProjectValidatorResult( name: 'FlutterProject.fuchsia.exists', value: _toJsonValue(project.fuchsia.existsSync()), status: StatusProjectValidator.info, )); result.add(ProjectValidatorResult( name: 'FlutterProject.android.isKotlin', value: _toJsonValue(project.android.isKotlin), status: StatusProjectValidator.info, )); result.add(ProjectValidatorResult( name: 'FlutterProject.ios.isSwift', value: _toJsonValue(project.ios.isSwift), status: StatusProjectValidator.info, )); result.add(ProjectValidatorResult( name: 'FlutterProject.isModule', value: _toJsonValue(project.isModule), status: StatusProjectValidator.info, )); result.add(ProjectValidatorResult( name: 'FlutterProject.isPlugin', value: _toJsonValue(project.isPlugin), status: StatusProjectValidator.info, )); result.add(ProjectValidatorResult( name: 'FlutterProject.manifest.appname', value: _toJsonValue(project.manifest.appName), status: StatusProjectValidator.info, )); // FlutterVersion final FlutterVersion version = FlutterVersion( flutterRoot: Cache.flutterRoot!, fs: fileSystem, ); result.add(ProjectValidatorResult( name: 'FlutterVersion.frameworkRevision', value: _toJsonValue(version.frameworkRevision), status: StatusProjectValidator.info, )); // Platform result.add(ProjectValidatorResult( name: 'Platform.operatingSystem', value: _toJsonValue(platform.operatingSystem), status: StatusProjectValidator.info, )); result.add(ProjectValidatorResult( name: 'Platform.isAndroid', value: _toJsonValue(platform.isAndroid), status: StatusProjectValidator.info, )); result.add(ProjectValidatorResult( name: 'Platform.isIOS', value: _toJsonValue(platform.isIOS), status: StatusProjectValidator.info, )); result.add(ProjectValidatorResult( name: 'Platform.isWindows', value: _toJsonValue(platform.isWindows), status: StatusProjectValidator.info, )); result.add(ProjectValidatorResult( name: 'Platform.isMacOS', value: _toJsonValue(platform.isMacOS), status: StatusProjectValidator.info, )); result.add(ProjectValidatorResult( name: 'Platform.isFuchsia', value: _toJsonValue(platform.isFuchsia), status: StatusProjectValidator.info, )); result.add(ProjectValidatorResult( name: 'Platform.pathSeparator', value: _toJsonValue(platform.pathSeparator), status: StatusProjectValidator.info, )); // Cache result.add(ProjectValidatorResult( name: 'Cache.flutterRoot', value: _toJsonValue(Cache.flutterRoot), status: StatusProjectValidator.info, )); return result; } @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": 4225 }
761
// 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 }
762
// 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) { 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); return shelf.Response.ok( file.openRead(), headers: <String, String>{ if (contentType != null) 'Content-Type': contentType }, ); }; } 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 File testDartJs, required File testHostDartJs, required ChromiumLauncher chromiumLauncher, required Logger logger, required Artifacts? artifacts, required ProcessManager processManager, required this.webRenderer, TestTimeRecorder? testTimeRecorder, }) : _fileSystem = fileSystem, _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')), )) .add(_handleStaticArtifact) .add(_localCanvasKitHandler) .add(_goldenFileHandler) .add(_wrapperHandler) .add(_handleTestRequest) .add(createDirectoryHandler( fileSystem.directory(fileSystem.path.join(fileSystem.currentDirectory.path, 'test')) )) .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 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; /// 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 Logger logger, required ChromiumLauncher chromiumLauncher, required Artifacts? artifacts, required ProcessManager processManager, required WebRendererMode webRenderer, 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, chromiumLauncher: chromiumLauncher, artifacts: artifacts, logger: logger, nullAssertions: nullAssertions, processManager: processManager, webRenderer: webRenderer, 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 _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('.dart.browser_test.dart.js')) { final String leadingPath = request.url.path.split('.browser_test.dart.js')[0]; final String generatedFile = '${_fileSystem.path.split(leadingPath).join('_')}.bootstrap.js'; return shelf.Response.ok(generateTestBootstrapFileContents('/$generatedFile', 'require.js', 'dart_stack_trace_mapper.js'), headers: <String, String>{ HttpHeaders.contentTypeHeader: 'text/javascript', }); } if (request.url.path.endsWith('.dart.bootstrap.js')) { final String leadingPath = request.url.path.split('.dart.bootstrap.js')[0]; final String generatedFile = '${_fileSystem.path.split(leadingPath).join('_')}.dart.test.dart.js'; return shelf.Response.ok(generateMainModule( nullAssertions: nullAssertions!, nativeNullAssertions: true, bootstrapModule: '${_fileSystem.path.basename(leadingPath)}.dart.bootstrap', entrypoint: '/$generatedFile' ), 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 { 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)); 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); } return shelf.Response.ok( _canvasKitFile(relativePath).openRead(), headers: <String, Object>{ HttpHeaders.contentTypeHeader: contentType, }, ); } // 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'; final String scriptBase = htmlEscape.convert(_fileSystem.path.basename(test)); final String link = '<link rel="x-dart-test" href="$scriptBase">'; return shelf.Response.ok(''' <!DOCTYPE html> <html> <head> <title>${htmlEscape.convert(test)} Test</title> <script> window.flutterConfiguration = { canvasKitBaseUrl: "/canvaskit/" }; </script> $link <script src="static/dart.js"></script> </head> </html> ''', headers: <String, String>{'Content-Type': 'text/html'}); } 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": 12001 }
763
// 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 }
764
// 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 }
765
<!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 }
766
<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 }
767
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 }
768
#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 }
769
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 }
770
#include <flutter_linux/flutter_linux.h> #include "include/{{projectName}}/{{pluginClassSnakeCase}}.h" // This file exposes some plugin internals for unit testing. See // https://github.com/flutter/flutter/issues/88724 for current limitations // in the unit-testable API. // Handles the getPlatformVersion method call. FlMethodResponse *get_platform_version();
flutter/packages/flutter_tools/templates/plugin/linux.tmpl/pluginClassSnakeCase_private.h.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/templates/plugin/linux.tmpl/pluginClassSnakeCase_private.h.tmpl", "repo_id": "flutter", "token_count": 106 }
771
# # To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html. # Run `pod lib lint {{projectName}}.podspec` to validate before publishing. # Pod::Spec.new do |s| s.name = '{{projectName}}' s.version = '0.0.1' s.summary = '{{description}}' s.description = <<-DESC {{description}} DESC s.homepage = 'http://example.com' s.license = { :file => '../LICENSE' } s.author = { 'Your Company' => '[email protected]' } # This will ensure the source files in Classes/ are included in the native # builds of apps using this FFI plugin. Podspec does not support relative # paths, so Classes contains a forwarder C file that relatively imports # `../src/*` so that the C sources can be shared among all target platforms. s.source = { :path => '.' } s.source_files = 'Classes/**/*' s.dependency 'Flutter' s.platform = :ios, '12.0' # Flutter.framework does not contain a i386 slice. s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386' } s.swift_version = '5.0' end
flutter/packages/flutter_tools/templates/plugin_ffi/ios.tmpl/projectName.podspec.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/templates/plugin_ffi/ios.tmpl/projectName.podspec.tmpl", "repo_id": "flutter", "token_count": 466 }
772
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="{{androidIdentifier}}"> </manifest>
flutter/packages/flutter_tools/templates/plugin_shared/android.tmpl/src/main/AndroidManifest.xml.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/templates/plugin_shared/android.tmpl/src/main/AndroidManifest.xml.tmpl", "repo_id": "flutter", "token_count": 41 }
773
import 'package:flutter/material.dart'; import 'settings_service.dart'; /// A class that many Widgets can interact with to read user settings, update /// user settings, or listen to user settings changes. /// /// Controllers glue Data Services to Flutter Widgets. The SettingsController /// uses the SettingsService to store and retrieve user settings. class SettingsController with ChangeNotifier { SettingsController(this._settingsService); // Make SettingsService a private variable so it is not used directly. final SettingsService _settingsService; // Make ThemeMode a private variable so it is not updated directly without // also persisting the changes with the SettingsService. late ThemeMode _themeMode; // Allow Widgets to read the user's preferred ThemeMode. ThemeMode get themeMode => _themeMode; /// Load the user's settings from the SettingsService. It may load from a /// local database or the internet. The controller only knows it can load the /// settings from the service. Future<void> loadSettings() async { _themeMode = await _settingsService.themeMode(); // Important! Inform listeners a change has occurred. notifyListeners(); } /// Update and persist the ThemeMode based on the user's selection. Future<void> updateThemeMode(ThemeMode? newThemeMode) async { if (newThemeMode == null) return; // Do not perform any work if new and old ThemeMode are identical if (newThemeMode == _themeMode) return; // Otherwise, store the new ThemeMode in memory _themeMode = newThemeMode; // Important! Inform listeners a change has occurred. notifyListeners(); // Persist the changes to a local database or the internet using the // SettingService. await _settingsService.updateThemeMode(newThemeMode); } }
flutter/packages/flutter_tools/templates/skeleton/lib/src/settings/settings_controller.dart.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/templates/skeleton/lib/src/settings/settings_controller.dart.tmpl", "repo_id": "flutter", "token_count": 468 }
774
// 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: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/process.dart'; import 'package:flutter_tools/src/build_info.dart'; import 'package:flutter_tools/src/build_system/build_system.dart'; import 'package:flutter_tools/src/cache.dart'; import 'package:flutter_tools/src/commands/build.dart'; import 'package:flutter_tools/src/commands/build_macos.dart'; import 'package:flutter_tools/src/features.dart'; import 'package:flutter_tools/src/ios/xcodeproj.dart'; import 'package:flutter_tools/src/project.dart'; import 'package:flutter_tools/src/reporting/reporting.dart'; 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_build_system.dart'; import '../../src/test_flutter_command_runner.dart'; class FakeXcodeProjectInterpreterWithProfile extends FakeXcodeProjectInterpreter { @override Future<XcodeProjectInfo> getInfo(String projectPath, { String? projectFilename }) async { return XcodeProjectInfo( <String>['Runner'], <String>['Debug', 'Profile', 'Release'], <String>['Runner'], BufferLogger.test(), ); } } final Platform macosPlatform = FakePlatform( operatingSystem: 'macos', environment: <String, String>{ 'FLUTTER_ROOT': '/', 'HOME': '/', } ); final FakePlatform macosPlatformCustomEnv = FakePlatform( operatingSystem: 'macos', environment: <String, String>{ 'FLUTTER_ROOT': '/', 'HOME': '/', } ); final Platform notMacosPlatform = FakePlatform( environment: <String, String>{ 'FLUTTER_ROOT': '/', } ); void main() { late FileSystem fileSystem; late TestUsage usage; late FakeProcessManager fakeProcessManager; late ProcessUtils processUtils; late BufferLogger logger; late XcodeProjectInterpreter xcodeProjectInterpreter; late Artifacts artifacts; late FakeAnalytics fakeAnalytics; setUpAll(() { Cache.disableLocking(); }); setUp(() { fileSystem = MemoryFileSystem.test(); artifacts = Artifacts.test(fileSystem: fileSystem); logger = BufferLogger.test(); usage = TestUsage(); fakeProcessManager = FakeProcessManager.empty(); processUtils = ProcessUtils( logger: logger, processManager: fakeProcessManager, ); xcodeProjectInterpreter = FakeXcodeProjectInterpreter(); fakeAnalytics = getInitializedFakeAnalyticsInstance( fs: fileSystem, fakeFlutterVersion: FakeFlutterVersion(), ); }); // Sets up the minimal mock project files necessary to look like a Flutter project. void createCoreMockProjectFiles() { fileSystem.file('pubspec.yaml').createSync(); fileSystem.file('.packages').createSync(); fileSystem.file(fileSystem.path.join('lib', 'main.dart')).createSync(recursive: true); } // Sets up the minimal mock project files necessary for macOS builds to succeed. void createMinimalMockProjectFiles() { fileSystem.directory(fileSystem.path.join('macos', 'Runner.xcworkspace')).createSync(recursive: true); createCoreMockProjectFiles(); } // Creates a FakeCommand for the xcodebuild call to build the app // in the given configuration. FakeCommand setUpFakeXcodeBuildHandler(String configuration, { bool verbose = false, void Function(List<String> command)? onRun }) { final FlutterProject flutterProject = FlutterProject.fromDirectory(fileSystem.currentDirectory); final Directory flutterBuildDir = fileSystem.directory(getMacOSBuildDirectory()); return FakeCommand( command: <String>[ '/usr/bin/env', 'xcrun', 'xcodebuild', '-workspace', flutterProject.macos.xcodeWorkspace!.path, '-configuration', configuration, '-scheme', 'Runner', '-derivedDataPath', flutterBuildDir.absolute.path, '-destination', 'platform=macOS', 'OBJROOT=${fileSystem.path.join(flutterBuildDir.absolute.path, 'Build', 'Intermediates.noindex')}', 'SYMROOT=${fileSystem.path.join(flutterBuildDir.absolute.path, 'Build', 'Products')}', if (verbose) 'VERBOSE_SCRIPT_LOGGING=YES' else '-quiet', 'COMPILER_INDEX_STORE_ENABLE=NO', ], stdout: ''' STDOUT STUFF note: Using new build system note: Planning note: Build preparation complete note: Building targets in dependency order ''', stderr: ''' 2022-03-24 10:07:21.954 xcodebuild[2096:1927385] Requested but did not find extension point with identifier Xcode.IDEKit.ExtensionSentinelHostApplications for extension Xcode.DebuggerFoundation.AppExtensionHosts.watchOS of plug-in com.apple.dt.IDEWatchSupportCore 2022-03-24 10:07:21.954 xcodebuild[2096:1927385] Requested but did not find extension point with identifier Xcode.IDEKit.ExtensionPointIdentifierToBundleIdentifier for extension Xcode.DebuggerFoundation.AppExtensionToBundleIdentifierMap.watchOS of plug-in com.apple.dt.IDEWatchSupportCore 2023-11-10 10:44:58.030 xcodebuild[61115:1017566] [MT] DVTAssertions: Warning in /System/Volumes/Data/SWE/Apps/DT/BuildRoots/BuildRoot11/ActiveBuildRoot/Library/Caches/com.apple.xbs/Sources/IDEFrameworks/IDEFrameworks-22267/IDEFoundation/Provisioning/Capabilities Infrastructure/IDECapabilityQuerySelection.swift:103 Details: createItemModels creation requirements should not create capability item model for a capability item model that already exists. Function: createItemModels(for:itemModelSource:) Thread: <_NSMainThread: 0x6000027c0280>{number = 1, name = main} Please file a bug at https://feedbackassistant.apple.com with this warning message and any useful information you can provide. STDERR STUFF ''', onRun: (List<String> command) { fileSystem.file(fileSystem.path.join('macos', 'Flutter', 'ephemeral', '.app_filename')) ..createSync(recursive: true) ..writeAsStringSync('example.app'); if (onRun != null) { onRun(command); } } ); } testUsingContext('macOS build fails when there is no macos project', () async { final BuildCommand command = BuildCommand( artifacts: artifacts, androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: fileSystem, logger: logger, processUtils: processUtils, osUtils: FakeOperatingSystemUtils(), ); createCoreMockProjectFiles(); expect(createTestCommandRunner(command).run( const <String>['build', 'macos', '--no-pub'] ), throwsToolExit(message: 'No macOS desktop project configured. See ' 'https://docs.flutter.dev/desktop#add-desktop-support-to-an-existing-flutter-app ' 'to learn about adding macOS support to a project.')); }, overrides: <Type, Generator>{ Platform: () => macosPlatform, FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.any(), FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true), }); testUsingContext('macOS build successfully with renamed .xcodeproj/.xcworkspace files', () async { final BuildCommand command = BuildCommand( artifacts: artifacts, androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: fileSystem, logger: logger, processUtils: processUtils, osUtils: FakeOperatingSystemUtils(), ); fileSystem.directory(fileSystem.path.join('macos', 'RenamedProj.xcodeproj')).createSync(recursive: true); fileSystem.directory(fileSystem.path.join('macos', 'RenamedWorkspace.xcworkspace')).createSync(recursive: true); createCoreMockProjectFiles(); await createTestCommandRunner(command).run( const <String>['build', 'macos', '--no-pub'] ); expect( analyticsTimingEventExists( sentEvents: fakeAnalytics.sentEvents, workflow: 'build', variableName: 'xcode-macos', ), true, ); }, overrides: <Type, Generator>{ Platform: () => macosPlatform, FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.any(), FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true), Analytics: () => fakeAnalytics, }); testUsingContext('macOS build fails on non-macOS platform', () async { final BuildCommand command = BuildCommand( artifacts: artifacts, androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: fileSystem, logger: logger, processUtils: processUtils, osUtils: FakeOperatingSystemUtils(), ); fileSystem.file('pubspec.yaml').createSync(); fileSystem.file(fileSystem.path.join('lib', 'main.dart')) .createSync(recursive: true); expect(createTestCommandRunner(command).run( const <String>['build', 'macos', '--no-pub'] ), throwsA(isA<UsageException>())); }, overrides: <Type, Generator>{ Platform: () => notMacosPlatform, FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.any(), FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true), }); testUsingContext('macOS build fails when feature is disabled', () async { final BuildCommand command = BuildCommand( artifacts: artifacts, androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: fileSystem, logger: logger, processUtils: processUtils, osUtils: FakeOperatingSystemUtils(), ); fileSystem.file('pubspec.yaml').createSync(); fileSystem.file(fileSystem.path.join('lib', 'main.dart')) .createSync(recursive: true); expect(createTestCommandRunner(command).run( const <String>['build', 'macos', '--no-pub'] ), throwsToolExit(message: '"build macos" is not currently supported. To enable, run "flutter config --enable-macos-desktop".')); }, overrides: <Type, Generator>{ Platform: () => macosPlatform, FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.any(), FeatureFlags: () => TestFeatureFlags(), }); testUsingContext('macOS build forwards error stdout to status logger error', () async { final BuildCommand command = BuildCommand( artifacts: artifacts, androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: fileSystem, logger: logger, processUtils: processUtils, osUtils: FakeOperatingSystemUtils(), ); createMinimalMockProjectFiles(); await createTestCommandRunner(command).run( const <String>['build', 'macos', '--debug', '--no-pub'] ); expect(testLogger.statusText, isNot(contains('STDOUT STUFF'))); expect(testLogger.traceText, isNot(contains('STDOUT STUFF'))); expect(testLogger.errorText, contains('STDOUT STUFF')); expect(testLogger.errorText, contains('STDERR STUFF')); // Filters out some xcodebuild logging spew. expect(testLogger.errorText, isNot(contains('xcodebuild[2096:1927385]'))); expect(testLogger.errorText, isNot(contains('Using new build system'))); expect(testLogger.errorText, isNot(contains('Building targets in dependency order'))); expect(testLogger.errorText, isNot(contains('DVTAssertions: Warning in'))); expect(testLogger.errorText, isNot(contains('createItemModels'))); expect(testLogger.errorText, isNot(contains('_NSMainThread:'))); expect(testLogger.errorText, isNot(contains('Please file a bug at https://feedbackassistant'))); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.list(<FakeCommand>[ setUpFakeXcodeBuildHandler('Debug'), ]), Platform: () => macosPlatform, FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true), }); testUsingContext('macOS build invokes xcode build (debug)', () async { final BuildCommand command = BuildCommand( artifacts: artifacts, androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: fileSystem, logger: logger, processUtils: processUtils, osUtils: FakeOperatingSystemUtils(), ); createMinimalMockProjectFiles(); await createTestCommandRunner(command).run( const <String>['build', 'macos', '--debug', '--no-pub'] ); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.list(<FakeCommand>[ setUpFakeXcodeBuildHandler('Debug'), ]), Platform: () => macosPlatform, FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true), }); testUsingContext('macOS build invokes xcode build (debug) with verbosity', () async { final BuildCommand command = BuildCommand( artifacts: artifacts, androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: fileSystem, logger: logger, processUtils: processUtils, osUtils: FakeOperatingSystemUtils(), ); createMinimalMockProjectFiles(); await createTestCommandRunner(command).run( const <String>['build', 'macos', '--debug', '--no-pub', '-v'] ); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.list(<FakeCommand>[ setUpFakeXcodeBuildHandler('Debug', verbose: true), ]), Platform: () => macosPlatform, FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true), }); testUsingContext('macOS build invokes xcode build (profile)', () async { final BuildCommand command = BuildCommand( artifacts: artifacts, androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: fileSystem, logger: logger, processUtils: processUtils, osUtils: FakeOperatingSystemUtils(), ); createMinimalMockProjectFiles(); await createTestCommandRunner(command).run( const <String>['build', 'macos', '--profile', '--no-pub'] ); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.list(<FakeCommand>[ setUpFakeXcodeBuildHandler('Profile'), ]), Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithProfile(), FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true), }); testUsingContext('macOS build invokes xcode build (release)', () async { final BuildCommand command = BuildCommand( artifacts: artifacts, androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: fileSystem, logger: logger, processUtils: processUtils, osUtils: FakeOperatingSystemUtils(), ); createMinimalMockProjectFiles(); await createTestCommandRunner(command).run( const <String>['build', 'macos', '--release', '--no-pub'] ); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.list(<FakeCommand>[ setUpFakeXcodeBuildHandler('Release'), ]), Platform: () => macosPlatform, FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true), }); testUsingContext('macOS build supports standard desktop build options', () async { final BuildCommand command = BuildCommand( artifacts: artifacts, androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: fileSystem, logger: logger, processUtils: processUtils, osUtils: FakeOperatingSystemUtils(), ); createMinimalMockProjectFiles(); fileSystem.file('lib/other.dart') .createSync(recursive: true); fileSystem.file('foo/bar.sksl.json') .createSync(recursive: true); await createTestCommandRunner(command).run( const <String>[ 'build', 'macos', '--target=lib/other.dart', '--no-pub', '--track-widget-creation', '--split-debug-info=foo/', '--enable-experiment=non-nullable', '--obfuscate', '--dart-define=foo.bar=2', '--dart-define=fizz.far=3', '--tree-shake-icons', '--bundle-sksl-path=foo/bar.sksl.json', ] ); final List<String> contents = fileSystem .file('./macos/Flutter/ephemeral/Flutter-Generated.xcconfig') .readAsLinesSync(); expect(contents, containsAll(<String>[ 'FLUTTER_APPLICATION_PATH=/', 'FLUTTER_TARGET=lib/other.dart', 'FLUTTER_BUILD_DIR=build', 'FLUTTER_BUILD_NAME=1.0.0', 'FLUTTER_BUILD_NUMBER=1', 'DART_DEFINES=Zm9vLmJhcj0y,Zml6ei5mYXI9Mw==', 'DART_OBFUSCATION=true', 'EXTRA_FRONT_END_OPTIONS=--enable-experiment=non-nullable', 'EXTRA_GEN_SNAPSHOT_OPTIONS=--enable-experiment=non-nullable', 'SPLIT_DEBUG_INFO=foo/', 'TRACK_WIDGET_CREATION=true', 'TREE_SHAKE_ICONS=true', 'BUNDLE_SKSL_PATH=foo/bar.sksl.json', 'PACKAGE_CONFIG=/.dart_tool/package_config.json', 'COCOAPODS_PARALLEL_CODE_SIGN=true', ])); expect(contents, isNot(contains('EXCLUDED_ARCHS'))); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.list(<FakeCommand>[ setUpFakeXcodeBuildHandler('Release'), ]), Platform: () => macosPlatform, FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true), Artifacts: () => Artifacts.test(), }); testUsingContext('build settings contains Flutter Xcode environment variables', () async { macosPlatformCustomEnv.environment = Map<String, String>.unmodifiable(<String, String>{ 'FLUTTER_XCODE_ASSETCATALOG_COMPILER_APPICON_NAME': 'AppIcon.special', }); final FlutterProject flutterProject = FlutterProject.fromDirectory(fileSystem.currentDirectory); final Directory flutterBuildDir = fileSystem.directory(getMacOSBuildDirectory()); createMinimalMockProjectFiles(); fakeProcessManager.addCommands(<FakeCommand>[ FakeCommand( command: <String>[ '/usr/bin/env', 'xcrun', 'xcodebuild', '-workspace', flutterProject.macos.xcodeWorkspace!.path, '-configuration', 'Debug', '-scheme', 'Runner', '-derivedDataPath', flutterBuildDir.absolute.path, '-destination', 'platform=macOS', 'OBJROOT=${fileSystem.path.join(flutterBuildDir.absolute.path, 'Build', 'Intermediates.noindex')}', 'SYMROOT=${fileSystem.path.join(flutterBuildDir.absolute.path, 'Build', 'Products')}', '-quiet', 'COMPILER_INDEX_STORE_ENABLE=NO', 'ASSETCATALOG_COMPILER_APPICON_NAME=AppIcon.special', ], ), ]); final BuildCommand command = BuildCommand( artifacts: artifacts, androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: fileSystem, logger: logger, processUtils: processUtils, osUtils: FakeOperatingSystemUtils(), ); await createTestCommandRunner(command).run( const <String>['build', 'macos', '--debug', '--no-pub'] ); expect(fakeProcessManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => fakeProcessManager, Platform: () => macosPlatformCustomEnv, FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true), XcodeProjectInterpreter: () => xcodeProjectInterpreter, }); testUsingContext('macOS build supports build-name and build-number', () async { final BuildCommand command = BuildCommand( artifacts: artifacts, androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: fileSystem, logger: logger, processUtils: processUtils, osUtils: FakeOperatingSystemUtils(), ); createMinimalMockProjectFiles(); await createTestCommandRunner(command).run( const <String>[ 'build', 'macos', '--debug', '--no-pub', '--build-name=1.2.3', '--build-number=42', ], ); final String contents = fileSystem .file('./macos/Flutter/ephemeral/Flutter-Generated.xcconfig') .readAsStringSync(); expect(contents, contains('FLUTTER_BUILD_NAME=1.2.3')); expect(contents, contains('FLUTTER_BUILD_NUMBER=42')); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.list(<FakeCommand>[ setUpFakeXcodeBuildHandler('Debug'), ]), Platform: () => macosPlatform, FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true), }); testUsingContext('Refuses to build for macOS when feature is disabled', () { final CommandRunner<void> runner = createTestCommandRunner(BuildCommand( artifacts: artifacts, androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: fileSystem, logger: logger, processUtils: processUtils, osUtils: FakeOperatingSystemUtils(), )); final bool supported = BuildMacosCommand(logger: BufferLogger.test(), verboseHelp: false).supported; expect(() => runner.run(<String>['build', 'macos', '--no-pub']), supported ? throwsToolExit() : throwsA(isA<UsageException>())); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(), }); testUsingContext('hidden when not enabled on macOS host', () { expect(BuildMacosCommand(logger: BufferLogger.test(), verboseHelp: false).hidden, true); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(), Platform: () => macosPlatform, }); testUsingContext('Not hidden when enabled and on macOS host', () { expect(BuildMacosCommand(logger: BufferLogger.test(), verboseHelp: false).hidden, false); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true), Platform: () => macosPlatform, }); testUsingContext('code size analysis throws StateError if no code size snapshot generated by gen_snapshot', () async { final BuildCommand command = BuildCommand( artifacts: artifacts, androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: fileSystem, logger: logger, processUtils: processUtils, osUtils: FakeOperatingSystemUtils(), ); createMinimalMockProjectFiles(); fileSystem.file('build/macos/Build/Products/Release/Runner.app/App') ..createSync(recursive: true) ..writeAsBytesSync(List<int>.generate(10000, (int index) => 0)); expect( () => createTestCommandRunner(command).run( const <String>['build', 'macos', '--no-pub', '--analyze-size'] ), throwsA( isA<StateError>().having( (StateError err) => err.message, 'message', 'No code size snapshot file (snapshot.<ARCH>.json) found in build/flutter_size_01', ), ), ); expect(testLogger.statusText, isEmpty); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.list(<FakeCommand>[ // we never generate code size snapshot here setUpFakeXcodeBuildHandler('Release'), ]), Platform: () => macosPlatform, FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true), FileSystemUtils: () => FileSystemUtils(fileSystem: fileSystem, platform: macosPlatform), Usage: () => usage, Analytics: () => fakeAnalytics, }); testUsingContext('Performs code size analysis and sends analytics from arm64 host', () async { final BuildCommand command = BuildCommand( artifacts: artifacts, androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: fileSystem, logger: logger, processUtils: processUtils, osUtils: FakeOperatingSystemUtils(), ); createMinimalMockProjectFiles(); fileSystem.file('build/macos/Build/Products/Release/Runner.app/App') ..createSync(recursive: true) ..writeAsBytesSync(List<int>.generate(10000, (int index) => 0)); await createTestCommandRunner(command).run( const <String>['build', 'macos', '--no-pub', '--analyze-size'] ); expect(testLogger.statusText, contains('A summary of your macOS bundle analysis can be found at')); expect(testLogger.statusText, contains('dart devtools --appSizeBase=')); expect(usage.events, contains( const TestUsageEvent('code-size-analysis', 'macos'), )); expect(fakeAnalytics.sentEvents, contains(Event.codeSizeAnalysis(platform: 'macos'))); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.list(<FakeCommand>[ // These are generated by gen_snapshot because flutter assemble passes // extra flags specifying this output path setUpFakeXcodeBuildHandler('Release', onRun: (_) { fileSystem.file('build/flutter_size_01/snapshot.arm64.json') ..createSync(recursive: true) ..writeAsStringSync(''' [ { "l": "dart:_internal", "c": "SubListIterable", "n": "[Optimized] skip", "s": 2400 } ]'''); fileSystem.file('build/flutter_size_01/trace.arm64.json') ..createSync(recursive: true) ..writeAsStringSync('{}'); }), ]), Platform: () => macosPlatform, FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true), FileSystemUtils: () => FileSystemUtils(fileSystem: fileSystem, platform: macosPlatform), Usage: () => usage, Analytics: () => fakeAnalytics, }); }
flutter/packages/flutter_tools/test/commands.shard/hermetic/build_macos_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/commands.shard/hermetic/build_macos_test.dart", "repo_id": "flutter", "token_count": 9642 }
775
// 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/base/file_system.dart'; import 'package:flutter_tools/src/cache.dart'; import 'package:flutter_tools/src/commands/ide_config.dart'; import 'package:flutter_tools/src/globals.dart' as globals; import 'package:flutter_tools/src/template.dart'; import '../../src/common.dart'; import '../../src/context.dart'; import '../../src/test_flutter_command_runner.dart'; void main() { group('ide_config', () { late Directory tempDir; late Directory templateDir; late Directory intellijDir; late Directory toolsDir; Map<String, String> getFilesystemContents([ Directory? root ]) { final String tempPath = tempDir.absolute.path; final List<String> paths = (root ?? tempDir).listSync(recursive: true).map((FileSystemEntity entity) { final String relativePath = globals.fs.path.relative(entity.path, from: tempPath); return relativePath; }).toList(); final Map<String, String> contents = <String, String>{}; for (final String path in paths) { final String absPath = globals.fs.path.join(tempPath, path); if (globals.fs.isDirectorySync(absPath)) { contents[path] = 'dir'; } else if (globals.fs.isFileSync(absPath)) { contents[path] = globals.fs.file(absPath).readAsStringSync(); } } return contents; } Map<String, String> getManifest(Directory base, String marker, { bool isTemplate = false }) { final String basePath = globals.fs.path.relative(base.path, from: tempDir.absolute.path); final String suffix = isTemplate ? Template.copyTemplateExtension : ''; return <String, String>{ globals.fs.path.join(basePath, '.idea'): 'dir', globals.fs.path.join(basePath, '.idea', 'modules.xml$suffix'): 'modules $marker', globals.fs.path.join(basePath, '.idea', 'vcs.xml$suffix'): 'vcs $marker', globals.fs.path.join(basePath, '.idea', '.name$suffix'): 'codeStyleSettings $marker', globals.fs.path.join(basePath, '.idea', 'runConfigurations'): 'dir', globals.fs.path.join(basePath, '.idea', 'runConfigurations', 'hello_world.xml$suffix'): 'hello_world $marker', globals.fs.path.join(basePath, 'flutter.iml$suffix'): 'flutter $marker', globals.fs.path.join(basePath, 'packages', 'new', 'deep.iml$suffix'): 'deep $marker', globals.fs.path.join(basePath, 'example', 'gallery', 'android.iml$suffix'): 'android $marker', }; } void populateDir(Map<String, String> manifest) { for (final String key in manifest.keys) { if (manifest[key] == 'dir') { tempDir.childDirectory(key).createSync(recursive: true); } } for (final String key in manifest.keys) { if (manifest[key] != 'dir') { tempDir.childFile(key) ..createSync(recursive: true) ..writeAsStringSync(manifest[key]!); } } } bool fileOrDirectoryExists(String path) { final String absPath = globals.fs.path.join(tempDir.absolute.path, path); return globals.fs.file(absPath).existsSync() || globals.fs.directory(absPath).existsSync(); } Future<void> updateIdeConfig({ Directory? dir, List<String> args = const <String>[], Map<String, String> expectedContents = const <String, String>{}, List<String> unexpectedPaths = const <String>[], }) async { dir ??= tempDir; Cache.flutterRoot = tempDir.absolute.path; final IdeConfigCommand command = IdeConfigCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>[ 'ide-config', ...args, ]); for (final String path in expectedContents.keys) { final String absPath = globals.fs.path.join(tempDir.absolute.path, path); expect(fileOrDirectoryExists(globals.fs.path.join(dir.path, path)), true, reason: "$path doesn't exist"); if (globals.fs.file(absPath).existsSync()) { expect(globals.fs.file(absPath).readAsStringSync(), equals(expectedContents[path]), reason: "$path contents don't match"); } } for (final String path in unexpectedPaths) { expect(fileOrDirectoryExists(globals.fs.path.join(dir.path, path)), false, reason: '$path exists'); } } setUpAll(() { Cache.disableLocking(); }); setUp(() { tempDir = globals.fs.systemTempDirectory.createTempSync('flutter_tools_ide_config_test.'); final Directory packagesDir = tempDir.childDirectory('packages')..createSync(recursive: true); toolsDir = packagesDir.childDirectory('flutter_tools')..createSync(); templateDir = toolsDir.childDirectory('ide_templates')..createSync(); intellijDir = templateDir.childDirectory('intellij')..createSync(); }); tearDown(() { tryToDelete(tempDir); }); testUsingContext("doesn't touch existing files without --overwrite", () async { final Map<String, String> templateManifest = getManifest( intellijDir, 'template', isTemplate: true, ); final Map<String, String> flutterManifest = getManifest( tempDir, 'existing', ); populateDir(templateManifest); populateDir(flutterManifest); final Map<String, String> expectedContents = getFilesystemContents(); return updateIdeConfig( expectedContents: expectedContents, ); }); testUsingContext('creates non-existent files', () async { final Map<String, String> templateManifest = getManifest( intellijDir, 'template', isTemplate: true, ); final Map<String, String> flutterManifest = getManifest( tempDir, 'template', ); populateDir(templateManifest); final Map<String, String> expectedContents = <String, String>{ ...templateManifest, ...flutterManifest, }; return updateIdeConfig( expectedContents: expectedContents, ); }); testUsingContext('overwrites existing files with --overwrite', () async { final Map<String, String> templateManifest = getManifest( intellijDir, 'template', isTemplate: true, ); final Map<String, String> flutterManifest = getManifest( tempDir, 'existing', ); populateDir(templateManifest); populateDir(flutterManifest); final Map<String, String> overwrittenManifest = getManifest( tempDir, 'template', ); final Map<String, String> expectedContents = <String, String>{ ...templateManifest, ...overwrittenManifest, }; return updateIdeConfig( args: <String>['--overwrite'], expectedContents: expectedContents, ); }); testUsingContext('only adds new templates without --overwrite', () async { final Map<String, String> templateManifest = getManifest( intellijDir, 'template', isTemplate: true, ); final String flutterIml = globals.fs.path.join( 'packages', 'flutter_tools', 'ide_templates', 'intellij', 'flutter.iml${Template.copyTemplateExtension}', ); templateManifest.remove(flutterIml); populateDir(templateManifest); templateManifest[flutterIml] = 'flutter existing'; final Map<String, String> flutterManifest = getManifest( tempDir, 'existing', ); populateDir(flutterManifest); final Map<String, String> expectedContents = <String, String>{ ...flutterManifest, ...templateManifest, }; return updateIdeConfig( args: <String>['--update-templates'], expectedContents: expectedContents, ); }); testUsingContext('update all templates with --overwrite', () async { final Map<String, String> templateManifest = getManifest( intellijDir, 'template', isTemplate: true, ); populateDir(templateManifest); final Map<String, String> flutterManifest = getManifest( tempDir, 'existing', ); populateDir(flutterManifest); final Map<String, String> updatedTemplates = getManifest( intellijDir, 'existing', isTemplate: true, ); final Map<String, String> expectedContents = <String, String>{ ...flutterManifest, ...updatedTemplates, }; return updateIdeConfig( args: <String>['--update-templates', '--overwrite'], expectedContents: expectedContents, ); }); testUsingContext('removes deleted imls with --overwrite', () async { final Map<String, String> templateManifest = getManifest( intellijDir, 'template', isTemplate: true, ); populateDir(templateManifest); final Map<String, String> flutterManifest = getManifest( tempDir, 'existing', ); flutterManifest.remove('flutter.iml'); populateDir(flutterManifest); final Map<String, String> updatedTemplates = getManifest( intellijDir, 'existing', isTemplate: true, ); final String flutterIml = globals.fs.path.join( 'packages', 'flutter_tools', 'ide_templates', 'intellij', 'flutter.iml${Template.copyTemplateExtension}', ); updatedTemplates.remove(flutterIml); final Map<String, String> expectedContents = <String, String>{ ...flutterManifest, ...updatedTemplates, }; return updateIdeConfig( args: <String>['--update-templates', '--overwrite'], expectedContents: expectedContents, ); }); testUsingContext('removes deleted imls with --overwrite, including empty parent dirs', () async { final Map<String, String> templateManifest = getManifest( intellijDir, 'template', isTemplate: true, ); populateDir(templateManifest); final Map<String, String> flutterManifest = getManifest( tempDir, 'existing', ); flutterManifest.remove(globals.fs.path.join('packages', 'new', 'deep.iml')); populateDir(flutterManifest); final Map<String, String> updatedTemplates = getManifest( intellijDir, 'existing', isTemplate: true, ); String deepIml = globals.fs.path.join( 'packages', 'flutter_tools', 'ide_templates', 'intellij'); // Remove the all the dir entries too. updatedTemplates.remove(deepIml); deepIml = globals.fs.path.join(deepIml, 'packages'); updatedTemplates.remove(deepIml); deepIml = globals.fs.path.join(deepIml, 'new'); updatedTemplates.remove(deepIml); deepIml = globals.fs.path.join(deepIml, 'deep.iml'); updatedTemplates.remove(deepIml); final Map<String, String> expectedContents = <String, String>{ ...flutterManifest, ...updatedTemplates, }; return updateIdeConfig( args: <String>['--update-templates', '--overwrite'], expectedContents: expectedContents, ); }); }); }
flutter/packages/flutter_tools/test/commands.shard/hermetic/ide_config_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/commands.shard/hermetic/ide_config_test.dart", "repo_id": "flutter", "token_count": 4694 }
776
// 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/android/android_builder.dart'; import 'package:flutter_tools/src/android/android_sdk.dart'; import 'package:flutter_tools/src/android/android_studio.dart'; import 'package:flutter_tools/src/android/java.dart'; import 'package:flutter_tools/src/base/file_system.dart'; import 'package:flutter_tools/src/base/logger.dart'; import 'package:flutter_tools/src/base/version.dart'; import 'package:flutter_tools/src/cache.dart'; import 'package:flutter_tools/src/commands/build_apk.dart'; import 'package:flutter_tools/src/globals.dart' as globals; import 'package:flutter_tools/src/project.dart'; import 'package:flutter_tools/src/reporting/reporting.dart'; import 'package:test/fake.dart'; import 'package:unified_analytics/unified_analytics.dart'; import '../../src/android_common.dart'; import '../../src/common.dart'; import '../../src/context.dart'; import '../../src/fake_process_manager.dart'; import '../../src/fakes.dart' show FakeFlutterVersion; import '../../src/test_flutter_command_runner.dart'; void main() { Cache.disableLocking(); group('Usage', () { late Directory tempDir; late TestUsage testUsage; late FakeAnalytics fakeAnalytics; setUp(() { testUsage = TestUsage(); tempDir = globals.fs.systemTempDirectory.createTempSync('flutter_tools_packages_test.'); fakeAnalytics = getInitializedFakeAnalyticsInstance( fs: MemoryFileSystem.test(), fakeFlutterVersion: FakeFlutterVersion(), ); }); tearDown(() { tryToDelete(tempDir); }); testUsingContext('indicate the default target platforms', () async { final String projectPath = await createProject(tempDir, arguments: <String>['--no-pub', '--template=app']); final BuildApkCommand command = await runBuildApkCommand(projectPath); expect((await command.usageValues).commandBuildApkTargetPlatform, 'android-arm,android-arm64,android-x64'); expect( fakeAnalytics.sentEvents, contains( Event.commandUsageValues( workflow: 'apk', commandHasTerminal: false, buildApkTargetPlatform: 'android-arm,android-arm64,android-x64', buildApkBuildMode: 'release', buildApkSplitPerAbi: false, ), ), ); }, overrides: <Type, Generator>{ AndroidBuilder: () => FakeAndroidBuilder(), Analytics: () => fakeAnalytics, }); testUsingContext('split per abi', () async { final String projectPath = await createProject(tempDir, arguments: <String>['--no-pub', '--template=app']); final BuildApkCommand commandWithFlag = await runBuildApkCommand(projectPath, arguments: <String>['--split-per-abi']); expect((await commandWithFlag.usageValues).commandBuildApkSplitPerAbi, true); final BuildApkCommand commandWithoutFlag = await runBuildApkCommand(projectPath); expect((await commandWithoutFlag.usageValues).commandBuildApkSplitPerAbi, false); }, overrides: <Type, Generator>{ AndroidBuilder: () => FakeAndroidBuilder(), }); testUsingContext('build type', () async { final String projectPath = await createProject(tempDir, arguments: <String>['--no-pub', '--template=app']); final BuildApkCommand commandDefault = await runBuildApkCommand(projectPath); expect((await commandDefault.usageValues).commandBuildApkBuildMode, 'release'); final BuildApkCommand commandInRelease = await runBuildApkCommand(projectPath, arguments: <String>['--release']); expect((await commandInRelease.usageValues).commandBuildApkBuildMode, 'release'); final BuildApkCommand commandInDebug = await runBuildApkCommand(projectPath, arguments: <String>['--debug']); expect((await commandInDebug.usageValues).commandBuildApkBuildMode, 'debug'); final BuildApkCommand commandInProfile = await runBuildApkCommand(projectPath, arguments: <String>['--profile']); expect((await commandInProfile.usageValues).commandBuildApkBuildMode, 'profile'); }, overrides: <Type, Generator>{ AndroidBuilder: () => FakeAndroidBuilder(), }); testUsingContext('logs success', () async { final String projectPath = await createProject(tempDir, arguments: <String>['--no-pub', '--template=app']); await runBuildApkCommand(projectPath); expect(testUsage.events, contains( const TestUsageEvent( 'tool-command-result', 'apk', label: 'success', ), )); }, overrides: <Type, Generator>{ AndroidBuilder: () => FakeAndroidBuilder(), Usage: () => testUsage, }); }); group('Gradle', () { late Directory tempDir; late FakeProcessManager processManager; late String gradlew; late AndroidSdk mockAndroidSdk; late TestUsage testUsage; setUp(() { testUsage = TestUsage(); tempDir = globals.fs.systemTempDirectory.createTempSync('flutter_tools_packages_test.'); gradlew = globals.fs.path.join(tempDir.path, 'flutter_project', 'android', globals.platform.isWindows ? 'gradlew.bat' : 'gradlew'); processManager = FakeProcessManager.empty(); mockAndroidSdk = FakeAndroidSdk(globals.fs.directory('irrelevant')); }); tearDown(() { tryToDelete(tempDir); }); group('AndroidSdk', () { testUsingContext('throws throwsToolExit if AndroidSdk is null', () async { final String projectPath = await createProject(tempDir, arguments: <String>['--no-pub', '--template=app', '--platform=android']); await expectLater( () => runBuildApkCommand( projectPath, arguments: <String>['--no-pub'], ), throwsToolExit( message: 'No Android SDK found. Try setting the ANDROID_HOME environment variable', ), ); }, overrides: <Type, Generator>{ AndroidSdk: () => null, Java: () => null, FlutterProjectFactory: () => FakeFlutterProjectFactory(tempDir), ProcessManager: () => processManager, AndroidStudio: () => FakeAndroidStudio(), }); }); testUsingContext('shrinking is enabled by default on release mode', () async { final String projectPath = await createProject(tempDir, arguments: <String>['--no-pub', '--template=app', '--platform=android']); processManager.addCommand(FakeCommand( command: <String>[ gradlew, '-q', '-Ptarget-platform=android-arm,android-arm64,android-x64', '-Ptarget=${globals.fs.path.join(tempDir.path, 'flutter_project', 'lib', 'main.dart')}', '-Pbase-application-name=android.app.Application', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=true', '-Ptree-shake-icons=true', 'assembleRelease', ], exitCode: 1, )); await expectLater( () => runBuildApkCommand(projectPath), throwsToolExit(message: 'Gradle task assembleRelease failed with exit code 1'), ); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ AndroidSdk: () => mockAndroidSdk, Java: () => null, FlutterProjectFactory: () => FakeFlutterProjectFactory(tempDir), ProcessManager: () => processManager, AndroidStudio: () => FakeAndroidStudio(), }); testUsingContext('--split-debug-info is enabled when an output directory is provided', () async { final String projectPath = await createProject(tempDir, arguments: <String>['--no-pub', '--template=app', '--platform=android']); processManager.addCommand(FakeCommand( command: <String>[ gradlew, '-q', '-Ptarget-platform=android-arm,android-arm64,android-x64', '-Ptarget=${globals.fs.path.join(tempDir.path, 'flutter_project', 'lib', 'main.dart')}', '-Pbase-application-name=android.app.Application', '-Pdart-obfuscation=false', '-Psplit-debug-info=${tempDir.path}', '-Ptrack-widget-creation=true', '-Ptree-shake-icons=true', 'assembleRelease', ], exitCode: 1, )); await expectLater( () => runBuildApkCommand(projectPath, arguments: <String>['--split-debug-info=${tempDir.path}']), throwsToolExit(message: 'Gradle task assembleRelease failed with exit code 1'), ); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ AndroidSdk: () => mockAndroidSdk, Java: () => null, FlutterProjectFactory: () => FakeFlutterProjectFactory(tempDir), ProcessManager: () => processManager, AndroidStudio: () => FakeAndroidStudio(), }); testUsingContext('--extra-front-end-options are provided to gradle project', () async { final String projectPath = await createProject(tempDir, arguments: <String>['--no-pub', '--template=app', '--platform=android']); processManager.addCommand(FakeCommand( command: <String>[ gradlew, '-q', '-Ptarget-platform=android-arm,android-arm64,android-x64', '-Ptarget=${globals.fs.path.join(tempDir.path, 'flutter_project', 'lib', 'main.dart')}', '-Pbase-application-name=android.app.Application', '-Pdart-obfuscation=false', '-Pextra-front-end-options=foo,bar', '-Ptrack-widget-creation=true', '-Ptree-shake-icons=true', 'assembleRelease', ], exitCode: 1, )); await expectLater(() => runBuildApkCommand(projectPath, arguments: <String>[ '--extra-front-end-options=foo', '--extra-front-end-options=bar', ]), throwsToolExit(message: 'Gradle task assembleRelease failed with exit code 1')); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ AndroidSdk: () => mockAndroidSdk, Java: () => null, FlutterProjectFactory: () => FakeFlutterProjectFactory(tempDir), ProcessManager: () => processManager, AndroidStudio: () => FakeAndroidStudio(), }); testUsingContext('shrinking is disabled when --no-shrink is passed', () async { final String projectPath = await createProject(tempDir, arguments: <String>['--no-pub', '--template=app', '--platform=android']); processManager.addCommand(FakeCommand( command: <String>[ gradlew, '-q', '-Ptarget-platform=android-arm,android-arm64,android-x64', '-Ptarget=${globals.fs.path.join(tempDir.path, 'flutter_project', 'lib', 'main.dart')}', '-Pbase-application-name=android.app.Application', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=true', '-Ptree-shake-icons=true', 'assembleRelease', ], exitCode: 1, )); await expectLater( () => runBuildApkCommand( projectPath, arguments: <String>['--no-shrink'], ), throwsToolExit(message: 'Gradle task assembleRelease failed with exit code 1'), ); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ AndroidSdk: () => mockAndroidSdk, Java: () => null, FlutterProjectFactory: () => FakeFlutterProjectFactory(tempDir), ProcessManager: () => processManager, AndroidStudio: () => FakeAndroidStudio(), }); testUsingContext('guides the user when the shrinker fails', () async { final String projectPath = await createProject(tempDir, arguments: <String>['--no-pub', '--template=app', '--platform=android']); const String r8StdoutWarning = "Execution failed for task ':app:transformClassesAndResourcesWithR8ForStageInternal'.\n" '> com.android.tools.r8.CompilationFailedException: Compilation failed to complete'; processManager.addCommand(FakeCommand( command: <String>[ gradlew, '-q', '-Ptarget-platform=android-arm,android-arm64,android-x64', '-Ptarget=${globals.fs.path.join(tempDir.path, 'flutter_project', 'lib', 'main.dart')}', '-Pbase-application-name=android.app.Application', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=true', '-Ptree-shake-icons=true', 'assembleRelease', ], exitCode: 1, stdout: r8StdoutWarning, )); await expectLater( () => runBuildApkCommand( projectPath, ), throwsToolExit(message: 'Gradle task assembleRelease failed with exit code 1'), ); expect( testLogger.statusText, allOf( containsIgnoringWhitespace('The shrinker may have failed to optimize the Java bytecode.'), containsIgnoringWhitespace('To disable the shrinker, pass the `--no-shrink` flag to this command.'), containsIgnoringWhitespace('To learn more, see: https://developer.android.com/studio/build/shrink-code'), ) ); expect(testUsage.events, contains( const TestUsageEvent( 'build', 'gradle', label: 'gradle-r8-failure', parameters: CustomDimensions(), ), )); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ AndroidSdk: () => mockAndroidSdk, Java: () => null, FlutterProjectFactory: () => FakeFlutterProjectFactory(tempDir), ProcessManager: () => processManager, Usage: () => testUsage, AndroidStudio: () => FakeAndroidStudio(), }); testUsingContext("reports when the app isn't using AndroidX", () async { final String projectPath = await createProject(tempDir, arguments: <String>['--no-pub', '--template=app', '--platform=android']); // Simulate a non-androidx project. tempDir .childDirectory('flutter_project') .childDirectory('android') .childFile('gradle.properties') .writeAsStringSync('android.useAndroidX=false'); processManager.addCommand(FakeCommand( command: <String>[ gradlew, '-q', '-Ptarget-platform=android-arm,android-arm64,android-x64', '-Ptarget=${globals.fs.path.join(tempDir.path, 'flutter_project', 'lib', 'main.dart')}', '-Pbase-application-name=android.app.Application', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=true', '-Ptree-shake-icons=true', 'assembleRelease', ], )); // The command throws a [ToolExit] because it expects an APK in the file system. await expectLater(() => runBuildApkCommand(projectPath), throwsToolExit()); expect( testLogger.statusText, allOf( containsIgnoringWhitespace("Your app isn't using AndroidX"), containsIgnoringWhitespace( 'To avoid potential build failures, you can quickly migrate your app by ' 'following the steps on https://goo.gl/CP92wY' ), ), ); expect(testUsage.events, contains( const TestUsageEvent( 'build', 'gradle', label: 'app-not-using-android-x', parameters: CustomDimensions(), ), )); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ AndroidSdk: () => mockAndroidSdk, FlutterProjectFactory: () => FakeFlutterProjectFactory(tempDir), Java: () => null, ProcessManager: () => processManager, Usage: () => testUsage, AndroidStudio: () => FakeAndroidStudio(), }); testUsingContext('reports when the app is using AndroidX', () async { final String projectPath = await createProject(tempDir, arguments: <String>['--no-pub', '--template=app', '--platform=android']); processManager.addCommand(FakeCommand( command: <String>[ gradlew, '-q', '-Ptarget-platform=android-arm,android-arm64,android-x64', '-Ptarget=${globals.fs.path.join(tempDir.path, 'flutter_project', 'lib', 'main.dart')}', '-Pbase-application-name=android.app.Application', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=true', '-Ptree-shake-icons=true', 'assembleRelease', ], )); // The command throws a [ToolExit] because it expects an APK in the file system. await expectLater(() => runBuildApkCommand(projectPath), throwsToolExit()); expect( testLogger.statusText, allOf( isNot(contains("[!] Your app isn't using AndroidX")), isNot(contains( 'To avoid potential build failures, you can quickly migrate your app by ' 'following the steps on https://goo.gl/CP92wY' )) ), ); expect(testUsage.events, contains( const TestUsageEvent( 'build', 'gradle', label: 'app-using-android-x', parameters: CustomDimensions(), ), )); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ AndroidSdk: () => mockAndroidSdk, FlutterProjectFactory: () => FakeFlutterProjectFactory(tempDir), Java: () => null, ProcessManager: () => processManager, Usage: () => testUsage, AndroidStudio: () => FakeAndroidStudio(), }); }); } Future<BuildApkCommand> runBuildApkCommand( String target, { List<String>? arguments, }) async { final BuildApkCommand command = BuildApkCommand(logger: BufferLogger.test()); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>[ 'apk', ...?arguments, '--no-pub', globals.fs.path.join(target, 'lib', 'main.dart'), ]); return command; } class FakeAndroidSdk extends Fake implements AndroidSdk { FakeAndroidSdk(this.directory); @override final Directory directory; } class FakeAndroidStudio extends Fake implements AndroidStudio { @override String get javaPath => 'java'; @override Version get version => Version(2021, 3, 1); }
flutter/packages/flutter_tools/test/commands.shard/permeable/build_apk_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/commands.shard/permeable/build_apk_test.dart", "repo_id": "flutter", "token_count": 7396 }
777
// 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/android/android_device.dart'; import 'package:flutter_tools/src/base/logger.dart'; import 'package:flutter_tools/src/device_port_forwarder.dart'; import '../../src/common.dart'; import '../../src/fake_process_manager.dart'; void main() { testWithoutContext('AndroidDevicePortForwarder returns the generated host ' 'port from stdout', () async { final AndroidDevicePortForwarder forwarder = AndroidDevicePortForwarder( adbPath: 'adb', deviceId: '1', processManager: FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['adb', '-s', '1', 'forward', 'tcp:0', 'tcp:123'], stdout: '456', ), ]), logger: BufferLogger.test(), ); expect(await forwarder.forward(123), 456); }); testWithoutContext('AndroidDevicePortForwarder returns the supplied host ' 'port when stdout is empty', () async { final AndroidDevicePortForwarder forwarder = AndroidDevicePortForwarder( adbPath: 'adb', deviceId: '1', processManager: FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['adb', '-s', '1', 'forward', 'tcp:456', 'tcp:123'], ), ]), logger: BufferLogger.test(), ); expect(await forwarder.forward(123, hostPort: 456), 456); }); testWithoutContext('AndroidDevicePortForwarder returns the supplied host port ' 'when stdout is the host port', () async { final AndroidDevicePortForwarder forwarder = AndroidDevicePortForwarder( adbPath: 'adb', deviceId: '1', processManager: FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['adb', '-s', '1', 'forward', 'tcp:456', 'tcp:123'], stdout: '456', ), ]), logger: BufferLogger.test(), ); expect(await forwarder.forward(123, hostPort: 456), 456); }); testWithoutContext('AndroidDevicePortForwarder throws an exception when stdout ' 'is not blank nor the host port', () async { final AndroidDevicePortForwarder forwarder = AndroidDevicePortForwarder( adbPath: 'adb', deviceId: '1', processManager: FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['adb', '-s', '1', 'forward', 'tcp:456', 'tcp:123'], stdout: '123456', ), ]), logger: BufferLogger.test(), ); expect(forwarder.forward(123, hostPort: 456), throwsProcessException()); }); testWithoutContext('AndroidDevicePortForwarder forwardedPorts returns empty ' 'list when forward failed', () { final AndroidDevicePortForwarder forwarder = AndroidDevicePortForwarder( adbPath: 'adb', deviceId: '1', processManager: FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['adb', '-s', '1', 'forward', '--list'], exitCode: 1, ), ]), logger: BufferLogger.test(), ); expect(forwarder.forwardedPorts, isEmpty); }); testWithoutContext('disposing device disposes the portForwarder', () async { final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['adb', '-s', '1', 'forward', 'tcp:0', 'tcp:123'], stdout: '456', ), const FakeCommand( command: <String>['adb', '-s', '1', 'forward', '--list'], stdout: '1234 tcp:456 tcp:123', ), const FakeCommand( command: <String>['adb', '-s', '1', 'forward', '--remove', 'tcp:456'], ), ]); final AndroidDevicePortForwarder forwarder = AndroidDevicePortForwarder( adbPath: 'adb', deviceId: '1', processManager: processManager, logger: BufferLogger.test(), ); expect(await forwarder.forward(123), equals(456)); await forwarder.dispose(); expect(processManager, hasNoRemainingExpectations); }); testWithoutContext('failures to unforward port do not throw if the forward is missing', () async { final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['adb', '-s', '1', 'forward', '--remove', 'tcp:456'], stderr: "error: listener 'tcp:456' not found", exitCode: 1, ), ]); final AndroidDevicePortForwarder forwarder = AndroidDevicePortForwarder( adbPath: 'adb', deviceId: '1', processManager: processManager, logger: BufferLogger.test(), ); await forwarder.unforward(ForwardedPort(456, 23)); }); testWithoutContext('failures to unforward port print error but are non-fatal', () async { final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['adb', '-s', '1', 'forward', '--remove', 'tcp:456'], stderr: 'error: everything is broken!', exitCode: 1, ), ]); final BufferLogger logger = BufferLogger.test(); final AndroidDevicePortForwarder forwarder = AndroidDevicePortForwarder( adbPath: 'adb', deviceId: '1', processManager: processManager, logger: logger, ); await forwarder.unforward(ForwardedPort(456, 23)); expect(logger.errorText, contains('Failed to unforward port: error: everything is broken!')); }); }
flutter/packages/flutter_tools/test/general.shard/android/android_device_port_forwarder_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/general.shard/android/android_device_port_forwarder_test.dart", "repo_id": "flutter", "token_count": 2133 }
778