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' as ui;
import 'package:flutter/foundation.dart';
import 'package:flutter/painting.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('PaintingBinding with memory pressure before initInstances', () async {
// Observed in devicelab: the device sends a memory pressure event
// to us before the binding is initialized, so as soon as the
// ServicesBinding's initInstances sets up the callbacks, we get a
// call. Previously this would happen synchronously during
// initInstances (and before the imageCache was initialized, which
// was a problem), but now it happens asynchronously just after.
ui.channelBuffers.push(SystemChannels.system.name, SystemChannels.system.codec.encodeMessage(<String, dynamic>{
'type': 'memoryPressure',
}), (ByteData? responseData) {
// The result is: SystemChannels.system.codec.decodeMessage(responseData)
// ...but we ignore it for the purposes of this test.
});
final TestPaintingBinding binding = TestPaintingBinding();
expect(binding._handled, isFalse);
expect(binding.imageCache, isNotNull);
expect(binding.imageCache.currentSize, 0);
await null; // allow microtasks to run
expect(binding._handled, isTrue);
});
}
class TestPaintingBinding extends BindingBase with SchedulerBinding, ServicesBinding, PaintingBinding {
@override
void handleMemoryPressure() {
super.handleMemoryPressure();
_handled = true;
}
bool _handled = false;
}
| flutter/packages/flutter/test/painting/image_cache_binding_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/painting/image_cache_binding_test.dart",
"repo_id": "flutter",
"token_count": 549
} | 671 |
// 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/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('TextSpan equals', () {
const TextSpan a1 = TextSpan(text: 'a');
const TextSpan a2 = TextSpan(text: 'a');
const TextSpan b1 = TextSpan(children: <TextSpan>[ a1 ]);
const TextSpan b2 = TextSpan(children: <TextSpan>[ a2 ]);
const TextSpan c1 = TextSpan();
const TextSpan c2 = TextSpan();
expect(a1 == a2, isTrue);
expect(b1 == b2, isTrue);
expect(c1 == c2, isTrue);
expect(a1 == b2, isFalse);
expect(b1 == c2, isFalse);
expect(c1 == a2, isFalse);
expect(a1 == c2, isFalse);
expect(b1 == a2, isFalse);
expect(c1 == b2, isFalse);
void callback1(PointerEnterEvent _) {}
void callback2(PointerEnterEvent _) {}
final TextSpan d1 = TextSpan(text: 'a', onEnter: callback1);
final TextSpan d2 = TextSpan(text: 'a', onEnter: callback1);
final TextSpan d3 = TextSpan(text: 'a', onEnter: callback2);
final TextSpan e1 = TextSpan(text: 'a', onEnter: callback2, mouseCursor: SystemMouseCursors.forbidden);
final TextSpan e2 = TextSpan(text: 'a', onEnter: callback2, mouseCursor: SystemMouseCursors.forbidden);
expect(a1 == d1, isFalse);
expect(d1 == d2, isTrue);
expect(d2 == d3, isFalse);
expect(d3 == e1, isFalse);
expect(e1 == e2, isTrue);
});
test('TextSpan toStringDeep', () {
const TextSpan test = TextSpan(
text: 'a',
style: TextStyle(
fontSize: 10.0,
),
children: <TextSpan>[
TextSpan(
text: 'b',
children: <TextSpan>[
TextSpan(),
],
),
TextSpan(
text: 'c',
),
],
);
expect(test.toStringDeep(), equals(
'TextSpan:\n'
' inherit: true\n'
' size: 10.0\n'
' "a"\n'
' TextSpan:\n'
' "b"\n'
' TextSpan:\n'
' (empty)\n'
' TextSpan:\n'
' "c"\n',
));
});
test('TextSpan toStringDeep for mouse', () {
const TextSpan test1 = TextSpan(
text: 'a',
);
expect(test1.toStringDeep(), equals(
'TextSpan:\n'
' "a"\n',
));
final TextSpan test2 = TextSpan(
text: 'a',
onEnter: (_) {},
onExit: (_) {},
mouseCursor: SystemMouseCursors.forbidden,
);
expect(test2.toStringDeep(), equals(
'TextSpan:\n'
' "a"\n'
' callbacks: enter, exit\n'
' mouseCursor: SystemMouseCursor(forbidden)\n',
));
});
test('TextSpan toPlainText', () {
const TextSpan textSpan = TextSpan(
text: 'a',
children: <TextSpan>[
TextSpan(text: 'b'),
TextSpan(text: 'c'),
],
);
expect(textSpan.toPlainText(), 'abc');
});
test('WidgetSpan toPlainText', () {
const TextSpan textSpan = TextSpan(
text: 'a',
children: <InlineSpan>[
TextSpan(text: 'b'),
WidgetSpan(child: SizedBox(width: 10, height: 10)),
TextSpan(text: 'c'),
],
);
expect(textSpan.toPlainText(), 'ab\uFFFCc');
});
test('TextSpan toPlainText with semanticsLabel', () {
const TextSpan textSpan = TextSpan(
text: 'a',
children: <TextSpan>[
TextSpan(text: 'b', semanticsLabel: 'foo'),
TextSpan(text: 'c'),
],
);
expect(textSpan.toPlainText(), 'afooc');
expect(textSpan.toPlainText(includeSemanticsLabels: false), 'abc');
});
test('TextSpan widget change test', () {
const TextSpan textSpan1 = TextSpan(
text: 'a',
children: <InlineSpan>[
TextSpan(text: 'b'),
WidgetSpan(child: SizedBox(width: 10, height: 10)),
TextSpan(text: 'c'),
],
);
const TextSpan textSpan2 = TextSpan(
text: 'a',
children: <InlineSpan>[
TextSpan(text: 'b'),
WidgetSpan(child: SizedBox(width: 10, height: 10)),
TextSpan(text: 'c'),
],
);
const TextSpan textSpan3 = TextSpan(
text: 'a',
children: <InlineSpan>[
TextSpan(text: 'b'),
WidgetSpan(child: SizedBox(width: 11, height: 10)),
TextSpan(text: 'c'),
],
);
const TextSpan textSpan4 = TextSpan(
text: 'a',
children: <InlineSpan>[
TextSpan(text: 'b'),
WidgetSpan(child: Text('test')),
TextSpan(text: 'c'),
],
);
const TextSpan textSpan5 = TextSpan(
text: 'a',
children: <InlineSpan>[
TextSpan(text: 'b'),
WidgetSpan(child: Text('different!')),
TextSpan(text: 'c'),
],
);
const TextSpan textSpan6 = TextSpan(
text: 'a',
children: <InlineSpan>[
TextSpan(text: 'b'),
WidgetSpan(
child: SizedBox(width: 10, height: 10),
alignment: PlaceholderAlignment.top,
),
TextSpan(text: 'c'),
],
);
expect(textSpan1.compareTo(textSpan3), RenderComparison.layout);
expect(textSpan1.compareTo(textSpan4), RenderComparison.layout);
expect(textSpan1.compareTo(textSpan1), RenderComparison.identical);
expect(textSpan2.compareTo(textSpan2), RenderComparison.identical);
expect(textSpan3.compareTo(textSpan3), RenderComparison.identical);
expect(textSpan2.compareTo(textSpan3), RenderComparison.layout);
expect(textSpan4.compareTo(textSpan5), RenderComparison.layout);
expect(textSpan3.compareTo(textSpan5), RenderComparison.layout);
expect(textSpan2.compareTo(textSpan5), RenderComparison.layout);
expect(textSpan1.compareTo(textSpan5), RenderComparison.layout);
expect(textSpan1.compareTo(textSpan6), RenderComparison.layout);
});
test('TextSpan nested widget change test', () {
const TextSpan textSpan1 = TextSpan(
text: 'a',
children: <InlineSpan>[
TextSpan(text: 'b'),
WidgetSpan(
child: Text.rich(
TextSpan(
children: <InlineSpan>[
WidgetSpan(child: SizedBox(width: 10, height: 10)),
TextSpan(text: 'The sky is falling :)'),
],
),
),
),
TextSpan(text: 'c'),
],
);
const TextSpan textSpan2 = TextSpan(
text: 'a',
children: <InlineSpan>[
TextSpan(text: 'b'),
WidgetSpan(
child: Text.rich(
TextSpan(
children: <InlineSpan>[
WidgetSpan(child: SizedBox(width: 10, height: 11)),
TextSpan(text: 'The sky is falling :)'),
],
),
),
),
TextSpan(text: 'c'),
],
);
expect(textSpan1.compareTo(textSpan2), RenderComparison.layout);
expect(textSpan1.compareTo(textSpan1), RenderComparison.identical);
expect(textSpan2.compareTo(textSpan2), RenderComparison.identical);
});
test('GetSpanForPosition', () {
const TextSpan textSpan = TextSpan(
text: '',
children: <InlineSpan>[
TextSpan(text: '', children: <InlineSpan>[
TextSpan(text: 'a'),
]),
TextSpan(text: 'b'),
TextSpan(text: 'c'),
],
);
expect((textSpan.getSpanForPosition(const TextPosition(offset: 0)) as TextSpan?)?.text, 'a');
expect((textSpan.getSpanForPosition(const TextPosition(offset: 1)) as TextSpan?)?.text, 'b');
expect((textSpan.getSpanForPosition(const TextPosition(offset: 2)) as TextSpan?)?.text, 'c');
expect((textSpan.getSpanForPosition(const TextPosition(offset: 3)) as TextSpan?)?.text, isNull);
});
test('GetSpanForPosition with WidgetSpan', () {
const TextSpan textSpan = TextSpan(
text: 'a',
children: <InlineSpan>[
TextSpan(text: 'b'),
WidgetSpan(
child: Text.rich(
TextSpan(
children: <InlineSpan>[
WidgetSpan(child: SizedBox(width: 10, height: 10)),
TextSpan(text: 'The sky is falling :)'),
],
),
),
),
TextSpan(text: 'c'),
],
);
expect(textSpan.getSpanForPosition(const TextPosition(offset: 0)).runtimeType, TextSpan);
expect(textSpan.getSpanForPosition(const TextPosition(offset: 1)).runtimeType, TextSpan);
expect(textSpan.getSpanForPosition(const TextPosition(offset: 2)).runtimeType, WidgetSpan);
expect(textSpan.getSpanForPosition(const TextPosition(offset: 3)).runtimeType, TextSpan);
});
test('TextSpan computeSemanticsInformation', () {
final List<InlineSpanSemanticsInformation> collector = <InlineSpanSemanticsInformation>[];
const TextSpan(text: 'aaa', semanticsLabel: 'bbb').computeSemanticsInformation(collector);
expect(collector[0].text, 'aaa');
expect(collector[0].semanticsLabel, 'bbb');
});
test('TextSpan visitDirectChildren', () {
List<InlineSpan> directChildrenOf(InlineSpan root) {
final List<InlineSpan> visitOrder = <InlineSpan>[];
root.visitDirectChildren((InlineSpan span) {
visitOrder.add(span);
return true;
});
return visitOrder;
}
const TextSpan leaf1 = TextSpan(text: 'leaf1');
const TextSpan leaf2 = TextSpan(text: 'leaf2');
const TextSpan branch1 = TextSpan(children: <InlineSpan>[leaf1, leaf2]);
const TextSpan branch2 = TextSpan(text: 'branch2');
const TextSpan root = TextSpan(children: <InlineSpan>[branch1, branch2]);
expect(directChildrenOf(root), <TextSpan>[branch1, branch2]);
expect(directChildrenOf(branch1), <TextSpan>[leaf1, leaf2]);
expect(directChildrenOf(branch2), isEmpty);
expect(directChildrenOf(leaf1), isEmpty);
expect(directChildrenOf(leaf2), isEmpty);
int? indexInTree(InlineSpan target) {
int index = 0;
bool findInSubtree(InlineSpan subtreeRoot) {
if (identical(target, subtreeRoot)) {
// return false to stop traversal.
return false;
}
index += 1;
return subtreeRoot.visitDirectChildren(findInSubtree);
}
return findInSubtree(root) ? null : index;
}
expect(indexInTree(root), 0);
expect(indexInTree(branch1), 1);
expect(indexInTree(leaf1), 2);
expect(indexInTree(leaf2), 3);
expect(indexInTree(branch2), 4);
expect(indexInTree(const TextSpan(text: 'foobar')), null);
});
testWidgets('handles mouse cursor', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: Text.rich(
TextSpan(
text: 'xxxxx',
children: <InlineSpan>[
TextSpan(
text: 'yyyyy',
mouseCursor: SystemMouseCursors.forbidden,
),
TextSpan(
text: 'xxxxx',
),
],
),
textAlign: TextAlign.center,
),
),
),
);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(tester.getCenter(find.byType(RichText)) - const Offset(40, 0));
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic);
await gesture.moveTo(tester.getCenter(find.byType(RichText)));
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.forbidden);
await gesture.moveTo(tester.getCenter(find.byType(RichText)) + const Offset(40, 0));
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic);
});
testWidgets('handles onEnter and onExit', (WidgetTester tester) async {
final List<PointerEvent> logEvents = <PointerEvent>[];
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: Text.rich(
TextSpan(
text: 'xxxxx',
children: <InlineSpan>[
TextSpan(
text: 'yyyyy',
onEnter: (PointerEnterEvent event) {
logEvents.add(event);
},
onExit: (PointerExitEvent event) {
logEvents.add(event);
},
),
const TextSpan(
text: 'xxxxx',
),
],
),
textAlign: TextAlign.center,
),
),
),
);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(tester.getCenter(find.byType(RichText)) - const Offset(40, 0));
expect(logEvents, isEmpty);
await gesture.moveTo(tester.getCenter(find.byType(RichText)));
expect(logEvents.length, 1);
expect(logEvents[0], isA<PointerEnterEvent>());
await gesture.moveTo(tester.getCenter(find.byType(RichText)) + const Offset(40, 0));
expect(logEvents.length, 2);
expect(logEvents[1], isA<PointerExitEvent>());
});
testWidgets('TextSpan can compute StringAttributes', (WidgetTester tester) async {
const TextSpan span = TextSpan(
text: 'aaaaa',
spellOut: true,
children: <InlineSpan>[
TextSpan(text: 'yyyyy', locale: Locale('es', 'MX')),
TextSpan(
text: 'xxxxx',
spellOut: false,
children: <InlineSpan>[
TextSpan(text: 'zzzzz'),
TextSpan(text: 'bbbbb', spellOut: true),
]
),
],
);
final List<InlineSpanSemanticsInformation> collector = <InlineSpanSemanticsInformation>[];
span.computeSemanticsInformation(collector);
expect(collector.length, 5);
expect(collector[0].stringAttributes.length, 1);
expect(collector[0].stringAttributes[0], isA<SpellOutStringAttribute>());
expect(collector[0].stringAttributes[0].range, const TextRange(start: 0, end: 5));
expect(collector[1].stringAttributes.length, 2);
expect(collector[1].stringAttributes[0], isA<SpellOutStringAttribute>());
expect(collector[1].stringAttributes[0].range, const TextRange(start: 0, end: 5));
expect(collector[1].stringAttributes[1], isA<LocaleStringAttribute>());
expect(collector[1].stringAttributes[1].range, const TextRange(start: 0, end: 5));
final LocaleStringAttribute localeStringAttribute = collector[1].stringAttributes[1] as LocaleStringAttribute;
expect(localeStringAttribute.locale, const Locale('es', 'MX'));
expect(collector[2].stringAttributes.length, 0);
expect(collector[3].stringAttributes.length, 0);
expect(collector[4].stringAttributes.length, 1);
expect(collector[4].stringAttributes[0], isA<SpellOutStringAttribute>());
expect(collector[4].stringAttributes[0].range, const TextRange(start: 0, end: 5));
final List<InlineSpanSemanticsInformation> combined = combineSemanticsInfo(collector);
expect(combined.length, 1);
expect(combined[0].stringAttributes.length, 4);
expect(combined[0].stringAttributes[0], isA<SpellOutStringAttribute>());
expect(combined[0].stringAttributes[0].range, const TextRange(start: 0, end: 5));
expect(combined[0].stringAttributes[1], isA<SpellOutStringAttribute>());
expect(combined[0].stringAttributes[1].range, const TextRange(start: 5, end: 10));
expect(combined[0].stringAttributes[2], isA<LocaleStringAttribute>());
expect(combined[0].stringAttributes[2].range, const TextRange(start: 5, end: 10));
final LocaleStringAttribute combinedLocaleStringAttribute = combined[0].stringAttributes[2] as LocaleStringAttribute;
expect(combinedLocaleStringAttribute.locale, const Locale('es', 'MX'));
expect(combined[0].stringAttributes[3], isA<SpellOutStringAttribute>());
expect(combined[0].stringAttributes[3].range, const TextRange(start: 20, end: 25));
});
}
| flutter/packages/flutter/test/painting/text_span_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/painting/text_span_test.dart",
"repo_id": "flutter",
"token_count": 7178
} | 672 |
// 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';
void main() {
test('BoxConstraints toString', () {
expect(const BoxConstraints.expand().toString(), contains('biggest'));
expect(const BoxConstraints().toString(), contains('unconstrained'));
expect(const BoxConstraints.tightFor(width: 50.0).toString(), contains('w=50'));
});
test('BoxConstraints copyWith', () {
const BoxConstraints constraints = BoxConstraints(
minWidth: 3.0,
maxWidth: 7.0,
minHeight: 11.0,
maxHeight: 17.0,
);
BoxConstraints copy = constraints.copyWith();
expect(copy, equals(constraints));
copy = constraints.copyWith(
minWidth: 13.0,
maxWidth: 17.0,
minHeight: 111.0,
maxHeight: 117.0,
);
expect(copy.minWidth, 13.0);
expect(copy.maxWidth, 17.0);
expect(copy.minHeight, 111.0);
expect(copy.maxHeight, 117.0);
expect(copy, isNot(equals(constraints)));
expect(copy.hashCode, isNot(equals(constraints.hashCode)));
});
test('BoxConstraints operators', () {
const BoxConstraints constraints = BoxConstraints(
minWidth: 3.0,
maxWidth: 7.0,
minHeight: 11.0,
maxHeight: 17.0,
);
BoxConstraints copy = constraints * 2.0;
expect(copy.minWidth, 6.0);
expect(copy.maxWidth, 14.0);
expect(copy.minHeight, 22.0);
expect(copy.maxHeight, 34.0);
expect(copy / 2.0, equals(constraints));
copy = constraints ~/ 2.0;
expect(copy.minWidth, 1.0);
expect(copy.maxWidth, 3.0);
expect(copy.minHeight, 5.0);
expect(copy.maxHeight, 8.0);
copy = constraints % 3.0;
expect(copy.minWidth, 0.0);
expect(copy.maxWidth, 1.0);
expect(copy.minHeight, 2.0);
expect(copy.maxHeight, 2.0);
});
test('BoxConstraints lerp', () {
expect(BoxConstraints.lerp(null, null, 0.5), isNull);
const BoxConstraints constraints = BoxConstraints(
minWidth: 3.0,
maxWidth: 7.0,
minHeight: 11.0,
maxHeight: 17.0,
);
BoxConstraints copy = BoxConstraints.lerp(null, constraints, 0.5)!;
expect(copy.minWidth, moreOrLessEquals(1.5));
expect(copy.maxWidth, moreOrLessEquals(3.5));
expect(copy.minHeight, moreOrLessEquals(5.5));
expect(copy.maxHeight, moreOrLessEquals(8.5));
copy = BoxConstraints.lerp(constraints, null, 0.5)!;
expect(copy.minWidth, moreOrLessEquals(1.5));
expect(copy.maxWidth, moreOrLessEquals(3.5));
expect(copy.minHeight, moreOrLessEquals(5.5));
expect(copy.maxHeight, moreOrLessEquals(8.5));
copy = BoxConstraints.lerp(const BoxConstraints(
minWidth: 13.0,
maxWidth: 17.0,
minHeight: 111.0,
maxHeight: 117.0,
), constraints, 0.2)!;
expect(copy.minWidth, moreOrLessEquals(11.0));
expect(copy.maxWidth, moreOrLessEquals(15.0));
expect(copy.minHeight, moreOrLessEquals(91.0));
expect(copy.maxHeight, moreOrLessEquals(97.0));
});
test('BoxConstraints.lerp identical a,b', () {
expect(BoxConstraints.lerp(null, null, 0), null);
const BoxConstraints constraints = BoxConstraints();
expect(identical(BoxConstraints.lerp(constraints, constraints, 0.5), constraints), true);
});
test('BoxConstraints lerp with unbounded width', () {
const BoxConstraints constraints1 = BoxConstraints(
minWidth: double.infinity,
minHeight: 10.0,
maxHeight: 20.0,
);
const BoxConstraints constraints2 = BoxConstraints(
minWidth: double.infinity,
minHeight: 20.0,
maxHeight: 30.0,
);
const BoxConstraints constraints3 = BoxConstraints(
minWidth: double.infinity,
minHeight: 15.0,
maxHeight: 25.0,
);
expect(BoxConstraints.lerp(constraints1, constraints2, 0.5), constraints3);
});
test('BoxConstraints lerp with unbounded height', () {
const BoxConstraints constraints1 = BoxConstraints(
minWidth: 10.0,
maxWidth: 20.0,
minHeight: double.infinity,
);
const BoxConstraints constraints2 = BoxConstraints(
minWidth: 20.0,
maxWidth: 30.0,
minHeight: double.infinity,
);
const BoxConstraints constraints3 = BoxConstraints(
minWidth: 15.0,
maxWidth: 25.0,
minHeight: double.infinity,
);
expect(BoxConstraints.lerp(constraints1, constraints2, 0.5), constraints3);
});
test('BoxConstraints lerp from bounded to unbounded', () {
const BoxConstraints constraints1 = BoxConstraints(
minWidth: double.infinity,
minHeight: double.infinity,
);
const BoxConstraints constraints2 = BoxConstraints(
minWidth: 20.0,
maxWidth: 30.0,
minHeight: double.infinity,
);
const BoxConstraints constraints3 = BoxConstraints(
minWidth: double.infinity,
minHeight: 20.0,
maxHeight: 30.0,
);
expect(() => BoxConstraints.lerp(constraints1, constraints2, 0.5), throwsAssertionError);
expect(() => BoxConstraints.lerp(constraints1, constraints3, 0.5), throwsAssertionError);
expect(() => BoxConstraints.lerp(constraints2, constraints3, 0.5), throwsAssertionError);
});
test('BoxConstraints normalize', () {
const BoxConstraints constraints = BoxConstraints(
minWidth: 3.0,
maxWidth: 2.0,
minHeight: 11.0,
maxHeight: 18.0,
);
final BoxConstraints copy = constraints.normalize();
expect(copy.minWidth, 3.0);
expect(copy.maxWidth, 3.0);
expect(copy.minHeight, 11.0);
expect(copy.maxHeight, 18.0);
});
test('BoxConstraints.fromViewConstraints', () {
final BoxConstraints unconstrained = BoxConstraints.fromViewConstraints(
const ViewConstraints(),
);
expect(unconstrained, const BoxConstraints());
final BoxConstraints constraints = BoxConstraints.fromViewConstraints(
const ViewConstraints(minWidth: 1, maxWidth: 2, minHeight: 3, maxHeight: 4),
);
expect(constraints, const BoxConstraints(minWidth: 1, maxWidth: 2, minHeight: 3, maxHeight: 4));
});
}
| flutter/packages/flutter/test/rendering/box_constraints_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/rendering/box_constraints_test.dart",
"repo_id": "flutter",
"token_count": 2503
} | 673 |
// 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';
// before using this, consider using RenderSizedBox from rendering_tester.dart
class RenderTestBox extends RenderBox {
RenderTestBox(this._intrinsicDimensions);
final BoxConstraints _intrinsicDimensions;
@override
double computeMinIntrinsicWidth(double height) {
return _intrinsicDimensions.minWidth;
}
@override
double computeMaxIntrinsicWidth(double height) {
return _intrinsicDimensions.maxWidth;
}
@override
double computeMinIntrinsicHeight(double width) {
return _intrinsicDimensions.minHeight;
}
@override
double computeMaxIntrinsicHeight(double width) {
return _intrinsicDimensions.maxHeight;
}
@override
bool get sizedByParent => true;
@override
void performResize() {
size = constraints.constrain(Size(
_intrinsicDimensions.minWidth + (_intrinsicDimensions.maxWidth - _intrinsicDimensions.minWidth) / 2.0,
_intrinsicDimensions.minHeight + (_intrinsicDimensions.maxHeight - _intrinsicDimensions.minHeight) / 2.0,
));
}
}
void main() {
TestRenderingFlutterBinding.ensureInitialized();
test('Shrink-wrapping width', () {
final RenderBox child = RenderTestBox(const BoxConstraints(
minWidth: 10.0,
maxWidth: 100.0,
minHeight: 20.0,
maxHeight: 200.0,
));
final RenderBox parent = RenderIntrinsicWidth(child: child);
layout(
parent,
constraints: const BoxConstraints(
minWidth: 5.0,
minHeight: 8.0,
maxWidth: 500.0,
maxHeight: 800.0,
),
);
expect(parent.size.width, equals(100.0));
expect(parent.size.height, equals(110.0));
expect(child.size.width, equals(100));
expect(child.size.height, equals(110));
expect(parent.getMinIntrinsicWidth(0.0), equals(100.0));
expect(parent.getMaxIntrinsicWidth(0.0), equals(100.0));
expect(parent.getMinIntrinsicHeight(0.0), equals(20.0));
expect(parent.getMaxIntrinsicHeight(0.0), equals(200.0));
expect(parent.getMinIntrinsicWidth(10.0), equals(100.0));
expect(parent.getMaxIntrinsicWidth(10.0), equals(100.0));
expect(parent.getMinIntrinsicHeight(10.0), equals(20.0));
expect(parent.getMaxIntrinsicHeight(10.0), equals(200.0));
expect(parent.getMinIntrinsicWidth(80.0), equals(100.0));
expect(parent.getMaxIntrinsicWidth(80.0), equals(100.0));
expect(parent.getMinIntrinsicHeight(80.0), equals(20.0));
expect(parent.getMaxIntrinsicHeight(80.0), equals(200.0));
expect(parent.getMinIntrinsicWidth(double.infinity), equals(100.0));
expect(parent.getMaxIntrinsicWidth(double.infinity), equals(100.0));
expect(parent.getMinIntrinsicHeight(double.infinity), equals(20.0));
expect(parent.getMaxIntrinsicHeight(double.infinity), equals(200.0));
});
test('IntrinsicWidth without a child', () {
final RenderBox parent = RenderIntrinsicWidth();
layout(
parent,
constraints: const BoxConstraints(
minWidth: 5.0,
minHeight: 8.0,
maxWidth: 500.0,
maxHeight: 800.0,
),
);
expect(parent.size.width, equals(5.0));
expect(parent.size.height, equals(8.0));
expect(parent.getMinIntrinsicWidth(0.0), equals(0.0));
expect(parent.getMaxIntrinsicWidth(0.0), equals(0.0));
expect(parent.getMinIntrinsicHeight(0.0), equals(0.0));
expect(parent.getMaxIntrinsicHeight(0.0), equals(0.0));
expect(parent.getMinIntrinsicWidth(10.0), equals(0.0));
expect(parent.getMaxIntrinsicWidth(10.0), equals(0.0));
expect(parent.getMinIntrinsicHeight(10.0), equals(0.0));
expect(parent.getMaxIntrinsicHeight(10.0), equals(0.0));
expect(parent.getMinIntrinsicWidth(80.0), equals(0.0));
expect(parent.getMaxIntrinsicWidth(80.0), equals(0.0));
expect(parent.getMinIntrinsicHeight(80.0), equals(0.0));
expect(parent.getMaxIntrinsicHeight(80.0), equals(0.0));
expect(parent.getMinIntrinsicWidth(double.infinity), equals(0.0));
expect(parent.getMaxIntrinsicWidth(double.infinity), equals(0.0));
expect(parent.getMinIntrinsicHeight(double.infinity), equals(0.0));
expect(parent.getMaxIntrinsicHeight(double.infinity), equals(0.0));
});
test('Shrink-wrapping width (stepped width)', () {
final RenderBox child = RenderTestBox(const BoxConstraints(
minWidth: 10.0,
maxWidth: 100.0,
minHeight: 20.0,
maxHeight: 200.0,
));
final RenderBox parent = RenderIntrinsicWidth(child: child, stepWidth: 47.0);
layout(
parent,
constraints: const BoxConstraints(
minWidth: 5.0,
minHeight: 8.0,
maxWidth: 500.0,
maxHeight: 800.0,
),
);
expect(parent.size.width, equals(3.0 * 47.0));
expect(parent.size.height, equals(110.0));
expect(child.size.width, equals(3 * 47));
expect(child.size.height, equals(110));
expect(parent.getMinIntrinsicWidth(0.0), equals(3.0 * 47.0));
expect(parent.getMaxIntrinsicWidth(0.0), equals(3.0 * 47.0));
expect(parent.getMinIntrinsicHeight(0.0), equals(20.0));
expect(parent.getMaxIntrinsicHeight(0.0), equals(200.0));
expect(parent.getMinIntrinsicWidth(10.0), equals(3.0 * 47.0));
expect(parent.getMaxIntrinsicWidth(10.0), equals(3.0 * 47.0));
expect(parent.getMinIntrinsicHeight(10.0), equals(20.0));
expect(parent.getMaxIntrinsicHeight(10.0), equals(200.0));
expect(parent.getMinIntrinsicWidth(80.0), equals(3.0 * 47.0));
expect(parent.getMaxIntrinsicWidth(80.0), equals(3.0 * 47.0));
expect(parent.getMinIntrinsicHeight(80.0), equals(20.0));
expect(parent.getMaxIntrinsicHeight(80.0), equals(200.0));
expect(parent.getMinIntrinsicWidth(double.infinity), equals(3.0 * 47.0));
expect(parent.getMaxIntrinsicWidth(double.infinity), equals(3.0 * 47.0));
expect(parent.getMinIntrinsicHeight(double.infinity), equals(20.0));
expect(parent.getMaxIntrinsicHeight(double.infinity), equals(200.0));
});
test('Shrink-wrapping width (stepped height)', () {
final RenderBox child = RenderTestBox(const BoxConstraints(
minWidth: 10.0,
maxWidth: 100.0,
minHeight: 20.0,
maxHeight: 200.0,
));
final RenderBox parent = RenderIntrinsicWidth(child: child, stepHeight: 47.0);
layout(
parent,
constraints: const BoxConstraints(
minWidth: 5.0,
minHeight: 8.0,
maxWidth: 500.0,
maxHeight: 800.0,
),
);
expect(parent.size.width, equals(100.0));
expect(parent.size.height, equals(235.0));
expect(parent.getMinIntrinsicWidth(0.0), equals(100.0));
expect(parent.getMaxIntrinsicWidth(0.0), equals(100.0));
expect(parent.getMinIntrinsicHeight(0.0), equals(1.0 * 47.0));
expect(parent.getMaxIntrinsicHeight(0.0), equals(5.0 * 47.0));
expect(parent.getMinIntrinsicWidth(10.0), equals(100.0));
expect(parent.getMaxIntrinsicWidth(10.0), equals(100.0));
expect(parent.getMinIntrinsicHeight(10.0), equals(1.0 * 47.0));
expect(parent.getMaxIntrinsicHeight(10.0), equals(5.0 * 47.0));
expect(parent.getMinIntrinsicWidth(80.0), equals(100.0));
expect(parent.getMaxIntrinsicWidth(80.0), equals(100.0));
expect(parent.getMinIntrinsicHeight(80.0), equals(1.0 * 47.0));
expect(parent.getMaxIntrinsicHeight(80.0), equals(5.0 * 47.0));
expect(parent.getMinIntrinsicWidth(double.infinity), equals(100.0));
expect(parent.getMaxIntrinsicWidth(double.infinity), equals(100.0));
expect(parent.getMinIntrinsicHeight(double.infinity), equals(1.0 * 47.0));
expect(parent.getMaxIntrinsicHeight(double.infinity), equals(5.0 * 47.0));
});
test('Shrink-wrapping width (stepped everything)', () {
final RenderBox child = RenderTestBox(const BoxConstraints(
minWidth: 10.0,
maxWidth: 100.0,
minHeight: 20.0,
maxHeight: 200.0,
));
final RenderBox parent = RenderIntrinsicWidth(child: child, stepHeight: 47.0, stepWidth: 37.0);
layout(
parent,
constraints: const BoxConstraints(
minWidth: 5.0,
minHeight: 8.0,
maxWidth: 500.0,
maxHeight: 800.0,
),
);
expect(parent.size.width, equals(3.0 * 37.0));
expect(parent.size.height, equals(235.0));
expect(parent.getMinIntrinsicWidth(0.0), equals(3.0 * 37.0));
expect(parent.getMaxIntrinsicWidth(0.0), equals(3.0 * 37.0));
expect(parent.getMinIntrinsicHeight(0.0), equals(1.0 * 47.0));
expect(parent.getMaxIntrinsicHeight(0.0), equals(5.0 * 47.0));
expect(parent.getMinIntrinsicWidth(10.0), equals(3.0 * 37.0));
expect(parent.getMaxIntrinsicWidth(10.0), equals(3.0 * 37.0));
expect(parent.getMinIntrinsicHeight(10.0), equals(1.0 * 47.0));
expect(parent.getMaxIntrinsicHeight(10.0), equals(5.0 * 47.0));
expect(parent.getMinIntrinsicWidth(80.0), equals(3.0 * 37.0));
expect(parent.getMaxIntrinsicWidth(80.0), equals(3.0 * 37.0));
expect(parent.getMinIntrinsicHeight(80.0), equals(1.0 * 47.0));
expect(parent.getMaxIntrinsicHeight(80.0), equals(5.0 * 47.0));
expect(parent.getMinIntrinsicWidth(double.infinity), equals(3.0 * 37.0));
expect(parent.getMaxIntrinsicWidth(double.infinity), equals(3.0 * 37.0));
expect(parent.getMinIntrinsicHeight(double.infinity), equals(1.0 * 47.0));
expect(parent.getMaxIntrinsicHeight(double.infinity), equals(5.0 * 47.0));
});
test('RenderIntrinsicWidth when parent is given loose constraints smaller than intrinsic width of child', () {
final RenderBox child = RenderTestBox(const BoxConstraints(
minWidth: 10.0,
maxWidth: 100.0,
minHeight: 20.0,
maxHeight: 200.0,
));
final RenderBox parent = RenderIntrinsicWidth(child: child);
layout(
parent,
constraints: const BoxConstraints(
minWidth: 50.0,
minHeight: 8.0,
maxWidth: 70.0,
maxHeight: 800.0,
),
);
expect(parent.size.width, equals(70));
expect(parent.size.height, equals(110));
expect(child.size.width, equals(70));
expect(child.size.height, equals(110));
});
test('RenderIntrinsicWidth when parent is given tight constraints larger than intrinsic width of child', () {
final RenderBox child =
RenderTestBox(const BoxConstraints(minWidth: 10.0, maxWidth: 100.0, minHeight: 20.0, maxHeight: 200.0));
final RenderBox parent = RenderIntrinsicWidth(child: child);
layout(
parent,
constraints: const BoxConstraints(
minWidth: 500.0,
minHeight: 8.0,
maxWidth: 500.0,
maxHeight: 800.0,
),
);
expect(parent.size.width, equals(500));
expect(parent.size.height, equals(110));
expect(child.size.width, equals(500));
expect(child.size.height, equals(110));
});
test('RenderIntrinsicWidth when parent is given tight constraints smaller than intrinsic width of child', () {
final RenderBox child = RenderTestBox(const BoxConstraints(
minWidth: 10.0,
maxWidth: 100.0,
minHeight: 20.0,
maxHeight: 200.0,
));
final RenderBox parent = RenderIntrinsicWidth(child: child);
layout(
parent,
constraints: const BoxConstraints(
minWidth: 50.0,
minHeight: 8.0,
maxWidth: 50.0,
maxHeight: 800.0,
),
);
expect(parent.size.width, equals(50));
expect(parent.size.height, equals(110));
expect(child.size.width, equals(50));
expect(child.size.height, equals(110));
});
test('Shrink-wrapping height', () {
final RenderBox child = RenderTestBox(const BoxConstraints(
minWidth: 10.0,
maxWidth: 100.0,
minHeight: 20.0,
maxHeight: 200.0,
));
final RenderBox parent = RenderIntrinsicHeight(child: child);
layout(
parent,
constraints: const BoxConstraints(
minWidth: 5.0,
minHeight: 8.0,
maxWidth: 500.0,
maxHeight: 800.0,
),
);
expect(parent.size.width, equals(55.0));
expect(parent.size.height, equals(200.0));
expect(parent.getMinIntrinsicWidth(0.0), equals(10.0));
expect(parent.getMaxIntrinsicWidth(0.0), equals(100.0));
expect(parent.getMinIntrinsicHeight(0.0), equals(200.0));
expect(parent.getMaxIntrinsicHeight(0.0), equals(200.0));
expect(parent.getMinIntrinsicWidth(10.0), equals(10.0));
expect(parent.getMaxIntrinsicWidth(10.0), equals(100.0));
expect(parent.getMinIntrinsicHeight(10.0), equals(200.0));
expect(parent.getMaxIntrinsicHeight(10.0), equals(200.0));
expect(parent.getMinIntrinsicWidth(80.0), equals(10.0));
expect(parent.getMaxIntrinsicWidth(80.0), equals(100.0));
expect(parent.getMinIntrinsicHeight(80.0), equals(200.0));
expect(parent.getMaxIntrinsicHeight(80.0), equals(200.0));
expect(parent.getMinIntrinsicWidth(double.infinity), equals(10.0));
expect(parent.getMaxIntrinsicWidth(double.infinity), equals(100.0));
expect(parent.getMinIntrinsicHeight(double.infinity), equals(200.0));
expect(parent.getMaxIntrinsicHeight(double.infinity), equals(200.0));
});
test('IntrinsicHeight without a child', () {
final RenderBox parent = RenderIntrinsicHeight();
layout(
parent,
constraints: const BoxConstraints(
minWidth: 5.0,
minHeight: 8.0,
maxWidth: 500.0,
maxHeight: 800.0,
),
);
expect(parent.size.width, equals(5.0));
expect(parent.size.height, equals(8.0));
expect(parent.getMinIntrinsicWidth(0.0), equals(0.0));
expect(parent.getMaxIntrinsicWidth(0.0), equals(0.0));
expect(parent.getMinIntrinsicHeight(0.0), equals(0.0));
expect(parent.getMaxIntrinsicHeight(0.0), equals(0.0));
expect(parent.getMinIntrinsicWidth(10.0), equals(0.0));
expect(parent.getMaxIntrinsicWidth(10.0), equals(0.0));
expect(parent.getMinIntrinsicHeight(10.0), equals(0.0));
expect(parent.getMaxIntrinsicHeight(10.0), equals(0.0));
expect(parent.getMinIntrinsicWidth(80.0), equals(0.0));
expect(parent.getMaxIntrinsicWidth(80.0), equals(0.0));
expect(parent.getMinIntrinsicHeight(80.0), equals(0.0));
expect(parent.getMaxIntrinsicHeight(80.0), equals(0.0));
expect(parent.getMinIntrinsicWidth(double.infinity), equals(0.0));
expect(parent.getMaxIntrinsicWidth(double.infinity), equals(0.0));
expect(parent.getMinIntrinsicHeight(double.infinity), equals(0.0));
expect(parent.getMaxIntrinsicHeight(double.infinity), equals(0.0));
});
test('RenderIntrinsicHeight when parent is given loose constraints smaller than intrinsic height of child', () {
final RenderBox child = RenderTestBox(const BoxConstraints(
minWidth: 10.0,
maxWidth: 100.0,
minHeight: 20.0,
maxHeight: 200.0,
));
final RenderBox parent = RenderIntrinsicHeight(child: child);
layout(
parent,
constraints: const BoxConstraints(
minWidth: 5.0,
minHeight: 8.0,
maxWidth: 500.0,
maxHeight: 80.0,
),
);
expect(parent.size.width, equals(55));
expect(parent.size.height, equals(80));
expect(child.size.width, equals(55));
expect(child.size.height, equals(80));
});
test('RenderIntrinsicHeight when parent is given tight constraints larger than intrinsic height of child', () {
final RenderBox child = RenderTestBox(const BoxConstraints(
minWidth: 10.0,
maxWidth: 100.0,
minHeight: 20.0,
maxHeight: 200.0,
));
final RenderBox parent = RenderIntrinsicHeight(child: child);
layout(
parent,
constraints: const BoxConstraints(
minWidth: 5.0,
minHeight: 400.0,
maxWidth: 500.0,
maxHeight: 400.0,
),
);
expect(parent.size.width, equals(55));
expect(parent.size.height, equals(400));
expect(child.size.width, equals(55));
expect(child.size.height, equals(400));
});
test('RenderIntrinsicHeight when parent is given tight constraints smaller than intrinsic height of child', () {
final RenderBox child = RenderTestBox(const BoxConstraints(
minWidth: 10.0,
maxWidth: 100.0,
minHeight: 20.0,
maxHeight: 200.0,
));
final RenderBox parent = RenderIntrinsicHeight(child: child);
layout(
parent,
constraints: const BoxConstraints(
minWidth: 5.0,
minHeight: 80.0,
maxWidth: 500.0,
maxHeight: 80.0,
),
);
expect(parent.size.width, equals(55));
expect(parent.size.height, equals(80));
expect(child.size.width, equals(55));
expect(child.size.height, equals(80));
});
test('Padding and boring intrinsics', () {
final RenderBox box = RenderPadding(
padding: const EdgeInsets.all(15.0),
child: RenderSizedBox(const Size(20.0, 20.0)),
);
expect(box.getMinIntrinsicWidth(0.0), 50.0);
expect(box.getMaxIntrinsicWidth(0.0), 50.0);
expect(box.getMinIntrinsicHeight(0.0), 50.0);
expect(box.getMaxIntrinsicHeight(0.0), 50.0);
expect(box.getMinIntrinsicWidth(10.0), 50.0);
expect(box.getMaxIntrinsicWidth(10.0), 50.0);
expect(box.getMinIntrinsicHeight(10.0), 50.0);
expect(box.getMaxIntrinsicHeight(10.0), 50.0);
expect(box.getMinIntrinsicWidth(80.0), 50.0);
expect(box.getMaxIntrinsicWidth(80.0), 50.0);
expect(box.getMinIntrinsicHeight(80.0), 50.0);
expect(box.getMaxIntrinsicHeight(80.0), 50.0);
expect(box.getMinIntrinsicWidth(double.infinity), 50.0);
expect(box.getMaxIntrinsicWidth(double.infinity), 50.0);
expect(box.getMinIntrinsicHeight(double.infinity), 50.0);
expect(box.getMaxIntrinsicHeight(double.infinity), 50.0);
// also a smoke test:
layout(
box,
constraints: const BoxConstraints(
minWidth: 10.0,
minHeight: 10.0,
maxWidth: 10.0,
maxHeight: 10.0,
),
);
});
test('Padding and interesting intrinsics', () {
final RenderBox box = RenderPadding(
padding: const EdgeInsets.all(15.0),
child: RenderAspectRatio(aspectRatio: 1.0),
);
expect(box.getMinIntrinsicWidth(0.0), 30.0);
expect(box.getMaxIntrinsicWidth(0.0), 30.0);
expect(box.getMinIntrinsicHeight(0.0), 30.0);
expect(box.getMaxIntrinsicHeight(0.0), 30.0);
expect(box.getMinIntrinsicWidth(10.0), 30.0);
expect(box.getMaxIntrinsicWidth(10.0), 30.0);
expect(box.getMinIntrinsicHeight(10.0), 30.0);
expect(box.getMaxIntrinsicHeight(10.0), 30.0);
expect(box.getMinIntrinsicWidth(80.0), 80.0);
expect(box.getMaxIntrinsicWidth(80.0), 80.0);
expect(box.getMinIntrinsicHeight(80.0), 80.0);
expect(box.getMaxIntrinsicHeight(80.0), 80.0);
expect(box.getMinIntrinsicWidth(double.infinity), 30.0);
expect(box.getMaxIntrinsicWidth(double.infinity), 30.0);
expect(box.getMinIntrinsicHeight(double.infinity), 30.0);
expect(box.getMaxIntrinsicHeight(double.infinity), 30.0);
// also a smoke test:
layout(
box,
constraints: const BoxConstraints(
minWidth: 10.0,
minHeight: 10.0,
maxWidth: 10.0,
maxHeight: 10.0,
),
);
});
test('Padding and boring intrinsics', () {
final RenderBox box = RenderPadding(
padding: const EdgeInsets.all(15.0),
child: RenderSizedBox(const Size(20.0, 20.0)),
);
expect(box.getMinIntrinsicWidth(0.0), 50.0);
expect(box.getMaxIntrinsicWidth(0.0), 50.0);
expect(box.getMinIntrinsicHeight(0.0), 50.0);
expect(box.getMaxIntrinsicHeight(0.0), 50.0);
expect(box.getMinIntrinsicWidth(10.0), 50.0);
expect(box.getMaxIntrinsicWidth(10.0), 50.0);
expect(box.getMinIntrinsicHeight(10.0), 50.0);
expect(box.getMaxIntrinsicHeight(10.0), 50.0);
expect(box.getMinIntrinsicWidth(80.0), 50.0);
expect(box.getMaxIntrinsicWidth(80.0), 50.0);
expect(box.getMinIntrinsicHeight(80.0), 50.0);
expect(box.getMaxIntrinsicHeight(80.0), 50.0);
expect(box.getMinIntrinsicWidth(double.infinity), 50.0);
expect(box.getMaxIntrinsicWidth(double.infinity), 50.0);
expect(box.getMinIntrinsicHeight(double.infinity), 50.0);
expect(box.getMaxIntrinsicHeight(double.infinity), 50.0);
// also a smoke test:
layout(
box,
constraints: const BoxConstraints(
minWidth: 10.0,
minHeight: 10.0,
maxWidth: 10.0,
maxHeight: 10.0,
),
);
});
test('Padding and interesting intrinsics', () {
final RenderBox box = RenderPadding(
padding: const EdgeInsets.all(15.0),
child: RenderAspectRatio(aspectRatio: 1.0),
);
expect(box.getMinIntrinsicWidth(0.0), 30.0);
expect(box.getMaxIntrinsicWidth(0.0), 30.0);
expect(box.getMinIntrinsicHeight(0.0), 30.0);
expect(box.getMaxIntrinsicHeight(0.0), 30.0);
expect(box.getMinIntrinsicWidth(10.0), 30.0);
expect(box.getMaxIntrinsicWidth(10.0), 30.0);
expect(box.getMinIntrinsicHeight(10.0), 30.0);
expect(box.getMaxIntrinsicHeight(10.0), 30.0);
expect(box.getMinIntrinsicWidth(80.0), 80.0);
expect(box.getMaxIntrinsicWidth(80.0), 80.0);
expect(box.getMinIntrinsicHeight(80.0), 80.0);
expect(box.getMaxIntrinsicHeight(80.0), 80.0);
expect(box.getMinIntrinsicWidth(double.infinity), 30.0);
expect(box.getMaxIntrinsicWidth(double.infinity), 30.0);
expect(box.getMinIntrinsicHeight(double.infinity), 30.0);
expect(box.getMaxIntrinsicHeight(double.infinity), 30.0);
// also a smoke test:
layout(
box,
constraints: const BoxConstraints(
minWidth: 10.0,
minHeight: 10.0,
maxWidth: 10.0,
maxHeight: 10.0,
),
);
});
}
| flutter/packages/flutter/test/rendering/intrinsic_width_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/rendering/intrinsic_width_test.dart",
"repo_id": "flutter",
"token_count": 9241
} | 674 |
// 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/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'rendering_tester.dart';
void main() {
TestRenderingFlutterBinding.ensureInitialized();
// This test has to be kept separate from object_test.dart because the way
// the rendering_test.dart dependency of this test uses the bindings in not
// compatible with existing tests in object_test.dart.
test('reentrant paint error', () {
late FlutterErrorDetails errorDetails;
final RenderBox root = TestReentrantPaintingErrorRenderBox();
layout(root, onErrors: () {
errorDetails = TestRenderingFlutterBinding.instance.takeFlutterErrorDetails()!;
});
pumpFrame(phase: EnginePhase.paint);
expect(errorDetails, isNotNull);
expect(errorDetails.stack, isNotNull);
// Check the ErrorDetails without the stack trace
final List<String> lines = errorDetails.toString().split('\n');
// The lines in the middle of the error message contain the stack trace
// which will change depending on where the test is run.
expect(lines.length, greaterThan(12));
expect(
lines.take(12).join('\n'),
equalsIgnoringHashCodes(
'══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞══════════════════════\n'
'The following assertion was thrown during paint():\n'
'Tried to paint a RenderObject reentrantly.\n'
'The following RenderObject was already being painted when it was painted again:\n'
' TestReentrantPaintingErrorRenderBox#00000:\n'
' parentData: <none>\n'
' constraints: BoxConstraints(w=800.0, h=600.0)\n'
' size: Size(100.0, 100.0)\n'
'Since this typically indicates an infinite recursion, it is\n'
'disallowed.\n'
'\n'
'When the exception was thrown, this was the stack:',
),
);
expect(
lines.getRange(lines.length - 8, lines.length).join('\n'),
equalsIgnoringHashCodes(
'The following RenderObject was being processed when the exception was fired:\n'
' TestReentrantPaintingErrorRenderBox#00000:\n'
' parentData: <none>\n'
' constraints: BoxConstraints(w=800.0, h=600.0)\n'
' size: Size(100.0, 100.0)\n'
'This RenderObject has no descendants.\n'
'═════════════════════════════════════════════════════════════════\n',
),
);
});
test('needsCompositingBitsUpdate paint error', () {
late FlutterError flutterError;
final RenderBox root = RenderRepaintBoundary(child: RenderSizedBox(const Size(100, 100)));
try {
layout(root);
PaintingContext.repaintCompositedChild(root, debugAlsoPaintedParent: true);
} on FlutterError catch (exception) {
flutterError = exception;
}
expect(flutterError, isNotNull);
// The lines in the middle of the error message contain the stack trace
// which will change depending on where the test is run.
expect(
flutterError.toStringDeep(),
equalsIgnoringHashCodes(
'FlutterError\n'
' Tried to paint a RenderObject before its compositing bits were\n'
' updated.\n'
' The following RenderObject was marked as having dirty compositing bits at the time that it was painted:\n'
' RenderRepaintBoundary#00000 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE:\n'
' needs compositing\n'
' parentData: <none>\n'
' constraints: BoxConstraints(w=800.0, h=600.0)\n'
' layer: OffsetLayer#00000 DETACHED\n'
' size: Size(800.0, 600.0)\n'
' metrics: 0.0% useful (1 bad vs 0 good)\n'
' diagnosis: insufficient data to draw conclusion (less than five\n'
' repaints)\n'
' A RenderObject that still has dirty compositing bits cannot be\n'
' painted because this indicates that the tree has not yet been\n'
' properly configured for creating the layer tree.\n'
' This usually indicates an error in the Flutter framework itself.\n',
),
);
expect(
flutterError.diagnostics.singleWhere((DiagnosticsNode node) => node.level == DiagnosticLevel.hint).toString(),
'This usually indicates an error in the Flutter framework itself.',
);
});
}
class TestReentrantPaintingErrorRenderBox extends RenderBox {
@override
void paint(PaintingContext context, Offset offset) {
// Cause a reentrant painting bug that would show up as a stack overflow if
// it was not for debugging checks in RenderObject.
context.paintChild(this, offset);
}
@override
void performLayout() {
size = const Size(100, 100);
}
}
| flutter/packages/flutter/test/rendering/paint_error_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/rendering/paint_error_test.dart",
"repo_id": "flutter",
"token_count": 1820
} | 675 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
const Rect rect = Rect.fromLTWH(100, 100, 200, 500);
const Offset outsideTopLeft = Offset(50, 50);
const Offset outsideLeft = Offset(50, 200);
const Offset outsideBottomLeft = Offset(50, 700);
const Offset outsideTop = Offset(200, 50);
const Offset outsideTopRight = Offset(350, 50);
const Offset outsideRight = Offset(350, 200);
const Offset outsideBottomRight = Offset(350, 700);
const Offset outsideBottom = Offset(200, 700);
const Offset center = Offset(150, 300);
group('selection utils', () {
test('selectionBasedOnRect works', () {
expect(
SelectionUtils.getResultBasedOnRect(rect, outsideTopLeft),
SelectionResult.previous,
);
expect(
SelectionUtils.getResultBasedOnRect(rect, outsideLeft),
SelectionResult.previous,
);
expect(
SelectionUtils.getResultBasedOnRect(rect, outsideBottomLeft),
SelectionResult.next,
);
expect(
SelectionUtils.getResultBasedOnRect(rect, outsideTop),
SelectionResult.previous,
);
expect(
SelectionUtils.getResultBasedOnRect(rect, outsideTopRight),
SelectionResult.previous,
);
expect(
SelectionUtils.getResultBasedOnRect(rect, outsideRight),
SelectionResult.next,
);
expect(
SelectionUtils.getResultBasedOnRect(rect, outsideBottomRight),
SelectionResult.next,
);
expect(
SelectionUtils.getResultBasedOnRect(rect, outsideBottom),
SelectionResult.next,
);
expect(
SelectionUtils.getResultBasedOnRect(rect, center),
SelectionResult.end,
);
});
test('adjustDragOffset works', () {
// ltr
expect(SelectionUtils.adjustDragOffset(rect, outsideTopLeft), rect.topLeft);
expect(SelectionUtils.adjustDragOffset(rect, outsideLeft), rect.topLeft);
expect(SelectionUtils.adjustDragOffset(rect, outsideBottomLeft), rect.bottomRight);
expect(SelectionUtils.adjustDragOffset(rect, outsideTop), rect.topLeft);
expect(SelectionUtils.adjustDragOffset(rect, outsideTopRight), rect.topLeft);
expect(SelectionUtils.adjustDragOffset(rect, outsideRight), rect.bottomRight);
expect(SelectionUtils.adjustDragOffset(rect, outsideBottomRight), rect.bottomRight);
expect(SelectionUtils.adjustDragOffset(rect, outsideBottom), rect.bottomRight);
expect(SelectionUtils.adjustDragOffset(rect, center), center);
// rtl
expect(SelectionUtils.adjustDragOffset(rect, outsideTopLeft, direction: TextDirection.rtl), rect.topRight);
expect(SelectionUtils.adjustDragOffset(rect, outsideLeft, direction: TextDirection.rtl), rect.topRight);
expect(SelectionUtils.adjustDragOffset(rect, outsideBottomLeft, direction: TextDirection.rtl), rect.bottomLeft);
expect(SelectionUtils.adjustDragOffset(rect, outsideTop, direction: TextDirection.rtl), rect.topRight);
expect(SelectionUtils.adjustDragOffset(rect, outsideTopRight, direction: TextDirection.rtl), rect.topRight);
expect(SelectionUtils.adjustDragOffset(rect, outsideRight, direction: TextDirection.rtl), rect.bottomLeft);
expect(SelectionUtils.adjustDragOffset(rect, outsideBottomRight, direction: TextDirection.rtl), rect.bottomLeft);
expect(SelectionUtils.adjustDragOffset(rect, outsideBottom, direction: TextDirection.rtl), rect.bottomLeft);
expect(SelectionUtils.adjustDragOffset(rect, center, direction: TextDirection.rtl), center);
});
});
}
| flutter/packages/flutter/test/rendering/selection_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/rendering/selection_test.dart",
"repo_id": "flutter",
"token_count": 1341
} | 676 |
// 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/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('SystemChrome - style', () {
const double statusBarHeight = 25.0;
const double navigationBarHeight = 54.0;
const double deviceHeight = 960.0;
const double deviceWidth = 480.0;
const double devicePixelRatio = 2.0;
void setupTestDevice(WidgetTester tester) {
const FakeViewPadding padding = FakeViewPadding(
top: statusBarHeight * devicePixelRatio,
bottom: navigationBarHeight * devicePixelRatio,
);
addTearDown(tester.view.reset);
tester.view
..viewPadding = padding
..padding = padding
..devicePixelRatio = devicePixelRatio
..physicalSize = const Size(
deviceWidth * devicePixelRatio,
deviceHeight * devicePixelRatio,
);
}
tearDown(() async {
SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle());
await pumpEventQueue();
});
group('status bar', () {
testWidgets("statusBarColor isn't set for unannotated view",
(WidgetTester tester) async {
await tester.pumpWidget(const SizedBox.expand());
await tester.pumpAndSettle();
expect(SystemChrome.latestStyle?.statusBarColor, isNull);
},
);
testWidgets('statusBarColor is set for annotated view',
(WidgetTester tester) async {
setupTestDevice(tester);
await tester.pumpWidget(const AnnotatedRegion<SystemUiOverlayStyle>(
value: SystemUiOverlayStyle(
statusBarColor: Colors.blue,
),
child: SizedBox.expand(),
));
await tester.pumpAndSettle();
expect(
SystemChrome.latestStyle?.statusBarColor,
Colors.blue,
);
},
variant: TargetPlatformVariant.mobile(),
);
testWidgets("statusBarColor isn't set when view covers less than half of the system status bar",
(WidgetTester tester) async {
setupTestDevice(tester);
const double lessThanHalfOfTheStatusBarHeight =
statusBarHeight / 2.0 - 1;
await tester.pumpWidget(const Align(
alignment: Alignment.topCenter,
child: AnnotatedRegion<SystemUiOverlayStyle>(
value: SystemUiOverlayStyle(
statusBarColor: Colors.blue,
),
child: SizedBox(
width: 100,
height: lessThanHalfOfTheStatusBarHeight,
),
),
));
await tester.pumpAndSettle();
expect(SystemChrome.latestStyle?.statusBarColor, isNull);
},
variant: TargetPlatformVariant.mobile(),
);
testWidgets('statusBarColor is set when view covers more than half of tye system status bar',
(WidgetTester tester) async {
setupTestDevice(tester);
const double moreThanHalfOfTheStatusBarHeight =
statusBarHeight / 2.0 + 1;
await tester.pumpWidget(const Align(
alignment: Alignment.topCenter,
child: AnnotatedRegion<SystemUiOverlayStyle>(
value: SystemUiOverlayStyle(
statusBarColor: Colors.blue,
),
child: SizedBox(
width: 100,
height: moreThanHalfOfTheStatusBarHeight,
),
),
));
await tester.pumpAndSettle();
expect(
SystemChrome.latestStyle?.statusBarColor,
Colors.blue,
);
},
variant: TargetPlatformVariant.mobile(),
);
});
group('navigation color (Android only)', () {
testWidgets("systemNavigationBarColor isn't set for non Android device",
(WidgetTester tester) async {
setupTestDevice(tester);
await tester.pumpWidget(const AnnotatedRegion<SystemUiOverlayStyle>(
value: SystemUiOverlayStyle(
systemNavigationBarColor: Colors.blue,
),
child: SizedBox.expand(),
));
await tester.pumpAndSettle();
expect(
SystemChrome.latestStyle?.systemNavigationBarColor,
isNull,
);
},
variant: TargetPlatformVariant.only(TargetPlatform.iOS),
);
testWidgets("systemNavigationBarColor isn't set for unannotated view",
(WidgetTester tester) async {
await tester.pumpWidget(const SizedBox.expand());
await tester.pumpAndSettle();
expect(SystemChrome.latestStyle?.systemNavigationBarColor, isNull);
},
variant: TargetPlatformVariant.only(TargetPlatform.android),
);
testWidgets('systemNavigationBarColor is set for annotated view',
(WidgetTester tester) async {
setupTestDevice(tester);
await tester.pumpWidget(const AnnotatedRegion<SystemUiOverlayStyle>(
value: SystemUiOverlayStyle(
systemNavigationBarColor: Colors.blue,
),
child: SizedBox.expand(),
));
await tester.pumpAndSettle();
expect(
SystemChrome.latestStyle?.systemNavigationBarColor,
Colors.blue,
);
},
variant: TargetPlatformVariant.only(TargetPlatform.android),
);
testWidgets("systemNavigationBarColor isn't set when view covers less than half of navigation bar",
(WidgetTester tester) async {
setupTestDevice(tester);
const double lessThanHalfOfTheNavigationBarHeight =
navigationBarHeight / 2.0 - 1;
await tester.pumpWidget(const Align(
alignment: Alignment.bottomCenter,
child: AnnotatedRegion<SystemUiOverlayStyle>(
value: SystemUiOverlayStyle(
systemNavigationBarColor: Colors.blue,
),
child: SizedBox(
width: 100,
height: lessThanHalfOfTheNavigationBarHeight,
),
),
));
await tester.pumpAndSettle();
expect(SystemChrome.latestStyle?.systemNavigationBarColor, isNull);
},
variant: TargetPlatformVariant.only(TargetPlatform.android),
);
testWidgets('systemNavigationBarColor is set when view covers more than half of navigation bar',
(WidgetTester tester) async {
setupTestDevice(tester);
const double moreThanHalfOfTheNavigationBarHeight =
navigationBarHeight / 2.0 + 1;
await tester.pumpWidget(const Align(
alignment: Alignment.bottomCenter,
child: AnnotatedRegion<SystemUiOverlayStyle>(
value: SystemUiOverlayStyle(
systemNavigationBarColor: Colors.blue,
),
child: SizedBox(
width: 100,
height: moreThanHalfOfTheNavigationBarHeight,
),
),
));
await tester.pumpAndSettle();
expect(
SystemChrome.latestStyle?.systemNavigationBarColor,
Colors.blue,
);
},
variant: TargetPlatformVariant.only(TargetPlatform.android),
);
});
testWidgets('Top AnnotatedRegion provides status bar overlay style and bottom AnnotatedRegion provides navigation bar overlay style', (WidgetTester tester) async {
setupTestDevice(tester);
await tester.pumpWidget(
const Column(children: <Widget>[
Expanded(child: AnnotatedRegion<SystemUiOverlayStyle>(
value: SystemUiOverlayStyle(
systemNavigationBarColor: Colors.blue,
statusBarColor: Colors.blue
),
child: SizedBox.expand(),
)),
Expanded(child: AnnotatedRegion<SystemUiOverlayStyle>(
value: SystemUiOverlayStyle(
systemNavigationBarColor: Colors.green,
statusBarColor: Colors.green,
),
child: SizedBox.expand(),
)),
]),
);
await tester.pumpAndSettle();
expect(SystemChrome.latestStyle?.statusBarColor, Colors.blue);
expect(SystemChrome.latestStyle?.systemNavigationBarColor, Colors.green);
}, variant: TargetPlatformVariant.only(TargetPlatform.android));
testWidgets('Top only AnnotatedRegion provides status bar and navigation bar style properties', (WidgetTester tester) async {
setupTestDevice(tester);
await tester.pumpWidget(
const Column(children: <Widget>[
Expanded(child: AnnotatedRegion<SystemUiOverlayStyle>(
value: SystemUiOverlayStyle(
systemNavigationBarColor: Colors.blue,
statusBarColor: Colors.blue
),
child: SizedBox.expand(),
)),
Expanded(child: SizedBox.expand()),
]),
);
await tester.pumpAndSettle();
expect(SystemChrome.latestStyle?.statusBarColor, Colors.blue);
expect(SystemChrome.latestStyle?.systemNavigationBarColor, Colors.blue);
}, variant: TargetPlatformVariant.only(TargetPlatform.android));
testWidgets('Bottom only AnnotatedRegion provides status bar and navigation bar style properties', (WidgetTester tester) async {
setupTestDevice(tester);
await tester.pumpWidget(
const Column(children: <Widget>[
Expanded(child: SizedBox.expand()),
Expanded(child: AnnotatedRegion<SystemUiOverlayStyle>(
value: SystemUiOverlayStyle(
systemNavigationBarColor: Colors.green,
statusBarColor: Colors.green
),
child: SizedBox.expand(),
)),
]),
);
await tester.pumpAndSettle();
expect(SystemChrome.latestStyle?.statusBarColor, Colors.green);
expect(SystemChrome.latestStyle?.systemNavigationBarColor, Colors.green);
}, variant: TargetPlatformVariant.only(TargetPlatform.android));
});
}
| flutter/packages/flutter/test/rendering/view_chrome_style_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/rendering/view_chrome_style_test.dart",
"repo_id": "flutter",
"token_count": 4599
} | 677 |
// 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';
void main() {
group(CustomSemanticsAction, () {
test('is provided a canonical id based on the label', () {
final CustomSemanticsAction action1 = CustomSemanticsAction(label: _nonconst('test'));
final CustomSemanticsAction action2 = CustomSemanticsAction(label: _nonconst('test'));
final CustomSemanticsAction action3 = CustomSemanticsAction(label: _nonconst('not test'));
final int id1 = CustomSemanticsAction.getIdentifier(action1);
final int id2 = CustomSemanticsAction.getIdentifier(action2);
final int id3 = CustomSemanticsAction.getIdentifier(action3);
expect(id1, id2);
expect(id2, isNot(id3));
expect(CustomSemanticsAction.getAction(id1), action1);
expect(CustomSemanticsAction.getAction(id2), action1);
expect(CustomSemanticsAction.getAction(id3), action3);
});
});
}
T _nonconst<T>(T value) => value;
| flutter/packages/flutter/test/semantics/custom_semantics_action_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/semantics/custom_semantics_action_test.dart",
"repo_id": "flutter",
"token_count": 385
} | 678 |
// 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:convert';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
ByteData makeByteData(String str) {
return ByteData.sublistView(utf8.encode(str));
}
test('default binary messenger calls callback once', () async {
int countInbound = 0;
int countOutbound = 0;
const String channel = 'foo';
final ByteData bar = makeByteData('bar');
final Completer<void> done = Completer<void>();
ServicesBinding.instance.channelBuffers.push(
channel,
bar,
(ByteData? message) async {
expect(message, isNull);
countOutbound += 1;
done.complete();
},
);
expect(countInbound, equals(0));
expect(countOutbound, equals(0));
ServicesBinding.instance.defaultBinaryMessenger.setMessageHandler(
channel,
(ByteData? message) async {
expect(message, bar);
countInbound += 1;
return null;
},
);
expect(countInbound, equals(0));
expect(countOutbound, equals(0));
await done.future;
expect(countInbound, equals(1));
expect(countOutbound, equals(1));
});
test('can check the mock handler', () {
Future<ByteData?> handler(ByteData? call) => Future<ByteData?>.value();
final TestDefaultBinaryMessenger messenger = TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
expect(messenger.checkMockMessageHandler('test_channel', null), true);
expect(messenger.checkMockMessageHandler('test_channel', handler), false);
messenger.setMockMessageHandler('test_channel', handler);
expect(messenger.checkMockMessageHandler('test_channel', handler), true);
messenger.setMockMessageHandler('test_channel', null);
});
}
| flutter/packages/flutter/test/services/default_binary_messenger_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/services/default_binary_messenger_test.dart",
"repo_id": "flutter",
"token_count": 696
} | 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/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'fake_platform_views.dart';
void main() {
final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized();
group('Android', () {
late FakeAndroidPlatformViewsController viewsController;
setUp(() {
viewsController = FakeAndroidPlatformViewsController();
});
test('create Android view of unregistered type', () async {
await expectLater(() =>
PlatformViewsService.initAndroidView(
id: 0,
viewType: 'web',
layoutDirection: TextDirection.ltr,
).create(size: const Size(100.0, 100.0)),
throwsA(isA<PlatformException>()),
);
viewsController.registerViewType('web');
try {
await PlatformViewsService.initSurfaceAndroidView(
id: 0,
viewType: 'web',
layoutDirection: TextDirection.ltr,
).create(size: const Size(1.0, 1.0));
} catch (e) {
expect(false, isTrue, reason: 'did not expected any exception, but instead got `$e`');
}
try {
await PlatformViewsService.initAndroidView(
id: 1,
viewType: 'web',
layoutDirection: TextDirection.ltr,
).create(size: const Size(1.0, 1.0));
} catch (e) {
expect(false, isTrue, reason: 'did not expected any exception, but instead got `$e`');
}
});
test('create VD-fallback Android views', () async {
viewsController.registerViewType('webview');
await PlatformViewsService.initAndroidView(id: 0, viewType: 'webview', layoutDirection: TextDirection.ltr)
.create(size: const Size(100.0, 100.0));
await PlatformViewsService.initAndroidView( id: 1, viewType: 'webview', layoutDirection: TextDirection.rtl)
.create(size: const Size(200.0, 300.0));
expect(
viewsController.views,
unorderedEquals(<FakeAndroidPlatformView>[
const FakeAndroidPlatformView(0, 'webview', Size(100.0, 100.0), AndroidViewController.kAndroidLayoutDirectionLtr),
const FakeAndroidPlatformView(1, 'webview', Size(200.0, 300.0), AndroidViewController.kAndroidLayoutDirectionRtl),
]),
);
});
test('create HC-fallback Android views', () async {
viewsController.registerViewType('webview');
await PlatformViewsService.initSurfaceAndroidView(id: 0, viewType: 'webview', layoutDirection: TextDirection.ltr)
.create(size: const Size(100.0, 100.0));
await PlatformViewsService.initSurfaceAndroidView( id: 1, viewType: 'webview', layoutDirection: TextDirection.rtl)
.create(size: const Size(200.0, 300.0));
expect(
viewsController.views,
unorderedEquals(<FakeAndroidPlatformView>[
const FakeAndroidPlatformView(0, 'webview', Size(100.0, 100.0), AndroidViewController.kAndroidLayoutDirectionLtr,
hybridFallback: true),
const FakeAndroidPlatformView(1, 'webview', Size(200.0, 300.0), AndroidViewController.kAndroidLayoutDirectionRtl,
hybridFallback: true),
]),
);
});
test('create HC-only Android views', () async {
viewsController.registerViewType('webview');
await PlatformViewsService.initExpensiveAndroidView(id: 0, viewType: 'webview', layoutDirection: TextDirection.ltr)
.create(size: const Size(100.0, 100.0));
await PlatformViewsService.initExpensiveAndroidView( id: 1, viewType: 'webview', layoutDirection: TextDirection.rtl)
.create(size: const Size(200.0, 300.0));
expect(
viewsController.views,
unorderedEquals(<FakeAndroidPlatformView>[
const FakeAndroidPlatformView(0, 'webview', null, AndroidViewController.kAndroidLayoutDirectionLtr,
hybrid: true),
const FakeAndroidPlatformView(1, 'webview', null, AndroidViewController.kAndroidLayoutDirectionRtl,
hybrid: true),
]),
);
});
test('default view does not use view composition by default', () async {
viewsController.registerViewType('webview');
final AndroidViewController controller = PlatformViewsService.initAndroidView(id: 0, viewType: 'webview', layoutDirection: TextDirection.ltr);
await controller.create(size: const Size(100.0, 100.0));
expect(controller.requiresViewComposition, false);
});
test('default view does not use view composition in fallback mode', () async {
viewsController.registerViewType('webview');
viewsController.allowTextureLayerMode = false;
final AndroidViewController controller = PlatformViewsService.initAndroidView(id: 0, viewType: 'webview', layoutDirection: TextDirection.ltr);
await controller.create(size: const Size(100.0, 100.0));
viewsController.allowTextureLayerMode = true;
expect(controller.requiresViewComposition, false);
});
test('surface view does not use view composition by default', () async {
viewsController.registerViewType('webview');
final AndroidViewController controller = PlatformViewsService.initSurfaceAndroidView(id: 0, viewType: 'webview', layoutDirection: TextDirection.ltr);
await controller.create(size: const Size(100.0, 100.0));
expect(controller.requiresViewComposition, false);
});
test('surface view does uses view composition in fallback mode', () async {
viewsController.registerViewType('webview');
viewsController.allowTextureLayerMode = false;
final AndroidViewController controller = PlatformViewsService.initSurfaceAndroidView(id: 0, viewType: 'webview', layoutDirection: TextDirection.ltr);
await controller.create(size: const Size(100.0, 100.0));
viewsController.allowTextureLayerMode = true;
expect(controller.requiresViewComposition, true);
});
test('expensive view uses view composition', () async {
viewsController.registerViewType('webview');
final AndroidViewController controller = PlatformViewsService.initExpensiveAndroidView(id: 0, viewType: 'webview', layoutDirection: TextDirection.ltr);
await controller.create(size: const Size(100.0, 100.0));
expect(controller.requiresViewComposition, true);
});
test('reuse Android view id', () async {
viewsController.registerViewType('webview');
final AndroidViewController controller = PlatformViewsService.initAndroidView(
id: 0,
viewType: 'webview',
layoutDirection: TextDirection.ltr,
);
await controller.create(size: const Size(100.0, 100.0));
await expectLater(
() {
final AndroidViewController controller = PlatformViewsService.initAndroidView(
id: 0,
viewType: 'web',
layoutDirection: TextDirection.ltr,
);
return controller.create(size: const Size(100.0, 100.0));
},
throwsA(isA<PlatformException>()),
);
});
test('dispose Android view', () async {
viewsController.registerViewType('webview');
await PlatformViewsService.initAndroidView(
id: 0,
viewType: 'webview',
layoutDirection: TextDirection.ltr,
).create(size: const Size(100.0, 100.0));
final AndroidViewController viewController = PlatformViewsService.initAndroidView(
id: 1,
viewType: 'webview',
layoutDirection: TextDirection.ltr,
);
await viewController.create(size: const Size(200.0, 300.0));
await viewController.dispose();
final AndroidViewController surfaceViewController = PlatformViewsService.initSurfaceAndroidView(
id: 1,
viewType: 'webview',
layoutDirection: TextDirection.ltr,
);
await surfaceViewController.create(size: const Size(200.0, 300.0));
await surfaceViewController.dispose();
expect(
viewsController.views,
unorderedEquals(<FakeAndroidPlatformView>[
const FakeAndroidPlatformView(0, 'webview', Size(100.0, 100.0), AndroidViewController.kAndroidLayoutDirectionLtr),
]),
);
});
test('dispose Android view twice', () async {
viewsController.registerViewType('webview');
final AndroidViewController viewController = PlatformViewsService.initAndroidView(
id: 1,
viewType: 'webview',
layoutDirection: TextDirection.ltr,
);
await viewController.create(size: const Size(200.0, 300.0));
await viewController.dispose();
await viewController.dispose();
});
test('dispose clears focusCallbacks', () async {
bool didFocus = false;
viewsController.registerViewType('webview');
final AndroidViewController viewController = PlatformViewsService.initAndroidView(
id: 0,
viewType: 'webview',
layoutDirection: TextDirection.ltr,
onFocus: () { didFocus = true; },
);
await viewController.create(size: const Size(100.0, 100.0));
await viewController.dispose();
final ByteData message =
SystemChannels.platform_views.codec.encodeMethodCall(const MethodCall('viewFocused', 0));
await binding.defaultBinaryMessenger.handlePlatformMessage(SystemChannels.platform_views.name, message, (_) { });
expect(didFocus, isFalse);
});
test('resize Android view', () async {
viewsController.registerViewType('webview');
await PlatformViewsService.initAndroidView(
id: 0,
viewType: 'webview',
layoutDirection: TextDirection.ltr,
).create(size: const Size(100.0, 100.0));
final AndroidViewController androidView = PlatformViewsService.initAndroidView(
id: 1,
viewType: 'webview',
layoutDirection: TextDirection.ltr,
);
await androidView.create(size: const Size(200.0, 300.0));
await androidView.setSize(const Size(500.0, 500.0));
expect(
viewsController.views,
unorderedEquals(<FakeAndroidPlatformView>[
const FakeAndroidPlatformView(0, 'webview', Size(100.0, 100.0), AndroidViewController.kAndroidLayoutDirectionLtr),
const FakeAndroidPlatformView(1, 'webview', Size(500.0, 500.0), AndroidViewController.kAndroidLayoutDirectionLtr),
]),
);
});
test('OnPlatformViewCreated callback', () async {
viewsController.registerViewType('webview');
final List<int> createdViews = <int>[];
void callback(int id) { createdViews.add(id); }
final AndroidViewController controller1 = PlatformViewsService.initAndroidView(
id: 0,
viewType: 'webview',
layoutDirection: TextDirection.ltr,
)..addOnPlatformViewCreatedListener(callback);
expect(createdViews, isEmpty);
await controller1.create(size: const Size(100.0, 100.0));
expect(createdViews, orderedEquals(<int>[0]));
final AndroidViewController controller2 = PlatformViewsService.initAndroidView(
id: 5,
viewType: 'webview',
layoutDirection: TextDirection.ltr,
)..addOnPlatformViewCreatedListener(callback);
expect(createdViews, orderedEquals(<int>[0]));
await controller2.create(size: const Size(100.0, 200.0));
expect(createdViews, orderedEquals(<int>[0, 5]));
final AndroidViewController controller3 = PlatformViewsService.initAndroidView(
id: 10,
viewType: 'webview',
layoutDirection: TextDirection.ltr,
)..addOnPlatformViewCreatedListener(callback);
expect(createdViews, orderedEquals(<int>[0, 5]));
await Future.wait(<Future<void>>[
controller3.create(size: const Size(100.0, 200.0)),
controller3.dispose(),
]);
expect(createdViews, orderedEquals(<int>[0, 5]));
});
test("change Android view's directionality before creation", () async {
viewsController.registerViewType('webview');
final AndroidViewController viewController = PlatformViewsService.initAndroidView(
id: 0,
viewType: 'webview',
layoutDirection: TextDirection.rtl,
);
await viewController.setLayoutDirection(TextDirection.ltr);
await viewController.create(size: const Size(100.0, 100.0));
expect(
viewsController.views,
unorderedEquals(<FakeAndroidPlatformView>[
const FakeAndroidPlatformView(0, 'webview', Size(100.0, 100.0), AndroidViewController.kAndroidLayoutDirectionLtr),
]),
);
});
test("change Android view's directionality after creation", () async {
viewsController.registerViewType('webview');
final AndroidViewController viewController = PlatformViewsService.initAndroidView(
id: 0,
viewType: 'webview',
layoutDirection: TextDirection.ltr,
);
await viewController.setLayoutDirection(TextDirection.rtl);
await viewController.create(size: const Size(100.0, 100.0));
expect(
viewsController.views,
unorderedEquals(<FakeAndroidPlatformView>[
const FakeAndroidPlatformView(0, 'webview', Size(100.0, 100.0), AndroidViewController.kAndroidLayoutDirectionRtl),
]),
);
});
test("set Android view's offset if view is created", () async {
viewsController.registerViewType('webview');
final AndroidViewController viewController = PlatformViewsService.initAndroidView(
id: 7,
viewType: 'webview',
layoutDirection: TextDirection.ltr,
);
await viewController.create(size: const Size(100.0, 100.0));
await viewController.setOffset(const Offset(10, 20));
expect(
viewsController.offsets,
equals(<int, Offset>{
7: const Offset(10, 20),
}),
);
});
test("doesn't set Android view's offset if view isn't created", () async {
viewsController.registerViewType('webview');
final AndroidViewController viewController = PlatformViewsService.initAndroidView(
id: 7,
viewType: 'webview',
layoutDirection: TextDirection.ltr,
);
await viewController.setOffset(const Offset(10, 20));
expect(viewsController.offsets, equals(<int, Offset>{}));
});
});
group('iOS', () {
late FakeIosPlatformViewsController viewsController;
setUp(() {
viewsController = FakeIosPlatformViewsController();
});
test('create iOS view of unregistered type', () async {
expect(
() {
return PlatformViewsService.initUiKitView(
id: 0,
viewType: 'web',
layoutDirection: TextDirection.ltr,
);
},
throwsA(isA<PlatformException>()),
);
});
test('create iOS views', () async {
viewsController.registerViewType('webview');
await PlatformViewsService.initUiKitView(id: 0, viewType: 'webview', layoutDirection: TextDirection.ltr);
await PlatformViewsService.initUiKitView(id: 1, viewType: 'webview', layoutDirection: TextDirection.rtl);
expect(
viewsController.views,
unorderedEquals(<FakeUiKitView>[
const FakeUiKitView(0, 'webview'),
const FakeUiKitView(1, 'webview'),
]),
);
});
test('reuse iOS view id', () async {
viewsController.registerViewType('webview');
await PlatformViewsService.initUiKitView(
id: 0,
viewType: 'webview',
layoutDirection: TextDirection.ltr,
);
expect(
() => PlatformViewsService.initUiKitView(id: 0, viewType: 'web', layoutDirection: TextDirection.ltr),
throwsA(isA<PlatformException>()),
);
});
test('dispose iOS view', () async {
viewsController.registerViewType('webview');
await PlatformViewsService.initUiKitView(id: 0, viewType: 'webview', layoutDirection: TextDirection.ltr);
final UiKitViewController viewController = await PlatformViewsService.initUiKitView(
id: 1,
viewType: 'webview',
layoutDirection: TextDirection.ltr,
);
viewController.dispose();
expect(
viewsController.views,
unorderedEquals(<FakeUiKitView>[
const FakeUiKitView(0, 'webview'),
]),
);
});
test('dispose inexisting iOS view', () async {
viewsController.registerViewType('webview');
await PlatformViewsService.initUiKitView(id: 0, viewType: 'webview', layoutDirection: TextDirection.ltr);
final UiKitViewController viewController = await PlatformViewsService.initUiKitView(
id: 1,
viewType: 'webview',
layoutDirection: TextDirection.ltr,
);
await viewController.dispose();
expect(
() async {
await viewController.dispose();
},
throwsA(isA<PlatformException>()),
);
});
});
test('toString works as intended', () async {
const AndroidPointerProperties androidPointerProperties = AndroidPointerProperties(id: 0, toolType: 0);
expect(androidPointerProperties.toString(), 'AndroidPointerProperties(id: 0, toolType: 0)');
const double zero = 0.0;
const AndroidPointerCoords androidPointerCoords = AndroidPointerCoords(
orientation: zero,
pressure: zero,
size: zero,
toolMajor: zero,
toolMinor: zero,
touchMajor: zero,
touchMinor: zero,
x: zero,
y: zero
);
expect(androidPointerCoords.toString(), 'AndroidPointerCoords(orientation: $zero, '
'pressure: $zero, '
'size: $zero, '
'toolMajor: $zero, '
'toolMinor: $zero, '
'touchMajor: $zero, '
'touchMinor: $zero, '
'x: $zero, '
'y: $zero)',
);
final AndroidMotionEvent androidMotionEvent = AndroidMotionEvent(
downTime: 0,
eventTime: 0,
action: 0,
pointerCount: 0,
pointerProperties: <AndroidPointerProperties>[],
pointerCoords: <AndroidPointerCoords>[],
metaState: 0,
buttonState: 0,
xPrecision: zero,
yPrecision: zero,
deviceId: 0,
edgeFlags: 0,
source: 0,
flags: 0,
motionEventId: 0
);
expect(androidMotionEvent.toString(), 'AndroidPointerEvent(downTime: 0, '
'eventTime: 0, '
'action: 0, '
'pointerCount: 0, '
'pointerProperties: [], '
'pointerCoords: [], '
'metaState: 0, '
'buttonState: 0, '
'xPrecision: $zero, '
'yPrecision: $zero, '
'deviceId: 0, '
'edgeFlags: 0, '
'source: 0, '
'flags: 0, '
'motionEventId: 0)',
);
});
}
| flutter/packages/flutter/test/services/platform_views_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/services/platform_views_test.dart",
"repo_id": "flutter",
"token_count": 7301
} | 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 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
// We need a separate test file for this test case (instead of including it
// in platform_channel_test.dart) since we rely on the WidgetsFlutterBinding
// not being initialized and we call ensureInitialized() in the other test
// file.
test('throws assertion error iff WidgetsFlutterBinding is not yet initialized', () {
const MethodChannel methodChannel = MethodChannel('mock');
// Ensure that accessing the binary messenger before initialization reports
// a helpful error message.
expect(() => methodChannel.binaryMessenger, throwsA(isA<AssertionError>()
.having((AssertionError e) => e.message, 'message', contains('WidgetsFlutterBinding.ensureInitialized()'))));
TestWidgetsFlutterBinding.ensureInitialized();
expect(() => methodChannel.binaryMessenger, returnsNormally);
});
}
| flutter/packages/flutter/test/services/use_platform_channel_without_initialization_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/services/use_platform_channel_without_initialization_test.dart",
"repo_id": "flutter",
"token_count": 314
} | 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:ui';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart';
void main() {
AppLifecycleListener? listener;
Future<void> setAppLifeCycleState(AppLifecycleState state) async {
final ByteData? message = const StringCodec().encodeMessage(state.toString());
await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.handlePlatformMessage('flutter/lifecycle', message, (_) {});
}
Future<void> sendAppExitRequest() async {
final ByteData message = const JSONMethodCodec().encodeMethodCall(const MethodCall('System.requestAppExit'));
await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.handlePlatformMessage('flutter/platform', message, (_) {});
}
setUp(() async {
WidgetsFlutterBinding.ensureInitialized();
WidgetsBinding.instance
..resetEpoch()
..platformDispatcher.onBeginFrame = null
..platformDispatcher.onDrawFrame = null;
final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.instance;
binding.readTestInitialLifecycleStateFromNativeWindow();
// Reset the state to detached. Going to paused first makes it a valid
// transition from any state, since the intermediate transitions will be
// generated.
await setAppLifeCycleState(AppLifecycleState.paused);
await setAppLifeCycleState(AppLifecycleState.detached);
});
tearDown(() {
listener?.dispose();
listener = null;
final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.instance;
binding.resetInternalState();
binding.platformDispatcher.resetInitialLifecycleState();
assert(TestAppLifecycleListener.registerCount == 0,
'There were ${TestAppLifecycleListener.registerCount} listeners that were not disposed of in tests.');
});
testWidgets('Default Diagnostics', (WidgetTester tester) async {
listener = TestAppLifecycleListener(binding: tester.binding);
expect(listener.toString(),
equalsIgnoringHashCodes('TestAppLifecycleListener#00000(binding: <AutomatedTestWidgetsFlutterBinding>)'));
});
testWidgets('Diagnostics', (WidgetTester tester) async {
Future<AppExitResponse> handleExitRequested() async {
return AppExitResponse.cancel;
}
listener = TestAppLifecycleListener(
binding: WidgetsBinding.instance,
onExitRequested: handleExitRequested,
onStateChange: (AppLifecycleState _) {},
);
expect(
listener.toString(),
equalsIgnoringHashCodes(
'TestAppLifecycleListener#00000(binding: <AutomatedTestWidgetsFlutterBinding>, onStateChange, onExitRequested)'));
});
testWidgets('listens to AppLifecycleState', (WidgetTester tester) async {
final List<AppLifecycleState> states = <AppLifecycleState>[tester.binding.lifecycleState!];
void stateChange(AppLifecycleState state) {
states.add(state);
}
listener = TestAppLifecycleListener(
binding: WidgetsBinding.instance,
onStateChange: stateChange,
);
expect(states, equals(<AppLifecycleState>[AppLifecycleState.detached]));
await setAppLifeCycleState(AppLifecycleState.inactive);
// "resumed" is generated.
expect(states,
equals(<AppLifecycleState>[AppLifecycleState.detached, AppLifecycleState.resumed, AppLifecycleState.inactive]));
await setAppLifeCycleState(AppLifecycleState.resumed);
expect(
states,
equals(<AppLifecycleState>[
AppLifecycleState.detached,
AppLifecycleState.resumed,
AppLifecycleState.inactive,
AppLifecycleState.resumed
]));
});
testWidgets('Triggers correct state transition callbacks', (WidgetTester tester) async {
final List<String> transitions = <String>[];
listener = TestAppLifecycleListener(
binding: WidgetsBinding.instance,
onDetach: () => transitions.add('detach'),
onHide: () => transitions.add('hide'),
onInactive: () => transitions.add('inactive'),
onPause: () => transitions.add('pause'),
onRestart: () => transitions.add('restart'),
onResume: () => transitions.add('resume'),
onShow: () => transitions.add('show'),
);
// Try "standard" sequence
await setAppLifeCycleState(AppLifecycleState.resumed);
expect(transitions, equals(<String>['resume']));
await setAppLifeCycleState(AppLifecycleState.inactive);
expect(transitions, equals(<String>['resume', 'inactive']));
await setAppLifeCycleState(AppLifecycleState.hidden);
expect(transitions, equals(<String>['resume', 'inactive', 'hide']));
await setAppLifeCycleState(AppLifecycleState.paused);
expect(transitions, equals(<String>['resume', 'inactive', 'hide', 'pause']));
// Go back to resume
transitions.clear();
await setAppLifeCycleState(AppLifecycleState.hidden);
expect(transitions, equals(<String>['restart']));
await setAppLifeCycleState(AppLifecycleState.inactive);
expect(transitions, equals(<String>['restart', 'show']));
await setAppLifeCycleState(AppLifecycleState.resumed);
expect(transitions, equals(<String>['restart', 'show', 'resume']));
// Generates intermediate states from lower to higher lifecycle states.
transitions.clear();
await setAppLifeCycleState(AppLifecycleState.paused);
expect(transitions, equals(<String>['inactive', 'hide', 'pause']));
// Wraps around from pause to detach.
await setAppLifeCycleState(AppLifecycleState.detached);
expect(transitions, equals(<String>['inactive', 'hide', 'pause', 'detach']));
await setAppLifeCycleState(AppLifecycleState.resumed);
expect(transitions, equals(<String>['inactive', 'hide', 'pause', 'detach', 'resume']));
await setAppLifeCycleState(AppLifecycleState.paused);
expect(transitions, equals(<String>['inactive', 'hide', 'pause', 'detach', 'resume', 'inactive', 'hide', 'pause']));
// Generates intermediate states from higher to lower lifecycle states.
transitions.clear();
await setAppLifeCycleState(AppLifecycleState.resumed);
expect(transitions, equals(<String>['restart', 'show', 'resume']));
// Go to detached
transitions.clear();
await setAppLifeCycleState(AppLifecycleState.detached);
expect(transitions, equals(<String>['inactive', 'hide', 'pause', 'detach']));
});
testWidgets('Receives exit requests', (WidgetTester tester) async {
bool exitRequested = false;
Future<AppExitResponse> handleExitRequested() async {
exitRequested = true;
return AppExitResponse.cancel;
}
listener = TestAppLifecycleListener(
binding: WidgetsBinding.instance,
onExitRequested: handleExitRequested,
);
await sendAppExitRequest();
expect(exitRequested, isTrue);
});
test('AppLifecycleListener dispatches memory events', () async {
await expectLater(
await memoryEvents(
() => AppLifecycleListener(binding: WidgetsBinding.instance).dispose(),
AppLifecycleListener,
),
areCreateAndDispose,
);
});
}
class TestAppLifecycleListener extends AppLifecycleListener {
TestAppLifecycleListener({
super.binding,
super.onResume,
super.onInactive,
super.onHide,
super.onShow,
super.onPause,
super.onRestart,
super.onDetach,
super.onExitRequested,
super.onStateChange,
}) {
registerCount += 1;
}
static int registerCount = 0;
@override
void dispose() {
super.dispose();
registerCount -= 1;
}
}
| flutter/packages/flutter/test/widgets/app_lifecycle_listener_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/app_lifecycle_listener_test.dart",
"repo_id": "flutter",
"token_count": 2749
} | 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 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('Can only schedule frames after widget binding attaches the root widget', () async {
final WidgetsFlutterBindingWithTestBinaryMessenger binding = WidgetsFlutterBindingWithTestBinaryMessenger();
expect(SchedulerBinding.instance.framesEnabled, isFalse);
expect(SchedulerBinding.instance.hasScheduledFrame, isFalse);
// Sends a message to notify that the engine is ready to accept frames.
final ByteData message = const StringCodec().encodeMessage('AppLifecycleState.resumed')!;
await binding.defaultBinaryMessenger.handlePlatformMessage('flutter/lifecycle', message, (_) { });
// Enables the semantics should not schedule any frames if the root widget
// has not been attached.
expect(binding.semanticsEnabled, isFalse);
binding.ensureSemantics();
expect(binding.semanticsEnabled, isTrue);
expect(SchedulerBinding.instance.framesEnabled, isFalse);
expect(SchedulerBinding.instance.hasScheduledFrame, isFalse);
// The widget binding should be ready to produce frames after it attaches
// the root widget.
binding.attachRootWidget(const Placeholder());
expect(SchedulerBinding.instance.framesEnabled, isTrue);
expect(SchedulerBinding.instance.hasScheduledFrame, isTrue);
});
}
class WidgetsFlutterBindingWithTestBinaryMessenger extends WidgetsFlutterBinding with TestDefaultBinaryMessengerBinding { }
| flutter/packages/flutter/test/widgets/binding_cannot_schedule_frame_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/binding_cannot_schedule_frame_test.dart",
"repo_id": "flutter",
"token_count": 513
} | 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.
// This file is run as part of a reduced test set in CI on Mac and Windows
// machines.
@Tags(<String>['reduced-test-set'])
@TestOn('!chrome')
library;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import '../impeller_test_helpers.dart';
void main() {
testWidgets('Color filter - red', (WidgetTester tester) async {
await tester.pumpWidget(
const RepaintBoundary(
child: ColorFiltered(
colorFilter: ColorFilter.mode(Colors.red, BlendMode.color),
child: Placeholder(),
),
),
);
await expectLater(
find.byType(ColorFiltered),
matchesGoldenFile('color_filter_red.png'),
);
});
testWidgets('Color filter - sepia', (WidgetTester tester) async {
const ColorFilter sepia = ColorFilter.matrix(<double>[
0.39, 0.769, 0.189, 0, 0, //
0.349, 0.686, 0.168, 0, 0, //
0.272, 0.534, 0.131, 0, 0, //
0, 0, 0, 1, 0, //
]);
await tester.pumpWidget(
RepaintBoundary(
child: ColorFiltered(
colorFilter: sepia,
child: MaterialApp(
debugShowCheckedModeBanner: false, // https://github.com/flutter/flutter/issues/143616
title: 'Flutter Demo',
theme: ThemeData(primarySwatch: Colors.blue, useMaterial3: false),
home: Scaffold(
appBar: AppBar(
title: const Text('Sepia ColorFilter Test'),
),
body: const Center(
child:Text('Hooray!'),
),
floatingActionButton: FloatingActionButton(
onPressed: () { },
tooltip: 'Increment',
child: const Icon(Icons.add),
),
),
),
),
),
);
await expectLater(
find.byType(ColorFiltered),
matchesGoldenFile('color_filter_sepia.png'),
);
}, skip: impellerEnabled); // https://github.com/flutter/flutter/issues/143616
testWidgets('Color filter - reuses its layer', (WidgetTester tester) async {
Future<void> pumpWithColor(Color color) async {
await tester.pumpWidget(
RepaintBoundary(
child: ColorFiltered(
colorFilter: ColorFilter.mode(color, BlendMode.color),
child: const Placeholder(),
),
),
);
}
await pumpWithColor(Colors.red);
final RenderObject renderObject = tester.firstRenderObject(find.byType(ColorFiltered));
final ColorFilterLayer originalLayer = renderObject.debugLayer! as ColorFilterLayer;
expect(originalLayer, isNotNull);
// Change color to force a repaint.
await pumpWithColor(Colors.green);
expect(renderObject.debugLayer, same(originalLayer));
});
}
| flutter/packages/flutter/test/widgets/color_filter_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/color_filter_test.dart",
"repo_id": "flutter",
"token_count": 1291
} | 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 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Text widget parameter takes precedence over DefaultTextHeightBehavior', (WidgetTester tester) async {
const TextHeightBehavior behavior1 = TextHeightBehavior(
applyHeightToLastDescent: false,
applyHeightToFirstAscent: false,
);
const TextHeightBehavior behavior2 = TextHeightBehavior(
applyHeightToFirstAscent: false,
);
await tester.pumpWidget(
const DefaultTextHeightBehavior(
textHeightBehavior: behavior2,
child: Text(
'Hello',
textDirection: TextDirection.ltr,
textHeightBehavior: behavior1,
),
),
);
final RichText text = tester.firstWidget(find.byType(RichText));
expect(text, isNotNull);
expect(text.textHeightBehavior, behavior1);
});
testWidgets('DefaultTextStyle.textHeightBehavior takes precedence over DefaultTextHeightBehavior ', (WidgetTester tester) async {
const TextHeightBehavior behavior1 = TextHeightBehavior(
applyHeightToLastDescent: false,
applyHeightToFirstAscent: false,
);
const TextHeightBehavior behavior2 = TextHeightBehavior(
applyHeightToFirstAscent: false,
);
await tester.pumpWidget(
const DefaultTextStyle(
style: TextStyle(),
textHeightBehavior: behavior1,
child: DefaultTextHeightBehavior(
textHeightBehavior: behavior2,
child: Text(
'Hello',
textDirection: TextDirection.ltr,
),
),
),
);
RichText text = tester.firstWidget(find.byType(RichText));
expect(text, isNotNull);
expect(text.textHeightBehavior, behavior1);
await tester.pumpWidget(
const DefaultTextHeightBehavior(
textHeightBehavior: behavior2,
child: DefaultTextStyle(
style: TextStyle(),
textHeightBehavior: behavior1,
child: Text(
'Hello',
textDirection: TextDirection.ltr,
),
),
),
);
text = tester.firstWidget(find.byType(RichText));
expect(text, isNotNull);
expect(text.textHeightBehavior, behavior1);
});
testWidgets('DefaultTextHeightBehavior changes propagate to Text', (WidgetTester tester) async {
const Text textWidget = Text('Hello', textDirection: TextDirection.ltr);
const TextHeightBehavior behavior1 = TextHeightBehavior(
applyHeightToLastDescent: false,
applyHeightToFirstAscent: false,
);
const TextHeightBehavior behavior2 = TextHeightBehavior(
applyHeightToLastDescent: false,
applyHeightToFirstAscent: false,
);
await tester.pumpWidget(const DefaultTextHeightBehavior(
textHeightBehavior: behavior1,
child: textWidget,
));
RichText text = tester.firstWidget(find.byType(RichText));
expect(text, isNotNull);
expect(text.textHeightBehavior, behavior1);
await tester.pumpWidget(const DefaultTextHeightBehavior(
textHeightBehavior: behavior2,
child: textWidget,
));
text = tester.firstWidget(find.byType(RichText));
expect(text, isNotNull);
expect(text.textHeightBehavior, behavior2);
});
testWidgets(
'DefaultTextHeightBehavior.of(context) returns null if no '
'DefaultTextHeightBehavior widget in tree',
(WidgetTester tester) async {
const Text textWidget = Text('Hello', textDirection: TextDirection.ltr);
TextHeightBehavior? textHeightBehavior;
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
textHeightBehavior = DefaultTextHeightBehavior.maybeOf(context);
return textWidget;
},
));
expect(textHeightBehavior, isNull);
final RichText text = tester.firstWidget(find.byType(RichText));
expect(text, isNotNull);
expect(text.textHeightBehavior, isNull);
},
);
}
| flutter/packages/flutter/test/widgets/default_text_height_behavior_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/default_text_height_behavior_test.dart",
"repo_id": "flutter",
"token_count": 1562
} | 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/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
/// On web, the context menu (aka toolbar) is provided by the browser.
const bool isContextMenuProvidedByPlatform = isBrowser;
// Returns the RenderEditable at the given index, or the first if not given.
RenderEditable findRenderEditable(WidgetTester tester, {int index = 0}) {
final RenderObject root = tester.renderObject(find.byType(EditableText).at(index));
expect(root, isNotNull);
late RenderEditable renderEditable;
void recursiveFinder(RenderObject child) {
if (child is RenderEditable) {
renderEditable = child;
return;
}
child.visitChildren(recursiveFinder);
}
root.visitChildren(recursiveFinder);
expect(renderEditable, isNotNull);
return renderEditable;
}
List<TextSelectionPoint> globalize(Iterable<TextSelectionPoint> points, RenderBox box) {
return points.map<TextSelectionPoint>((TextSelectionPoint point) {
return TextSelectionPoint(
box.localToGlobal(point.point),
point.direction,
);
}).toList();
}
Offset textOffsetToPosition(WidgetTester tester, int offset, {int index = 0}) {
final RenderEditable renderEditable = findRenderEditable(tester, index: index);
final List<TextSelectionPoint> endpoints = globalize(
renderEditable.getEndpointsForSelection(
TextSelection.collapsed(offset: offset),
),
renderEditable,
);
expect(endpoints.length, 1);
return endpoints[0].point + const Offset(kIsWeb? 1.0 : 0.0, -2.0);
}
/// Mimic key press events by sending key down and key up events via the [tester].
Future<void> sendKeys(
WidgetTester tester,
List<LogicalKeyboardKey> keys, {
bool shift = false,
bool wordModifier = false,
bool lineModifier = false,
bool shortcutModifier = false,
required TargetPlatform targetPlatform,
}) async {
final String targetPlatformString = targetPlatform.toString();
final String platform = targetPlatformString.substring(targetPlatformString.indexOf('.') + 1).toLowerCase();
if (shift) {
await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft, platform: platform);
}
if (shortcutModifier) {
await tester.sendKeyDownEvent(
platform == 'macos' || platform == 'ios' ? LogicalKeyboardKey.metaLeft : LogicalKeyboardKey.controlLeft,
platform: platform,
);
}
if (wordModifier) {
await tester.sendKeyDownEvent(
platform == 'macos' || platform == 'ios' ? LogicalKeyboardKey.altLeft : LogicalKeyboardKey.controlLeft,
platform: platform,
);
}
if (lineModifier) {
await tester.sendKeyDownEvent(
platform == 'macos' || platform == 'ios' ? LogicalKeyboardKey.metaLeft : LogicalKeyboardKey.altLeft,
platform: platform,
);
}
for (final LogicalKeyboardKey key in keys) {
await tester.sendKeyEvent(key, platform: platform);
await tester.pump();
}
if (lineModifier) {
await tester.sendKeyUpEvent(
platform == 'macos' || platform == 'ios' ? LogicalKeyboardKey.metaLeft : LogicalKeyboardKey.altLeft,
platform: platform,
);
}
if (wordModifier) {
await tester.sendKeyUpEvent(
platform == 'macos' || platform == 'ios' ? LogicalKeyboardKey.altLeft : LogicalKeyboardKey.controlLeft,
platform: platform,
);
}
if (shortcutModifier) {
await tester.sendKeyUpEvent(
platform == 'macos' || platform == 'ios' ? LogicalKeyboardKey.metaLeft : LogicalKeyboardKey.controlLeft,
platform: platform,
);
}
if (shift) {
await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft, platform: platform);
}
if (shift || wordModifier || lineModifier) {
await tester.pump();
}
}
// Simple controller that builds a WidgetSpan with 100 height.
class OverflowWidgetTextEditingController extends TextEditingController {
@override
TextSpan buildTextSpan({
required BuildContext context,
TextStyle? style,
required bool withComposing,
}) {
return TextSpan(
style: style,
children: <InlineSpan>[
const TextSpan(text: 'Hi'),
WidgetSpan(
child: Container(
color: Colors.redAccent,
height: 100.0,
),
),
],
);
}
}
| flutter/packages/flutter/test/widgets/editable_text_utils.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/editable_text_utils.dart",
"repo_id": "flutter",
"token_count": 1600
} | 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/gestures.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
const Offset forcePressOffset = Offset(400.0, 50.0);
testWidgets('Uncontested scrolls start immediately', (WidgetTester tester) async {
bool didStartDrag = false;
double? updatedDragDelta;
bool didEndDrag = false;
final Widget widget = GestureDetector(
onVerticalDragStart: (DragStartDetails details) {
didStartDrag = true;
},
onVerticalDragUpdate: (DragUpdateDetails details) {
updatedDragDelta = details.primaryDelta;
},
onVerticalDragEnd: (DragEndDetails details) {
didEndDrag = true;
},
child: Container(
color: const Color(0xFF00FF00),
),
);
await tester.pumpWidget(widget);
expect(didStartDrag, isFalse);
expect(updatedDragDelta, isNull);
expect(didEndDrag, isFalse);
const Offset firstLocation = Offset(10.0, 10.0);
final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7);
expect(didStartDrag, isTrue);
didStartDrag = false;
expect(updatedDragDelta, isNull);
expect(didEndDrag, isFalse);
const Offset secondLocation = Offset(10.0, 9.0);
await gesture.moveTo(secondLocation);
expect(didStartDrag, isFalse);
expect(updatedDragDelta, -1.0);
updatedDragDelta = null;
expect(didEndDrag, isFalse);
await gesture.up();
expect(didStartDrag, isFalse);
expect(updatedDragDelta, isNull);
expect(didEndDrag, isTrue);
didEndDrag = false;
await tester.pumpWidget(Container());
});
testWidgets('Match two scroll gestures in succession', (WidgetTester tester) async {
int gestureCount = 0;
double dragDistance = 0.0;
const Offset downLocation = Offset(10.0, 10.0);
const Offset upLocation = Offset(10.0, 50.0); // must be far enough to be more than kTouchSlop
final Widget widget = GestureDetector(
dragStartBehavior: DragStartBehavior.down,
onVerticalDragUpdate: (DragUpdateDetails details) { dragDistance += details.primaryDelta ?? 0; },
onVerticalDragEnd: (DragEndDetails details) { gestureCount += 1; },
onHorizontalDragUpdate: (DragUpdateDetails details) { fail('gesture should not match'); },
onHorizontalDragEnd: (DragEndDetails details) { fail('gesture should not match'); },
child: Container(
color: const Color(0xFF00FF00),
),
);
await tester.pumpWidget(widget);
TestGesture gesture = await tester.startGesture(downLocation, pointer: 7);
await gesture.moveTo(upLocation);
await gesture.up();
gesture = await tester.startGesture(downLocation, pointer: 7);
await gesture.moveTo(upLocation);
await gesture.up();
expect(gestureCount, 2);
expect(dragDistance, 40.0 * 2.0); // delta between down and up, twice
await tester.pumpWidget(Container());
});
testWidgets("Pan doesn't crash", (WidgetTester tester) async {
bool didStartPan = false;
Offset? panDelta;
bool didEndPan = false;
await tester.pumpWidget(
GestureDetector(
onPanStart: (DragStartDetails details) {
didStartPan = true;
},
onPanUpdate: (DragUpdateDetails details) {
panDelta = (panDelta ?? Offset.zero) + details.delta;
},
onPanEnd: (DragEndDetails details) {
didEndPan = true;
},
child: Container(
color: const Color(0xFF00FF00),
),
),
);
expect(didStartPan, isFalse);
expect(panDelta, isNull);
expect(didEndPan, isFalse);
await tester.dragFrom(const Offset(10.0, 10.0), const Offset(20.0, 30.0));
expect(didStartPan, isTrue);
expect(panDelta!.dx, 20.0);
expect(panDelta!.dy, 30.0);
expect(didEndPan, isTrue);
});
testWidgets('DragEndDetails returns the last known position', (WidgetTester tester) async {
Offset updateOffset = const Offset(10.0, 10.0);
const EdgeInsets paddingOffset = EdgeInsets.all(10.0);
Offset? endOffset;
Offset? globalEndOffset;
await tester.pumpWidget(
Padding(
padding: paddingOffset,
child: GestureDetector(
onPanStart: (DragStartDetails details) {
},
onPanUpdate: (DragUpdateDetails details) {
updateOffset += details.delta;
},
onPanEnd: (DragEndDetails details) {
endOffset = details.localPosition;
globalEndOffset = details.globalPosition;
},
child: Container(
color: const Color(0xFF00FF00),
),
),
),
);
await tester.dragFrom(const Offset(20.0, 20.0), const Offset(30.0, 40.0));
expect(endOffset, isNotNull);
expect(updateOffset, endOffset);
// Make sure details.globalPosition works correctly.
expect(Offset(endOffset!.dx + paddingOffset.left, endOffset!.dy + paddingOffset.top), globalEndOffset);
});
group('Tap', () {
final ButtonVariant buttonVariant = ButtonVariant(
values: <int>[kPrimaryButton, kSecondaryButton, kTertiaryButton],
descriptions: <int, String>{
kPrimaryButton: 'primary',
kSecondaryButton: 'secondary',
kTertiaryButton: 'tertiary',
},
);
testWidgets('Translucent', (WidgetTester tester) async {
bool didReceivePointerDown;
bool didTap;
Future<void> pumpWidgetTree(HitTestBehavior? behavior) {
return tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Stack(
children: <Widget>[
Listener(
onPointerDown: (_) {
didReceivePointerDown = true;
},
child: Container(
width: 100.0,
height: 100.0,
color: const Color(0xFF00FF00),
),
),
SizedBox(
width: 100.0,
height: 100.0,
child: GestureDetector(
onTap: ButtonVariant.button == kPrimaryButton ? () {
didTap = true;
} : null,
onSecondaryTap: ButtonVariant.button == kSecondaryButton ? () {
didTap = true;
} : null,
onTertiaryTapDown: ButtonVariant.button == kTertiaryButton ? (_) {
didTap = true;
} : null,
behavior: behavior,
),
),
],
),
),
);
}
didReceivePointerDown = false;
didTap = false;
await pumpWidgetTree(null);
await tester.tapAt(const Offset(10.0, 10.0), buttons: ButtonVariant.button);
expect(didReceivePointerDown, isTrue);
expect(didTap, isTrue);
didReceivePointerDown = false;
didTap = false;
await pumpWidgetTree(HitTestBehavior.deferToChild);
await tester.tapAt(const Offset(10.0, 10.0), buttons: ButtonVariant.button);
expect(didReceivePointerDown, isTrue);
expect(didTap, isFalse);
didReceivePointerDown = false;
didTap = false;
await pumpWidgetTree(HitTestBehavior.opaque);
await tester.tapAt(const Offset(10.0, 10.0), buttons: ButtonVariant.button);
expect(didReceivePointerDown, isFalse);
expect(didTap, isTrue);
didReceivePointerDown = false;
didTap = false;
await pumpWidgetTree(HitTestBehavior.translucent);
await tester.tapAt(const Offset(10.0, 10.0), buttons: ButtonVariant.button);
expect(didReceivePointerDown, isTrue);
expect(didTap, isTrue);
}, variant: buttonVariant);
testWidgets('Empty', (WidgetTester tester) async {
bool didTap = false;
await tester.pumpWidget(
Center(
child: GestureDetector(
onTap: ButtonVariant.button == kPrimaryButton ? () {
didTap = true;
} : null,
onSecondaryTap: ButtonVariant.button == kSecondaryButton ? () {
didTap = true;
} : null,
onTertiaryTapUp: ButtonVariant.button == kTertiaryButton ? (_) {
didTap = true;
} : null,
),
),
);
expect(didTap, isFalse);
await tester.tapAt(const Offset(10.0, 10.0), buttons: ButtonVariant.button);
expect(didTap, isTrue);
}, variant: buttonVariant);
testWidgets('Only container', (WidgetTester tester) async {
bool didTap = false;
await tester.pumpWidget(
Center(
child: GestureDetector(
onTap: ButtonVariant.button == kPrimaryButton ? () {
didTap = true;
} : null,
onSecondaryTap: ButtonVariant.button == kSecondaryButton ? () {
didTap = true;
} : null,
onTertiaryTapUp: ButtonVariant.button == kTertiaryButton ? (_) {
didTap = true;
} : null,
child: Container(),
),
),
);
expect(didTap, isFalse);
await tester.tapAt(const Offset(10.0, 10.0));
expect(didTap, isFalse);
}, variant: buttonVariant);
testWidgets('cache render object', (WidgetTester tester) async {
void inputCallback() { }
await tester.pumpWidget(
Center(
child: GestureDetector(
onTap: ButtonVariant.button == kPrimaryButton ? inputCallback : null,
onSecondaryTap: ButtonVariant.button == kSecondaryButton ? inputCallback : null,
onTertiaryTapUp: ButtonVariant.button == kTertiaryButton ? (_) => inputCallback() : null,
child: Container(),
),
),
);
final RenderSemanticsGestureHandler renderObj1 = tester.renderObject(find.byType(GestureDetector));
await tester.pumpWidget(
Center(
child: GestureDetector(
onTap: ButtonVariant.button == kPrimaryButton ? inputCallback : null,
onSecondaryTap: ButtonVariant.button == kSecondaryButton ? inputCallback : null,
onTertiaryTapUp: ButtonVariant.button == kTertiaryButton ? (_) => inputCallback() : null,
child: Container(),
),
),
);
final RenderSemanticsGestureHandler renderObj2 = tester.renderObject(find.byType(GestureDetector));
expect(renderObj1, same(renderObj2));
}, variant: buttonVariant);
testWidgets('Tap down occurs after kPressTimeout', (WidgetTester tester) async {
int tapDown = 0;
int tap = 0;
int tapCancel = 0;
int longPress = 0;
await tester.pumpWidget(
Container(
alignment: Alignment.topLeft,
child: Container(
alignment: Alignment.center,
height: 100.0,
color: const Color(0xFF00FF00),
child: RawGestureDetector(
behavior: HitTestBehavior.translucent,
// Adding long press callbacks here will cause the on*TapDown callbacks to be executed only after
// kPressTimeout has passed. Without the long press callbacks, there would be no press pointers
// competing in the arena. Hence, we add them to the arena to test this behavior.
//
// We use a raw gesture detector directly here because gesture detector does
// not expose callbacks for the tertiary variant of long presses, i.e. no onTertiaryLongPress*
// callbacks are exposed in GestureDetector.
//
// The primary and secondary long press callbacks could also be put into the gesture detector below,
// however, it is clearer when they are all in one place.
gestures: <Type, GestureRecognizerFactory>{
LongPressGestureRecognizer: GestureRecognizerFactoryWithHandlers<LongPressGestureRecognizer>(
() => LongPressGestureRecognizer(),
(LongPressGestureRecognizer instance) {
instance
..onLongPress = ButtonVariant.button == kPrimaryButton ? () {
longPress += 1;
} : null
..onSecondaryLongPress = ButtonVariant.button == kSecondaryButton ? () {
longPress += 1;
} : null
..onTertiaryLongPress = ButtonVariant.button == kTertiaryButton ? () {
longPress += 1;
} : null;
},
),
},
child: GestureDetector(
onTapDown: ButtonVariant.button == kPrimaryButton ? (TapDownDetails details) {
tapDown += 1;
} : null,
onSecondaryTapDown: ButtonVariant.button == kSecondaryButton ? (TapDownDetails details) {
tapDown += 1;
} : null,
onTertiaryTapDown: ButtonVariant.button == kTertiaryButton ? (TapDownDetails details) {
tapDown += 1;
} : null,
onTap: ButtonVariant.button == kPrimaryButton ? () {
tap += 1;
} : null,
onSecondaryTap: ButtonVariant.button == kSecondaryButton ? () {
tap += 1;
} : null,
onTertiaryTapUp: ButtonVariant.button == kTertiaryButton ? (TapUpDetails details) {
tap += 1;
} : null,
onTapCancel: ButtonVariant.button == kPrimaryButton ? () {
tapCancel += 1;
} : null,
onSecondaryTapCancel: ButtonVariant.button == kSecondaryButton ? () {
tapCancel += 1;
} : null,
onTertiaryTapCancel: ButtonVariant.button == kTertiaryButton ? () {
tapCancel += 1;
} : null,
),
),
),
),
);
// Pointer is dragged from the center of the 800x100 gesture detector
// to a point (400,300) below it. This should never call onTap.
Future<void> dragOut(Duration timeout) async {
final TestGesture gesture =
await tester.startGesture(const Offset(400.0, 50.0), buttons: ButtonVariant.button);
// If the timeout is less than kPressTimeout the recognizer will not
// trigger any callbacks. If the timeout is greater than kLongPressTimeout
// then onTapDown, onLongPress, and onCancel will be called.
await tester.pump(timeout);
await gesture.moveTo(const Offset(400.0, 300.0));
await gesture.up();
}
await dragOut(kPressTimeout * 0.5); // generates nothing
expect(tapDown, 0);
expect(tapCancel, 0);
expect(tap, 0);
expect(longPress, 0);
await dragOut(kPressTimeout); // generates tapDown, tapCancel
expect(tapDown, 1);
expect(tapCancel, 1);
expect(tap, 0);
expect(longPress, 0);
await dragOut(kLongPressTimeout); // generates tapDown, longPress, tapCancel
expect(tapDown, 2);
expect(tapCancel, 2);
expect(tap, 0);
expect(longPress, 1);
}, variant: buttonVariant);
testWidgets('Long Press Up Callback called after long press', (WidgetTester tester) async {
int longPressUp = 0;
await tester.pumpWidget(
Container(
alignment: Alignment.topLeft,
child: Container(
alignment: Alignment.center,
height: 100.0,
color: const Color(0xFF00FF00),
child: RawGestureDetector(
// We use a raw gesture detector directly here because gesture detector does
// not expose callbacks for the tertiary variant of long presses, i.e. no onTertiaryLongPress*
// callbacks are exposed in GestureDetector, and we want to test all three variants.
//
// The primary and secondary long press callbacks could also be put into the gesture detector below,
// however, it is more convenient to have them all in one place.
gestures: <Type, GestureRecognizerFactory>{
LongPressGestureRecognizer: GestureRecognizerFactoryWithHandlers<LongPressGestureRecognizer>(
() => LongPressGestureRecognizer(),
(LongPressGestureRecognizer instance) {
instance
..onLongPressUp = ButtonVariant.button == kPrimaryButton ? () {
longPressUp += 1;
} : null
..onSecondaryLongPressUp = ButtonVariant.button == kSecondaryButton ? () {
longPressUp += 1;
} : null
..onTertiaryLongPressUp = ButtonVariant.button == kTertiaryButton ? () {
longPressUp += 1;
} : null;
},
),
},
),
),
),
);
Future<void> longPress(Duration timeout) async {
final TestGesture gesture = await tester.startGesture(const Offset(400.0, 50.0), buttons: ButtonVariant.button);
await tester.pump(timeout);
await gesture.up();
}
await longPress(kLongPressTimeout + const Duration(seconds: 1)); // To make sure the time for long press has occurred
expect(longPressUp, 1);
}, variant: buttonVariant);
});
testWidgets('Primary and secondary long press callbacks should work together in GestureDetector', (WidgetTester tester) async {
bool primaryLongPress = false, secondaryLongPress = false;
await tester.pumpWidget(
Container(
alignment: Alignment.topLeft,
child: Container(
alignment: Alignment.center,
height: 100.0,
color: const Color(0xFF00FF00),
child: GestureDetector(
onLongPress: () {
primaryLongPress = true;
},
onSecondaryLongPress: () {
secondaryLongPress = true;
},
),
),
),
);
Future<void> longPress(Duration timeout, int buttons) async {
final TestGesture gesture = await tester.startGesture(const Offset(400.0, 50.0), buttons: buttons);
await tester.pump(timeout);
await gesture.up();
}
// Adding a second to make sure the time for long press has occurred.
await longPress(kLongPressTimeout + const Duration(seconds: 1), kPrimaryButton);
expect(primaryLongPress, isTrue);
await longPress(kLongPressTimeout + const Duration(seconds: 1), kSecondaryButton);
expect(secondaryLongPress, isTrue);
});
testWidgets('Force Press Callback called after force press', (WidgetTester tester) async {
int forcePressStart = 0;
int forcePressPeaked = 0;
int forcePressUpdate = 0;
int forcePressEnded = 0;
await tester.pumpWidget(
Container(
alignment: Alignment.topLeft,
child: Container(
alignment: Alignment.center,
height: 100.0,
color: const Color(0xFF00FF00),
child: GestureDetector(
onForcePressStart: (_) => forcePressStart += 1,
onForcePressEnd: (_) => forcePressEnded += 1,
onForcePressPeak: (_) => forcePressPeaked += 1,
onForcePressUpdate: (_) => forcePressUpdate += 1,
),
),
),
);
final int pointerValue = tester.nextPointer;
final TestGesture gesture = await tester.createGesture();
await gesture.downWithCustomEvent(
forcePressOffset,
PointerDownEvent(
pointer: pointerValue,
position: forcePressOffset,
pressure: 0.0,
pressureMax: 6.0,
pressureMin: 0.0,
),
);
await gesture.updateWithCustomEvent(PointerMoveEvent(
pointer: pointerValue,
pressure: 0.3,
pressureMin: 0,
));
expect(forcePressStart, 0);
expect(forcePressPeaked, 0);
expect(forcePressUpdate, 0);
expect(forcePressEnded, 0);
await gesture.updateWithCustomEvent(PointerMoveEvent(
pointer: pointerValue,
pressure: 0.5,
pressureMin: 0,
));
expect(forcePressStart, 1);
expect(forcePressPeaked, 0);
expect(forcePressUpdate, 1);
expect(forcePressEnded, 0);
await gesture.updateWithCustomEvent(PointerMoveEvent(
pointer: pointerValue,
pressure: 0.6,
pressureMin: 0,
));
await gesture.updateWithCustomEvent(PointerMoveEvent(
pointer: pointerValue,
pressure: 0.7,
pressureMin: 0,
));
await gesture.updateWithCustomEvent(PointerMoveEvent(
pointer: pointerValue,
pressure: 0.2,
pressureMin: 0,
));
await gesture.updateWithCustomEvent(PointerMoveEvent(
pointer: pointerValue,
pressure: 0.3,
pressureMin: 0,
));
expect(forcePressStart, 1);
expect(forcePressPeaked, 0);
expect(forcePressUpdate, 5);
expect(forcePressEnded, 0);
await gesture.updateWithCustomEvent(PointerMoveEvent(
pointer: pointerValue,
pressure: 0.9,
pressureMin: 0,
));
expect(forcePressStart, 1);
expect(forcePressPeaked, 1);
expect(forcePressUpdate, 6);
expect(forcePressEnded, 0);
await gesture.up();
expect(forcePressStart, 1);
expect(forcePressPeaked, 1);
expect(forcePressUpdate, 6);
expect(forcePressEnded, 1);
});
testWidgets('Force Press Callback not called if long press triggered before force press', (WidgetTester tester) async {
int forcePressStart = 0;
int longPressTimes = 0;
await tester.pumpWidget(
Container(
alignment: Alignment.topLeft,
child: Container(
alignment: Alignment.center,
height: 100.0,
color: const Color(0xFF00FF00),
child: GestureDetector(
onForcePressStart: (_) => forcePressStart += 1,
onLongPress: () => longPressTimes += 1,
),
),
),
);
final int pointerValue = tester.nextPointer;
const double maxPressure = 6.0;
final TestGesture gesture = await tester.createGesture();
await gesture.downWithCustomEvent(
forcePressOffset,
PointerDownEvent(
pointer: pointerValue,
position: forcePressOffset,
pressure: 0.0,
pressureMax: maxPressure,
pressureMin: 0.0,
),
);
await gesture.updateWithCustomEvent(PointerMoveEvent(
pointer: pointerValue,
position: const Offset(400.0, 50.0),
pressure: 0.3,
pressureMin: 0,
pressureMax: maxPressure,
));
expect(forcePressStart, 0);
expect(longPressTimes, 0);
// Trigger the long press.
await tester.pump(kLongPressTimeout + const Duration(seconds: 1));
expect(longPressTimes, 1);
expect(forcePressStart, 0);
// Failed attempt to trigger the force press.
await gesture.updateWithCustomEvent(PointerMoveEvent(
pointer: pointerValue,
position: const Offset(400.0, 50.0),
pressure: 0.5,
pressureMin: 0,
pressureMax: maxPressure,
));
expect(longPressTimes, 1);
expect(forcePressStart, 0);
});
testWidgets('Force Press Callback not called if drag triggered before force press', (WidgetTester tester) async {
int forcePressStart = 0;
int horizontalDragStart = 0;
await tester.pumpWidget(
Container(
alignment: Alignment.topLeft,
child: Container(
alignment: Alignment.center,
height: 100.0,
color: const Color(0xFF00FF00),
child: GestureDetector(
onForcePressStart: (_) => forcePressStart += 1,
onHorizontalDragStart: (_) => horizontalDragStart += 1,
),
),
),
);
final int pointerValue = tester.nextPointer;
final TestGesture gesture = await tester.createGesture();
await gesture.downWithCustomEvent(
forcePressOffset,
PointerDownEvent(
pointer: pointerValue,
position: forcePressOffset,
pressure: 0.0,
pressureMax: 6.0,
pressureMin: 0.0,
),
);
await gesture.updateWithCustomEvent(PointerMoveEvent(
pointer: pointerValue,
pressure: 0.3,
pressureMin: 0,
));
expect(forcePressStart, 0);
expect(horizontalDragStart, 0);
// Trigger horizontal drag.
await gesture.moveBy(const Offset(100, 0));
expect(horizontalDragStart, 1);
expect(forcePressStart, 0);
// Failed attempt to trigger the force press.
await gesture.updateWithCustomEvent(PointerMoveEvent(
pointer: pointerValue,
pressure: 0.5,
pressureMin: 0,
));
expect(horizontalDragStart, 1);
expect(forcePressStart, 0);
});
group("RawGestureDetectorState's debugFillProperties", () {
testWidgets('when default', (WidgetTester tester) async {
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
final GlobalKey key = GlobalKey();
await tester.pumpWidget(RawGestureDetector(
key: key,
));
key.currentState!.debugFillProperties(builder);
final List<String> description = builder.properties
.where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info))
.map((DiagnosticsNode node) => node.toString())
.toList();
expect(description, <String>[
'gestures: <none>',
]);
});
testWidgets('should show gestures, custom semantics and behavior', (WidgetTester tester) async {
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
final GlobalKey key = GlobalKey();
await tester.pumpWidget(RawGestureDetector(
key: key,
behavior: HitTestBehavior.deferToChild,
gestures: <Type, GestureRecognizerFactory>{
TapGestureRecognizer: GestureRecognizerFactoryWithHandlers<TapGestureRecognizer>(
() => TapGestureRecognizer(),
(TapGestureRecognizer recognizer) {
recognizer.onTap = () {};
},
),
LongPressGestureRecognizer: GestureRecognizerFactoryWithHandlers<LongPressGestureRecognizer>(
() => LongPressGestureRecognizer(),
(LongPressGestureRecognizer recognizer) {
recognizer.onLongPress = () {};
},
),
},
semantics: _EmptySemanticsGestureDelegate(),
child: Container(),
));
key.currentState!.debugFillProperties(builder);
final List<String> description = builder.properties
.where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info))
.map((DiagnosticsNode node) => node.toString())
.toList();
expect(description, <String>[
'gestures: tap, long press',
'semantics: _EmptySemanticsGestureDelegate()',
'behavior: deferToChild',
]);
});
testWidgets('should not show semantics when excludeFromSemantics is true', (WidgetTester tester) async {
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
final GlobalKey key = GlobalKey();
await tester.pumpWidget(RawGestureDetector(
key: key,
semantics: _EmptySemanticsGestureDelegate(),
excludeFromSemantics: true,
child: Container(),
));
key.currentState!.debugFillProperties(builder);
final List<String> description = builder.properties
.where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info))
.map((DiagnosticsNode node) => node.toString())
.toList();
expect(description, <String>[
'gestures: <none>',
'excludeFromSemantics: true',
]);
});
group('error control test', () {
test('constructor redundant pan and scale', () {
late FlutterError error;
try {
GestureDetector(onScaleStart: (_) {}, onPanStart: (_) {});
} on FlutterError catch (e) {
error = e;
} finally {
expect(
error.toStringDeep(),
'FlutterError\n'
' Incorrect GestureDetector arguments.\n'
' Having both a pan gesture recognizer and a scale gesture\n'
' recognizer is redundant; scale is a superset of pan.\n'
' Just use the scale gesture recognizer.\n',
);
expect(error.diagnostics.last.level, DiagnosticLevel.hint);
expect(
error.diagnostics.last.toStringDeep(),
equalsIgnoringHashCodes(
'Just use the scale gesture recognizer.\n',
),
);
}
});
test('constructor duplicate drag recognizer', () {
late FlutterError error;
try {
GestureDetector(
onVerticalDragStart: (_) {},
onHorizontalDragStart: (_) {},
onPanStart: (_) {},
);
} on FlutterError catch (e) {
error = e;
} finally {
expect(
error.toStringDeep(),
'FlutterError\n'
' Incorrect GestureDetector arguments.\n'
' Simultaneously having a vertical drag gesture recognizer, a\n'
' horizontal drag gesture recognizer, and a pan gesture recognizer\n'
' will result in the pan gesture recognizer being ignored, since\n'
' the other two will catch all drags.\n',
);
}
});
testWidgets('replaceGestureRecognizers not during layout', (WidgetTester tester) async {
final GlobalKey<RawGestureDetectorState> key = GlobalKey<RawGestureDetectorState>();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: RawGestureDetector(
key: key,
child: const Text('Text'),
),
),
);
late FlutterError error;
try {
key.currentState!.replaceGestureRecognizers(<Type, GestureRecognizerFactory>{});
} on FlutterError catch (e) {
error = e;
} finally {
expect(error.diagnostics.last.level, DiagnosticLevel.hint);
expect(
error.diagnostics.last.toStringDeep(),
equalsIgnoringHashCodes(
'To set the gesture recognizers at other times, trigger a new\n'
'build using setState() and provide the new gesture recognizers as\n'
'constructor arguments to the corresponding RawGestureDetector or\n'
'GestureDetector object.\n',
),
);
expect(
error.toStringDeep(),
'FlutterError\n'
' Unexpected call to replaceGestureRecognizers() method of\n'
' RawGestureDetectorState.\n'
' The replaceGestureRecognizers() method can only be called during\n'
' the layout phase.\n'
' To set the gesture recognizers at other times, trigger a new\n'
' build using setState() and provide the new gesture recognizers as\n'
' constructor arguments to the corresponding RawGestureDetector or\n'
' GestureDetector object.\n',
);
}
});
});
});
testWidgets('supportedDevices update test', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/111716
bool didStartPan = false;
Offset? panDelta;
bool didEndPan = false;
Widget buildFrame(Set<PointerDeviceKind>? supportedDevices) {
return GestureDetector(
onPanStart: (DragStartDetails details) {
didStartPan = true;
},
onPanUpdate: (DragUpdateDetails details) {
panDelta = (panDelta ?? Offset.zero) + details.delta;
},
onPanEnd: (DragEndDetails details) {
didEndPan = true;
},
supportedDevices: supportedDevices,
child: Container(
color: const Color(0xFF00FF00),
)
);
}
await tester.pumpWidget(buildFrame(<PointerDeviceKind>{PointerDeviceKind.mouse}));
expect(didStartPan, isFalse);
expect(panDelta, isNull);
expect(didEndPan, isFalse);
await tester.dragFrom(const Offset(10.0, 10.0), const Offset(20.0, 30.0), kind: PointerDeviceKind.mouse);
// Matching device should allow gesture.
expect(didStartPan, isTrue);
expect(panDelta!.dx, 20.0);
expect(panDelta!.dy, 30.0);
expect(didEndPan, isTrue);
didStartPan = false;
panDelta = null;
didEndPan = false;
await tester.pumpWidget(buildFrame(<PointerDeviceKind>{PointerDeviceKind.stylus}));
await tester.dragFrom(const Offset(10.0, 10.0), const Offset(20.0, 30.0), kind: PointerDeviceKind.mouse);
// Non-matching device should not lead to any callbacks.
expect(didStartPan, isFalse);
expect(panDelta, isNull);
expect(didEndPan, isFalse);
await tester.dragFrom(const Offset(10.0, 10.0), const Offset(20.0, 30.0), kind: PointerDeviceKind.stylus);
// Matching device should allow gesture.
expect(didStartPan, isTrue);
expect(panDelta!.dx, 20.0);
expect(panDelta!.dy, 30.0);
expect(didEndPan, isTrue);
didStartPan = false;
panDelta = null;
didEndPan = false;
// If set to null, events from all device types will be recognized
await tester.pumpWidget(buildFrame(null));
await tester.dragFrom(const Offset(10.0, 10.0), const Offset(20.0, 30.0), kind: PointerDeviceKind.unknown);
expect(didStartPan, isTrue);
expect(panDelta!.dx, 20.0);
expect(panDelta!.dy, 30.0);
expect(didEndPan, isTrue);
});
testWidgets('supportedDevices is respected', (WidgetTester tester) async {
bool didStartPan = false;
Offset? panDelta;
bool didEndPan = false;
await tester.pumpWidget(
GestureDetector(
onPanStart: (DragStartDetails details) {
didStartPan = true;
},
onPanUpdate: (DragUpdateDetails details) {
panDelta = (panDelta ?? Offset.zero) + details.delta;
},
onPanEnd: (DragEndDetails details) {
didEndPan = true;
},
supportedDevices: const <PointerDeviceKind>{PointerDeviceKind.mouse},
child: Container(
color: const Color(0xFF00FF00),
)
),
);
expect(didStartPan, isFalse);
expect(panDelta, isNull);
expect(didEndPan, isFalse);
await tester.dragFrom(const Offset(10.0, 10.0), const Offset(20.0, 30.0), kind: PointerDeviceKind.mouse);
// Matching device should allow gesture.
expect(didStartPan, isTrue);
expect(panDelta!.dx, 20.0);
expect(panDelta!.dy, 30.0);
expect(didEndPan, isTrue);
didStartPan = false;
panDelta = null;
didEndPan = false;
await tester.dragFrom(const Offset(10.0, 10.0), const Offset(20.0, 30.0), kind: PointerDeviceKind.stylus);
// Non-matching device should not lead to any callbacks.
expect(didStartPan, isFalse);
expect(panDelta, isNull);
expect(didEndPan, isFalse);
});
group('DoubleTap', () {
testWidgets('onDoubleTap is called even if onDoubleTapDown has not been not provided', (WidgetTester tester) async {
final List<String> log = <String>[];
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: GestureDetector(
onDoubleTap: () => log.add('double-tap'),
child: Container(
width: 100.0,
height: 100.0,
color: const Color(0xFF00FF00),
),
),
),
);
await tester.tap(find.byType(Container));
await tester.pump(kDoubleTapMinTime);
await tester.tap(find.byType(Container));
await tester.pumpAndSettle();
expect(log, <String>['double-tap']);
});
testWidgets('onDoubleTapDown is called even if onDoubleTap has not been not provided', (WidgetTester tester) async {
final List<String> log = <String>[];
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: GestureDetector(
onDoubleTapDown: (_) => log.add('double-tap-down'),
child: Container(
width: 100.0,
height: 100.0,
color: const Color(0xFF00FF00),
),
),
),
);
await tester.tap(find.byType(Container));
await tester.pump(kDoubleTapMinTime);
await tester.tap(find.byType(Container));
await tester.pumpAndSettle();
expect(log, <String>['double-tap-down']);
});
});
}
class _EmptySemanticsGestureDelegate extends SemanticsGestureDelegate {
@override
void assignSemantics(RenderSemanticsGestureHandler renderObject) {
}
}
/// A [TestVariant] that runs tests multiple times with different buttons.
class ButtonVariant extends TestVariant<int> {
const ButtonVariant({
required this.values,
required this.descriptions,
}) : assert(values.length != 0);
@override
final List<int> values;
final Map<int, String> descriptions;
static int button = 0;
@override
String describeValue(int value) {
assert(descriptions.containsKey(value), 'Unknown button');
return descriptions[value]!;
}
@override
Future<int> setUp(int value) async {
final int oldValue = button;
button = value;
return oldValue;
}
@override
Future<void> tearDown(int value, int memento) async {
button = memento;
}
}
| flutter/packages/flutter/test/widgets/gesture_detector_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/gesture_detector_test.dart",
"repo_id": "flutter",
"token_count": 16491
} | 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.
// This file is run as part of a reduced test set in CI on Mac and Windows
// machines.
@Tags(<String>['reduced-test-set'])
library;
import 'dart:math';
import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Image filter - blur', (WidgetTester tester) async {
await tester.pumpWidget(
RepaintBoundary(
child: ImageFiltered(
imageFilter: ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0),
child: const Placeholder(),
),
),
);
await expectLater(
find.byType(ImageFiltered),
matchesGoldenFile('image_filter_blur.png'),
);
});
testWidgets('Image filter - blur with offset', (WidgetTester tester) async {
final Key key = GlobalKey();
await tester.pumpWidget(
RepaintBoundary(
key: key,
child: Transform.translate(
offset: const Offset(50, 50),
child: ImageFiltered(
imageFilter: ImageFilter.blur(sigmaX: 3.0, sigmaY: 3.0),
child: const Placeholder(),
),
),
),
);
await expectLater(
find.byKey(key),
matchesGoldenFile('image_filter_blur_offset.png'),
);
});
testWidgets('Image filter - dilate', (WidgetTester tester) async {
await tester.pumpWidget(
RepaintBoundary(
child: ImageFiltered(
imageFilter: ImageFilter.dilate(radiusX: 10.0, radiusY: 10.0),
child: const Placeholder(),
),
),
);
await expectLater(
find.byType(ImageFiltered),
matchesGoldenFile('image_filter_dilate.png'),
);
}, skip: kIsWeb); // https://github.com/flutter/flutter/issues/101874
testWidgets('Image filter - erode', (WidgetTester tester) async {
await tester.pumpWidget(
RepaintBoundary(
child: ImageFiltered(
// Do not erode too much, otherwise we will see nothing left.
imageFilter: ImageFilter.erode(radiusX: 1.0, radiusY: 1.0),
child: const Placeholder(strokeWidth: 4),
),
),
);
await expectLater(
find.byType(ImageFiltered),
matchesGoldenFile('image_filter_erode.png'),
);
}, skip: kIsWeb); // https://github.com/flutter/flutter/issues/101874
testWidgets('Image filter - matrix', (WidgetTester tester) async {
final ImageFilter matrix = ImageFilter.matrix(Float64List.fromList(<double>[
0.5, 0.0, 0.0, 0.0, //
0.0, 0.5, 0.0, 0.0, //
0.0, 0.0, 1.0, 0.0, //
0.0, 0.0, 0.0, 1.0, //
]));
await tester.pumpWidget(
RepaintBoundary(
child: ImageFiltered(
imageFilter: matrix,
child: MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(useMaterial3: false, primarySwatch: Colors.blue),
debugShowCheckedModeBanner: false, // https://github.com/flutter/flutter/issues/143616
home: Scaffold(
appBar: AppBar(
title: const Text('Matrix ImageFilter Test'),
),
body: const Center(
child:Text('Hooray!'),
),
floatingActionButton: FloatingActionButton(
onPressed: () { },
tooltip: 'Increment',
child: const Icon(Icons.add),
),
),
),
),
),
);
await expectLater(
find.byType(ImageFiltered),
matchesGoldenFile('image_filter_matrix.png'),
);
});
testWidgets('Image filter - matrix with offset', (WidgetTester tester) async {
final Matrix4 matrix = Matrix4.rotationZ(pi / 18);
final ImageFilter matrixFilter = ImageFilter.matrix(matrix.storage);
final Key key = GlobalKey();
await tester.pumpWidget(
RepaintBoundary(
key: key,
child: Transform.translate(
offset: const Offset(50, 50),
child: ImageFiltered(
imageFilter: matrixFilter,
child: MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(useMaterial3: false, primarySwatch: Colors.blue),
debugShowCheckedModeBanner: false, // https://github.com/flutter/flutter/issues/143616
home: Scaffold(
appBar: AppBar(
title: const Text('Matrix ImageFilter Test'),
),
body: const Center(
child:Text('Hooray!'),
),
floatingActionButton: FloatingActionButton(
onPressed: () { },
tooltip: 'Increment',
child: const Icon(Icons.add),
),
),
),
),
),
),
);
await expectLater(
find.byKey(key),
matchesGoldenFile('image_filter_matrix_offset.png'),
);
});
testWidgets('Image filter - reuses its layer', (WidgetTester tester) async {
Future<void> pumpWithSigma(double sigma) async {
await tester.pumpWidget(
RepaintBoundary(
child: ImageFiltered(
imageFilter: ImageFilter.blur(sigmaX: sigma, sigmaY: sigma),
child: const Placeholder(),
),
),
);
}
await pumpWithSigma(5.0);
final RenderObject renderObject = tester.firstRenderObject(find.byType(ImageFiltered));
final ImageFilterLayer originalLayer = renderObject.debugLayer! as ImageFilterLayer;
// Change blur sigma to force a repaint.
await pumpWithSigma(10.0);
expect(renderObject.debugLayer, same(originalLayer));
});
testWidgets('Image filter - enabled and disabled', (WidgetTester tester) async {
Future<void> pumpWithEnabledState(bool enabled) async {
await tester.pumpWidget(
RepaintBoundary(
child: ImageFiltered(
enabled: enabled,
imageFilter: ImageFilter.blur(sigmaX: 5, sigmaY: 5),
child: const Placeholder(),
),
),
);
}
await pumpWithEnabledState(false);
expect(tester.layers, isNot(contains(isA<ImageFilterLayer>())));
await pumpWithEnabledState(true);
expect(tester.layers, contains(isA<ImageFilterLayer>()));
});
}
| flutter/packages/flutter/test/widgets/image_filter_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/image_filter_test.dart",
"repo_id": "flutter",
"token_count": 2901
} | 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/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Intrinsic stepWidth, stepHeight', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/25224
Widget buildFrame(double? stepWidth, double? stepHeight) {
return Center(
child: IntrinsicWidth(
stepWidth: stepWidth,
stepHeight: stepHeight,
child: const SizedBox(width: 100.0, height: 50.0),
),
);
}
await tester.pumpWidget(buildFrame(null, null));
expect(tester.getSize(find.byType(IntrinsicWidth)), const Size(100.0, 50.0));
await tester.pumpWidget(buildFrame(0.0, 0.0));
expect(tester.getSize(find.byType(IntrinsicWidth)), const Size(100.0, 50.0));
expect(() { buildFrame(-1.0, 0.0); }, throwsAssertionError);
expect(() { buildFrame(0.0, -1.0); }, throwsAssertionError);
});
}
| flutter/packages/flutter/test/widgets/intrinsic_width_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/intrinsic_width_test.dart",
"repo_id": "flutter",
"token_count": 426
} | 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/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
const List<int> items = <int>[0, 1, 2, 3, 4, 5];
Widget buildFrame({ bool reverse = false, required TextDirection textDirection }) {
return Directionality(
textDirection: textDirection,
child: Center(
child: SizedBox(
height: 50.0,
child: ListView(
itemExtent: 290.0,
scrollDirection: Axis.horizontal,
reverse: reverse,
physics: const BouncingScrollPhysics(),
children: items.map<Widget>((int item) {
return Text('$item');
}).toList(),
),
),
),
);
}
void main() {
testWidgets('Drag horizontally with scroll anchor at start (LTR)', (WidgetTester tester) async {
await tester.pumpWidget(buildFrame(textDirection: TextDirection.ltr));
await tester.pump(const Duration(seconds: 1));
await tester.drag(find.text('1'), const Offset(-300.0, 0.0), touchSlopX: 0.0);
await tester.pump(const Duration(seconds: 1));
// screen is 800px wide, and has the following items:
// -10..280 = 1
// 280..570 = 2
// 570..860 = 3
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
expect(find.text('2'), findsOneWidget);
expect(find.text('3'), findsOneWidget);
expect(find.text('4'), findsNothing);
expect(find.text('5'), findsNothing);
// the center of item 3 is visible, so this works;
// if item 3 was a bit wider, such that its center was past the 800px mark, this would fail,
// because it wouldn't be hit tested when scrolling from its center, as drag() does.
await tester.pump(const Duration(seconds: 1));
await tester.drag(find.text('3'), const Offset(-290.0, 0.0), touchSlopX: 0.0);
await tester.pump(const Duration(seconds: 1));
// screen is 800px wide, and has the following items:
// -10..280 = 2
// 280..570 = 3
// 570..860 = 4
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsNothing);
expect(find.text('2'), findsOneWidget);
expect(find.text('3'), findsOneWidget);
expect(find.text('4'), findsOneWidget);
expect(find.text('5'), findsNothing);
await tester.pump(const Duration(seconds: 1));
await tester.drag(find.text('3'), const Offset(0.0, -290.0), touchSlopX: 0.0);
await tester.pump(const Duration(seconds: 1));
// unchanged
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsNothing);
expect(find.text('2'), findsOneWidget);
expect(find.text('3'), findsOneWidget);
expect(find.text('4'), findsOneWidget);
expect(find.text('5'), findsNothing);
await tester.pump(const Duration(seconds: 1));
await tester.drag(find.text('3'), const Offset(-290.0, 0.0), touchSlopX: 0.0);
await tester.pump(const Duration(seconds: 1));
// screen is 800px wide, and has the following items:
// -10..280 = 3
// 280..570 = 4
// 570..860 = 5
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsNothing);
expect(find.text('2'), findsNothing);
expect(find.text('3'), findsOneWidget);
expect(find.text('4'), findsOneWidget);
expect(find.text('5'), findsOneWidget);
await tester.pump(const Duration(seconds: 1));
// at this point we can drag 60 pixels further before we hit the friction zone
// then, every pixel we drag is equivalent to half a pixel of movement
// to move item 3 entirely off screen therefore takes:
// 60 + (290-60)*2 = 520 pixels
// plus a couple more to be sure
await tester.drag(find.text('3'), const Offset(-522.0, 0.0), touchSlopX: 0.0);
await tester.pump(); // just after release
// screen is 800px wide, and has the following items:
// -11..279 = 4
// 279..569 = 5
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsNothing);
expect(find.text('2'), findsNothing);
expect(find.text('3'), findsNothing);
expect(find.text('4'), findsOneWidget);
expect(find.text('5'), findsOneWidget);
await tester.pump(const Duration(seconds: 1)); // a second after release
// screen is 800px wide, and has the following items:
// -70..220 = 3
// 220..510 = 4
// 510..800 = 5
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsNothing);
expect(find.text('2'), findsNothing);
expect(find.text('3'), findsOneWidget);
expect(find.text('4'), findsOneWidget);
expect(find.text('5'), findsOneWidget);
await tester.pumpWidget(Container());
await tester.pumpWidget(buildFrame(textDirection: TextDirection.ltr), duration: const Duration(seconds: 1));
await tester.drag(find.text('2'), const Offset(-280.0, 0.0), touchSlopX: 0.0);
await tester.pump(const Duration(seconds: 1));
// screen is 800px wide, and has the following items:
// -280..10 = 0
// 10..300 = 1
// 300..590 = 2
// 590..880 = 3
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsOneWidget);
expect(find.text('2'), findsOneWidget);
expect(find.text('3'), findsOneWidget);
expect(find.text('4'), findsNothing);
expect(find.text('5'), findsNothing);
await tester.pump(const Duration(seconds: 1));
await tester.drag(find.text('2'), const Offset(-290.0, 0.0), touchSlopX: 0.0);
await tester.pump(const Duration(seconds: 1));
// screen is 800px wide, and has the following items:
// -280..10 = 1
// 10..300 = 2
// 300..590 = 3
// 590..880 = 4
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
expect(find.text('2'), findsOneWidget);
expect(find.text('3'), findsOneWidget);
expect(find.text('4'), findsOneWidget);
expect(find.text('5'), findsNothing);
});
testWidgets('Drag horizontally with scroll anchor at end (LTR)', (WidgetTester tester) async {
await tester.pumpWidget(buildFrame(reverse: true, textDirection: TextDirection.ltr));
await tester.pump(const Duration(seconds: 1));
// screen is 800px wide, and has the following items:
// -70..220 = 2
// 220..510 = 1
// 510..800 = 0
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsOneWidget);
expect(find.text('2'), findsOneWidget);
expect(find.text('3'), findsNothing);
expect(find.text('4'), findsNothing);
expect(find.text('5'), findsNothing);
await tester.drag(find.text('0'), const Offset(300.0, 0.0), touchSlopX: 0.0);
await tester.pump(const Duration(seconds: 1));
// screen is 800px wide, and has the following items:
// -80..210 = 3
// 230..520 = 2
// 520..810 = 1
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
expect(find.text('2'), findsOneWidget);
expect(find.text('3'), findsOneWidget);
expect(find.text('4'), findsNothing);
expect(find.text('5'), findsNothing);
// the center of item 3 is visible, so this works;
// if item 3 was a bit wider, such that its center was past the 800px mark, this would fail,
// because it wouldn't be hit tested when scrolling from its center, as drag() does.
await tester.pump(const Duration(seconds: 1));
await tester.drag(find.text('2'), const Offset(290.0, 0.0), touchSlopX: 0.0);
await tester.pump(const Duration(seconds: 1));
// screen is 800px wide, and has the following items:
// -10..280 = 4
// 280..570 = 3
// 570..860 = 2
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsNothing);
expect(find.text('2'), findsOneWidget);
expect(find.text('3'), findsOneWidget);
expect(find.text('4'), findsOneWidget);
expect(find.text('5'), findsNothing);
await tester.pump(const Duration(seconds: 1));
await tester.drag(find.text('2'), const Offset(0.0, 290.0), touchSlopY: 0.0);
await tester.pump(const Duration(seconds: 1));
// unchanged
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsNothing);
expect(find.text('2'), findsOneWidget);
expect(find.text('3'), findsOneWidget);
expect(find.text('4'), findsOneWidget);
expect(find.text('5'), findsNothing);
await tester.pump(const Duration(seconds: 1));
await tester.drag(find.text('3'), const Offset(290.0, 0.0), touchSlopX: 0.0);
await tester.pump(const Duration(seconds: 1));
// screen is 800px wide, and has the following items:
// -10..280 = 5
// 280..570 = 4
// 570..860 = 3
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsNothing);
expect(find.text('2'), findsNothing);
expect(find.text('3'), findsOneWidget);
expect(find.text('4'), findsOneWidget);
expect(find.text('5'), findsOneWidget);
await tester.pump(const Duration(seconds: 1));
// at this point we can drag 60 pixels further before we hit the friction zone
// then, every pixel we drag is equivalent to half a pixel of movement
// to move item 3 entirely off screen therefore takes:
// 60 + (290-60)*2 = 520 pixels
// plus a couple more to be sure
await tester.drag(find.text('4'), const Offset(522.0, 0.0), touchSlopX: 0.0);
await tester.pump(); // just after release
// screen is 800px wide, and has the following items:
// 280..570 = 5
// 570..860 = 4
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsNothing);
expect(find.text('2'), findsNothing);
expect(find.text('3'), findsNothing);
expect(find.text('4'), findsOneWidget);
expect(find.text('5'), findsOneWidget);
await tester.pump(const Duration(seconds: 1)); // a second after release
// screen is 800px wide, and has the following items:
// 0..290 = 5
// 290..580 = 4
// 580..870 = 3
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsNothing);
expect(find.text('2'), findsNothing);
expect(find.text('3'), findsOneWidget);
expect(find.text('4'), findsOneWidget);
expect(find.text('5'), findsOneWidget);
});
testWidgets('Drag horizontally with scroll anchor at start (RTL)', (WidgetTester tester) async {
await tester.pumpWidget(buildFrame(textDirection: TextDirection.rtl));
await tester.pump(const Duration(seconds: 1));
// screen is 800px wide, and has the following items:
// -70..220 = 2
// 220..510 = 1
// 510..800 = 0
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsOneWidget);
expect(find.text('2'), findsOneWidget);
expect(find.text('3'), findsNothing);
expect(find.text('4'), findsNothing);
expect(find.text('5'), findsNothing);
await tester.drag(find.text('0'), const Offset(300.0, 0.0), touchSlopX: 0.0);
await tester.pump(const Duration(seconds: 1));
// screen is 800px wide, and has the following items:
// -80..210 = 3
// 230..520 = 2
// 520..810 = 1
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
expect(find.text('2'), findsOneWidget);
expect(find.text('3'), findsOneWidget);
expect(find.text('4'), findsNothing);
expect(find.text('5'), findsNothing);
// the center of item 3 is visible, so this works;
// if item 3 was a bit wider, such that its center was past the 800px mark, this would fail,
// because it wouldn't be hit tested when scrolling from its center, as drag() does.
await tester.pump(const Duration(seconds: 1));
await tester.drag(find.text('2'), const Offset(290.0, 0.0), touchSlopX: 0.0);
await tester.pump(const Duration(seconds: 1));
// screen is 800px wide, and has the following items:
// -10..280 = 4
// 280..570 = 3
// 570..860 = 2
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsNothing);
expect(find.text('2'), findsOneWidget);
expect(find.text('3'), findsOneWidget);
expect(find.text('4'), findsOneWidget);
expect(find.text('5'), findsNothing);
await tester.pump(const Duration(seconds: 1));
await tester.drag(find.text('2'), const Offset(0.0, 290.0), touchSlopY: 0.0);
await tester.pump(const Duration(seconds: 1));
// unchanged
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsNothing);
expect(find.text('2'), findsOneWidget);
expect(find.text('3'), findsOneWidget);
expect(find.text('4'), findsOneWidget);
expect(find.text('5'), findsNothing);
await tester.pump(const Duration(seconds: 1));
await tester.drag(find.text('3'), const Offset(290.0, 0.0), touchSlopX: 0.0);
await tester.pump(const Duration(seconds: 1));
// screen is 800px wide, and has the following items:
// -10..280 = 5
// 280..570 = 4
// 570..860 = 3
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsNothing);
expect(find.text('2'), findsNothing);
expect(find.text('3'), findsOneWidget);
expect(find.text('4'), findsOneWidget);
expect(find.text('5'), findsOneWidget);
await tester.pump(const Duration(seconds: 1));
// at this point we can drag 60 pixels further before we hit the friction zone
// then, every pixel we drag is equivalent to half a pixel of movement
// to move item 3 entirely off screen therefore takes:
// 60 + (290-60)*2 = 520 pixels
// plus a couple more to be sure
await tester.drag(find.text('4'), const Offset(522.0, 0.0), touchSlopX: 0.0);
await tester.pump(); // just after release
// screen is 800px wide, and has the following items:
// 280..570 = 5
// 570..860 = 4
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsNothing);
expect(find.text('2'), findsNothing);
expect(find.text('3'), findsNothing);
expect(find.text('4'), findsOneWidget);
expect(find.text('5'), findsOneWidget);
await tester.pump(const Duration(seconds: 1)); // a second after release
// screen is 800px wide, and has the following items:
// 0..290 = 5
// 290..580 = 4
// 580..870 = 3
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsNothing);
expect(find.text('2'), findsNothing);
expect(find.text('3'), findsOneWidget);
expect(find.text('4'), findsOneWidget);
expect(find.text('5'), findsOneWidget);
});
testWidgets('Drag horizontally with scroll anchor at end (LTR)', (WidgetTester tester) async {
await tester.pumpWidget(buildFrame(reverse: true, textDirection: TextDirection.rtl));
await tester.pump(const Duration(seconds: 1));
await tester.drag(find.text('1'), const Offset(-300.0, 0.0), touchSlopX: 0.0);
await tester.pump(const Duration(seconds: 1));
// screen is 800px wide, and has the following items:
// -10..280 = 1
// 280..570 = 2
// 570..860 = 3
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
expect(find.text('2'), findsOneWidget);
expect(find.text('3'), findsOneWidget);
expect(find.text('4'), findsNothing);
expect(find.text('5'), findsNothing);
// the center of item 3 is visible, so this works;
// if item 3 was a bit wider, such that its center was past the 800px mark, this would fail,
// because it wouldn't be hit tested when scrolling from its center, as drag() does.
await tester.pump(const Duration(seconds: 1));
await tester.drag(find.text('3'), const Offset(-290.0, 0.0), touchSlopX: 0.0);
await tester.pump(const Duration(seconds: 1));
// screen is 800px wide, and has the following items:
// -10..280 = 2
// 280..570 = 3
// 570..860 = 4
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsNothing);
expect(find.text('2'), findsOneWidget);
expect(find.text('3'), findsOneWidget);
expect(find.text('4'), findsOneWidget);
expect(find.text('5'), findsNothing);
await tester.pump(const Duration(seconds: 1));
await tester.drag(find.text('3'), const Offset(0.0, -290.0), touchSlopX: 0.0);
await tester.pump(const Duration(seconds: 1));
// unchanged
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsNothing);
expect(find.text('2'), findsOneWidget);
expect(find.text('3'), findsOneWidget);
expect(find.text('4'), findsOneWidget);
expect(find.text('5'), findsNothing);
await tester.pump(const Duration(seconds: 1));
await tester.drag(find.text('3'), const Offset(-290.0, 0.0), touchSlopX: 0.0);
await tester.pump(const Duration(seconds: 1));
// screen is 800px wide, and has the following items:
// -10..280 = 3
// 280..570 = 4
// 570..860 = 5
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsNothing);
expect(find.text('2'), findsNothing);
expect(find.text('3'), findsOneWidget);
expect(find.text('4'), findsOneWidget);
expect(find.text('5'), findsOneWidget);
await tester.pump(const Duration(seconds: 1));
// at this point we can drag 60 pixels further before we hit the friction zone
// then, every pixel we drag is equivalent to half a pixel of movement
// to move item 3 entirely off screen therefore takes:
// 60 + (290-60)*2 = 520 pixels
// plus a couple more to be sure
await tester.drag(find.text('3'), const Offset(-522.0, 0.0), touchSlopX: 0.0);
await tester.pump(); // just after release
// screen is 800px wide, and has the following items:
// -11..279 = 4
// 279..569 = 5
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsNothing);
expect(find.text('2'), findsNothing);
expect(find.text('3'), findsNothing);
expect(find.text('4'), findsOneWidget);
expect(find.text('5'), findsOneWidget);
await tester.pump(const Duration(seconds: 1)); // a second after release
// screen is 800px wide, and has the following items:
// -70..220 = 3
// 220..510 = 4
// 510..800 = 5
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsNothing);
expect(find.text('2'), findsNothing);
expect(find.text('3'), findsOneWidget);
expect(find.text('4'), findsOneWidget);
expect(find.text('5'), findsOneWidget);
await tester.pumpWidget(Container());
await tester.pumpWidget(buildFrame(reverse: true, textDirection: TextDirection.rtl), duration: const Duration(seconds: 1));
await tester.drag(find.text('2'), const Offset(-280.0, 0.0), touchSlopX: 0.0);
await tester.pump(const Duration(seconds: 1));
// screen is 800px wide, and has the following items:
// -280..10 = 0
// 10..300 = 1
// 300..590 = 2
// 590..880 = 3
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsOneWidget);
expect(find.text('2'), findsOneWidget);
expect(find.text('3'), findsOneWidget);
expect(find.text('4'), findsNothing);
expect(find.text('5'), findsNothing);
await tester.pump(const Duration(seconds: 1));
await tester.drag(find.text('2'), const Offset(-290.0, 0.0), touchSlopX: 0.0);
await tester.pump(const Duration(seconds: 1));
// screen is 800px wide, and has the following items:
// -280..10 = 1
// 10..300 = 2
// 300..590 = 3
// 590..880 = 4
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
expect(find.text('2'), findsOneWidget);
expect(find.text('3'), findsOneWidget);
expect(find.text('4'), findsOneWidget);
expect(find.text('5'), findsNothing);
});
}
| flutter/packages/flutter/test/widgets/list_view_horizontal_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/list_view_horizontal_test.dart",
"repo_id": "flutter",
"token_count": 7335
} | 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 'dart:ui' show Brightness, DisplayFeature, DisplayFeatureState, DisplayFeatureType, GestureSettings;
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
class _MediaQueryAspectCase {
const _MediaQueryAspectCase(this.method, this.data);
final void Function(BuildContext) method;
final MediaQueryData data;
}
class _MediaQueryAspectVariant extends TestVariant<_MediaQueryAspectCase> {
_MediaQueryAspectVariant({
required this.values
});
@override
final List<_MediaQueryAspectCase> values;
static _MediaQueryAspectCase? aspect;
@override
String describeValue(_MediaQueryAspectCase value) {
return value.method.toString();
}
@override
Future<_MediaQueryAspectCase?> setUp(_MediaQueryAspectCase value) async {
final _MediaQueryAspectCase? oldAspect = aspect;
aspect = value;
return oldAspect;
}
@override
Future<void> tearDown(_MediaQueryAspectCase value, _MediaQueryAspectCase? memento) async {
aspect = memento;
}
}
void main() {
testWidgets('MediaQuery does not have a default', (WidgetTester tester) async {
late final FlutterError error;
// Cannot use tester.pumpWidget here because it wraps the widget in a View,
// which introduces a MediaQuery ancestor.
await tester.pumpWidget(
wrapWithView: false,
Builder(
builder: (BuildContext context) {
try {
MediaQuery.of(context);
} on FlutterError catch (e) {
error = e;
}
return View(
view: tester.view,
child: const SizedBox(),
);
},
),
);
expect(
error.toStringDeep(),
startsWith(
'FlutterError\n'
' No MediaQuery widget ancestor found.\n'
' Builder widgets require a MediaQuery widget ancestor.\n'
' The specific widget that could not find a MediaQuery ancestor\n'
' was:\n'
' Builder\n'
' The ownership chain for the affected widget is: "Builder ←', // Full ownership chain omitted, not relevant for test.
),
);
expect(
error.toStringDeep(),
endsWith(
'[root]"\n' // End of ownership chain.
' No MediaQuery ancestor could be found starting from the context\n'
' that was passed to MediaQuery.of(). This can happen because the\n'
' context used is not a descendant of a View widget, which\n'
' introduces a MediaQuery.\n'
),
);
});
testWidgets('MediaQuery.of finds a MediaQueryData when there is one', (WidgetTester tester) async {
bool tested = false;
await tester.pumpWidget(
MediaQuery(
data: const MediaQueryData(),
child: Builder(
builder: (BuildContext context) {
final MediaQueryData data = MediaQuery.of(context);
expect(data, isNotNull);
tested = true;
return Container();
},
),
),
);
final dynamic exception = tester.takeException();
expect(exception, isNull);
expect(tested, isTrue);
});
testWidgets('MediaQuery.maybeOf defaults to null', (WidgetTester tester) async {
bool tested = false;
// Cannot use tester.pumpWidget here because it wraps the widget in a View,
// which introduces a MediaQuery ancestor.
await tester.pumpWidget(
wrapWithView: false,
Builder(
builder: (BuildContext context) {
final MediaQueryData? data = MediaQuery.maybeOf(context);
expect(data, isNull);
tested = true;
return View(
view: tester.view,
child: const SizedBox(),
);
},
),
);
expect(tested, isTrue);
});
testWidgets('MediaQuery.maybeOf finds a MediaQueryData when there is one', (WidgetTester tester) async {
bool tested = false;
await tester.pumpWidget(
MediaQuery(
data: const MediaQueryData(),
child: Builder(
builder: (BuildContext context) {
final MediaQueryData? data = MediaQuery.maybeOf(context);
expect(data, isNotNull);
tested = true;
return Container();
},
),
),
);
expect(tested, isTrue);
});
testWidgets('MediaQueryData.fromView is sane', (WidgetTester tester) async {
final MediaQueryData data = MediaQueryData.fromView(tester.view);
expect(data, hasOneLineDescription);
expect(data.hashCode, equals(data.copyWith().hashCode));
expect(data.size, equals(tester.view.physicalSize / tester.view.devicePixelRatio));
expect(data.accessibleNavigation, false);
expect(data.invertColors, false);
expect(data.disableAnimations, false);
expect(data.boldText, false);
expect(data.highContrast, false);
expect(data.onOffSwitchLabels, false);
expect(data.platformBrightness, Brightness.light);
expect(data.gestureSettings.touchSlop, null);
expect(data.displayFeatures, isEmpty);
});
testWidgets('MediaQueryData.fromView uses platformData if provided', (WidgetTester tester) async {
const MediaQueryData platformData = MediaQueryData(
textScaler: TextScaler.linear(1234),
platformBrightness: Brightness.dark,
accessibleNavigation: true,
invertColors: true,
disableAnimations: true,
boldText: true,
highContrast: true,
onOffSwitchLabels: true,
alwaysUse24HourFormat: true,
navigationMode: NavigationMode.directional,
);
final MediaQueryData data = MediaQueryData.fromView(tester.view, platformData: platformData);
expect(data, hasOneLineDescription);
expect(data.hashCode, data.copyWith().hashCode);
expect(data.size, tester.view.physicalSize / tester.view.devicePixelRatio);
expect(data.devicePixelRatio, tester.view.devicePixelRatio);
expect(data.textScaler, TextScaler.linear(platformData.textScaleFactor));
expect(data.platformBrightness, platformData.platformBrightness);
expect(data.padding, EdgeInsets.fromViewPadding(tester.view.padding, tester.view.devicePixelRatio));
expect(data.viewPadding, EdgeInsets.fromViewPadding(tester.view.viewPadding, tester.view.devicePixelRatio));
expect(data.viewInsets, EdgeInsets.fromViewPadding(tester.view.viewInsets, tester.view.devicePixelRatio));
expect(data.systemGestureInsets, EdgeInsets.fromViewPadding(tester.view.systemGestureInsets, tester.view.devicePixelRatio));
expect(data.accessibleNavigation, platformData.accessibleNavigation);
expect(data.invertColors, platformData.invertColors);
expect(data.disableAnimations, platformData.disableAnimations);
expect(data.boldText, platformData.boldText);
expect(data.highContrast, platformData.highContrast);
expect(data.onOffSwitchLabels, platformData.onOffSwitchLabels);
expect(data.alwaysUse24HourFormat, platformData.alwaysUse24HourFormat);
expect(data.navigationMode, platformData.navigationMode);
expect(data.gestureSettings, DeviceGestureSettings.fromView(tester.view));
expect(data.displayFeatures, tester.view.displayFeatures);
});
testWidgets('MediaQueryData.fromView uses data from platformDispatcher if no platformData is provided', (WidgetTester tester) async {
tester.platformDispatcher
..textScaleFactorTestValue = 123
..platformBrightnessTestValue = Brightness.dark
..accessibilityFeaturesTestValue = FakeAccessibilityFeatures.allOn;
addTearDown(() => tester.platformDispatcher.clearAllTestValues());
final MediaQueryData data = MediaQueryData.fromView(tester.view);
expect(data, hasOneLineDescription);
expect(data.hashCode, data.copyWith().hashCode);
expect(data.size, tester.view.physicalSize / tester.view.devicePixelRatio);
expect(data.devicePixelRatio, tester.view.devicePixelRatio);
expect(data.textScaler, TextScaler.linear(tester.platformDispatcher.textScaleFactor));
expect(data.platformBrightness, tester.platformDispatcher.platformBrightness);
expect(data.padding, EdgeInsets.fromViewPadding(tester.view.padding, tester.view.devicePixelRatio));
expect(data.viewPadding, EdgeInsets.fromViewPadding(tester.view.viewPadding, tester.view.devicePixelRatio));
expect(data.viewInsets, EdgeInsets.fromViewPadding(tester.view.viewInsets, tester.view.devicePixelRatio));
expect(data.systemGestureInsets, EdgeInsets.fromViewPadding(tester.view.systemGestureInsets, tester.view.devicePixelRatio));
expect(data.accessibleNavigation, tester.platformDispatcher.accessibilityFeatures.accessibleNavigation);
expect(data.invertColors, tester.platformDispatcher.accessibilityFeatures.invertColors);
expect(data.disableAnimations, tester.platformDispatcher.accessibilityFeatures.disableAnimations);
expect(data.boldText, tester.platformDispatcher.accessibilityFeatures.boldText);
expect(data.highContrast, tester.platformDispatcher.accessibilityFeatures.highContrast);
expect(data.onOffSwitchLabels, tester.platformDispatcher.accessibilityFeatures.onOffSwitchLabels);
expect(data.alwaysUse24HourFormat, tester.platformDispatcher.alwaysUse24HourFormat);
expect(data.navigationMode, NavigationMode.traditional);
expect(data.gestureSettings, DeviceGestureSettings.fromView(tester.view));
expect(data.displayFeatures, tester.view.displayFeatures);
});
testWidgets('MediaQuery.fromView injects a new MediaQuery with data from view, preserving platform-specific data', (WidgetTester tester) async {
const MediaQueryData platformData = MediaQueryData(
textScaler: TextScaler.linear(1234),
platformBrightness: Brightness.dark,
accessibleNavigation: true,
invertColors: true,
disableAnimations: true,
boldText: true,
highContrast: true,
onOffSwitchLabels: true,
alwaysUse24HourFormat: true,
navigationMode: NavigationMode.directional,
);
late MediaQueryData data;
await tester.pumpWidget(MediaQuery(
data: platformData,
child: MediaQuery.fromView(
view: tester.view,
child: Builder(
builder: (BuildContext context) {
data = MediaQuery.of(context);
return const Placeholder();
},
)
)
));
expect(data, isNot(platformData));
expect(data.size, tester.view.physicalSize / tester.view.devicePixelRatio);
expect(data.devicePixelRatio, tester.view.devicePixelRatio);
expect(data.textScaler, TextScaler.linear(platformData.textScaleFactor));
expect(data.platformBrightness, platformData.platformBrightness);
expect(data.padding, EdgeInsets.fromViewPadding(tester.view.padding, tester.view.devicePixelRatio));
expect(data.viewPadding, EdgeInsets.fromViewPadding(tester.view.viewPadding, tester.view.devicePixelRatio));
expect(data.viewInsets, EdgeInsets.fromViewPadding(tester.view.viewInsets, tester.view.devicePixelRatio));
expect(data.systemGestureInsets, EdgeInsets.fromViewPadding(tester.view.systemGestureInsets, tester.view.devicePixelRatio));
expect(data.accessibleNavigation, platformData.accessibleNavigation);
expect(data.invertColors, platformData.invertColors);
expect(data.disableAnimations, platformData.disableAnimations);
expect(data.boldText, platformData.boldText);
expect(data.highContrast, platformData.highContrast);
expect(data.onOffSwitchLabels, platformData.onOffSwitchLabels);
expect(data.alwaysUse24HourFormat, platformData.alwaysUse24HourFormat);
expect(data.navigationMode, platformData.navigationMode);
expect(data.gestureSettings, DeviceGestureSettings.fromView(tester.view));
expect(data.displayFeatures, tester.view.displayFeatures);
});
testWidgets('MediaQuery.fromView injects a new MediaQuery with data from view when no surrounding MediaQuery exists', (WidgetTester tester) async {
tester.platformDispatcher
..textScaleFactorTestValue = 123
..platformBrightnessTestValue = Brightness.dark
..accessibilityFeaturesTestValue = FakeAccessibilityFeatures.allOn;
addTearDown(() => tester.platformDispatcher.clearAllTestValues());
late MediaQueryData data;
MediaQueryData? outerData;
await tester.pumpWidget(
wrapWithView: false,
Builder(
builder: (BuildContext context) {
outerData = MediaQuery.maybeOf(context);
return MediaQuery.fromView(
view: tester.view,
child: Builder(
builder: (BuildContext context) {
data = MediaQuery.of(context);
return View(
view: tester.view,
child: const SizedBox(),
);
},
)
);
},
),
);
expect(outerData, isNull);
expect(data.size, tester.view.physicalSize / tester.view.devicePixelRatio);
expect(data.devicePixelRatio, tester.view.devicePixelRatio);
expect(data.textScaler, TextScaler.linear(tester.platformDispatcher.textScaleFactor));
expect(data.platformBrightness, tester.platformDispatcher.platformBrightness);
expect(data.padding, EdgeInsets.fromViewPadding(tester.view.padding, tester.view.devicePixelRatio));
expect(data.viewPadding, EdgeInsets.fromViewPadding(tester.view.viewPadding, tester.view.devicePixelRatio));
expect(data.viewInsets, EdgeInsets.fromViewPadding(tester.view.viewInsets, tester.view.devicePixelRatio));
expect(data.systemGestureInsets, EdgeInsets.fromViewPadding(tester.view.systemGestureInsets, tester.view.devicePixelRatio));
expect(data.accessibleNavigation, tester.platformDispatcher.accessibilityFeatures.accessibleNavigation);
expect(data.invertColors, tester.platformDispatcher.accessibilityFeatures.invertColors);
expect(data.disableAnimations, tester.platformDispatcher.accessibilityFeatures.disableAnimations);
expect(data.boldText, tester.platformDispatcher.accessibilityFeatures.boldText);
expect(data.highContrast, tester.platformDispatcher.accessibilityFeatures.highContrast);
expect(data.onOffSwitchLabels, tester.platformDispatcher.accessibilityFeatures.onOffSwitchLabels);
expect(data.alwaysUse24HourFormat, tester.platformDispatcher.alwaysUse24HourFormat);
expect(data.navigationMode, NavigationMode.traditional);
expect(data.gestureSettings, DeviceGestureSettings.fromView(tester.view));
expect(data.displayFeatures, tester.view.displayFeatures);
});
testWidgets('MediaQuery.fromView updates on notifications (no parent data)', (WidgetTester tester) async {
addTearDown(() => tester.platformDispatcher.clearAllTestValues());
addTearDown(() => tester.view.reset());
tester.platformDispatcher
..textScaleFactorTestValue = 123
..platformBrightnessTestValue = Brightness.dark
..accessibilityFeaturesTestValue = FakeAccessibilityFeatures.allOn;
tester.view.devicePixelRatio = 44;
late MediaQueryData data;
MediaQueryData? outerData;
int rebuildCount = 0;
await tester.pumpWidget(
wrapWithView: false,
Builder(
builder: (BuildContext context) {
outerData = MediaQuery.maybeOf(context);
return MediaQuery.fromView(
view: tester.view,
child: Builder(
builder: (BuildContext context) {
rebuildCount++;
data = MediaQuery.of(context);
return View(
view: tester.view,
child: const SizedBox(),
);
},
),
);
},
),
);
expect(outerData, isNull);
expect(rebuildCount, 1);
expect(data.textScaler, const TextScaler.linear(123));
tester.platformDispatcher.textScaleFactorTestValue = 456;
await tester.pump();
expect(data.textScaler, const TextScaler.linear(456));
expect(rebuildCount, 2);
expect(data.platformBrightness, Brightness.dark);
tester.platformDispatcher.platformBrightnessTestValue = Brightness.light;
await tester.pump();
expect(data.platformBrightness, Brightness.light);
expect(rebuildCount, 3);
expect(data.accessibleNavigation, true);
tester.platformDispatcher.accessibilityFeaturesTestValue = const FakeAccessibilityFeatures();
await tester.pump();
expect(data.accessibleNavigation, false);
expect(rebuildCount, 4);
expect(data.devicePixelRatio, 44);
tester.view.devicePixelRatio = 55;
await tester.pump();
expect(data.devicePixelRatio, 55);
expect(rebuildCount, 5);
});
testWidgets('MediaQuery.fromView updates on notifications (with parent data)', (WidgetTester tester) async {
addTearDown(() => tester.platformDispatcher.clearAllTestValues());
addTearDown(() => tester.view.reset());
tester.platformDispatcher
..textScaleFactorTestValue = 123
..platformBrightnessTestValue = Brightness.dark
..accessibilityFeaturesTestValue = FakeAccessibilityFeatures.allOn;
tester.view.devicePixelRatio = 44;
late MediaQueryData data;
int rebuildCount = 0;
await tester.pumpWidget(
MediaQuery(
data: const MediaQueryData(
textScaler: TextScaler.linear(44),
platformBrightness: Brightness.dark,
accessibleNavigation: true,
),
child: MediaQuery.fromView(
view: tester.view,
child: Builder(
builder: (BuildContext context) {
rebuildCount++;
data = MediaQuery.of(context);
return const Placeholder();
},
),
),
),
);
expect(rebuildCount, 1);
expect(data.textScaler, const TextScaler.linear(44));
tester.platformDispatcher.textScaleFactorTestValue = 456;
await tester.pump();
expect(data.textScaler, const TextScaler.linear(44));
expect(rebuildCount, 1);
expect(data.platformBrightness, Brightness.dark);
tester.platformDispatcher.platformBrightnessTestValue = Brightness.light;
await tester.pump();
expect(data.platformBrightness, Brightness.dark);
expect(rebuildCount, 1);
expect(data.accessibleNavigation, true);
tester.platformDispatcher.accessibilityFeaturesTestValue = const FakeAccessibilityFeatures();
await tester.pump();
expect(data.accessibleNavigation, true);
expect(rebuildCount, 1);
expect(data.devicePixelRatio, 44);
tester.view.devicePixelRatio = 55;
await tester.pump();
expect(data.devicePixelRatio, 55);
expect(rebuildCount, 2);
});
testWidgets('MediaQuery.fromView updates when parent data changes', (WidgetTester tester) async {
late MediaQueryData data;
int rebuildCount = 0;
TextScaler textScaler = const TextScaler.linear(55);
late StateSetter stateSetter;
await tester.pumpWidget(
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
stateSetter = setState;
return MediaQuery(
data: MediaQueryData(textScaler: textScaler),
child: MediaQuery.fromView(
view: tester.view,
child: Builder(
builder: (BuildContext context) {
rebuildCount++;
data = MediaQuery.of(context);
return const Placeholder();
},
),
),
);
},
),
);
expect(rebuildCount, 1);
expect(data.textScaler, const TextScaler.linear(55));
stateSetter(() {
textScaler = const TextScaler.linear(66);
});
await tester.pump();
expect(data.textScaler, const TextScaler.linear(66));
expect(rebuildCount, 2);
});
testWidgets('MediaQueryData.copyWith defaults to source', (WidgetTester tester) async {
final MediaQueryData data = MediaQueryData.fromView(tester.view);
final MediaQueryData copied = data.copyWith();
expect(copied.size, data.size);
expect(copied.devicePixelRatio, data.devicePixelRatio);
expect(copied.textScaler, data.textScaler);
expect(copied.padding, data.padding);
expect(copied.viewPadding, data.viewPadding);
expect(copied.viewInsets, data.viewInsets);
expect(copied.systemGestureInsets, data.systemGestureInsets);
expect(copied.alwaysUse24HourFormat, data.alwaysUse24HourFormat);
expect(copied.accessibleNavigation, data.accessibleNavigation);
expect(copied.invertColors, data.invertColors);
expect(copied.disableAnimations, data.disableAnimations);
expect(copied.boldText, data.boldText);
expect(copied.highContrast, data.highContrast);
expect(copied.onOffSwitchLabels, data.onOffSwitchLabels);
expect(copied.platformBrightness, data.platformBrightness);
expect(copied.gestureSettings, data.gestureSettings);
expect(copied.displayFeatures, data.displayFeatures);
});
testWidgets('MediaQuery.copyWith copies specified values', (WidgetTester tester) async {
// Random and unique double values are used to ensure that the correct
// values are copied over exactly
const Size customSize = Size(3.14, 2.72);
const double customDevicePixelRatio = 1.41;
const TextScaler customTextScaler = TextScaler.linear(1.23);
const EdgeInsets customPadding = EdgeInsets.all(9.10938);
const EdgeInsets customViewPadding = EdgeInsets.all(11.24031);
const EdgeInsets customViewInsets = EdgeInsets.all(1.67262);
const EdgeInsets customSystemGestureInsets = EdgeInsets.all(1.5556);
const DeviceGestureSettings gestureSettings = DeviceGestureSettings(touchSlop: 8.0);
const List<DisplayFeature> customDisplayFeatures = <DisplayFeature>[
DisplayFeature(
bounds: Rect.zero,
type: DisplayFeatureType.cutout,
state: DisplayFeatureState.unknown,
),
];
final MediaQueryData data = MediaQueryData.fromView(tester.view);
final MediaQueryData copied = data.copyWith(
size: customSize,
devicePixelRatio: customDevicePixelRatio,
textScaler: customTextScaler,
padding: customPadding,
viewPadding: customViewPadding,
viewInsets: customViewInsets,
systemGestureInsets: customSystemGestureInsets,
alwaysUse24HourFormat: true,
accessibleNavigation: true,
invertColors: true,
disableAnimations: true,
boldText: true,
highContrast: true,
onOffSwitchLabels: true,
platformBrightness: Brightness.dark,
navigationMode: NavigationMode.directional,
gestureSettings: gestureSettings,
displayFeatures: customDisplayFeatures,
);
expect(copied.size, customSize);
expect(copied.devicePixelRatio, customDevicePixelRatio);
expect(copied.textScaler, customTextScaler);
expect(copied.padding, customPadding);
expect(copied.viewPadding, customViewPadding);
expect(copied.viewInsets, customViewInsets);
expect(copied.systemGestureInsets, customSystemGestureInsets);
expect(copied.alwaysUse24HourFormat, true);
expect(copied.accessibleNavigation, true);
expect(copied.invertColors, true);
expect(copied.disableAnimations, true);
expect(copied.boldText, true);
expect(copied.highContrast, true);
expect(copied.onOffSwitchLabels, true);
expect(copied.platformBrightness, Brightness.dark);
expect(copied.navigationMode, NavigationMode.directional);
expect(copied.gestureSettings, gestureSettings);
expect(copied.displayFeatures, customDisplayFeatures);
});
testWidgets('MediaQuery.removePadding removes specified padding', (WidgetTester tester) async {
const Size size = Size(2.0, 4.0);
const double devicePixelRatio = 2.0;
const TextScaler textScaler = TextScaler.linear(1.2);
const EdgeInsets padding = EdgeInsets.only(top: 1.0, right: 2.0, left: 3.0, bottom: 4.0);
const EdgeInsets viewPadding = EdgeInsets.only(top: 6.0, right: 8.0, left: 10.0, bottom: 12.0);
const EdgeInsets viewInsets = EdgeInsets.only(top: 5.0, right: 6.0, left: 7.0, bottom: 8.0);
const List<DisplayFeature> displayFeatures = <DisplayFeature>[
DisplayFeature(
bounds: Rect.zero,
type: DisplayFeatureType.cutout,
state: DisplayFeatureState.unknown,
),
];
late MediaQueryData unpadded;
await tester.pumpWidget(
MediaQuery(
data: const MediaQueryData(
size: size,
devicePixelRatio: devicePixelRatio,
textScaler: textScaler,
padding: padding,
viewPadding: viewPadding,
viewInsets: viewInsets,
alwaysUse24HourFormat: true,
accessibleNavigation: true,
invertColors: true,
disableAnimations: true,
boldText: true,
highContrast: true,
onOffSwitchLabels: true,
navigationMode: NavigationMode.directional,
displayFeatures: displayFeatures,
),
child: Builder(
builder: (BuildContext context) {
return MediaQuery.removePadding(
context: context,
removeLeft: true,
removeTop: true,
removeRight: true,
removeBottom: true,
child: Builder(
builder: (BuildContext context) {
unpadded = MediaQuery.of(context);
return Container();
},
),
);
},
),
),
);
expect(unpadded.size, size);
expect(unpadded.devicePixelRatio, devicePixelRatio);
expect(unpadded.textScaler, textScaler);
expect(unpadded.padding, EdgeInsets.zero);
expect(unpadded.viewPadding, viewInsets);
expect(unpadded.viewInsets, viewInsets);
expect(unpadded.alwaysUse24HourFormat, true);
expect(unpadded.accessibleNavigation, true);
expect(unpadded.invertColors, true);
expect(unpadded.disableAnimations, true);
expect(unpadded.boldText, true);
expect(unpadded.highContrast, true);
expect(unpadded.onOffSwitchLabels, true);
expect(unpadded.navigationMode, NavigationMode.directional);
expect(unpadded.displayFeatures, displayFeatures);
});
testWidgets('MediaQuery.removePadding only removes specified padding', (WidgetTester tester) async {
const Size size = Size(2.0, 4.0);
const double devicePixelRatio = 2.0;
const TextScaler textScaler = TextScaler.linear(1.2);
const EdgeInsets padding = EdgeInsets.only(top: 1.0, right: 2.0, left: 3.0, bottom: 4.0);
const EdgeInsets viewPadding = EdgeInsets.only(top: 6.0, right: 8.0, left: 10.0, bottom: 12.0);
const EdgeInsets viewInsets = EdgeInsets.only(top: 5.0, right: 6.0, left: 7.0, bottom: 8.0);
const List<DisplayFeature> displayFeatures = <DisplayFeature>[
DisplayFeature(
bounds: Rect.zero,
type: DisplayFeatureType.cutout,
state: DisplayFeatureState.unknown,
),
];
late MediaQueryData unpadded;
await tester.pumpWidget(
MediaQuery(
data: const MediaQueryData(
size: size,
devicePixelRatio: devicePixelRatio,
textScaler: textScaler,
padding: padding,
viewPadding: viewPadding,
viewInsets: viewInsets,
alwaysUse24HourFormat: true,
accessibleNavigation: true,
invertColors: true,
disableAnimations: true,
boldText: true,
highContrast: true,
onOffSwitchLabels: true,
navigationMode: NavigationMode.directional,
displayFeatures: displayFeatures,
),
child: Builder(
builder: (BuildContext context) {
return MediaQuery.removePadding(
removeTop: true,
context: context,
child: Builder(
builder: (BuildContext context) {
unpadded = MediaQuery.of(context);
return Container();
},
),
);
},
),
),
);
expect(unpadded.size, size);
expect(unpadded.devicePixelRatio, devicePixelRatio);
expect(unpadded.textScaler, textScaler);
expect(unpadded.padding, padding.copyWith(top: 0));
expect(unpadded.viewPadding, viewPadding.copyWith(top: viewInsets.top));
expect(unpadded.viewInsets, viewInsets);
expect(unpadded.alwaysUse24HourFormat, true);
expect(unpadded.accessibleNavigation, true);
expect(unpadded.invertColors, true);
expect(unpadded.disableAnimations, true);
expect(unpadded.boldText, true);
expect(unpadded.highContrast, true);
expect(unpadded.onOffSwitchLabels, true);
expect(unpadded.navigationMode, NavigationMode.directional);
expect(unpadded.displayFeatures, displayFeatures);
});
testWidgets('MediaQuery.removeViewInsets removes specified viewInsets', (WidgetTester tester) async {
const Size size = Size(2.0, 4.0);
const double devicePixelRatio = 2.0;
const TextScaler textScaler = TextScaler.linear(1.2);
const EdgeInsets padding = EdgeInsets.only(top: 5.0, right: 6.0, left: 7.0, bottom: 8.0);
const EdgeInsets viewPadding = EdgeInsets.only(top: 6.0, right: 8.0, left: 10.0, bottom: 12.0);
const EdgeInsets viewInsets = EdgeInsets.only(top: 1.0, right: 2.0, left: 3.0, bottom: 4.0);
const List<DisplayFeature> displayFeatures = <DisplayFeature>[
DisplayFeature(
bounds: Rect.zero,
type: DisplayFeatureType.cutout,
state: DisplayFeatureState.unknown,
),
];
late MediaQueryData unpadded;
await tester.pumpWidget(
MediaQuery(
data: const MediaQueryData(
size: size,
devicePixelRatio: devicePixelRatio,
textScaler: textScaler,
padding: padding,
viewPadding: viewPadding,
viewInsets: viewInsets,
alwaysUse24HourFormat: true,
accessibleNavigation: true,
invertColors: true,
disableAnimations: true,
boldText: true,
highContrast: true,
onOffSwitchLabels: true,
navigationMode: NavigationMode.directional,
displayFeatures: displayFeatures,
),
child: Builder(
builder: (BuildContext context) {
return MediaQuery.removeViewInsets(
context: context,
removeLeft: true,
removeTop: true,
removeRight: true,
removeBottom: true,
child: Builder(
builder: (BuildContext context) {
unpadded = MediaQuery.of(context);
return Container();
},
),
);
},
),
),
);
expect(unpadded.size, size);
expect(unpadded.devicePixelRatio, devicePixelRatio);
expect(unpadded.textScaler, textScaler);
expect(unpadded.padding, padding);
expect(unpadded.viewPadding, padding);
expect(unpadded.viewInsets, EdgeInsets.zero);
expect(unpadded.alwaysUse24HourFormat, true);
expect(unpadded.accessibleNavigation, true);
expect(unpadded.invertColors, true);
expect(unpadded.disableAnimations, true);
expect(unpadded.boldText, true);
expect(unpadded.highContrast, true);
expect(unpadded.onOffSwitchLabels, true);
expect(unpadded.navigationMode, NavigationMode.directional);
expect(unpadded.displayFeatures, displayFeatures);
});
testWidgets('MediaQuery.removeViewInsets removes only specified viewInsets', (WidgetTester tester) async {
const Size size = Size(2.0, 4.0);
const double devicePixelRatio = 2.0;
const TextScaler textScaler = TextScaler.linear(1.2);
const EdgeInsets padding = EdgeInsets.only(top: 5.0, right: 6.0, left: 7.0, bottom: 8.0);
const EdgeInsets viewPadding = EdgeInsets.only(top: 6.0, right: 8.0, left: 10.0, bottom: 12.0);
const EdgeInsets viewInsets = EdgeInsets.only(top: 1.0, right: 2.0, left: 3.0, bottom: 4.0);
const List<DisplayFeature> displayFeatures = <DisplayFeature>[
DisplayFeature(
bounds: Rect.zero,
type: DisplayFeatureType.cutout,
state: DisplayFeatureState.unknown,
),
];
late MediaQueryData unpadded;
await tester.pumpWidget(
MediaQuery(
data: const MediaQueryData(
size: size,
devicePixelRatio: devicePixelRatio,
textScaler: textScaler,
padding: padding,
viewPadding: viewPadding,
viewInsets: viewInsets,
alwaysUse24HourFormat: true,
accessibleNavigation: true,
invertColors: true,
disableAnimations: true,
boldText: true,
highContrast: true,
onOffSwitchLabels: true,
navigationMode: NavigationMode.directional,
displayFeatures: displayFeatures,
),
child: Builder(
builder: (BuildContext context) {
return MediaQuery.removeViewInsets(
context: context,
removeBottom: true,
child: Builder(
builder: (BuildContext context) {
unpadded = MediaQuery.of(context);
return Container();
},
),
);
},
),
),
);
expect(unpadded.size, size);
expect(unpadded.devicePixelRatio, devicePixelRatio);
expect(unpadded.textScaler, textScaler);
expect(unpadded.padding, padding);
expect(unpadded.viewPadding, viewPadding.copyWith(bottom: 8));
expect(unpadded.viewInsets, viewInsets.copyWith(bottom: 0));
expect(unpadded.alwaysUse24HourFormat, true);
expect(unpadded.accessibleNavigation, true);
expect(unpadded.invertColors, true);
expect(unpadded.disableAnimations, true);
expect(unpadded.boldText, true);
expect(unpadded.highContrast, true);
expect(unpadded.onOffSwitchLabels, true);
expect(unpadded.navigationMode, NavigationMode.directional);
expect(unpadded.displayFeatures, displayFeatures);
});
testWidgets('MediaQuery.removeViewPadding removes specified viewPadding', (WidgetTester tester) async {
const Size size = Size(2.0, 4.0);
const double devicePixelRatio = 2.0;
const TextScaler textScaler = TextScaler.linear(1.2);
const EdgeInsets padding = EdgeInsets.only(top: 5.0, right: 6.0, left: 7.0, bottom: 8.0);
const EdgeInsets viewPadding = EdgeInsets.only(top: 6.0, right: 8.0, left: 10.0, bottom: 12.0);
const EdgeInsets viewInsets = EdgeInsets.only(top: 1.0, right: 2.0, left: 3.0, bottom: 4.0);
const List<DisplayFeature> displayFeatures = <DisplayFeature>[
DisplayFeature(
bounds: Rect.zero,
type: DisplayFeatureType.cutout,
state: DisplayFeatureState.unknown,
),
];
late MediaQueryData unpadded;
await tester.pumpWidget(
MediaQuery(
data: const MediaQueryData(
size: size,
devicePixelRatio: devicePixelRatio,
textScaler: textScaler,
padding: padding,
viewPadding: viewPadding,
viewInsets: viewInsets,
alwaysUse24HourFormat: true,
accessibleNavigation: true,
invertColors: true,
disableAnimations: true,
boldText: true,
highContrast: true,
onOffSwitchLabels: true,
navigationMode: NavigationMode.directional,
displayFeatures: displayFeatures,
),
child: Builder(
builder: (BuildContext context) {
return MediaQuery.removeViewPadding(
context: context,
removeLeft: true,
removeTop: true,
removeRight: true,
removeBottom: true,
child: Builder(
builder: (BuildContext context) {
unpadded = MediaQuery.of(context);
return Container();
},
),
);
},
),
),
);
expect(unpadded.size, size);
expect(unpadded.devicePixelRatio, devicePixelRatio);
expect(unpadded.textScaler, textScaler);
expect(unpadded.padding, EdgeInsets.zero);
expect(unpadded.viewPadding, EdgeInsets.zero);
expect(unpadded.viewInsets, viewInsets);
expect(unpadded.alwaysUse24HourFormat, true);
expect(unpadded.accessibleNavigation, true);
expect(unpadded.invertColors, true);
expect(unpadded.disableAnimations, true);
expect(unpadded.boldText, true);
expect(unpadded.highContrast, true);
expect(unpadded.onOffSwitchLabels, true);
expect(unpadded.navigationMode, NavigationMode.directional);
expect(unpadded.displayFeatures, displayFeatures);
});
testWidgets('MediaQuery.removeViewPadding removes only specified viewPadding', (WidgetTester tester) async {
const Size size = Size(2.0, 4.0);
const double devicePixelRatio = 2.0;
const TextScaler textScaler = TextScaler.linear(1.2);
const EdgeInsets padding = EdgeInsets.only(top: 5.0, right: 6.0, left: 7.0, bottom: 8.0);
const EdgeInsets viewPadding = EdgeInsets.only(top: 6.0, right: 8.0, left: 10.0, bottom: 12.0);
const EdgeInsets viewInsets = EdgeInsets.only(top: 1.0, right: 2.0, left: 3.0, bottom: 4.0);
const List<DisplayFeature> displayFeatures = <DisplayFeature>[
DisplayFeature(
bounds: Rect.zero,
type: DisplayFeatureType.cutout,
state: DisplayFeatureState.unknown,
),
];
late MediaQueryData unpadded;
await tester.pumpWidget(
MediaQuery(
data: const MediaQueryData(
size: size,
devicePixelRatio: devicePixelRatio,
textScaler: textScaler,
padding: padding,
viewPadding: viewPadding,
viewInsets: viewInsets,
alwaysUse24HourFormat: true,
accessibleNavigation: true,
invertColors: true,
disableAnimations: true,
boldText: true,
highContrast: true,
onOffSwitchLabels: true,
navigationMode: NavigationMode.directional,
displayFeatures: displayFeatures,
),
child: Builder(
builder: (BuildContext context) {
return MediaQuery.removeViewPadding(
context: context,
removeLeft: true,
child: Builder(
builder: (BuildContext context) {
unpadded = MediaQuery.of(context);
return Container();
},
),
);
},
),
),
);
expect(unpadded.size, size);
expect(unpadded.devicePixelRatio, devicePixelRatio);
expect(unpadded.textScaler, textScaler);
expect(unpadded.padding, padding.copyWith(left: 0));
expect(unpadded.viewPadding, viewPadding.copyWith(left: 0));
expect(unpadded.viewInsets, viewInsets);
expect(unpadded.alwaysUse24HourFormat, true);
expect(unpadded.accessibleNavigation, true);
expect(unpadded.invertColors, true);
expect(unpadded.disableAnimations, true);
expect(unpadded.boldText, true);
expect(unpadded.highContrast, true);
expect(unpadded.onOffSwitchLabels, true);
expect(unpadded.navigationMode, NavigationMode.directional);
expect(unpadded.displayFeatures, displayFeatures);
});
testWidgets('MediaQuery.textScalerOf', (WidgetTester tester) async {
late TextScaler outsideTextScaler;
late TextScaler insideTextScaler;
await tester.pumpWidget(
Builder(
builder: (BuildContext context) {
outsideTextScaler = MediaQuery.textScalerOf(context);
return MediaQuery(
data: const MediaQueryData(
textScaler: TextScaler.linear(4.0),
),
child: Builder(
builder: (BuildContext context) {
insideTextScaler = MediaQuery.textScalerOf(context);
return Container();
},
),
);
},
),
);
expect(outsideTextScaler, TextScaler.noScaling);
expect(insideTextScaler, const TextScaler.linear(4.0));
});
testWidgets('MediaQuery.platformBrightnessOf', (WidgetTester tester) async {
late Brightness outsideBrightness;
late Brightness insideBrightness;
await tester.pumpWidget(
Builder(
builder: (BuildContext context) {
outsideBrightness = MediaQuery.platformBrightnessOf(context);
return MediaQuery(
data: const MediaQueryData(
platformBrightness: Brightness.dark,
),
child: Builder(
builder: (BuildContext context) {
insideBrightness = MediaQuery.platformBrightnessOf(context);
return Container();
},
),
);
},
),
);
expect(outsideBrightness, Brightness.light);
expect(insideBrightness, Brightness.dark);
});
testWidgets('MediaQuery.highContrastOf', (WidgetTester tester) async {
late bool outsideHighContrast;
late bool insideHighContrast;
await tester.pumpWidget(
Builder(
builder: (BuildContext context) {
outsideHighContrast = MediaQuery.highContrastOf(context);
return MediaQuery(
data: const MediaQueryData(
highContrast: true,
),
child: Builder(
builder: (BuildContext context) {
insideHighContrast = MediaQuery.highContrastOf(context);
return Container();
},
),
);
},
),
);
expect(outsideHighContrast, false);
expect(insideHighContrast, true);
});
testWidgets('MediaQuery.onOffSwitchLabelsOf', (WidgetTester tester) async {
late bool outsideOnOffSwitchLabels;
late bool insideOnOffSwitchLabels;
await tester.pumpWidget(
Builder(
builder: (BuildContext context) {
outsideOnOffSwitchLabels = MediaQuery.onOffSwitchLabelsOf(context);
return MediaQuery(
data: const MediaQueryData(
onOffSwitchLabels: true,
),
child: Builder(
builder: (BuildContext context) {
insideOnOffSwitchLabels = MediaQuery.onOffSwitchLabelsOf(context);
return Container();
},
),
);
},
),
);
expect(outsideOnOffSwitchLabels, false);
expect(insideOnOffSwitchLabels, true);
});
testWidgets('MediaQuery.boldTextOf', (WidgetTester tester) async {
late bool outsideBoldTextOverride;
late bool insideBoldTextOverride;
await tester.pumpWidget(
Builder(
builder: (BuildContext context) {
outsideBoldTextOverride = MediaQuery.boldTextOf(context);
return MediaQuery(
data: const MediaQueryData(
boldText: true,
),
child: Builder(
builder: (BuildContext context) {
insideBoldTextOverride = MediaQuery.boldTextOf(context);
return Container();
},
),
);
},
),
);
expect(outsideBoldTextOverride, false);
expect(insideBoldTextOverride, true);
});
testWidgets('MediaQuery.fromView creates a MediaQuery', (WidgetTester tester) async {
MediaQuery? mediaQueryOutside;
MediaQuery? mediaQueryInside;
await tester.pumpWidget(
Builder(
builder: (BuildContext context) {
mediaQueryOutside = context.findAncestorWidgetOfExactType<MediaQuery>();
return MediaQuery.fromView(
view: View.of(context),
child: Builder(
builder: (BuildContext context) {
mediaQueryInside = context.findAncestorWidgetOfExactType<MediaQuery>();
return const SizedBox();
},
),
);
},
),
);
expect(mediaQueryInside, isNotNull);
expect(mediaQueryOutside, isNot(mediaQueryInside));
});
testWidgets('MediaQueryData.fromWindow is created using window values', (WidgetTester tester) async {
final MediaQueryData windowData = MediaQueryData.fromWindow(tester.view);
late MediaQueryData fromWindowData;
await tester.pumpWidget(
MediaQuery.fromWindow(
child: Builder(
builder: (BuildContext context) {
fromWindowData = MediaQuery.of(context);
return const SizedBox();
},
),
),
);
expect(windowData, equals(fromWindowData));
});
test('DeviceGestureSettings has reasonable hashCode', () {
final DeviceGestureSettings settingsA = DeviceGestureSettings(touchSlop: nonconst(16));
final DeviceGestureSettings settingsB = DeviceGestureSettings(touchSlop: nonconst(8));
final DeviceGestureSettings settingsC = DeviceGestureSettings(touchSlop: nonconst(16));
expect(settingsA.hashCode, settingsC.hashCode);
expect(settingsA.hashCode, isNot(settingsB.hashCode));
});
test('DeviceGestureSettings has reasonable equality', () {
final DeviceGestureSettings settingsA = DeviceGestureSettings(touchSlop: nonconst(16));
final DeviceGestureSettings settingsB = DeviceGestureSettings(touchSlop: nonconst(8));
final DeviceGestureSettings settingsC = DeviceGestureSettings(touchSlop: nonconst(16));
expect(settingsA, equals(settingsC));
expect(settingsA, isNot(settingsB));
});
testWidgets('MediaQuery.removeDisplayFeatures removes specified display features and padding', (WidgetTester tester) async {
const Size size = Size(82.0, 40.0);
const double devicePixelRatio = 2.0;
const TextScaler textScaler = TextScaler.linear(1.2);
const EdgeInsets padding = EdgeInsets.only(top: 1.0, right: 2.0, left: 3.0, bottom: 4.0);
const EdgeInsets viewPadding = EdgeInsets.only(top: 6.0, right: 8.0, left: 10.0, bottom: 12.0);
const EdgeInsets viewInsets = EdgeInsets.only(top: 5.0, right: 6.0, left: 7.0, bottom: 8.0);
const List<DisplayFeature> displayFeatures = <DisplayFeature>[
DisplayFeature(
bounds: Rect.fromLTRB(40, 0, 42, 40),
type: DisplayFeatureType.hinge,
state: DisplayFeatureState.postureFlat,
),
DisplayFeature(
bounds: Rect.fromLTRB(70, 10, 74, 14),
type: DisplayFeatureType.cutout,
state: DisplayFeatureState.unknown,
),
];
// A section of the screen that intersects no display feature or padding area
const Rect subScreen = Rect.fromLTRB(20, 10, 40, 20);
late MediaQueryData subScreenMediaQuery;
await tester.pumpWidget(
MediaQuery(
data: const MediaQueryData(
size: size,
devicePixelRatio: devicePixelRatio,
textScaler: textScaler,
padding: padding,
viewPadding: viewPadding,
viewInsets: viewInsets,
alwaysUse24HourFormat: true,
accessibleNavigation: true,
invertColors: true,
disableAnimations: true,
boldText: true,
highContrast: true,
onOffSwitchLabels: true,
displayFeatures: displayFeatures,
),
child: Builder(
builder: (BuildContext context) {
return MediaQuery(
data: MediaQuery.of(context).removeDisplayFeatures(subScreen),
child: Builder(
builder: (BuildContext context) {
subScreenMediaQuery = MediaQuery.of(context);
return Container();
},
),
);
},
),
),
);
expect(subScreenMediaQuery.size, size);
expect(subScreenMediaQuery.devicePixelRatio, devicePixelRatio);
expect(subScreenMediaQuery.textScaler, textScaler);
expect(subScreenMediaQuery.padding, EdgeInsets.zero);
expect(subScreenMediaQuery.viewPadding, EdgeInsets.zero);
expect(subScreenMediaQuery.viewInsets, EdgeInsets.zero);
expect(subScreenMediaQuery.alwaysUse24HourFormat, true);
expect(subScreenMediaQuery.accessibleNavigation, true);
expect(subScreenMediaQuery.invertColors, true);
expect(subScreenMediaQuery.disableAnimations, true);
expect(subScreenMediaQuery.boldText, true);
expect(subScreenMediaQuery.highContrast, true);
expect(subScreenMediaQuery.onOffSwitchLabels, true);
expect(subScreenMediaQuery.displayFeatures, isEmpty);
});
testWidgets('MediaQuery.removePadding only removes specified display features and padding', (WidgetTester tester) async {
const Size size = Size(82.0, 40.0);
const double devicePixelRatio = 2.0;
const TextScaler textScaler = TextScaler.linear(1.2);
const EdgeInsets padding = EdgeInsets.only(top: 1.0, right: 2.0, left: 3.0, bottom: 4.0);
const EdgeInsets viewPadding = EdgeInsets.only(top: 6.0, right: 8.0, left: 46.0, bottom: 12.0);
const EdgeInsets viewInsets = EdgeInsets.only(top: 5.0, right: 6.0, left: 7.0, bottom: 8.0);
const DisplayFeature cutoutDisplayFeature = DisplayFeature(
bounds: Rect.fromLTRB(70, 10, 74, 14),
type: DisplayFeatureType.cutout,
state: DisplayFeatureState.unknown,
);
const List<DisplayFeature> displayFeatures = <DisplayFeature>[
DisplayFeature(
bounds: Rect.fromLTRB(40, 0, 42, 40),
type: DisplayFeatureType.hinge,
state: DisplayFeatureState.postureFlat,
),
cutoutDisplayFeature,
];
// A section of the screen that does contain display features and padding
const Rect subScreen = Rect.fromLTRB(42, 0, 82, 40);
late MediaQueryData subScreenMediaQuery;
await tester.pumpWidget(
MediaQuery(
data: const MediaQueryData(
size: size,
devicePixelRatio: devicePixelRatio,
textScaler: textScaler,
padding: padding,
viewPadding: viewPadding,
viewInsets: viewInsets,
alwaysUse24HourFormat: true,
accessibleNavigation: true,
invertColors: true,
disableAnimations: true,
boldText: true,
highContrast: true,
onOffSwitchLabels: true,
displayFeatures: displayFeatures,
),
child: Builder(
builder: (BuildContext context) {
return MediaQuery(
data: MediaQuery.of(context).removeDisplayFeatures(subScreen),
child: Builder(
builder: (BuildContext context) {
subScreenMediaQuery = MediaQuery.of(context);
return Container();
},
),
);
},
),
),
);
expect(subScreenMediaQuery.size, size);
expect(subScreenMediaQuery.devicePixelRatio, devicePixelRatio);
expect(subScreenMediaQuery.textScaler, textScaler);
expect(
subScreenMediaQuery.padding,
const EdgeInsets.only(top: 1.0, right: 2.0, bottom: 4.0),
);
expect(
subScreenMediaQuery.viewPadding,
const EdgeInsets.only(top: 6.0, left: 4.0, right: 8.0, bottom: 12.0),
);
expect(
subScreenMediaQuery.viewInsets,
const EdgeInsets.only(top: 5.0, right: 6.0, bottom: 8.0),
);
expect(subScreenMediaQuery.alwaysUse24HourFormat, true);
expect(subScreenMediaQuery.accessibleNavigation, true);
expect(subScreenMediaQuery.invertColors, true);
expect(subScreenMediaQuery.disableAnimations, true);
expect(subScreenMediaQuery.boldText, true);
expect(subScreenMediaQuery.highContrast, true);
expect(subScreenMediaQuery.onOffSwitchLabels, true);
expect(subScreenMediaQuery.displayFeatures, <DisplayFeature>[cutoutDisplayFeature]);
});
testWidgets('MediaQueryData.gestureSettings is set from view.gestureSettings', (WidgetTester tester) async {
tester.view.gestureSettings = const GestureSettings(physicalDoubleTapSlop: 100, physicalTouchSlop: 100);
addTearDown(() => tester.view.resetGestureSettings());
expect(MediaQueryData.fromView(tester.view).gestureSettings.touchSlop, closeTo(33.33, 0.1)); // Repeating, of course
});
testWidgets('MediaQuery can be partially depended-on', (WidgetTester tester) async {
MediaQueryData data = const MediaQueryData(
size: Size(800, 600),
textScaler: TextScaler.linear(1.1),
);
int sizeBuildCount = 0;
int textScalerBuildCount = 0;
final Widget showSize = Builder(
builder: (BuildContext context) {
sizeBuildCount++;
return Text('size: ${MediaQuery.sizeOf(context)}');
}
);
final Widget showTextScaler = Builder(
builder: (BuildContext context) {
textScalerBuildCount++;
return Text('textScaler: ${MediaQuery.textScalerOf(context)}');
}
);
final Widget page = StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return MediaQuery(
data: data,
child: Center(
child: Column(
children: <Widget>[
showSize,
showTextScaler,
ElevatedButton(
onPressed: () {
setState(() {
data = data.copyWith(size: Size(data.size.width + 100, data.size.height));
});
},
child: const Text('Increase width by 100')
),
ElevatedButton(
onPressed: () {
setState(() {
data = data.copyWith(textScaler: TextScaler.noScaling);
});
},
child: const Text('Disable text scaling')
)
]
)
)
);
},
);
await tester.pumpWidget(MaterialApp(home: page));
expect(find.text('size: Size(800.0, 600.0)'), findsOneWidget);
expect(find.text('textScaler: linear (1.1x)'), findsOneWidget);
expect(sizeBuildCount, 1);
expect(textScalerBuildCount, 1);
await tester.tap(find.text('Increase width by 100'));
await tester.pumpAndSettle();
expect(find.text('size: Size(900.0, 600.0)'), findsOneWidget);
expect(find.text('textScaler: linear (1.1x)'), findsOneWidget);
expect(sizeBuildCount, 2);
expect(textScalerBuildCount, 1);
await tester.tap(find.text('Disable text scaling'));
await tester.pumpAndSettle();
expect(find.text('size: Size(900.0, 600.0)'), findsOneWidget);
expect(find.text('textScaler: no scaling'), findsOneWidget);
expect(sizeBuildCount, 2);
expect(textScalerBuildCount, 2);
});
testWidgets('MediaQuery partial dependencies', (WidgetTester tester) async {
MediaQueryData data = const MediaQueryData();
int buildCount = 0;
final Widget builder = Builder(
builder: (BuildContext context) {
_MediaQueryAspectVariant.aspect!.method(context);
buildCount++;
return const SizedBox.shrink();
}
);
final Widget page = StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return MediaQuery(
data: data,
child: ListView(
children: <Widget>[
builder,
ElevatedButton(
onPressed: () {
setState(() {
data = _MediaQueryAspectVariant.aspect!.data;
});
},
child: const Text('Change data')
),
ElevatedButton(
onPressed: () {
setState(() {
data = data.copyWith();
});
},
child: const Text('Copy data')
)
]
)
);
},
);
await tester.pumpWidget(MaterialApp(home: page));
expect(buildCount, 1);
await tester.tap(find.text('Copy data'));
await tester.pumpAndSettle();
expect(buildCount, 1);
await tester.tap(find.text('Change data'));
await tester.pumpAndSettle();
expect(buildCount, 2);
await tester.tap(find.text('Copy data'));
await tester.pumpAndSettle();
expect(buildCount, 2);
}, variant: _MediaQueryAspectVariant(
values: <_MediaQueryAspectCase>[
const _MediaQueryAspectCase(MediaQuery.sizeOf, MediaQueryData(size: Size(1, 1))),
const _MediaQueryAspectCase(MediaQuery.maybeSizeOf, MediaQueryData(size: Size(1, 1))),
const _MediaQueryAspectCase(MediaQuery.orientationOf, MediaQueryData(size: Size(2, 1))),
const _MediaQueryAspectCase(MediaQuery.maybeOrientationOf, MediaQueryData(size: Size(2, 1))),
const _MediaQueryAspectCase(MediaQuery.devicePixelRatioOf, MediaQueryData(devicePixelRatio: 1.1)),
const _MediaQueryAspectCase(MediaQuery.maybeDevicePixelRatioOf, MediaQueryData(devicePixelRatio: 1.1)),
const _MediaQueryAspectCase(MediaQuery.textScaleFactorOf, MediaQueryData(textScaleFactor: 1.1)),
const _MediaQueryAspectCase(MediaQuery.maybeTextScaleFactorOf, MediaQueryData(textScaleFactor: 1.1)),
const _MediaQueryAspectCase(MediaQuery.textScalerOf, MediaQueryData(textScaler: TextScaler.linear(1.1))),
const _MediaQueryAspectCase(MediaQuery.maybeTextScalerOf, MediaQueryData(textScaler: TextScaler.linear(1.1))),
const _MediaQueryAspectCase(MediaQuery.platformBrightnessOf, MediaQueryData(platformBrightness: Brightness.dark)),
const _MediaQueryAspectCase(MediaQuery.maybePlatformBrightnessOf, MediaQueryData(platformBrightness: Brightness.dark)),
const _MediaQueryAspectCase(MediaQuery.paddingOf, MediaQueryData(padding: EdgeInsets.all(1))),
const _MediaQueryAspectCase(MediaQuery.maybePaddingOf, MediaQueryData(padding: EdgeInsets.all(1))),
const _MediaQueryAspectCase(MediaQuery.viewInsetsOf, MediaQueryData(viewInsets: EdgeInsets.all(1))),
const _MediaQueryAspectCase(MediaQuery.maybeViewInsetsOf, MediaQueryData(viewInsets: EdgeInsets.all(1))),
const _MediaQueryAspectCase(MediaQuery.systemGestureInsetsOf, MediaQueryData(systemGestureInsets: EdgeInsets.all(1))),
const _MediaQueryAspectCase(MediaQuery.maybeSystemGestureInsetsOf, MediaQueryData(systemGestureInsets: EdgeInsets.all(1))),
const _MediaQueryAspectCase(MediaQuery.viewPaddingOf, MediaQueryData(viewPadding: EdgeInsets.all(1))),
const _MediaQueryAspectCase(MediaQuery.maybeViewPaddingOf, MediaQueryData(viewPadding: EdgeInsets.all(1))),
const _MediaQueryAspectCase(MediaQuery.alwaysUse24HourFormatOf, MediaQueryData(alwaysUse24HourFormat: true)),
const _MediaQueryAspectCase(MediaQuery.maybeAlwaysUse24HourFormatOf, MediaQueryData(alwaysUse24HourFormat: true)),
const _MediaQueryAspectCase(MediaQuery.accessibleNavigationOf, MediaQueryData(accessibleNavigation: true)),
const _MediaQueryAspectCase(MediaQuery.maybeAccessibleNavigationOf, MediaQueryData(accessibleNavigation: true)),
const _MediaQueryAspectCase(MediaQuery.invertColorsOf, MediaQueryData(invertColors: true)),
const _MediaQueryAspectCase(MediaQuery.maybeInvertColorsOf, MediaQueryData(invertColors: true)),
const _MediaQueryAspectCase(MediaQuery.highContrastOf, MediaQueryData(highContrast: true)),
const _MediaQueryAspectCase(MediaQuery.maybeHighContrastOf, MediaQueryData(highContrast: true)),
const _MediaQueryAspectCase(MediaQuery.onOffSwitchLabelsOf, MediaQueryData(onOffSwitchLabels: true)),
const _MediaQueryAspectCase(MediaQuery.maybeOnOffSwitchLabelsOf, MediaQueryData(onOffSwitchLabels: true)),
const _MediaQueryAspectCase(MediaQuery.disableAnimationsOf, MediaQueryData(disableAnimations: true)),
const _MediaQueryAspectCase(MediaQuery.maybeDisableAnimationsOf, MediaQueryData(disableAnimations: true)),
const _MediaQueryAspectCase(MediaQuery.boldTextOf, MediaQueryData(boldText: true)),
const _MediaQueryAspectCase(MediaQuery.maybeBoldTextOf, MediaQueryData(boldText: true)),
const _MediaQueryAspectCase(MediaQuery.navigationModeOf, MediaQueryData(navigationMode: NavigationMode.directional)),
const _MediaQueryAspectCase(MediaQuery.maybeNavigationModeOf, MediaQueryData(navigationMode: NavigationMode.directional)),
const _MediaQueryAspectCase(MediaQuery.gestureSettingsOf, MediaQueryData(gestureSettings: DeviceGestureSettings(touchSlop: 1))),
const _MediaQueryAspectCase(MediaQuery.maybeGestureSettingsOf, MediaQueryData(gestureSettings: DeviceGestureSettings(touchSlop: 1))),
const _MediaQueryAspectCase(MediaQuery.displayFeaturesOf, MediaQueryData(displayFeatures: <DisplayFeature>[DisplayFeature(bounds: Rect.zero, type: DisplayFeatureType.unknown, state: DisplayFeatureState.unknown)])),
const _MediaQueryAspectCase(MediaQuery.maybeDisplayFeaturesOf, MediaQueryData(displayFeatures: <DisplayFeature>[DisplayFeature(bounds: Rect.zero, type: DisplayFeatureType.unknown, state: DisplayFeatureState.unknown)])),
]
));
}
| flutter/packages/flutter/test/widgets/media_query_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/media_query_test.dart",
"repo_id": "flutter",
"token_count": 24541
} | 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/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
class MyNotification extends Notification { }
void main() {
testWidgets('Notification basics - toString', (WidgetTester tester) async {
expect(MyNotification(), hasOneLineDescription);
});
testWidgets('Notification basics - dispatch', (WidgetTester tester) async {
final List<dynamic> log = <dynamic>[];
final GlobalKey key = GlobalKey();
await tester.pumpWidget(NotificationListener<MyNotification>(
onNotification: (MyNotification value) {
log.add('a');
log.add(value);
return true;
},
child: NotificationListener<MyNotification>(
onNotification: (MyNotification value) {
log.add('b');
log.add(value);
return false;
},
child: Container(key: key),
),
));
expect(log, isEmpty);
final Notification notification = MyNotification();
expect(() { notification.dispatch(key.currentContext); }, isNot(throwsException));
expect(log, <dynamic>['b', notification, 'a', notification]);
});
testWidgets('Notification basics - cancel', (WidgetTester tester) async {
final List<dynamic> log = <dynamic>[];
final GlobalKey key = GlobalKey();
await tester.pumpWidget(NotificationListener<MyNotification>(
onNotification: (MyNotification value) {
log.add('a - error');
log.add(value);
return true;
},
child: NotificationListener<MyNotification>(
onNotification: (MyNotification value) {
log.add('b');
log.add(value);
return true;
},
child: Container(key: key),
),
));
expect(log, isEmpty);
final Notification notification = MyNotification();
expect(() { notification.dispatch(key.currentContext); }, isNot(throwsException));
expect(log, <dynamic>['b', notification]);
});
testWidgets('Notification basics - listener null return value', (WidgetTester tester) async {
final List<Type> log = <Type>[];
final GlobalKey key = GlobalKey();
await tester.pumpWidget(NotificationListener<MyNotification>(
onNotification: (MyNotification value) {
log.add(value.runtimeType);
return false;
},
child: NotificationListener<MyNotification>(
onNotification: (MyNotification value) => false,
child: Container(key: key),
),
));
expect(() { MyNotification().dispatch(key.currentContext); }, isNot(throwsException));
expect(log, <Type>[MyNotification]);
});
testWidgets('Notification basics - listener null return value', (WidgetTester tester) async {
await tester.pumpWidget(const Placeholder());
final ScrollMetricsNotification n1 = ScrollMetricsNotification(
metrics: FixedScrollMetrics(
minScrollExtent: 1.0,
maxScrollExtent: 2.0,
pixels: 3.0,
viewportDimension: 4.0,
axisDirection: AxisDirection.down,
devicePixelRatio: 5.0,
),
context: tester.allElements.first,
);
expect(n1.metrics.pixels, 3.0);
final ScrollUpdateNotification n2 = n1.asScrollUpdate();
expect(n2.metrics.pixels, 3.0);
});
}
| flutter/packages/flutter/test/widgets/notification_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/notification_test.dart",
"repo_id": "flutter",
"token_count": 1274
} | 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';
Size pageSize = const Size(600.0, 300.0);
const List<int> defaultPages = <int>[0, 1, 2, 3, 4, 5];
final List<GlobalKey> globalKeys = defaultPages.map<GlobalKey>((_) => GlobalKey()).toList();
int? currentPage;
Widget buildPage(int page) {
return SizedBox(
key: globalKeys[page],
width: pageSize.width,
height: pageSize.height,
child: Text(page.toString()),
);
}
Widget buildFrame({
bool reverse = false,
List<int> pages = defaultPages,
required TextDirection textDirection,
}) {
final PageView child = PageView(
reverse: reverse,
onPageChanged: (int page) { currentPage = page; },
children: pages.map<Widget>(buildPage).toList(),
);
// The test framework forces the frame to be 800x600, so we need to create
// an outer container where we can change the size.
return Directionality(
textDirection: textDirection,
child: Center(
child: SizedBox(
width: pageSize.width, height: pageSize.height, child: child,
),
),
);
}
Future<void> page(WidgetTester tester, Offset offset) {
return TestAsyncUtils.guard(() async {
final String itemText = currentPage != null ? currentPage.toString() : '0';
await tester.drag(find.text(itemText), offset);
await tester.pumpAndSettle();
});
}
Future<void> pageLeft(WidgetTester tester) {
return page(tester, Offset(-pageSize.width, 0.0));
}
Future<void> pageRight(WidgetTester tester) {
return page(tester, Offset(pageSize.width, 0.0));
}
void main() {
testWidgets('PageView default control', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: PageView(),
),
),
);
});
testWidgets('PageView control test (LTR)', (WidgetTester tester) async {
currentPage = null;
await tester.pumpWidget(buildFrame(textDirection: TextDirection.ltr));
expect(currentPage, isNull);
await pageLeft(tester);
expect(currentPage, equals(1));
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
expect(find.text('2'), findsNothing);
expect(find.text('3'), findsNothing);
expect(find.text('4'), findsNothing);
expect(find.text('5'), findsNothing);
await pageRight(tester);
expect(currentPage, equals(0));
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
expect(find.text('2'), findsNothing);
expect(find.text('3'), findsNothing);
expect(find.text('4'), findsNothing);
expect(find.text('5'), findsNothing);
await pageRight(tester);
expect(currentPage, equals(0));
});
testWidgets('PageView with reverse (LTR)', (WidgetTester tester) async {
currentPage = null;
await tester.pumpWidget(buildFrame(reverse: true, textDirection: TextDirection.ltr));
await pageRight(tester);
expect(currentPage, equals(1));
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
expect(find.text('2'), findsNothing);
expect(find.text('3'), findsNothing);
expect(find.text('4'), findsNothing);
expect(find.text('5'), findsNothing);
await pageLeft(tester);
expect(currentPage, equals(0));
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
expect(find.text('2'), findsNothing);
expect(find.text('3'), findsNothing);
expect(find.text('4'), findsNothing);
expect(find.text('5'), findsNothing);
await pageLeft(tester);
expect(currentPage, equals(0));
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
expect(find.text('2'), findsNothing);
expect(find.text('3'), findsNothing);
expect(find.text('4'), findsNothing);
expect(find.text('5'), findsNothing);
});
testWidgets('PageView control test (RTL)', (WidgetTester tester) async {
currentPage = null;
await tester.pumpWidget(buildFrame(textDirection: TextDirection.rtl));
await pageRight(tester);
expect(currentPage, equals(1));
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
expect(find.text('2'), findsNothing);
expect(find.text('3'), findsNothing);
expect(find.text('4'), findsNothing);
expect(find.text('5'), findsNothing);
await pageLeft(tester);
expect(currentPage, equals(0));
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
expect(find.text('2'), findsNothing);
expect(find.text('3'), findsNothing);
expect(find.text('4'), findsNothing);
expect(find.text('5'), findsNothing);
await pageLeft(tester);
expect(currentPage, equals(0));
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
expect(find.text('2'), findsNothing);
expect(find.text('3'), findsNothing);
expect(find.text('4'), findsNothing);
expect(find.text('5'), findsNothing);
});
testWidgets('PageView with reverse (RTL)', (WidgetTester tester) async {
currentPage = null;
await tester.pumpWidget(buildFrame(reverse: true, textDirection: TextDirection.rtl));
expect(currentPage, isNull);
await pageLeft(tester);
expect(currentPage, equals(1));
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
expect(find.text('2'), findsNothing);
expect(find.text('3'), findsNothing);
expect(find.text('4'), findsNothing);
expect(find.text('5'), findsNothing);
await pageRight(tester);
expect(currentPage, equals(0));
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
expect(find.text('2'), findsNothing);
expect(find.text('3'), findsNothing);
expect(find.text('4'), findsNothing);
expect(find.text('5'), findsNothing);
await pageRight(tester);
expect(currentPage, equals(0));
});
}
| flutter/packages/flutter/test/widgets/pageable_list_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/pageable_list_test.dart",
"repo_id": "flutter",
"token_count": 2201
} | 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 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
// This is a regression test for https://github.com/flutter/flutter/issues/5588.
class OrderSwitcher extends StatefulWidget {
const OrderSwitcher({
super.key,
required this.a,
required this.b,
});
final Widget a;
final Widget b;
@override
OrderSwitcherState createState() => OrderSwitcherState();
}
class OrderSwitcherState extends State<OrderSwitcher> {
bool _aFirst = true;
void switchChildren() {
setState(() {
_aFirst = false;
});
}
@override
Widget build(BuildContext context) {
return Stack(
textDirection: TextDirection.ltr,
children: _aFirst
? <Widget>[
KeyedSubtree(child: widget.a),
widget.b,
]
: <Widget>[
KeyedSubtree(child: widget.b),
widget.a,
],
);
}
}
class DummyStatefulWidget extends StatefulWidget {
const DummyStatefulWidget(Key? key) : super(key: key);
@override
DummyStatefulWidgetState createState() => DummyStatefulWidgetState();
}
class DummyStatefulWidgetState extends State<DummyStatefulWidget> {
@override
Widget build(BuildContext context) => const Text('LEAF', textDirection: TextDirection.ltr);
}
class RekeyableDummyStatefulWidgetWrapper extends StatefulWidget {
const RekeyableDummyStatefulWidgetWrapper({
super.key,
required this.initialKey,
});
final GlobalKey initialKey;
@override
RekeyableDummyStatefulWidgetWrapperState createState() => RekeyableDummyStatefulWidgetWrapperState();
}
class RekeyableDummyStatefulWidgetWrapperState extends State<RekeyableDummyStatefulWidgetWrapper> {
GlobalKey? _key;
@override
void initState() {
super.initState();
_key = widget.initialKey;
}
void _setChild(GlobalKey? value) {
setState(() {
_key = value;
});
}
@override
Widget build(BuildContext context) {
return DummyStatefulWidget(_key);
}
}
void main() {
testWidgets('Handle GlobalKey reparenting in weird orders', (WidgetTester tester) async {
// This is a bit of a weird test so let's try to explain it a bit.
//
// Basically what's happening here is that we have a complicated tree, and
// in one frame, we change it to a slightly different tree with a specific
// set of mutations:
//
// * The keyA subtree is regrafted to be one level higher, but later than
// the keyB subtree.
// * The keyB subtree is, similarly, moved one level deeper, but earlier, than
// the keyA subtree.
// * The keyD subtree is replaced by the previously earlier and shallower
// keyC subtree. This happens during a LayoutBuilder layout callback, so it
// happens long after A and B have finished their dance.
//
// The net result is that when keyC is moved, it has already been marked
// dirty from being removed then reinserted into the tree (redundantly, as
// it turns out, though this isn't known at the time), and has already been
// visited once by the code that tries to clean nodes (though at that point
// nothing happens since it isn't in the tree).
//
// This test verifies that none of the asserts go off during this dance.
final GlobalKey<OrderSwitcherState> keyRoot = GlobalKey(debugLabel: 'Root');
final GlobalKey keyA = GlobalKey(debugLabel: 'A');
final GlobalKey keyB = GlobalKey(debugLabel: 'B');
final GlobalKey keyC = GlobalKey(debugLabel: 'C');
final GlobalKey keyD = GlobalKey(debugLabel: 'D');
await tester.pumpWidget(OrderSwitcher(
key: keyRoot,
a: KeyedSubtree(
key: keyA,
child: RekeyableDummyStatefulWidgetWrapper(
initialKey: keyC,
),
),
b: KeyedSubtree(
key: keyB,
child: Builder(
builder: (BuildContext context) {
return Builder(
builder: (BuildContext context) {
return Builder(
builder: (BuildContext context) {
return LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
return RekeyableDummyStatefulWidgetWrapper(
initialKey: keyD,
);
},
);
},
);
},
);
},
),
),
));
expect(find.byKey(keyA), findsOneWidget);
expect(find.byKey(keyB), findsOneWidget);
expect(find.byKey(keyC), findsOneWidget);
expect(find.byKey(keyD), findsOneWidget);
expect(find.byType(RekeyableDummyStatefulWidgetWrapper), findsNWidgets(2));
expect(find.byType(DummyStatefulWidget), findsNWidgets(2));
keyRoot.currentState!.switchChildren();
final List<State> states = tester.stateList(find.byType(RekeyableDummyStatefulWidgetWrapper)).toList();
final RekeyableDummyStatefulWidgetWrapperState a = states[0] as RekeyableDummyStatefulWidgetWrapperState;
a._setChild(null);
final RekeyableDummyStatefulWidgetWrapperState b = states[1] as RekeyableDummyStatefulWidgetWrapperState;
b._setChild(keyC);
await tester.pump();
expect(find.byKey(keyA), findsOneWidget);
expect(find.byKey(keyB), findsOneWidget);
expect(find.byKey(keyC), findsOneWidget);
expect(find.byKey(keyD), findsNothing);
expect(find.byType(RekeyableDummyStatefulWidgetWrapper), findsNWidgets(2));
expect(find.byType(DummyStatefulWidget), findsNWidgets(2));
});
}
| flutter/packages/flutter/test/widgets/reparent_state_harder_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/reparent_state_harder_test.dart",
"repo_id": "flutter",
"token_count": 2208
} | 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/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Padding RTL', (WidgetTester tester) async {
const Widget child = Padding(
padding: EdgeInsetsDirectional.only(start: 10.0),
child: Placeholder(),
);
await tester.pumpWidget(const Directionality(
textDirection: TextDirection.ltr,
child: child,
));
expect(tester.getTopLeft(find.byType(Placeholder)), const Offset(10.0, 0.0));
await tester.pumpWidget(const Directionality(
textDirection: TextDirection.rtl,
child: child,
));
expect(tester.getTopLeft(find.byType(Placeholder)), Offset.zero);
await tester.pumpWidget(
const Padding(
key: GlobalObjectKey<State<StatefulWidget>>(Object()),
padding: EdgeInsets.only(left: 1.0),
),
);
await tester.pumpWidget(const Directionality(
textDirection: TextDirection.rtl,
child: Padding(
key: GlobalObjectKey<State<StatefulWidget>>(Object()),
padding: EdgeInsetsDirectional.only(start: 1.0),
),
));
await tester.pumpWidget(
const Padding(
key: GlobalObjectKey<State<StatefulWidget>>(Object()),
padding: EdgeInsets.only(left: 1.0),
),
);
});
testWidgets('Container padding/margin RTL', (WidgetTester tester) async {
final Widget child = Container(
padding: const EdgeInsetsDirectional.only(start: 6.0),
margin: const EdgeInsetsDirectional.only(end: 20.0, start: 4.0),
child: const Placeholder(),
);
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: child,
));
expect(tester.getTopLeft(find.byType(Placeholder)), const Offset(10.0, 0.0));
expect(tester.getTopRight(find.byType(Placeholder)), const Offset(780.0, 0.0));
await tester.pumpWidget(Directionality(
textDirection: TextDirection.rtl,
child: child,
));
expect(tester.getTopLeft(find.byType(Placeholder)), const Offset(20.0, 0.0));
expect(tester.getTopRight(find.byType(Placeholder)), const Offset(790.0, 0.0));
});
testWidgets('Container padding/margin mixed RTL/absolute', (WidgetTester tester) async {
final Widget child = Container(
padding: const EdgeInsets.only(left: 6.0),
margin: const EdgeInsetsDirectional.only(end: 20.0, start: 4.0),
child: const Placeholder(),
);
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: child,
));
expect(tester.getTopLeft(find.byType(Placeholder)), const Offset(10.0, 0.0));
expect(tester.getTopRight(find.byType(Placeholder)), const Offset(780.0, 0.0));
await tester.pumpWidget(Directionality(
textDirection: TextDirection.rtl,
child: child,
));
expect(tester.getTopLeft(find.byType(Placeholder)), const Offset(26.0, 0.0));
expect(tester.getTopRight(find.byType(Placeholder)), const Offset(796.0, 0.0));
});
testWidgets('EdgeInsetsDirectional without Directionality', (WidgetTester tester) async {
await tester.pumpWidget(const Padding(padding: EdgeInsetsDirectional.zero));
expect(tester.takeException(), isAssertionError);
});
}
| flutter/packages/flutter/test/widgets/rtl_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/rtl_test.dart",
"repo_id": "flutter",
"token_count": 1323
} | 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 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'test_widgets.dart';
void main() {
testWidgets('simultaneously dispose a widget and end the scroll animation', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: FlipWidget(
left: ListView(children: List<Widget>.generate(250, (int i) => Text('$i'))),
right: Container(),
),
),
);
await tester.fling(find.byType(ListView), const Offset(0.0, -200.0), 1000.0);
await tester.pump();
tester.state<FlipWidgetState>(find.byType(FlipWidget)).flip();
await tester.pump(const Duration(hours: 5));
});
testWidgets('Disposing a (nested) Scrollable while holding in overscroll does not crash', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/27707.
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
final Key outerContainer = GlobalKey();
await tester.pumpWidget(
MaterialApp(
home: Center(
child: Container(
key: outerContainer,
color: Colors.purple,
width: 400.0,
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: SizedBox(
width: 500.0,
child: ListView.builder(
controller: controller,
itemBuilder: (BuildContext context, int index) {
return Container(
color: index.isEven ? Colors.red : Colors.green,
height: 200.0,
child: Text('Hello $index'),
);
},
),
),
),
),
),
),
);
// Go into overscroll.
double lastScrollOffset;
await tester.fling(find.text('Hello 0'), const Offset(0.0, 1000.0), 1000.0);
await tester.pump(const Duration(milliseconds: 100));
expect(lastScrollOffset = controller.offset, lessThan(0.0));
// Reduce the overscroll a little, but don't let it go back to 0.0.
await tester.pump(const Duration(milliseconds: 100));
expect(controller.offset, greaterThan(lastScrollOffset));
expect(controller.offset, lessThan(0.0));
final double currentOffset = controller.offset;
// Start a hold activity by putting one pointer down.
final TestGesture gesture = await tester.startGesture(tester.getTopLeft(find.byKey(outerContainer)) + const Offset(50.0, 50.0));
await tester.pumpAndSettle(); // This shouldn't change the scroll offset because of the down event above.
expect(controller.offset, currentOffset);
// Dispose the scrollables while the finger is still down, this should not crash.
await tester.pumpWidget(
MaterialApp(
home: Container(),
),
);
await tester.pumpAndSettle();
expect(controller.hasClients, isFalse);
// Finish gesture to release resources.
await gesture.up();
await tester.pumpAndSettle();
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }));
}
| flutter/packages/flutter/test/widgets/scrollable_dispose_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/scrollable_dispose_test.dart",
"repo_id": "flutter",
"token_count": 1386
} | 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 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
Future<void> pumpContainer(WidgetTester tester, Widget child) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: DefaultSelectionStyle(
selectionColor: Colors.red,
child: child,
),
),
);
}
testWidgets('updates its registrar and delegate based on the number of selectables', (WidgetTester tester) async {
final TestSelectionRegistrar registrar = TestSelectionRegistrar();
final TestContainerDelegate delegate = TestContainerDelegate();
addTearDown(delegate.dispose);
await pumpContainer(
tester,
SelectionContainer(
registrar: registrar,
delegate: delegate,
child: const Column(
children: <Widget>[
Text('column1', textDirection: TextDirection.ltr),
Text('column2', textDirection: TextDirection.ltr),
Text('column3', textDirection: TextDirection.ltr),
],
),
),
);
await tester.pumpAndSettle();
expect(registrar.selectables.length, 1);
expect(delegate.selectables.length, 3);
});
testWidgets('disabled container', (WidgetTester tester) async {
final TestSelectionRegistrar registrar = TestSelectionRegistrar();
final TestContainerDelegate delegate = TestContainerDelegate();
addTearDown(delegate.dispose);
await pumpContainer(
tester,
SelectionContainer(
registrar: registrar,
delegate: delegate,
child: const SelectionContainer.disabled(
child: Column(
children: <Widget>[
Text('column1', textDirection: TextDirection.ltr),
Text('column2', textDirection: TextDirection.ltr),
Text('column3', textDirection: TextDirection.ltr),
],
),
),
),
);
expect(registrar.selectables.length, 0);
expect(delegate.selectables.length, 0);
});
testWidgets('Swapping out container delegate does not crash', (WidgetTester tester) async {
final TestSelectionRegistrar registrar = TestSelectionRegistrar();
final TestContainerDelegate delegate = TestContainerDelegate();
addTearDown(delegate.dispose);
final TestContainerDelegate childDelegate = TestContainerDelegate();
addTearDown(childDelegate.dispose);
await pumpContainer(
tester,
SelectionContainer(
registrar: registrar,
delegate: delegate,
child: Builder(
builder: (BuildContext context) {
return SelectionContainer(
registrar: SelectionContainer.maybeOf(context),
delegate: childDelegate,
child: const Text('dummy'),
);
},
)
),
);
await tester.pumpAndSettle();
expect(registrar.selectables.length, 1);
expect(delegate.value.hasContent, isTrue);
final TestContainerDelegate newDelegate = TestContainerDelegate();
addTearDown(newDelegate.dispose);
await pumpContainer(
tester,
SelectionContainer(
registrar: registrar,
delegate: delegate,
child: Builder(
builder: (BuildContext context) {
return SelectionContainer(
registrar: SelectionContainer.maybeOf(context),
delegate: newDelegate,
child: const Text('dummy'),
);
},
)
),
);
await tester.pumpAndSettle();
expect(registrar.selectables.length, 1);
expect(delegate.value.hasContent, isTrue);
expect(tester.takeException(), isNull);
});
testWidgets('Can update within one frame', (WidgetTester tester) async {
final TestSelectionRegistrar registrar = TestSelectionRegistrar();
final TestContainerDelegate delegate = TestContainerDelegate();
addTearDown(delegate.dispose);
final TestContainerDelegate childDelegate = TestContainerDelegate();
addTearDown(childDelegate.dispose);
await pumpContainer(
tester,
SelectionContainer(
registrar: registrar,
delegate: delegate,
child: Builder(
builder: (BuildContext context) {
return SelectionContainer(
registrar: SelectionContainer.maybeOf(context),
delegate: childDelegate,
child: const Text('dummy'),
);
},
)
),
);
await tester.pump();
// Should finish update after flushing the micro tasks.
await tester.idle();
expect(registrar.selectables.length, 1);
expect(delegate.value.hasContent, isTrue);
});
testWidgets('selection container registers itself if there is a selectable child', (WidgetTester tester) async {
final TestSelectionRegistrar registrar = TestSelectionRegistrar();
final TestContainerDelegate delegate = TestContainerDelegate();
addTearDown(delegate.dispose);
await pumpContainer(
tester,
SelectionContainer(
registrar: registrar,
delegate: delegate,
child: const Column(
),
),
);
expect(registrar.selectables.length, 0);
await pumpContainer(
tester,
SelectionContainer(
registrar: registrar,
delegate: delegate,
child: const Column(
children: <Widget>[
Text('column1', textDirection: TextDirection.ltr),
],
),
),
);
await tester.pumpAndSettle();
expect(registrar.selectables.length, 1);
await pumpContainer(
tester,
SelectionContainer(
registrar: registrar,
delegate: delegate,
child: const Column(
),
),
);
await tester.pumpAndSettle();
expect(registrar.selectables.length, 0);
});
testWidgets('selection container gets registrar from context if not provided', (WidgetTester tester) async {
final TestSelectionRegistrar registrar = TestSelectionRegistrar();
final TestContainerDelegate delegate = TestContainerDelegate();
addTearDown(delegate.dispose);
await pumpContainer(
tester,
SelectionRegistrarScope(
registrar: registrar,
child: SelectionContainer(
delegate: delegate,
child: const Column(
children: <Widget>[
Text('column1', textDirection: TextDirection.ltr),
],
),
),
),
);
await tester.pumpAndSettle();
expect(registrar.selectables.length, 1);
});
}
class TestContainerDelegate extends MultiSelectableSelectionContainerDelegate {
@override
SelectionResult dispatchSelectionEventToChild(Selectable selectable, SelectionEvent event) {
throw UnimplementedError();
}
@override
void ensureChildUpdated(Selectable selectable) {
throw UnimplementedError();
}
}
class TestSelectionRegistrar extends SelectionRegistrar {
final Set<Selectable> selectables = <Selectable>{};
@override
void add(Selectable selectable) => selectables.add(selectable);
@override
void remove(Selectable selectable) => selectables.remove(selectable);
}
| flutter/packages/flutter/test/widgets/selection_container_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/selection_container_test.dart",
"repo_id": "flutter",
"token_count": 2926
} | 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/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'semantics_tester.dart';
void main() {
testWidgets('Un-layouted RenderObject in keep alive offstage area do not crash semantics compiler', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/20313.
final SemanticsTester semantics = SemanticsTester(tester);
const String initialLabel = 'Foo';
const double bottomScrollOffset = 3000.0;
final ScrollController controller = ScrollController(initialScrollOffset: bottomScrollOffset);
addTearDown(controller.dispose);
await tester.pumpWidget(_buildTestWidget(
extraPadding: false,
text: initialLabel,
controller: controller,
));
await tester.pumpAndSettle();
// The ProblemWidget has been instantiated (it is on screen).
expect(tester.widgetList(find.widgetWithText(ProblemWidget, initialLabel)), hasLength(1));
expect(semantics, includesNodeWith(label: initialLabel));
controller.jumpTo(0.0);
await tester.pumpAndSettle();
// The ProblemWidget is not on screen...
expect(tester.widgetList(find.widgetWithText(ProblemWidget, initialLabel)), hasLength(0));
// ... but still in the tree as offstage.
expect(tester.widgetList(find.widgetWithText(ProblemWidget, initialLabel, skipOffstage: false)), hasLength(1));
expect(semantics, isNot(includesNodeWith(label: initialLabel)));
// Introduce a new Padding widget to offstage subtree that will not get its
// size calculated because it's offstage.
await tester.pumpWidget(_buildTestWidget(
extraPadding: true,
text: initialLabel,
controller: controller,
));
final RenderPadding renderPadding = tester.renderObject(find.byKey(paddingWidget, skipOffstage: false));
expect(renderPadding.hasSize, isFalse);
expect(semantics, isNot(includesNodeWith(label: initialLabel)));
// Change the semantics of the offstage ProblemWidget without crashing.
const String newLabel = 'Bar';
expect(newLabel, isNot(equals(initialLabel)));
await tester.pumpWidget(_buildTestWidget(
extraPadding: true,
text: newLabel,
controller: controller,
));
// The label has changed.
expect(tester.widgetList(find.widgetWithText(ProblemWidget, initialLabel, skipOffstage: false)), hasLength(0));
expect(tester.widgetList(find.widgetWithText(ProblemWidget, newLabel, skipOffstage: false)), hasLength(1));
expect(semantics, isNot(includesNodeWith(label: initialLabel)));
expect(semantics, isNot(includesNodeWith(label: newLabel)));
// Bringing the offstage node back on the screen produces correct semantics tree.
controller.jumpTo(bottomScrollOffset);
await tester.pumpAndSettle();
expect(tester.widgetList(find.widgetWithText(ProblemWidget, initialLabel)), hasLength(0));
expect(tester.widgetList(find.widgetWithText(ProblemWidget, newLabel)), hasLength(1));
expect(semantics, isNot(includesNodeWith(label: initialLabel)));
expect(semantics, includesNodeWith(label: newLabel));
semantics.dispose();
});
}
final Key paddingWidget = GlobalKey();
Widget _buildTestWidget({
required bool extraPadding,
required String text,
required ScrollController controller,
}) {
return MaterialApp(
home: Scaffold(
body: Column(
children: <Widget>[
Expanded(
child: Container(),
),
SizedBox(
height: 500.0,
child: ListView(
controller: controller,
children: List<Widget>.generate(10, (int i) {
return Container(
color: i.isEven ? Colors.red : Colors.blue,
height: 250.0,
child: Text('Item $i'),
);
})..add(ProblemWidget(
extraPadding: extraPadding,
text: text,
)),
),
),
Expanded(
child: Container(),
),
],
),
),
);
}
class ProblemWidget extends StatefulWidget {
const ProblemWidget({
super.key,
required this.extraPadding,
required this.text,
});
final bool extraPadding;
final String text;
@override
State<ProblemWidget> createState() => ProblemWidgetState();
}
class ProblemWidgetState extends State<ProblemWidget> with AutomaticKeepAliveClientMixin<ProblemWidget> {
@override
Widget build(BuildContext context) {
super.build(context);
Widget child = Semantics(
container: true,
child: Text(widget.text),
);
if (widget.extraPadding) {
child = Semantics(
container: true,
child: Padding(
key: paddingWidget,
padding: const EdgeInsets.all(20.0),
child: child,
),
);
}
return child;
}
@override
bool get wantKeepAlive => true;
}
| flutter/packages/flutter/test/widgets/semantics_keep_alive_offstage_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/semantics_keep_alive_offstage_test.dart",
"repo_id": "flutter",
"token_count": 1895
} | 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 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('SharedAppData basics', (WidgetTester tester) async {
int columnBuildCount = 0;
int child1BuildCount = 0;
int child2BuildCount = 0;
late void Function(BuildContext context) setSharedAppDataValue;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: SharedAppData(
child: Builder(
builder: (BuildContext context) {
columnBuildCount += 1;
return GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () {
setSharedAppDataValue.call(context);
},
child: Column(
children: <Widget>[
Builder(
builder: (BuildContext context) {
child1BuildCount += 1;
return Text(SharedAppData.getValue<String, String>(context, 'child1Text', () => 'null'));
},
),
Builder(
builder: (BuildContext context) {
child2BuildCount += 1;
return Text(SharedAppData.getValue<String, String>(context, 'child2Text', () => 'null'));
}
),
],
),
);
},
),
),
),
);
expect(columnBuildCount, 1);
expect(child1BuildCount, 1);
expect(child2BuildCount, 1);
expect(find.text('null').evaluate().length, 2);
// SharedAppData.setValue<String, String>(context, 'child1Text', 'child1')
// causes the first Text widget to be rebuilt with its text to be
// set to 'child1'. Nothing else is rebuilt.
setSharedAppDataValue = (BuildContext context) {
SharedAppData.setValue<String, String>(context, 'child1Text', 'child1');
};
await tester.tap(find.byType(GestureDetector));
await tester.pump();
expect(columnBuildCount, 1);
expect(child1BuildCount, 2);
expect(child2BuildCount, 1);
expect(find.text('child1'), findsOneWidget);
expect(find.text('null'), findsOneWidget);
// SharedAppData.setValue<String, String>(context, 'child2Text', 'child1')
// causes the second Text widget to be rebuilt with its text to be
// set to 'child2'. Nothing else is rebuilt.
setSharedAppDataValue = (BuildContext context) {
SharedAppData.setValue<String, String>(context, 'child2Text', 'child2');
};
await tester.tap(find.byType(GestureDetector));
await tester.pump();
expect(columnBuildCount, 1);
expect(child1BuildCount, 2);
expect(child2BuildCount, 2);
expect(find.text('child1'), findsOneWidget);
expect(find.text('child2'), findsOneWidget);
// Resetting a key's value to the same value does not
// cause any widgets to be rebuilt.
setSharedAppDataValue = (BuildContext context) {
SharedAppData.setValue<String, String>(context, 'child1Text', 'child1');
SharedAppData.setValue<String, String>(context, 'child2Text', 'child2');
};
await tester.tap(find.byType(GestureDetector));
await tester.pump();
expect(columnBuildCount, 1);
expect(child1BuildCount, 2);
expect(child2BuildCount, 2);
// More of the same, resetting the values to null..
setSharedAppDataValue = (BuildContext context) {
SharedAppData.setValue<String, String>(context, 'child1Text', 'null');
};
await tester.tap(find.byType(GestureDetector));
await tester.pump();
expect(columnBuildCount, 1);
expect(child1BuildCount, 3);
expect(child2BuildCount, 2);
expect(find.text('null'), findsOneWidget);
expect(find.text('child2'), findsOneWidget);
setSharedAppDataValue = (BuildContext context) {
SharedAppData.setValue<String, String>(context, 'child2Text', 'null');
};
await tester.tap(find.byType(GestureDetector));
await tester.pump();
expect(columnBuildCount, 1);
expect(child1BuildCount, 3);
expect(child2BuildCount, 3);
expect(find.text('null').evaluate().length, 2);
});
testWidgets('WidgetsApp SharedAppData ', (WidgetTester tester) async {
int parentBuildCount = 0;
int childBuildCount = 0;
await tester.pumpWidget(
WidgetsApp(
color: const Color(0xff00ff00),
builder: (BuildContext context, Widget? child) {
parentBuildCount += 1;
return GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () {
SharedAppData.setValue<String, String>(context, 'childText', 'child');
},
child: Center(
child: Builder(
builder: (BuildContext context) {
childBuildCount += 1;
return Text(SharedAppData.getValue<String, String>(context, 'childText', () => 'null'));
},
),
),
);
},
),
);
expect(find.text('null'), findsOneWidget);
expect(parentBuildCount, 1);
expect(childBuildCount, 1);
await tester.tap(find.byType(GestureDetector));
await tester.pump();
expect(parentBuildCount, 1);
expect(childBuildCount, 2);
expect(find.text('child'), findsOneWidget);
});
testWidgets('WidgetsApp SharedAppData Shadowing', (WidgetTester tester) async {
int innerTapCount = 0;
int outerTapCount = 0;
await tester.pumpWidget(
WidgetsApp(
color: const Color(0xff00ff00),
builder: (BuildContext context, Widget? child) {
return GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () {
outerTapCount += 1;
SharedAppData.setValue<String, String>(context, 'childText', 'child');
},
child: Center(
child: SharedAppData(
child: Builder(
builder: (BuildContext context) {
return GestureDetector(
onTap: () {
innerTapCount += 1;
SharedAppData.setValue<String, String>(context, 'childText', 'child');
},
child: Text(SharedAppData.getValue<String, String>(context, 'childText', () => 'null')),
);
},
),
),
),
);
},
),
);
expect(find.text('null'), findsOneWidget);
await tester.tapAt(const Offset(10, 10));
await tester.pump();
expect(outerTapCount, 1);
expect(innerTapCount, 0);
expect(find.text('null'), findsOneWidget);
await tester.tap(find.text('null'));
await tester.pump();
expect(outerTapCount, 1);
expect(innerTapCount, 1);
expect(find.text('child'), findsOneWidget);
});
}
| flutter/packages/flutter/test/widgets/shared_app_data_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/shared_app_data_test.dart",
"repo_id": "flutter",
"token_count": 3153
} | 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.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
class TestItem extends StatelessWidget {
const TestItem({ super.key, required this.item, this.width, this.height });
final int item;
final double? width;
final double? height;
@override
Widget build(BuildContext context) {
return Container(
width: width,
height: height,
alignment: Alignment.center,
child: Text('Item $item', textDirection: TextDirection.ltr),
);
}
}
Widget buildFrame({ int? count, double? width, double? height, Axis? scrollDirection, Key? prototypeKey }) {
return Directionality(
textDirection: TextDirection.ltr,
child: CustomScrollView(
scrollDirection: scrollDirection ?? Axis.vertical,
slivers: <Widget>[
SliverPrototypeExtentList(
prototypeItem: TestItem(item: -1, width: width, height: height, key: prototypeKey),
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) => TestItem(item: index),
childCount: count,
),
),
],
),
);
}
void main() {
testWidgets('SliverPrototypeExtentList.builder test', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: CustomScrollView(
slivers: <Widget>[
SliverPrototypeExtentList.builder(
itemBuilder: (BuildContext context, int index) => TestItem(item: index),
prototypeItem: const TestItem(item: -1, height: 100.0),
itemCount: 20,
),
],
),
),
),
);
// The viewport is 600 pixels high, lazily created items are 100 pixels high.
for (int i = 0; i < 6; i += 1) {
final Finder item = find.widgetWithText(Container, 'Item $i');
expect(item, findsOneWidget);
expect(tester.getTopLeft(item).dy, i * 100.0);
expect(tester.getSize(item).height, 100.0);
}
for (int i = 7; i < 20; i += 1) {
expect(find.text('Item $i'), findsNothing);
}
});
testWidgets('SliverPrototypeExtentList.builder test', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: CustomScrollView(
slivers: <Widget>[
SliverPrototypeExtentList.list(
prototypeItem: const TestItem(item: -1, height: 100.0),
children: <int>[0, 1, 2, 3, 4, 5, 6, 7].map((int index) => TestItem(item: index)).toList(),
),
],
),
),
),
);
// The viewport is 600 pixels high, lazily created items are 100 pixels high.
for (int i = 0; i < 6; i += 1) {
final Finder item = find.widgetWithText(Container, 'Item $i');
expect(item, findsOneWidget);
expect(tester.getTopLeft(item).dy, i * 100.0);
expect(tester.getSize(item).height, 100.0);
}
expect(find.text('Item 7'), findsNothing);
});
testWidgets('SliverPrototypeExtentList vertical scrolling basics', (WidgetTester tester) async {
await tester.pumpWidget(buildFrame(count: 20, height: 100.0));
// The viewport is 600 pixels high, lazily created items are 100 pixels high.
for (int i = 0; i < 6; i += 1) {
final Finder item = find.widgetWithText(Container, 'Item $i');
expect(item, findsOneWidget);
expect(tester.getTopLeft(item).dy, i * 100.0);
expect(tester.getSize(item).height, 100.0);
}
for (int i = 7; i < 20; i += 1) {
expect(find.text('Item $i'), findsNothing);
}
// Fling scroll to the end.
await tester.fling(find.text('Item 2'), const Offset(0.0, -200.0), 5000.0);
await tester.pumpAndSettle();
for (int i = 19; i >= 14; i -= 1) {
expect(find.text('Item $i'), findsOneWidget);
}
for (int i = 13; i >= 0; i -= 1) {
expect(find.text('Item $i'), findsNothing);
}
});
testWidgets('SliverPrototypeExtentList horizontal scrolling basics', (WidgetTester tester) async {
await tester.pumpWidget(buildFrame(count: 20, width: 100.0, scrollDirection: Axis.horizontal));
// The viewport is 800 pixels wide, lazily created items are 100 pixels wide.
for (int i = 0; i < 8; i += 1) {
final Finder item = find.widgetWithText(Container, 'Item $i');
expect(item, findsOneWidget);
expect(tester.getTopLeft(item).dx, i * 100.0);
expect(tester.getSize(item).width, 100.0);
}
for (int i = 9; i < 20; i += 1) {
expect(find.text('Item $i'), findsNothing);
}
// Fling scroll to the end.
await tester.fling(find.text('Item 3'), const Offset(-200.0, 0.0), 5000.0);
await tester.pumpAndSettle();
for (int i = 19; i >= 12; i -= 1) {
expect(find.text('Item $i'), findsOneWidget);
}
for (int i = 11; i >= 0; i -= 1) {
expect(find.text('Item $i'), findsNothing);
}
});
testWidgets('SliverPrototypeExtentList change the prototype item', (WidgetTester tester) async {
await tester.pumpWidget(buildFrame(count: 10, height: 60.0));
// The viewport is 600 pixels high, each of the 10 items is 60 pixels high
for (int i = 0; i < 10; i += 1) {
expect(find.text('Item $i'), findsOneWidget);
}
await tester.pumpWidget(buildFrame(count: 10, height: 120.0));
// Now the items are 120 pixels high, so only 5 fit.
for (int i = 0; i < 5; i += 1) {
expect(find.text('Item $i'), findsOneWidget);
}
for (int i = 5; i < 10; i += 1) {
expect(find.text('Item $i'), findsNothing);
}
await tester.pumpWidget(buildFrame(count: 10, height: 60.0));
// Now they all fit again
for (int i = 0; i < 10; i += 1) {
expect(find.text('Item $i'), findsOneWidget);
}
});
testWidgets('SliverPrototypeExtentList first item is also the prototype', (WidgetTester tester) async {
final List<Widget> items = List<Widget>.generate(10, (int index) {
return TestItem(key: ValueKey<int>(index), item: index, height: index == 0 ? 60.0 : null);
}).toList();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: CustomScrollView(
slivers: <Widget>[
SliverPrototypeExtentList(
prototypeItem: items[0],
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) => items[index],
childCount: 10,
),
),
],
),
),
);
// Item 0 exists in the list and as the prototype item.
expect(tester.widgetList(find.text('Item 0', skipOffstage: false)).length, 2);
for (int i = 1; i < 10; i += 1) {
expect(find.text('Item $i'), findsOneWidget);
}
});
testWidgets('SliverPrototypeExtentList prototypeItem paint transform is zero.', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/67117
// This test ensures that the SliverPrototypeExtentList does not cause an
// assertion error when calculating the paint transform of its prototypeItem.
// The paint transform of the prototypeItem should be zero, since it is not visible.
final GlobalKey prototypeKey = GlobalKey();
await tester.pumpWidget(buildFrame(count: 20, height: 100.0, prototypeKey: prototypeKey));
final RenderObject scrollView = tester.renderObject(find.byType(CustomScrollView));
final RenderObject prototype = prototypeKey.currentContext!.findRenderObject()!;
expect(prototype.getTransformTo(scrollView), Matrix4.zero());
});
}
| flutter/packages/flutter/test/widgets/sliver_prototype_item_extent_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/sliver_prototype_item_extent_test.dart",
"repo_id": "flutter",
"token_count": 3102
} | 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.
// This file is run as part of a reduced test set in CI on Mac and Windows
// machines.
@Tags(<String>['reduced-test-set'])
library;
import 'dart:ui' as ui;
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart';
import '../impeller_test_helpers.dart';
void main() {
testWidgets('SnapshotWidget can rasterize child', (WidgetTester tester) async {
final SnapshotController controller = SnapshotController(allowSnapshotting: true);
addTearDown(controller.dispose);
final Key key = UniqueKey();
await tester.pumpWidget(RepaintBoundary(
key: key,
child: TestDependencies(
child: SnapshotWidget(
controller: controller,
child: Container(
width: 100,
height: 100,
color: const Color(0xFFAABB11),
),
),
),
));
await expectLater(find.byKey(key), matchesGoldenFile('raster_widget.yellow.png'));
// Now change the color and assert the old snapshot still matches.
await tester.pumpWidget(RepaintBoundary(
key: key,
child: TestDependencies(
child: SnapshotWidget(
controller: controller,
child: Container(
width: 100,
height: 100,
color: const Color(0xFFAA0000),
),
),
),
));
await expectLater(find.byKey(key), matchesGoldenFile('raster_widget.yellow.png'));
// Now invoke clear and the raster is re-generated.
controller.clear();
await tester.pump();
await expectLater(find.byKey(key), matchesGoldenFile('raster_widget.red.png'));
}, skip: kIsWeb); // TODO(jonahwilliams): https://github.com/flutter/flutter/issues/106689
testWidgets('Changing devicePixelRatio does not repaint if snapshotting is not enabled', (WidgetTester tester) async {
final SnapshotController controller = SnapshotController();
addTearDown(controller.dispose);
final TestPainter painter = TestPainter();
addTearDown(painter.dispose);
double devicePixelRatio = 1.0;
late StateSetter localSetState;
await tester.pumpWidget(
StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
localSetState = setState;
return Center(
child: TestDependencies(
devicePixelRatio: devicePixelRatio,
child: SnapshotWidget(
controller: controller,
painter: painter,
child: const SizedBox(width: 100, height: 100),
),
),
);
}),
);
expect(painter.count, 1);
localSetState(() {
devicePixelRatio = 2.0;
});
await tester.pump();
// Not repainted as dpr was not used.
expect(painter.count, 1);
}, skip: kIsWeb); // TODO(jonahwilliams): https://github.com/flutter/flutter/issues/106689
testWidgets('Changing devicePixelRatio forces raster regeneration', (WidgetTester tester) async {
final SnapshotController controller = SnapshotController(allowSnapshotting: true);
addTearDown(controller.dispose);
final TestPainter painter = TestPainter();
addTearDown(painter.dispose);
double devicePixelRatio = 1.0;
late StateSetter localSetState;
await tester.pumpWidget(
StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
localSetState = setState;
return Center(
child: TestDependencies(
devicePixelRatio: devicePixelRatio,
child: SnapshotWidget(
controller: controller,
painter: painter,
child: const SizedBox(width: 100, height: 100),
),
),
);
}),
);
final ui.Image? raster = painter.lastImage;
expect(raster, isNotNull);
expect(painter.count, 1);
localSetState(() {
devicePixelRatio = 2.0;
});
await tester.pump();
final ui.Image? newRaster = painter.lastImage;
expect(painter.count, 2);
expect(raster, isNot(newRaster));
}, skip: kIsWeb); // TODO(jonahwilliams): https://github.com/flutter/flutter/issues/106689
testWidgets('SnapshotWidget paints its child as a single picture layer', (WidgetTester tester) async {
final SnapshotController controller = SnapshotController(allowSnapshotting: true);
addTearDown(controller.dispose);
await tester.pumpWidget(RepaintBoundary(
child: Center(
child: TestDependencies(
child: SnapshotWidget(
controller: controller,
child: Container(
width: 100,
height: 100,
color: const Color(0xFFAABB11),
),
),
),
),
));
expect(tester.layers, hasLength(3));
expect(tester.layers.last, isA<PictureLayer>());
controller.allowSnapshotting = false;
await tester.pump();
expect(tester.layers, hasLength(3));
expect(tester.layers.last, isA<PictureLayer>());
}, skip: kIsWeb); // TODO(jonahwilliams): https://github.com/flutter/flutter/issues/106689
testWidgets('SnapshotWidget can update the painter type', (WidgetTester tester) async {
final SnapshotController controller = SnapshotController(allowSnapshotting: true);
addTearDown(controller.dispose);
final TestPainter painter1 = TestPainter();
addTearDown(painter1.dispose);
final TestPainter2 painter2 = TestPainter2();
addTearDown(painter2.dispose);
await tester.pumpWidget(
Center(
child: TestDependencies(
child: SnapshotWidget(
controller: controller,
painter: painter1,
child: const SizedBox(),
),
),
),
);
await tester.pumpWidget(
Center(
child: TestDependencies(
child: SnapshotWidget(
controller: controller,
painter: painter2,
child: const SizedBox(),
),
),
),
);
expect(tester.takeException(), isNull);
}, skip: kIsWeb); // TODO(jonahwilliams): https://github.com/flutter/flutter/issues/106689
testWidgets('RenderSnapshotWidget does not error on rasterization of child with empty size', (WidgetTester tester) async {
final SnapshotController controller = SnapshotController(allowSnapshotting: true);
addTearDown(controller.dispose);
await tester.pumpWidget(
Center(
child: TestDependencies(
child: SnapshotWidget(
controller: controller,
child: const SizedBox(),
),
),
),
);
expect(tester.takeException(), isNull);
}, skip: kIsWeb); // TODO(jonahwilliams): https://github.com/flutter/flutter/issues/106689
testWidgets('RenderSnapshotWidget throws assertion if platform view is encountered', (WidgetTester tester) async {
final SnapshotController controller = SnapshotController(allowSnapshotting: true);
addTearDown(controller.dispose);
await tester.pumpWidget(
Center(
child: TestDependencies(
child: SnapshotWidget(
controller: controller,
child: const SizedBox(
width: 100,
height: 100,
child: TestPlatformView(),
),
),
),
),
);
expect(tester.takeException(), isA<FlutterError>()
.having((FlutterError error) => error.message, 'message', contains('SnapshotWidget used with a child that contains a PlatformView')));
}, skip: kIsWeb); // TODO(jonahwilliams): https://github.com/flutter/flutter/issues/106689
testWidgets('RenderSnapshotWidget does not assert if SnapshotMode.forced', (WidgetTester tester) async {
final SnapshotController controller = SnapshotController(allowSnapshotting: true);
addTearDown(controller.dispose);
await tester.pumpWidget(
Center(
child: TestDependencies(
child: SnapshotWidget(
controller: controller,
mode: SnapshotMode.forced,
child: const SizedBox(
width: 100,
height: 100,
child: TestPlatformView(),
),
),
),
),
);
expect(tester.takeException(), isNull);
}, skip: kIsWeb); // TODO(jonahwilliams): https://github.com/flutter/flutter/issues/106689
testWidgets('RenderSnapshotWidget does not take a snapshot if a platform view is encountered with SnapshotMode.permissive', (WidgetTester tester) async {
final SnapshotController controller = SnapshotController(allowSnapshotting: true);
addTearDown(controller.dispose);
await tester.pumpWidget(
Center(
child: TestDependencies(
child: SnapshotWidget(
controller: controller,
mode: SnapshotMode.permissive,
child: const SizedBox(
width: 100,
height: 100,
child: TestPlatformView(),
),
),
),
),
);
expect(tester.takeException(), isNull);
expect(tester.layers.last, isA<PlatformViewLayer>());
},
skip: kIsWeb); // TODO(jonahwilliams): https://github.com/flutter/flutter/issues/106689
testWidgets('SnapshotWidget should have same result when enabled', (WidgetTester tester) async {
addTearDown(tester.view.reset);
tester.view
..physicalSize = const Size(10, 10)
..devicePixelRatio = 1;
const ValueKey<String> repaintBoundaryKey = ValueKey<String>('boundary');
final SnapshotController controller = SnapshotController();
addTearDown(controller.dispose);
await tester.pumpWidget(RepaintBoundary(
key: repaintBoundaryKey,
child: MaterialApp(
debugShowCheckedModeBanner: false,
home: Container(
color: Colors.black,
padding: const EdgeInsets.only(right: 0.6, bottom: 0.6),
child: SnapshotWidget(
controller: controller,
child: Container(
margin: const EdgeInsets.only(right: 0.4, bottom: 0.4),
color: Colors.blue,
),
),
),
),
));
final ui.Image imageWhenDisabled = (tester.renderObject(find.byKey(repaintBoundaryKey)) as RenderRepaintBoundary).toImageSync();
addTearDown(imageWhenDisabled.dispose);
controller.allowSnapshotting = true;
await tester.pump();
await expectLater(find.byKey(repaintBoundaryKey), matchesReferenceImage(imageWhenDisabled));
},
skip: kIsWeb || impellerEnabled); // TODO(jonahwilliams): https://github.com/flutter/flutter/issues/106689
test('SnapshotPainter dispatches memory events', () async {
await expectLater(
await memoryEvents(
() => TestPainter().dispose(),
TestPainter,
),
areCreateAndDispose,
);
});
}
class TestPlatformView extends SingleChildRenderObjectWidget {
const TestPlatformView({super.key});
@override
RenderObject createRenderObject(BuildContext context) {
return RenderTestPlatformView();
}
}
class RenderTestPlatformView extends RenderProxyBox {
@override
void paint(PaintingContext context, ui.Offset offset) {
context.addLayer(PlatformViewLayer(rect: offset & size, viewId: 1));
}
}
class TestPainter extends SnapshotPainter {
int count = 0;
bool shouldRepaintValue = false;
ui.Image? lastImage;
int addedListenerCount = 0;
int removedListenerCount = 0;
@override
void addListener(ui.VoidCallback listener) {
addedListenerCount += 1;
super.addListener(listener);
}
@override
void removeListener(ui.VoidCallback listener) {
removedListenerCount += 1;
super.removeListener(listener);
}
@override
void paintSnapshot(PaintingContext context, Offset offset, Size size, ui.Image image, Size sourceSize, double pixelRatio) {
count += 1;
lastImage = image;
}
@override
void paint(PaintingContext context, ui.Offset offset, ui.Size size, PaintingContextCallback painter) {
count += 1;
}
@override
bool shouldRepaint(covariant TestPainter oldDelegate) => shouldRepaintValue;
}
class TestPainter2 extends TestPainter {
@override
bool shouldRepaint(covariant TestPainter2 oldDelegate) => shouldRepaintValue;
}
class TestDependencies extends StatelessWidget {
const TestDependencies({required this.child, super.key, this.devicePixelRatio});
final Widget child;
final double? devicePixelRatio;
@override
Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.ltr,
child: MediaQuery(
data: const MediaQueryData().copyWith(devicePixelRatio: devicePixelRatio),
child: child,
),
);
}
}
| flutter/packages/flutter/test/widgets/snapshot_widget_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/snapshot_widget_test.dart",
"repo_id": "flutter",
"token_count": 5131
} | 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/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart';
import 'clipboard_utils.dart';
import 'editable_text_utils.dart';
const int kSingleTapUpTimeout = 500;
void main() {
late int tapCount;
late int singleTapUpCount;
late int singleTapCancelCount;
late int singleLongTapStartCount;
late int doubleTapDownCount;
late int tripleTapDownCount;
late int forcePressStartCount;
late int forcePressEndCount;
late int dragStartCount;
late int dragUpdateCount;
late int dragEndCount;
const Offset forcePressOffset = Offset(400.0, 50.0);
void handleTapDown(TapDragDownDetails details) { tapCount++; }
void handleSingleTapUp(TapDragUpDetails details) { singleTapUpCount++; }
void handleSingleTapCancel() { singleTapCancelCount++; }
void handleSingleLongTapStart(LongPressStartDetails details) { singleLongTapStartCount++; }
void handleDoubleTapDown(TapDragDownDetails details) { doubleTapDownCount++; }
void handleTripleTapDown(TapDragDownDetails details) { tripleTapDownCount++; }
void handleForcePressStart(ForcePressDetails details) { forcePressStartCount++; }
void handleForcePressEnd(ForcePressDetails details) { forcePressEndCount++; }
void handleDragSelectionStart(TapDragStartDetails details) { dragStartCount++; }
void handleDragSelectionUpdate(TapDragUpdateDetails details) { dragUpdateCount++; }
void handleDragSelectionEnd(TapDragEndDetails details) { dragEndCount++; }
setUp(() {
tapCount = 0;
singleTapUpCount = 0;
singleTapCancelCount = 0;
singleLongTapStartCount = 0;
doubleTapDownCount = 0;
tripleTapDownCount = 0;
forcePressStartCount = 0;
forcePressEndCount = 0;
dragStartCount = 0;
dragUpdateCount = 0;
dragEndCount = 0;
});
Future<void> pumpGestureDetector(WidgetTester tester) async {
await tester.pumpWidget(
TextSelectionGestureDetector(
behavior: HitTestBehavior.opaque,
onTapDown: handleTapDown,
onSingleTapUp: handleSingleTapUp,
onSingleTapCancel: handleSingleTapCancel,
onSingleLongTapStart: handleSingleLongTapStart,
onDoubleTapDown: handleDoubleTapDown,
onTripleTapDown: handleTripleTapDown,
onForcePressStart: handleForcePressStart,
onForcePressEnd: handleForcePressEnd,
onDragSelectionStart: handleDragSelectionStart,
onDragSelectionUpdate: handleDragSelectionUpdate,
onDragSelectionEnd: handleDragSelectionEnd,
child: Container(),
),
);
}
Future<void> pumpTextSelectionGestureDetectorBuilder(
WidgetTester tester, {
bool forcePressEnabled = true,
bool selectionEnabled = true,
}) async {
final GlobalKey<EditableTextState> editableTextKey = GlobalKey<EditableTextState>();
final FakeTextSelectionGestureDetectorBuilderDelegate delegate = FakeTextSelectionGestureDetectorBuilderDelegate(
editableTextKey: editableTextKey,
forcePressEnabled: forcePressEnabled,
selectionEnabled: selectionEnabled,
);
final TextSelectionGestureDetectorBuilder provider =
TextSelectionGestureDetectorBuilder(delegate: delegate);
final TextEditingController controller = TextEditingController();
addTearDown(controller.dispose);
final FocusNode focusNode = FocusNode();
addTearDown(focusNode.dispose);
await tester.pumpWidget(
MaterialApp(
home: provider.buildGestureDetector(
behavior: HitTestBehavior.translucent,
child: FakeEditableText(
key: editableTextKey,
controller: controller,
focusNode: focusNode,
),
),
),
);
}
testWidgets('a series of taps all call onTaps', (WidgetTester tester) async {
await pumpGestureDetector(tester);
await tester.tapAt(const Offset(200, 200));
await tester.pump(const Duration(milliseconds: 150));
await tester.tapAt(const Offset(200, 200));
await tester.pump(const Duration(milliseconds: 150));
await tester.tapAt(const Offset(200, 200));
await tester.pump(const Duration(milliseconds: 150));
await tester.tapAt(const Offset(200, 200));
await tester.pump(const Duration(milliseconds: 150));
await tester.tapAt(const Offset(200, 200));
await tester.pump(const Duration(milliseconds: 150));
await tester.tapAt(const Offset(200, 200));
expect(tapCount, 6);
});
testWidgets('in a series of rapid taps, onTapDown, onDoubleTapDown, and onTripleTapDown alternate', (WidgetTester tester) async {
await pumpGestureDetector(tester);
await tester.tapAt(const Offset(200, 200));
await tester.pump(const Duration(milliseconds: 50));
expect(singleTapUpCount, 1);
await tester.tapAt(const Offset(200, 200));
await tester.pump(const Duration(milliseconds: 50));
expect(singleTapUpCount, 1);
expect(doubleTapDownCount, 1);
await tester.tapAt(const Offset(200, 200));
await tester.pump(const Duration(milliseconds: 50));
expect(singleTapUpCount, 1);
expect(doubleTapDownCount, 1);
expect(tripleTapDownCount, 1);
await tester.tapAt(const Offset(200, 200));
await tester.pump(const Duration(milliseconds: 50));
expect(singleTapUpCount, 2);
expect(doubleTapDownCount, 1);
expect(tripleTapDownCount, 1);
await tester.tapAt(const Offset(200, 200));
await tester.pump(const Duration(milliseconds: 50));
expect(singleTapUpCount, 2);
expect(doubleTapDownCount, 2);
expect(tripleTapDownCount, 1);
await tester.tapAt(const Offset(200, 200));
await tester.pump(const Duration(milliseconds: 50));
expect(singleTapUpCount, 2);
expect(doubleTapDownCount, 2);
expect(tripleTapDownCount, 2);
await tester.tapAt(const Offset(200, 200));
expect(singleTapUpCount, 3);
expect(doubleTapDownCount, 2);
expect(tripleTapDownCount, 2);
expect(tapCount, 7);
});
testWidgets('quick tap-tap-hold is a double tap down', (WidgetTester tester) async {
await pumpGestureDetector(tester);
await tester.tapAt(const Offset(200, 200));
await tester.pump(const Duration(milliseconds: 50));
expect(singleTapUpCount, 1);
final TestGesture gesture = await tester.startGesture(const Offset(200, 200));
await tester.pump(const Duration(milliseconds: 200));
expect(singleTapUpCount, 1);
// Every down is counted.
expect(tapCount, 2);
// No cancels because the second tap of the double tap is a second successful
// single tap behind the scene.
expect(singleTapCancelCount, 0);
expect(doubleTapDownCount, 1);
// The double tap down hold supersedes the single tap down.
expect(singleLongTapStartCount, 0);
await gesture.up();
// Nothing else happens on up.
expect(singleTapUpCount, 1);
expect(tapCount, 2);
expect(singleTapCancelCount, 0);
expect(doubleTapDownCount, 1);
expect(singleLongTapStartCount, 0);
});
testWidgets('a very quick swipe is ignored', (WidgetTester tester) async {
await pumpGestureDetector(tester);
final TestGesture gesture = await tester.startGesture(const Offset(200, 200));
await tester.pump(const Duration(milliseconds: 20));
await gesture.moveBy(const Offset(100, 100));
await tester.pump();
expect(singleTapUpCount, 0);
// Before the move to TapAndDragGestureRecognizer the tapCount was 0 because the
// TapGestureRecognizer rejected itself when the initial pointer moved past a certain
// threshold. With TapAndDragGestureRecognizer, we have two thresholds, a normal tap
// threshold, and a drag threshold, so it is possible for the tap count to increase
// even though the original pointer has moved beyond the tap threshold.
expect(tapCount, 1);
expect(singleTapCancelCount, 0);
expect(doubleTapDownCount, 0);
expect(singleLongTapStartCount, 0);
await gesture.up();
// Nothing else happens on up.
expect(singleTapUpCount, 0);
expect(tapCount, 1);
expect(singleTapCancelCount, 0);
expect(doubleTapDownCount, 0);
expect(singleLongTapStartCount, 0);
});
testWidgets('a slower swipe has a tap down and a canceled tap', (WidgetTester tester) async {
await pumpGestureDetector(tester);
final TestGesture gesture = await tester.startGesture(const Offset(200, 200));
await tester.pump(const Duration(milliseconds: 120));
await gesture.moveBy(const Offset(100, 100));
await tester.pump();
expect(singleTapUpCount, 0);
expect(tapCount, 1);
expect(singleTapCancelCount, 0);
expect(doubleTapDownCount, 0);
expect(singleLongTapStartCount, 0);
});
testWidgets('a force press initiates a force press', (WidgetTester tester) async {
await pumpGestureDetector(tester);
final int pointerValue = tester.nextPointer;
final TestGesture gesture = await tester.createGesture();
await gesture.downWithCustomEvent(
forcePressOffset,
PointerDownEvent(
pointer: pointerValue,
position: forcePressOffset,
pressure: 0.0,
pressureMax: 6.0,
pressureMin: 0.0,
),
);
await gesture.updateWithCustomEvent(PointerMoveEvent(
pointer: pointerValue,
pressure: 0.5,
pressureMin: 0,
));
await gesture.up();
await tester.pumpAndSettle();
await gesture.downWithCustomEvent(
forcePressOffset,
PointerDownEvent(
pointer: pointerValue,
position: forcePressOffset,
pressure: 0.0,
pressureMax: 6.0,
pressureMin: 0.0,
),
);
await gesture.updateWithCustomEvent(PointerMoveEvent(
pointer: pointerValue,
pressure: 0.5,
pressureMin: 0,
));
await gesture.up();
await tester.pump(const Duration(milliseconds: 20));
await gesture.downWithCustomEvent(
forcePressOffset,
PointerDownEvent(
pointer: pointerValue,
position: forcePressOffset,
pressure: 0.0,
pressureMax: 6.0,
pressureMin: 0.0,
),
);
await gesture.updateWithCustomEvent(PointerMoveEvent(
pointer: pointerValue,
pressure: 0.5,
pressureMin: 0,
));
await gesture.up();
await tester.pump(const Duration(milliseconds: 20));
await gesture.downWithCustomEvent(
forcePressOffset,
PointerDownEvent(
pointer: pointerValue,
position: forcePressOffset,
pressure: 0.0,
pressureMax: 6.0,
pressureMin: 0.0,
),
);
await gesture.updateWithCustomEvent(PointerMoveEvent(
pointer: pointerValue,
pressure: 0.5,
pressureMin: 0,
));
await gesture.up();
expect(forcePressStartCount, 4);
});
testWidgets('a tap and then force press initiates a force press and not a double tap', (WidgetTester tester) async {
await pumpGestureDetector(tester);
final int pointerValue = tester.nextPointer;
final TestGesture gesture = await tester.createGesture();
await gesture.downWithCustomEvent(
forcePressOffset,
PointerDownEvent(
pointer: pointerValue,
position: forcePressOffset,
pressure: 0.0,
pressureMax: 6.0,
pressureMin: 0.0,
),
);
// Initiate a quick tap.
await gesture.updateWithCustomEvent(
PointerMoveEvent(
pointer: pointerValue,
pressure: 0.0,
pressureMin: 0,
),
);
await tester.pump(const Duration(milliseconds: 50));
await gesture.up();
// Initiate a force tap.
await gesture.downWithCustomEvent(
forcePressOffset,
PointerDownEvent(
pointer: pointerValue,
position: forcePressOffset,
pressure: 0.0,
pressureMax: 6.0,
pressureMin: 0.0,
),
);
await gesture.updateWithCustomEvent(PointerMoveEvent(
pointer: pointerValue,
pressure: 0.5,
pressureMin: 0,
));
expect(forcePressStartCount, 1);
await tester.pump(const Duration(milliseconds: 50));
await gesture.up();
await tester.pumpAndSettle();
expect(forcePressEndCount, 1);
expect(doubleTapDownCount, 0);
});
testWidgets('a long press from a touch device is recognized as a long single tap', (WidgetTester tester) async {
await pumpGestureDetector(tester);
final int pointerValue = tester.nextPointer;
final TestGesture gesture = await tester.startGesture(
const Offset(200.0, 200.0),
pointer: pointerValue,
);
await tester.pump(const Duration(seconds: 2));
await gesture.up();
await tester.pumpAndSettle();
expect(tapCount, 1);
expect(singleTapUpCount, 0);
expect(singleLongTapStartCount, 1);
});
testWidgets('a long press from a mouse is just a tap', (WidgetTester tester) async {
await pumpGestureDetector(tester);
final int pointerValue = tester.nextPointer;
final TestGesture gesture = await tester.startGesture(
const Offset(200.0, 200.0),
pointer: pointerValue,
kind: PointerDeviceKind.mouse,
);
await tester.pump(const Duration(seconds: 2));
await gesture.up();
await tester.pumpAndSettle();
expect(tapCount, 1);
expect(singleTapUpCount, 1);
expect(singleLongTapStartCount, 0);
});
testWidgets('a touch drag is recognized for text selection', (WidgetTester tester) async {
await pumpGestureDetector(tester);
final int pointerValue = tester.nextPointer;
final TestGesture gesture = await tester.startGesture(
const Offset(200.0, 200.0),
pointer: pointerValue,
);
await tester.pump();
await gesture.moveBy(const Offset(210.0, 200.0));
await tester.pump();
await gesture.up();
await tester.pumpAndSettle();
expect(tapCount, 1);
expect(singleTapUpCount, 0);
expect(singleTapCancelCount, 0);
expect(dragStartCount, 1);
expect(dragUpdateCount, 1);
expect(dragEndCount, 1);
});
testWidgets('a mouse drag is recognized for text selection', (WidgetTester tester) async {
await pumpGestureDetector(tester);
final int pointerValue = tester.nextPointer;
final TestGesture gesture = await tester.startGesture(
const Offset(200.0, 200.0),
pointer: pointerValue,
kind: PointerDeviceKind.mouse,
);
await tester.pump();
await gesture.moveBy(const Offset(210.0, 200.0));
await tester.pump();
await gesture.up();
await tester.pumpAndSettle();
// The tap and drag gesture recognizer will detect the tap down, but not the tap up.
expect(tapCount, 1);
expect(singleTapCancelCount, 0);
expect(singleTapUpCount, 0);
expect(dragStartCount, 1);
expect(dragUpdateCount, 1);
expect(dragEndCount, 1);
});
testWidgets('a slow mouse drag is still recognized for text selection', (WidgetTester tester) async {
await pumpGestureDetector(tester);
final int pointerValue = tester.nextPointer;
final TestGesture gesture = await tester.startGesture(
const Offset(200.0, 200.0),
pointer: pointerValue,
kind: PointerDeviceKind.mouse,
);
await tester.pump(const Duration(seconds: 2));
await gesture.moveBy(const Offset(210.0, 200.0));
await tester.pump();
await gesture.up();
await tester.pumpAndSettle();
// The tap and drag gesture recognizer will detect the tap down, but not the tap up.
expect(tapCount, 1);
expect(singleTapCancelCount, 0);
expect(singleTapUpCount, 0);
expect(dragStartCount, 1);
expect(dragUpdateCount, 1);
expect(dragEndCount, 1);
});
testWidgets('test TextSelectionGestureDetectorBuilder long press on Apple Platforms - focused renderEditable', (WidgetTester tester) async {
await pumpTextSelectionGestureDetectorBuilder(tester);
final FakeEditableTextState state = tester.state(find.byType(FakeEditableText));
final FakeRenderEditable renderEditable = tester.renderObject(find.byType(FakeEditable));
renderEditable.hasFocus = true;
final TestGesture gesture = await tester.startGesture(
const Offset(200.0, 200.0),
pointer: 0,
);
await tester.pump(const Duration(seconds: 2));
await gesture.up();
await tester.pumpAndSettle();
expect(state.showToolbarCalled, isTrue);
expect(renderEditable.selectPositionAtCalled, isTrue);
expect(renderEditable.lastCause, SelectionChangedCause.longPress);
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }));
testWidgets('test TextSelectionGestureDetectorBuilder long press on iOS - renderEditable not focused', (WidgetTester tester) async {
await pumpTextSelectionGestureDetectorBuilder(tester);
final FakeEditableTextState state = tester.state(find.byType(FakeEditableText));
final FakeRenderEditable renderEditable = tester.renderObject(find.byType(FakeEditable));
final TestGesture gesture = await tester.startGesture(
const Offset(200.0, 200.0),
pointer: 0,
);
await tester.pump(const Duration(seconds: 2));
await gesture.up();
await tester.pumpAndSettle();
expect(state.showToolbarCalled, isTrue);
expect(renderEditable.selectWordCalled, isTrue);
expect(renderEditable.lastCause, SelectionChangedCause.longPress);
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS }));
testWidgets('test TextSelectionGestureDetectorBuilder long press on non-Apple Platforms', (WidgetTester tester) async {
await pumpTextSelectionGestureDetectorBuilder(tester);
final TestGesture gesture = await tester.startGesture(
const Offset(200.0, 200.0),
pointer: 0,
);
await tester.pump(const Duration(seconds: 2));
await gesture.up();
await tester.pumpAndSettle();
final FakeEditableTextState state = tester.state(find.byType(FakeEditableText));
final FakeRenderEditable renderEditable = tester.renderObject(find.byType(FakeEditable));
expect(state.showToolbarCalled, isTrue);
expect(renderEditable.selectWordCalled, isTrue);
expect(renderEditable.lastCause, SelectionChangedCause.longPress);
}, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }));
testWidgets('TextSelectionGestureDetectorBuilder right click Apple platforms', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/80119
await pumpTextSelectionGestureDetectorBuilder(tester);
final FakeRenderEditable renderEditable = tester.renderObject(find.byType(FakeEditable));
renderEditable.text = const TextSpan(text: 'one two three four five six seven');
await tester.pump();
final TestGesture gesture = await tester.createGesture(
pointer: 0,
kind: PointerDeviceKind.mouse,
buttons: kSecondaryButton,
);
// Get the location of the 10th character
final Offset charLocation = renderEditable
.getLocalRectForCaret(const TextPosition(offset: 10)).center;
final Offset globalCharLocation = charLocation + tester.getTopLeft(find.byType(FakeEditable));
// Right clicking on a word should select it
await gesture.down(globalCharLocation);
await gesture.up();
await tester.pump();
expect(renderEditable.selectWordCalled, isTrue);
expect(renderEditable.lastCause, SelectionChangedCause.tap);
// Right clicking on a word within a selection shouldn't change the selection
renderEditable.selectWordCalled = false;
renderEditable.selection = const TextSelection(baseOffset: 3, extentOffset: 20);
await gesture.down(globalCharLocation);
await gesture.up();
await tester.pump();
expect(renderEditable.selectWordCalled, isFalse);
// Right clicking on a word within a reverse (right-to-left) selection shouldn't change the selection
renderEditable.selectWordCalled = false;
renderEditable.selection = const TextSelection(baseOffset: 20, extentOffset: 3);
await gesture.down(globalCharLocation);
await gesture.up();
await tester.pump();
expect(renderEditable.selectWordCalled, isFalse);
},
variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }),
);
testWidgets('TextSelectionGestureDetectorBuilder right click non-Apple platforms', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/80119
await pumpTextSelectionGestureDetectorBuilder(tester);
final FakeRenderEditable renderEditable = tester.renderObject(find.byType(FakeEditable));
renderEditable.text = const TextSpan(text: 'one two three four five six seven');
await tester.pump();
final TestGesture gesture = await tester.createGesture(
pointer: 0,
kind: PointerDeviceKind.mouse,
buttons: kSecondaryButton,
);
// Get the location of the 10th character
final Offset charLocation = renderEditable
.getLocalRectForCaret(const TextPosition(offset: 10)).center;
final Offset globalCharLocation = charLocation + tester.getTopLeft(find.byType(FakeEditable));
// Right clicking on an unfocused field should place the cursor, not select
// the word.
await gesture.down(globalCharLocation);
await gesture.up();
await tester.pump();
expect(renderEditable.selectWordCalled, isFalse);
expect(renderEditable.selectPositionCalled, isTrue);
// Right clicking on a focused field with selection shouldn't change the
// selection.
renderEditable.selectPositionCalled = false;
renderEditable.selection = const TextSelection(baseOffset: 3, extentOffset: 20);
renderEditable.hasFocus = true;
await gesture.down(globalCharLocation);
await gesture.up();
await tester.pump();
expect(renderEditable.selectWordCalled, isFalse);
expect(renderEditable.selectPositionCalled, isFalse);
// Right clicking on a focused field with a reverse (right to left)
// selection shouldn't change the selection.
renderEditable.selection = const TextSelection(baseOffset: 20, extentOffset: 3);
await gesture.down(globalCharLocation);
await gesture.up();
await tester.pump();
expect(renderEditable.selectWordCalled, isFalse);
expect(renderEditable.selectPositionCalled, isFalse);
},
variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.fuchsia, TargetPlatform.linux, TargetPlatform.windows }),
);
testWidgets('test TextSelectionGestureDetectorBuilder tap', (WidgetTester tester) async {
await pumpTextSelectionGestureDetectorBuilder(tester);
final TestGesture gesture = await tester.startGesture(
const Offset(200.0, 200.0),
pointer: 0,
);
await gesture.up();
await tester.pumpAndSettle();
final FakeEditableTextState state = tester.state(find.byType(FakeEditableText));
final FakeRenderEditable renderEditable = tester.renderObject(find.byType(FakeEditable));
expect(state.showToolbarCalled, isFalse);
switch (defaultTargetPlatform) {
case TargetPlatform.iOS:
expect(renderEditable.selectWordEdgeCalled, isTrue);
expect(renderEditable.lastCause, SelectionChangedCause.tap);
case TargetPlatform.macOS:
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
expect(renderEditable.selectPositionAtCalled, isTrue);
expect(renderEditable.lastCause, SelectionChangedCause.tap);
}
}, variant: TargetPlatformVariant.all());
testWidgets('test TextSelectionGestureDetectorBuilder toggles toolbar on single tap on previous selection iOS', (WidgetTester tester) async {
await pumpTextSelectionGestureDetectorBuilder(tester);
final FakeEditableTextState state = tester.state(find.byType(FakeEditableText));
final FakeRenderEditable renderEditable = tester.renderObject(find.byType(FakeEditable));
expect(state.showToolbarCalled, isFalse);
expect(state.toggleToolbarCalled, isFalse);
renderEditable.selection = const TextSelection(baseOffset: 2, extentOffset: 6);
renderEditable.hasFocus = true;
final TestGesture gesture = await tester.startGesture(
const Offset(25.0, 200.0),
pointer: 0,
);
await gesture.up();
await tester.pumpAndSettle();
switch (defaultTargetPlatform) {
case TargetPlatform.iOS:
expect(renderEditable.selectWordEdgeCalled, isFalse);
expect(state.toggleToolbarCalled, isTrue);
case TargetPlatform.macOS:
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
expect(renderEditable.selectPositionAtCalled, isTrue);
expect(renderEditable.lastCause, SelectionChangedCause.tap);
}
}, variant: TargetPlatformVariant.all());
testWidgets('test TextSelectionGestureDetectorBuilder shows spell check toolbar on single tap on Android', (WidgetTester tester) async {
await pumpTextSelectionGestureDetectorBuilder(tester);
final FakeEditableTextState state = tester.state(find.byType(FakeEditableText));
final FakeRenderEditable renderEditable = tester.renderObject(find.byType(FakeEditable));
expect(state.showSpellCheckSuggestionsToolbarCalled, isFalse);
renderEditable.selection = const TextSelection(baseOffset: 2, extentOffset: 6);
renderEditable.hasFocus = true;
final TestGesture gesture = await tester.startGesture(
const Offset(25.0, 200.0),
pointer: 0,
);
await gesture.up();
await tester.pumpAndSettle();
expect(state.showSpellCheckSuggestionsToolbarCalled, isTrue);
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android }));
testWidgets('test TextSelectionGestureDetectorBuilder shows spell check toolbar on single tap on iOS if word misspelled and text selection toolbar on additional taps', (WidgetTester tester) async {
await pumpTextSelectionGestureDetectorBuilder(tester);
final FakeEditableTextState state = tester.state(find.byType(FakeEditableText));
final FakeRenderEditable renderEditable = tester.renderObject(find.byType(FakeEditable));
const TextSelection selection = TextSelection.collapsed(offset: 1);
state.updateEditingValue(const TextEditingValue(text: 'something misspelled', selection: selection));
// Mark word to be tapped as misspelled for testing.
state.markCurrentSelectionAsMisspelled = true;
await tester.pump();
// Test spell check suggestions toolbar is shown on first tap of misspelled word.
const Offset position = Offset(25.0, 200.0);
await tester.tapAt(position);
await tester.pumpAndSettle();
expect(state.showSpellCheckSuggestionsToolbarCalled, isTrue);
// Reset and test text selection toolbar is toggled for additional taps.
state.showSpellCheckSuggestionsToolbarCalled = false;
renderEditable.selection = selection;
await tester.pump(const Duration(milliseconds: kSingleTapUpTimeout));
// Test first tap.
await tester.tapAt(position);
await tester.pumpAndSettle();
expect(state.showSpellCheckSuggestionsToolbarCalled, isFalse);
expect(state.toggleToolbarCalled, isTrue);
// Reset and test second tap.
state.toggleToolbarCalled = false;
await tester.pump(const Duration(milliseconds: kSingleTapUpTimeout));
await tester.tapAt(position);
await tester.pumpAndSettle();
expect(state.showSpellCheckSuggestionsToolbarCalled, isFalse);
expect(state.toggleToolbarCalled, isTrue);
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS }));
testWidgets('test TextSelectionGestureDetectorBuilder double tap', (WidgetTester tester) async {
await pumpTextSelectionGestureDetectorBuilder(tester);
final TestGesture gesture = await tester.startGesture(
const Offset(200.0, 200.0),
pointer: 0,
);
await tester.pump(const Duration(milliseconds: 50));
await gesture.up();
await gesture.down(const Offset(200.0, 200.0));
await tester.pump(const Duration(milliseconds: 50));
await gesture.up();
await tester.pumpAndSettle();
final FakeEditableTextState state = tester.state(find.byType(FakeEditableText));
final FakeRenderEditable renderEditable = tester.renderObject(find.byType(FakeEditable));
expect(state.showToolbarCalled, isTrue);
expect(renderEditable.selectWordCalled, isTrue);
expect(renderEditable.lastCause, SelectionChangedCause.doubleTap);
});
testWidgets('test TextSelectionGestureDetectorBuilder forcePress enabled', (WidgetTester tester) async {
await pumpTextSelectionGestureDetectorBuilder(tester);
final TestGesture gesture = await tester.createGesture();
await gesture.downWithCustomEvent(
const Offset(200.0, 200.0),
const PointerDownEvent(
position: Offset(200.0, 200.0),
pressure: 3.0,
pressureMax: 6.0,
pressureMin: 0.0,
),
);
await gesture.updateWithCustomEvent(
const PointerUpEvent(
position: Offset(200.0, 200.0),
pressureMax: 6.0,
pressureMin: 0.0,
),
);
await tester.pump();
final FakeEditableTextState state = tester.state(find.byType(FakeEditableText));
final FakeRenderEditable renderEditable = tester.renderObject(find.byType(FakeEditable));
expect(state.showToolbarCalled, isTrue);
expect(renderEditable.selectWordsInRangeCalled, isTrue);
});
testWidgets('Mouse drag does not show handles nor toolbar', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/69001
await tester.pumpWidget(
const MaterialApp(
home: Scaffold(
body: SelectableText('I love Flutter!'),
),
),
);
final Offset textFieldStart = tester.getTopLeft(find.byType(SelectableText));
final TestGesture gesture = await tester.startGesture(textFieldStart, kind: PointerDeviceKind.mouse);
await tester.pump();
await gesture.moveTo(textFieldStart + const Offset(50.0, 0));
await tester.pump();
await gesture.up();
await tester.pumpAndSettle();
final EditableTextState editableText = tester.state(find.byType(EditableText));
expect(editableText.selectionOverlay!.handlesAreVisible, isFalse);
expect(editableText.selectionOverlay!.toolbarIsVisible, isFalse);
});
testWidgets('Mouse drag selects and cannot drag cursor', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/102928
final TextEditingController controller = TextEditingController(
text: 'I love flutter!',
);
addTearDown(controller.dispose);
final GlobalKey<EditableTextState> editableTextKey = GlobalKey<EditableTextState>();
final FakeTextSelectionGestureDetectorBuilderDelegate delegate = FakeTextSelectionGestureDetectorBuilderDelegate(
editableTextKey: editableTextKey,
forcePressEnabled: false,
selectionEnabled: true,
);
final TextSelectionGestureDetectorBuilder provider =
TextSelectionGestureDetectorBuilder(delegate: delegate);
final FocusNode focusNode = FocusNode();
addTearDown(focusNode.dispose);
await tester.pumpWidget(
MaterialApp(
home: provider.buildGestureDetector(
behavior: HitTestBehavior.translucent,
child: EditableText(
key: editableTextKey,
controller: controller,
focusNode: focusNode,
backgroundCursorColor: Colors.white,
cursorColor: Colors.white,
style: const TextStyle(),
selectionControls: materialTextSelectionControls,
),
),
),
);
expect(controller.selection.isCollapsed, isTrue);
expect(controller.selection.baseOffset, -1);
final Offset position = textOffsetToPosition(tester, 4);
await tester.tapAt(position);
// Don't do a double tap drag.
await tester.pump(const Duration(milliseconds: 300));
expect(controller.selection.isCollapsed, isTrue);
expect(controller.selection.baseOffset, 4);
final TestGesture gesture = await tester.startGesture(position, kind: PointerDeviceKind.mouse);
// Checking that double-tap was not registered.
expect(controller.selection.isCollapsed, isTrue);
expect(controller.selection.baseOffset, 4);
addTearDown(gesture.removePointer);
await tester.pump();
await gesture.moveTo(textOffsetToPosition(tester, 7));
await tester.pump();
await gesture.moveTo(textOffsetToPosition(tester, 10));
await tester.pump();
await gesture.up();
await tester.pumpAndSettle();
expect(controller.selection.isCollapsed, isFalse);
expect(controller.selection.baseOffset, 4);
expect(controller.selection.extentOffset, 10);
});
testWidgets('Touch drag moves the cursor', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/102928
final TextEditingController controller = TextEditingController(
text: 'I love flutter!',
);
addTearDown(controller.dispose);
final GlobalKey<EditableTextState> editableTextKey = GlobalKey<EditableTextState>();
final FakeTextSelectionGestureDetectorBuilderDelegate delegate = FakeTextSelectionGestureDetectorBuilderDelegate(
editableTextKey: editableTextKey,
forcePressEnabled: false,
selectionEnabled: true,
);
final TextSelectionGestureDetectorBuilder provider =
TextSelectionGestureDetectorBuilder(delegate: delegate);
final FocusNode focusNode = FocusNode();
addTearDown(focusNode.dispose);
await tester.pumpWidget(
MaterialApp(
home: provider.buildGestureDetector(
behavior: HitTestBehavior.translucent,
child: EditableText(
key: editableTextKey,
controller: controller,
focusNode: focusNode,
backgroundCursorColor: Colors.white,
cursorColor: Colors.white,
style: const TextStyle(),
selectionControls: materialTextSelectionControls,
),
),
),
);
expect(controller.selection.isCollapsed, isTrue);
expect(controller.selection.baseOffset, -1);
final Offset position = textOffsetToPosition(tester, 4);
await tester.tapAt(position);
await tester.pump();
expect(controller.selection.isCollapsed, isTrue);
expect(controller.selection.baseOffset, 4);
final TestGesture gesture = await tester.startGesture(position);
addTearDown(gesture.removePointer);
await tester.pump();
await gesture.moveTo(textOffsetToPosition(tester, 7));
await tester.pump();
await gesture.moveTo(textOffsetToPosition(tester, 10));
await tester.pump();
await gesture.up();
await tester.pumpAndSettle();
expect(controller.selection.isCollapsed, isTrue);
expect(controller.selection.baseOffset, 10);
});
testWidgets('Stylus drag moves the cursor', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/102928
final TextEditingController controller = TextEditingController(
text: 'I love flutter!',
);
addTearDown(controller.dispose);
final GlobalKey<EditableTextState> editableTextKey = GlobalKey<EditableTextState>();
final FakeTextSelectionGestureDetectorBuilderDelegate delegate = FakeTextSelectionGestureDetectorBuilderDelegate(
editableTextKey: editableTextKey,
forcePressEnabled: false,
selectionEnabled: true,
);
final TextSelectionGestureDetectorBuilder provider =
TextSelectionGestureDetectorBuilder(delegate: delegate);
final FocusNode focusNode = FocusNode();
addTearDown(focusNode.dispose);
await tester.pumpWidget(
MaterialApp(
home: provider.buildGestureDetector(
behavior: HitTestBehavior.translucent,
child: EditableText(
key: editableTextKey,
controller: controller,
focusNode: focusNode,
backgroundCursorColor: Colors.white,
cursorColor: Colors.white,
style: const TextStyle(),
selectionControls: materialTextSelectionControls,
),
),
),
);
expect(controller.selection.isCollapsed, isTrue);
expect(controller.selection.baseOffset, -1);
final Offset position = textOffsetToPosition(tester, 4);
await tester.tapAt(position);
await tester.pump();
expect(controller.selection.isCollapsed, isTrue);
expect(controller.selection.baseOffset, 4);
final TestGesture gesture = await tester.startGesture(position, kind: PointerDeviceKind.stylus);
addTearDown(gesture.removePointer);
await tester.pump();
await gesture.moveTo(textOffsetToPosition(tester, 7));
await tester.pump();
await gesture.moveTo(textOffsetToPosition(tester, 10));
await tester.pump();
await gesture.up();
await tester.pumpAndSettle();
expect(controller.selection.isCollapsed, isTrue);
expect(controller.selection.baseOffset, 10);
});
testWidgets('Drag of unknown type moves the cursor', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/102928
final TextEditingController controller = TextEditingController(
text: 'I love flutter!',
);
addTearDown(controller.dispose);
final GlobalKey<EditableTextState> editableTextKey = GlobalKey<EditableTextState>();
final FakeTextSelectionGestureDetectorBuilderDelegate delegate = FakeTextSelectionGestureDetectorBuilderDelegate(
editableTextKey: editableTextKey,
forcePressEnabled: false,
selectionEnabled: true,
);
final TextSelectionGestureDetectorBuilder provider =
TextSelectionGestureDetectorBuilder(delegate: delegate);
final FocusNode focusNode = FocusNode();
addTearDown(focusNode.dispose);
await tester.pumpWidget(
MaterialApp(
home: provider.buildGestureDetector(
behavior: HitTestBehavior.translucent,
child: EditableText(
key: editableTextKey,
controller: controller,
focusNode: focusNode,
backgroundCursorColor: Colors.white,
cursorColor: Colors.white,
style: const TextStyle(),
selectionControls: materialTextSelectionControls,
),
),
),
);
expect(controller.selection.isCollapsed, isTrue);
expect(controller.selection.baseOffset, -1);
final Offset position = textOffsetToPosition(tester, 4);
await tester.tapAt(position);
await tester.pump();
expect(controller.selection.isCollapsed, isTrue);
expect(controller.selection.baseOffset, 4);
final TestGesture gesture = await tester.startGesture(position, kind: PointerDeviceKind.unknown);
addTearDown(gesture.removePointer);
await tester.pump();
await gesture.moveTo(textOffsetToPosition(tester, 7));
await tester.pump();
await gesture.moveTo(textOffsetToPosition(tester, 10));
await tester.pump();
await gesture.up();
await tester.pumpAndSettle();
expect(controller.selection.isCollapsed, isTrue);
expect(controller.selection.baseOffset, 10);
});
testWidgets('test TextSelectionGestureDetectorBuilder drag with RenderEditable viewport offset change', (WidgetTester tester) async {
await pumpTextSelectionGestureDetectorBuilder(tester);
final FakeRenderEditable renderEditable = tester.renderObject(find.byType(FakeEditable));
// Reconfigure the RenderEditable for multi-line.
renderEditable.maxLines = null;
final ViewportOffset offset1 = ViewportOffset.fixed(20.0);
addTearDown(offset1.dispose);
renderEditable.offset = offset1;
renderEditable.layout(const BoxConstraints.tightFor(width: 400, height: 300.0));
await tester.pumpAndSettle();
final TestGesture gesture = await tester.startGesture(
const Offset(200.0, 200.0),
kind: PointerDeviceKind.mouse,
);
await tester.pumpAndSettle();
expect(renderEditable.selectPositionAtCalled, isFalse);
await gesture.moveTo(const Offset(300.0, 200.0));
await tester.pumpAndSettle();
expect(renderEditable.selectPositionAtCalled, isTrue);
expect(renderEditable.selectPositionAtFrom, const Offset(200.0, 200.0));
expect(renderEditable.selectPositionAtTo, const Offset(300.0, 200.0));
// Move the viewport offset (scroll).
final ViewportOffset offset2 = ViewportOffset.fixed(150.0);
addTearDown(offset2.dispose);
renderEditable.offset = offset2;
renderEditable.layout(const BoxConstraints.tightFor(width: 400, height: 300.0));
await tester.pumpAndSettle();
await gesture.moveTo(const Offset(300.0, 400.0));
await tester.pumpAndSettle();
await gesture.up();
await tester.pumpAndSettle();
expect(renderEditable.selectPositionAtCalled, isTrue);
expect(renderEditable.selectPositionAtFrom, const Offset(200.0, 70.0));
expect(renderEditable.selectPositionAtTo, const Offset(300.0, 400.0));
});
testWidgets('test TextSelectionGestureDetectorBuilder selection disabled', (WidgetTester tester) async {
await pumpTextSelectionGestureDetectorBuilder(tester, selectionEnabled: false);
final TestGesture gesture = await tester.startGesture(
const Offset(200.0, 200.0),
pointer: 0,
);
await tester.pump(const Duration(seconds: 2));
await gesture.up();
await tester.pumpAndSettle();
final FakeEditableTextState state = tester.state(find.byType(FakeEditableText));
final FakeRenderEditable renderEditable = tester.renderObject(find.byType(FakeEditable));
expect(state.showToolbarCalled, isTrue);
expect(renderEditable.selectWordsInRangeCalled, isFalse);
});
testWidgets('test TextSelectionGestureDetectorBuilder mouse drag disabled', (WidgetTester tester) async {
await pumpTextSelectionGestureDetectorBuilder(tester, selectionEnabled: false);
final TestGesture gesture = await tester.startGesture(
Offset.zero,
kind: PointerDeviceKind.mouse,
);
await tester.pump();
await gesture.moveTo(const Offset(50.0, 0));
await tester.pump();
await gesture.up();
await tester.pumpAndSettle();
final FakeRenderEditable renderEditable = tester.renderObject(find.byType(FakeEditable));
expect(renderEditable.selectPositionAtCalled, isFalse);
});
testWidgets('test TextSelectionGestureDetectorBuilder forcePress disabled', (WidgetTester tester) async {
await pumpTextSelectionGestureDetectorBuilder(tester, forcePressEnabled: false);
final TestGesture gesture = await tester.createGesture();
await gesture.downWithCustomEvent(
const Offset(200.0, 200.0),
const PointerDownEvent(
position: Offset(200.0, 200.0),
pressure: 3.0,
pressureMax: 6.0,
pressureMin: 0.0,
),
);
await gesture.up();
await tester.pump();
final FakeEditableTextState state = tester.state(find.byType(FakeEditableText));
final FakeRenderEditable renderEditable = tester.renderObject(find.byType(FakeEditable));
expect(state.showToolbarCalled, isFalse);
expect(renderEditable.selectWordsInRangeCalled, isFalse);
});
// Regression test for https://github.com/flutter/flutter/issues/37032.
testWidgets("selection handle's GestureDetector should not cover the entire screen", (WidgetTester tester) async {
final TextEditingController controller = TextEditingController(text: 'a');
addTearDown(controller.dispose);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: TextField(
autofocus: true,
controller: controller,
),
),
),
);
await tester.pumpAndSettle();
final Finder gestureDetector = find.descendant(
of: find.byType(CompositedTransformFollower),
matching: find.descendant(
of: find.byType(FadeTransition),
matching: find.byType(RawGestureDetector),
),
);
expect(gestureDetector, findsOneWidget);
// The GestureDetector's size should not exceed that of the TextField.
final Rect hitRect = tester.getRect(gestureDetector);
final Rect textFieldRect = tester.getRect(find.byType(TextField));
expect(hitRect.size.width, lessThan(textFieldRect.size.width));
expect(hitRect.size.height, lessThan(textFieldRect.size.height));
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS }));
group('SelectionOverlay', () {
Future<SelectionOverlay> pumpApp(WidgetTester tester, {
ValueChanged<DragStartDetails>? onStartDragStart,
ValueChanged<DragUpdateDetails>? onStartDragUpdate,
ValueChanged<DragEndDetails>? onStartDragEnd,
ValueChanged<DragStartDetails>? onEndDragStart,
ValueChanged<DragUpdateDetails>? onEndDragUpdate,
ValueChanged<DragEndDetails>? onEndDragEnd,
VoidCallback? onSelectionHandleTapped,
TextSelectionControls? selectionControls,
TextMagnifierConfiguration? magnifierConfiguration,
}) async {
final UniqueKey column = UniqueKey();
final LayerLink startHandleLayerLink = LayerLink();
final LayerLink endHandleLayerLink = LayerLink();
final LayerLink toolbarLayerLink = LayerLink();
await tester.pumpWidget(MaterialApp(
home: Column(
key: column,
children: <Widget>[
CompositedTransformTarget(
link: startHandleLayerLink,
child: const Text('start handle'),
),
CompositedTransformTarget(
link: endHandleLayerLink,
child: const Text('end handle'),
),
CompositedTransformTarget(
link: toolbarLayerLink,
child: const Text('toolbar'),
),
],
),
));
final FakeClipboardStatusNotifier clipboardStatus = FakeClipboardStatusNotifier();
addTearDown(clipboardStatus.dispose);
return SelectionOverlay(
context: tester.element(find.byKey(column)),
onSelectionHandleTapped: onSelectionHandleTapped,
startHandleType: TextSelectionHandleType.collapsed,
startHandleLayerLink: startHandleLayerLink,
lineHeightAtStart: 0.0,
onStartHandleDragStart: onStartDragStart,
onStartHandleDragUpdate: onStartDragUpdate,
onStartHandleDragEnd: onStartDragEnd,
endHandleType: TextSelectionHandleType.collapsed,
endHandleLayerLink: endHandleLayerLink,
lineHeightAtEnd: 0.0,
onEndHandleDragStart: onEndDragStart,
onEndHandleDragUpdate: onEndDragUpdate,
onEndHandleDragEnd: onEndDragEnd,
clipboardStatus: clipboardStatus,
selectionDelegate: FakeTextSelectionDelegate(),
selectionControls: selectionControls,
selectionEndpoints: const <TextSelectionPoint>[],
toolbarLayerLink: toolbarLayerLink,
magnifierConfiguration: magnifierConfiguration ?? TextMagnifierConfiguration.disabled,
);
}
testWidgets('dispatches memory events', (WidgetTester tester) async {
await expectLater(
await memoryEvents(
() async {
final SelectionOverlay overlay = await pumpApp(tester);
overlay.dispose();
},
SelectionOverlay,
),
areCreateAndDispose,
);
});
testWidgets('can show and hide handles', (WidgetTester tester) async {
final TextSelectionControlsSpy spy = TextSelectionControlsSpy();
final SelectionOverlay selectionOverlay = await pumpApp(
tester,
selectionControls: spy,
);
selectionOverlay
..startHandleType = TextSelectionHandleType.left
..endHandleType = TextSelectionHandleType.right
..selectionEndpoints = const <TextSelectionPoint>[
TextSelectionPoint(Offset(10, 10), TextDirection.ltr),
TextSelectionPoint(Offset(20, 20), TextDirection.ltr),
];
selectionOverlay.showHandles();
await tester.pump();
expect(find.byKey(spy.leftHandleKey), findsOneWidget);
expect(find.byKey(spy.rightHandleKey), findsOneWidget);
selectionOverlay.hideHandles();
await tester.pump();
expect(find.byKey(spy.leftHandleKey), findsNothing);
expect(find.byKey(spy.rightHandleKey), findsNothing);
selectionOverlay.showToolbar();
await tester.pump();
expect(find.byKey(spy.toolBarKey), findsOneWidget);
selectionOverlay.hideToolbar();
await tester.pump();
expect(find.byKey(spy.toolBarKey), findsNothing);
selectionOverlay.showHandles();
selectionOverlay.showToolbar();
await tester.pump();
expect(find.byKey(spy.leftHandleKey), findsOneWidget);
expect(find.byKey(spy.rightHandleKey), findsOneWidget);
expect(find.byKey(spy.toolBarKey), findsOneWidget);
selectionOverlay.hide();
await tester.pump();
expect(find.byKey(spy.leftHandleKey), findsNothing);
expect(find.byKey(spy.rightHandleKey), findsNothing);
expect(find.byKey(spy.toolBarKey), findsNothing);
selectionOverlay.dispose();
await tester.pumpAndSettle();
});
testWidgets('only paints one collapsed handle', (WidgetTester tester) async {
final TextSelectionControlsSpy spy = TextSelectionControlsSpy();
final SelectionOverlay selectionOverlay = await pumpApp(
tester,
selectionControls: spy,
);
selectionOverlay
..startHandleType = TextSelectionHandleType.collapsed
..endHandleType = TextSelectionHandleType.collapsed
..selectionEndpoints = const <TextSelectionPoint>[
TextSelectionPoint(Offset(10, 10), TextDirection.ltr),
TextSelectionPoint(Offset(20, 20), TextDirection.ltr),
];
selectionOverlay.showHandles();
await tester.pump();
expect(find.byKey(spy.leftHandleKey), findsNothing);
expect(find.byKey(spy.rightHandleKey), findsNothing);
expect(find.byKey(spy.collapsedHandleKey), findsOneWidget);
selectionOverlay.dispose();
await tester.pumpAndSettle();
});
testWidgets('can change handle parameter', (WidgetTester tester) async {
final TextSelectionControlsSpy spy = TextSelectionControlsSpy();
final SelectionOverlay selectionOverlay = await pumpApp(
tester,
selectionControls: spy,
);
selectionOverlay
..startHandleType = TextSelectionHandleType.left
..lineHeightAtStart = 10.0
..endHandleType = TextSelectionHandleType.right
..lineHeightAtEnd = 11.0
..selectionEndpoints = const <TextSelectionPoint>[
TextSelectionPoint(Offset(10, 10), TextDirection.ltr),
TextSelectionPoint(Offset(20, 20), TextDirection.ltr),
];
selectionOverlay.showHandles();
await tester.pump();
Text leftHandle = tester.widget(find.byKey(spy.leftHandleKey)) as Text;
Text rightHandle = tester.widget(find.byKey(spy.rightHandleKey)) as Text;
expect(leftHandle.data, 'height 10');
expect(rightHandle.data, 'height 11');
selectionOverlay
..startHandleType = TextSelectionHandleType.right
..lineHeightAtStart = 12.0
..endHandleType = TextSelectionHandleType.left
..lineHeightAtEnd = 13.0;
await tester.pump();
leftHandle = tester.widget(find.byKey(spy.leftHandleKey)) as Text;
rightHandle = tester.widget(find.byKey(spy.rightHandleKey)) as Text;
expect(leftHandle.data, 'height 13');
expect(rightHandle.data, 'height 12');
selectionOverlay.dispose();
await tester.pumpAndSettle();
});
testWidgets('can trigger selection handle onTap', (WidgetTester tester) async {
bool selectionHandleTapped = false;
void handleTapped() => selectionHandleTapped = true;
final TextSelectionControlsSpy spy = TextSelectionControlsSpy();
final SelectionOverlay selectionOverlay = await pumpApp(
tester,
onSelectionHandleTapped: handleTapped,
selectionControls: spy,
);
selectionOverlay
..startHandleType = TextSelectionHandleType.left
..lineHeightAtStart = 10.0
..endHandleType = TextSelectionHandleType.right
..lineHeightAtEnd = 11.0
..selectionEndpoints = const <TextSelectionPoint>[
TextSelectionPoint(Offset(10, 10), TextDirection.ltr),
TextSelectionPoint(Offset(20, 20), TextDirection.ltr),
];
selectionOverlay.showHandles();
await tester.pump();
expect(find.byKey(spy.leftHandleKey), findsOneWidget);
expect(find.byKey(spy.rightHandleKey), findsOneWidget);
expect(selectionHandleTapped, isFalse);
await tester.tap(find.byKey(spy.leftHandleKey));
expect(selectionHandleTapped, isTrue);
selectionHandleTapped = false;
await tester.tap(find.byKey(spy.rightHandleKey));
expect(selectionHandleTapped, isTrue);
selectionOverlay.dispose();
await tester.pumpAndSettle();
});
testWidgets('can trigger selection handle drag', (WidgetTester tester) async {
DragStartDetails? startDragStartDetails;
DragUpdateDetails? startDragUpdateDetails;
DragEndDetails? startDragEndDetails;
DragStartDetails? endDragStartDetails;
DragUpdateDetails? endDragUpdateDetails;
DragEndDetails? endDragEndDetails;
void startDragStart(DragStartDetails details) => startDragStartDetails = details;
void startDragUpdate(DragUpdateDetails details) => startDragUpdateDetails = details;
void startDragEnd(DragEndDetails details) => startDragEndDetails = details;
void endDragStart(DragStartDetails details) => endDragStartDetails = details;
void endDragUpdate(DragUpdateDetails details) => endDragUpdateDetails = details;
void endDragEnd(DragEndDetails details) => endDragEndDetails = details;
final TextSelectionControlsSpy spy = TextSelectionControlsSpy();
final SelectionOverlay selectionOverlay = await pumpApp(
tester,
onStartDragStart: startDragStart,
onStartDragUpdate: startDragUpdate,
onStartDragEnd: startDragEnd,
onEndDragStart: endDragStart,
onEndDragUpdate: endDragUpdate,
onEndDragEnd: endDragEnd,
selectionControls: spy,
);
selectionOverlay
..startHandleType = TextSelectionHandleType.left
..lineHeightAtStart = 10.0
..endHandleType = TextSelectionHandleType.right
..lineHeightAtEnd = 11.0
..selectionEndpoints = const <TextSelectionPoint>[
TextSelectionPoint(Offset(10, 10), TextDirection.ltr),
TextSelectionPoint(Offset(20, 20), TextDirection.ltr),
];
selectionOverlay.showHandles();
await tester.pump();
expect(find.byKey(spy.leftHandleKey), findsOneWidget);
expect(find.byKey(spy.rightHandleKey), findsOneWidget);
expect(startDragStartDetails, isNull);
expect(startDragUpdateDetails, isNull);
expect(startDragEndDetails, isNull);
expect(endDragStartDetails, isNull);
expect(endDragUpdateDetails, isNull);
expect(endDragEndDetails, isNull);
final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byKey(spy.leftHandleKey)));
await tester.pump(const Duration(milliseconds: 200));
expect(startDragStartDetails!.globalPosition, tester.getCenter(find.byKey(spy.leftHandleKey)));
const Offset newLocation = Offset(20, 20);
await gesture.moveTo(newLocation);
await tester.pump(const Duration(milliseconds: 20));
expect(startDragUpdateDetails!.globalPosition, newLocation);
await gesture.up();
await tester.pump(const Duration(milliseconds: 20));
expect(startDragEndDetails, isNotNull);
final TestGesture gesture2 = await tester.startGesture(tester.getCenter(find.byKey(spy.rightHandleKey)));
addTearDown(gesture2.removePointer);
await tester.pump(const Duration(milliseconds: 200));
expect(endDragStartDetails!.globalPosition, tester.getCenter(find.byKey(spy.rightHandleKey)));
await gesture2.moveTo(newLocation);
await tester.pump(const Duration(milliseconds: 20));
expect(endDragUpdateDetails!.globalPosition, newLocation);
await gesture2.up();
await tester.pump(const Duration(milliseconds: 20));
expect(endDragEndDetails, isNotNull);
selectionOverlay.dispose();
await tester.pumpAndSettle();
});
testWidgets('can show magnifier when no handles exist', (WidgetTester tester) async {
final GlobalKey magnifierKey = GlobalKey();
final SelectionOverlay selectionOverlay = await pumpApp(
tester,
magnifierConfiguration: TextMagnifierConfiguration(
shouldDisplayHandlesInMagnifier: false,
magnifierBuilder: (BuildContext context, MagnifierController controller, ValueNotifier<MagnifierInfo>? notifier) {
return SizedBox.shrink(
key: magnifierKey,
);
},
),
);
expect(find.byKey(magnifierKey), findsNothing);
final MagnifierInfo info = MagnifierInfo(
globalGesturePosition: Offset.zero,
caretRect: Offset.zero & const Size(5.0, 20.0),
fieldBounds: Offset.zero & const Size(200.0, 50.0),
currentLineBoundaries: Offset.zero & const Size(200.0, 50.0),
);
selectionOverlay.showMagnifier(info);
await tester.pump();
expect(tester.takeException(), isNull);
expect(find.byKey(magnifierKey), findsOneWidget);
selectionOverlay.dispose();
await tester.pumpAndSettle();
});
});
group('ClipboardStatusNotifier', () {
group('when Clipboard fails', () {
setUp(() {
final MockClipboard mockClipboard = MockClipboard(hasStringsThrows: true);
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, mockClipboard.handleMethodCall);
});
tearDown(() {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, null);
});
test('Clipboard API failure is gracefully recovered from', () async {
final ClipboardStatusNotifier notifier = ClipboardStatusNotifier();
expect(notifier.value, ClipboardStatus.unknown);
await expectLater(notifier.update(), completes);
expect(notifier.value, ClipboardStatus.unknown);
});
});
group('when Clipboard succeeds', () {
final MockClipboard mockClipboard = MockClipboard();
setUp(() {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, mockClipboard.handleMethodCall);
});
tearDown(() {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, null);
});
test('update sets value based on clipboard contents', () async {
final ClipboardStatusNotifier notifier = ClipboardStatusNotifier();
expect(notifier.value, ClipboardStatus.unknown);
await expectLater(notifier.update(), completes);
expect(notifier.value, ClipboardStatus.notPasteable);
mockClipboard.handleMethodCall(const MethodCall(
'Clipboard.setData',
<String, dynamic>{
'text': 'pasteablestring',
},
));
await expectLater(notifier.update(), completes);
expect(notifier.value, ClipboardStatus.pasteable);
});
});
});
testWidgets('Mouse edge scrolling works in an outer scrollable', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/102484
final TextEditingController controller = TextEditingController(
text: 'I love flutter!\n' * 8,
);
addTearDown(controller.dispose);
final GlobalKey<EditableTextState> editableTextKey = GlobalKey<EditableTextState>();
final FakeTextSelectionGestureDetectorBuilderDelegate delegate = FakeTextSelectionGestureDetectorBuilderDelegate(
editableTextKey: editableTextKey,
forcePressEnabled: false,
selectionEnabled: true,
);
final ScrollController scrollController = ScrollController();
addTearDown(scrollController.dispose);
const double kLineHeight = 16.0;
final TextSelectionGestureDetectorBuilder provider =
TextSelectionGestureDetectorBuilder(
delegate: delegate,
);
final FocusNode focusNode = FocusNode();
addTearDown(focusNode.dispose);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: SizedBox(
// Only 4 lines visible of 8 given.
height: kLineHeight * 4,
child: SingleChildScrollView(
controller: scrollController,
child: provider.buildGestureDetector(
behavior: HitTestBehavior.translucent,
child: EditableText(
key: editableTextKey,
controller: controller,
focusNode: focusNode,
backgroundCursorColor: Colors.white,
cursorColor: Colors.white,
style: const TextStyle(),
selectionControls: materialTextSelectionControls,
// EditableText will expand to the full 8 line height and will
// not scroll itself.
maxLines: null,
),
),
),
),
),
),
);
expect(controller.selection.isCollapsed, isTrue);
expect(controller.selection.baseOffset, -1);
expect(scrollController.position.pixels, 0.0);
final Offset position = textOffsetToPosition(tester, 4);
await tester.tapAt(position);
await tester.pump();
expect(controller.selection.isCollapsed, isTrue);
expect(controller.selection.baseOffset, 4);
// Select all text with the mouse.
final TestGesture gesture = await tester.startGesture(position, kind: PointerDeviceKind.mouse);
addTearDown(gesture.removePointer);
await tester.pump();
await gesture.moveTo(textOffsetToPosition(tester, (controller.text.length / 2).floor()));
await tester.pump();
await gesture.moveTo(textOffsetToPosition(tester, controller.text.length));
await tester.pump();
await gesture.up();
await tester.pumpAndSettle();
expect(controller.selection.isCollapsed, isFalse);
expect(controller.selection.baseOffset, 4);
expect(controller.selection.extentOffset, controller.text.length);
expect(scrollController.position.pixels, scrollController.position.maxScrollExtent);
});
testWidgets('Mouse edge scrolling works with both an outer scrollable and scrolling in the EditableText', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/102484
final TextEditingController controller = TextEditingController(
text: 'I love flutter!\n' * 8,
);
addTearDown(controller.dispose);
final GlobalKey<EditableTextState> editableTextKey = GlobalKey<EditableTextState>();
final FakeTextSelectionGestureDetectorBuilderDelegate delegate = FakeTextSelectionGestureDetectorBuilderDelegate(
editableTextKey: editableTextKey,
forcePressEnabled: false,
selectionEnabled: true,
);
final ScrollController scrollController = ScrollController();
addTearDown(scrollController.dispose);
const double kLineHeight = 16.0;
final TextSelectionGestureDetectorBuilder provider =
TextSelectionGestureDetectorBuilder(
delegate: delegate,
);
final FocusNode focusNode = FocusNode();
addTearDown(focusNode.dispose);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: SizedBox(
// Only 4 lines visible of 8 given.
height: kLineHeight * 4,
child: SingleChildScrollView(
controller: scrollController,
child: provider.buildGestureDetector(
behavior: HitTestBehavior.translucent,
child: EditableText(
key: editableTextKey,
controller: controller,
focusNode: focusNode,
backgroundCursorColor: Colors.white,
cursorColor: Colors.white,
style: const TextStyle(),
selectionControls: materialTextSelectionControls,
// EditableText is taller than the SizedBox but not taller
// than the text.
maxLines: 6,
),
),
),
),
),
),
);
expect(controller.selection.isCollapsed, isTrue);
expect(controller.selection.baseOffset, -1);
expect(scrollController.position.pixels, 0.0);
final Offset position = textOffsetToPosition(tester, 4);
await tester.tapAt(position);
await tester.pump();
expect(controller.selection.isCollapsed, isTrue);
expect(controller.selection.baseOffset, 4);
// Select all text with the mouse.
final TestGesture gesture = await tester.startGesture(position, kind: PointerDeviceKind.mouse);
addTearDown(gesture.removePointer);
await tester.pump();
await gesture.moveTo(textOffsetToPosition(tester, (controller.text.length / 2).floor()));
await tester.pump();
await gesture.moveTo(textOffsetToPosition(tester, controller.text.length));
await tester.pump();
await gesture.up();
await tester.pumpAndSettle();
expect(controller.selection.isCollapsed, isFalse);
expect(controller.selection.baseOffset, 4);
expect(controller.selection.extentOffset, controller.text.length);
expect(scrollController.position.pixels, scrollController.position.maxScrollExtent);
});
group('TextSelectionOverlay', () {
Future<TextSelectionOverlay> pumpApp(WidgetTester tester) async {
final UniqueKey column = UniqueKey();
final LayerLink startHandleLayerLink = LayerLink();
final LayerLink endHandleLayerLink = LayerLink();
final LayerLink toolbarLayerLink = LayerLink();
final UniqueKey editableText = UniqueKey();
final TextEditingController controller = TextEditingController();
addTearDown(controller.dispose);
final FocusNode focusNode = FocusNode();
addTearDown(focusNode.dispose);
await tester.pumpWidget(MaterialApp(
home: Column(
key: column,
children: <Widget>[
FakeEditableText(
key: editableText,
controller: controller,
focusNode: focusNode,
),
CompositedTransformTarget(
link: startHandleLayerLink,
child: const Text('start handle'),
),
CompositedTransformTarget(
link: endHandleLayerLink,
child: const Text('end handle'),
),
CompositedTransformTarget(
link: toolbarLayerLink,
child: const Text('toolbar'),
),
],
),
));
return TextSelectionOverlay(
value: TextEditingValue.empty,
renderObject: tester.state<EditableTextState>(find.byKey(editableText)).renderEditable,
context: tester.element(find.byKey(column)),
onSelectionHandleTapped: () {},
startHandleLayerLink: startHandleLayerLink,
endHandleLayerLink: endHandleLayerLink,
selectionDelegate: FakeTextSelectionDelegate(),
toolbarLayerLink: toolbarLayerLink,
magnifierConfiguration: TextMagnifierConfiguration.disabled,
);
}
testWidgets('dispatches memory events', (WidgetTester tester) async {
await expectLater(
await memoryEvents(
() async {
final TextSelectionOverlay overlay = await pumpApp(tester);
overlay.dispose();
},
TextSelectionOverlay,
),
areCreateAndDispose,
);
});
});
testWidgets('Context menus', (WidgetTester tester) async {
final TextEditingController controller = TextEditingController(
text: 'You make wine from sour grapes',
);
addTearDown(controller.dispose);
final GlobalKey<EditableTextState> editableTextKey = GlobalKey<EditableTextState>();
final FakeTextSelectionGestureDetectorBuilderDelegate delegate = FakeTextSelectionGestureDetectorBuilderDelegate(
editableTextKey: editableTextKey,
forcePressEnabled: false,
selectionEnabled: true,
);
final TextSelectionGestureDetectorBuilder provider =
TextSelectionGestureDetectorBuilder(delegate: delegate);
final FocusNode focusNode = FocusNode();
addTearDown(focusNode.dispose);
await tester.pumpWidget(
MaterialApp(
home: provider.buildGestureDetector(
behavior: HitTestBehavior.translucent,
child: EditableText(
key: editableTextKey,
controller: controller,
focusNode: focusNode,
backgroundCursorColor: Colors.white,
cursorColor: Colors.white,
style: const TextStyle(),
contextMenuBuilder: (
BuildContext context,
EditableTextState editableTextState,
) {
return const Placeholder();
},
),
),
),
);
final Offset position = textOffsetToPosition(tester, 0);
expect(find.byType(Placeholder), findsNothing);
await tester.tapAt(position, buttons: kSecondaryMouseButton, kind: PointerDeviceKind.mouse);
await tester.pump();
expect(find.byType(Placeholder), findsOneWidget);
}, skip: kIsWeb); // [intended] On web, we use native context menus for text fields.
}
class FakeTextSelectionGestureDetectorBuilderDelegate implements TextSelectionGestureDetectorBuilderDelegate {
FakeTextSelectionGestureDetectorBuilderDelegate({
required this.editableTextKey,
required this.forcePressEnabled,
required this.selectionEnabled,
});
@override
final GlobalKey<EditableTextState> editableTextKey;
@override
final bool forcePressEnabled;
@override
final bool selectionEnabled;
}
class FakeEditableText extends EditableText {
FakeEditableText({
required super.controller,
required super.focusNode,
super.key,
}): super(
backgroundCursorColor: Colors.white,
cursorColor: Colors.white,
style: const TextStyle(),
);
@override
FakeEditableTextState createState() => FakeEditableTextState();
}
class FakeEditableTextState extends EditableTextState {
final GlobalKey _editableKey = GlobalKey();
bool showToolbarCalled = false;
bool toggleToolbarCalled = false;
bool showSpellCheckSuggestionsToolbarCalled = false;
bool markCurrentSelectionAsMisspelled = false;
@override
RenderEditable get renderEditable => _editableKey.currentContext!.findRenderObject()! as RenderEditable;
@override
bool showToolbar() {
showToolbarCalled = true;
return true;
}
@override
void toggleToolbar([bool hideHandles = true]) {
toggleToolbarCalled = true;
return;
}
@override
bool showSpellCheckSuggestionsToolbar() {
showSpellCheckSuggestionsToolbarCalled = true;
return true;
}
@override
SuggestionSpan? findSuggestionSpanAtCursorIndex(int cursorIndex) {
return markCurrentSelectionAsMisspelled
? const SuggestionSpan(
TextRange(start: 7, end: 12),
<String>['word', 'world', 'old'],
) : null;
}
@override
Widget build(BuildContext context) {
super.build(context);
return FakeEditable(this, key: _editableKey);
}
}
class FakeEditable extends LeafRenderObjectWidget {
const FakeEditable(
this.delegate, {
super.key,
});
final EditableTextState delegate;
@override
RenderEditable createRenderObject(BuildContext context) {
return FakeRenderEditable(delegate);
}
}
class FakeRenderEditable extends RenderEditable {
FakeRenderEditable(EditableTextState delegate)
: this._(delegate, ViewportOffset.fixed(10.0));
FakeRenderEditable._(
EditableTextState delegate,
this._offset,
) : super(
text: const TextSpan(
style: TextStyle(height: 1.0, fontSize: 10.0),
text: 'placeholder',
),
startHandleLayerLink: LayerLink(),
endHandleLayerLink: LayerLink(),
ignorePointer: true,
textAlign: TextAlign.start,
textDirection: TextDirection.ltr,
locale: const Locale('en', 'US'),
offset: _offset,
textSelectionDelegate: delegate,
selection: const TextSelection.collapsed(
offset: 0,
),
);
SelectionChangedCause? lastCause;
ViewportOffset _offset;
bool selectWordsInRangeCalled = false;
@override
void selectWordsInRange({ required Offset from, Offset? to, required SelectionChangedCause cause }) {
selectWordsInRangeCalled = true;
hasFocus = true;
lastCause = cause;
}
bool selectWordEdgeCalled = false;
@override
void selectWordEdge({ required SelectionChangedCause cause }) {
selectWordEdgeCalled = true;
hasFocus = true;
lastCause = cause;
}
bool selectPositionAtCalled = false;
Offset? selectPositionAtFrom;
Offset? selectPositionAtTo;
@override
void selectPositionAt({ required Offset from, Offset? to, required SelectionChangedCause cause }) {
selectPositionAtCalled = true;
selectPositionAtFrom = from;
selectPositionAtTo = to;
hasFocus = true;
lastCause = cause;
}
bool selectPositionCalled = false;
@override
void selectPosition({ required SelectionChangedCause cause }) {
selectPositionCalled = true;
lastCause = cause;
return super.selectPosition(cause: cause);
}
bool selectWordCalled = false;
@override
void selectWord({ required SelectionChangedCause cause }) {
selectWordCalled = true;
hasFocus = true;
lastCause = cause;
}
@override
bool hasFocus = false;
@override
void dispose() {
_offset.dispose();
super.dispose();
}
}
class TextSelectionControlsSpy extends TextSelectionControls {
UniqueKey leftHandleKey = UniqueKey();
UniqueKey rightHandleKey = UniqueKey();
UniqueKey collapsedHandleKey = UniqueKey();
UniqueKey toolBarKey = UniqueKey();
@override
Widget buildHandle(BuildContext context, TextSelectionHandleType type, double textLineHeight, [VoidCallback? onTap]) {
return ElevatedButton(
onPressed: onTap,
child: Text(
key: switch (type) {
TextSelectionHandleType.left => leftHandleKey,
TextSelectionHandleType.right => rightHandleKey,
TextSelectionHandleType.collapsed => collapsedHandleKey,
},
'height ${textLineHeight.toInt()}',
),
);
}
@override
Widget buildToolbar(
BuildContext context,
Rect globalEditableRegion,
double textLineHeight,
Offset position,
List<TextSelectionPoint> endpoints,
TextSelectionDelegate delegate,
ValueListenable<ClipboardStatus>? clipboardStatus,
Offset? lastSecondaryTapDownPosition,
) {
return Text('dummy', key: toolBarKey);
}
@override
Offset getHandleAnchor(TextSelectionHandleType type, double textLineHeight) {
return Offset.zero;
}
@override
Size getHandleSize(double textLineHeight) {
return Size(textLineHeight, textLineHeight);
}
}
class FakeClipboardStatusNotifier extends ClipboardStatusNotifier {
FakeClipboardStatusNotifier() : super(value: ClipboardStatus.unknown);
bool updateCalled = false;
@override
Future<void> update() async {
updateCalled = true;
}
}
class FakeTextSelectionDelegate extends Fake implements TextSelectionDelegate {
@override
void cutSelection(SelectionChangedCause cause) { }
@override
void copySelection(SelectionChangedCause cause) { }
}
| flutter/packages/flutter/test/widgets/text_selection_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/text_selection_test.dart",
"repo_id": "flutter",
"token_count": 27974
} | 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:math' as math;
import 'package:flutter/foundation.dart' show clampDouble;
import 'package:flutter/gestures.dart' show DragStartBehavior;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart' show ViewportOffset;
// BUILDER DELEGATE ---
final TwoDimensionalChildBuilderDelegate builderDelegate = TwoDimensionalChildBuilderDelegate(
maxXIndex: 5,
maxYIndex: 5,
builder: (BuildContext context, ChildVicinity vicinity) {
return Container(
key: ValueKey<ChildVicinity>(vicinity),
color: vicinity.xIndex.isEven && vicinity.yIndex.isEven
? Colors.amber[100]
: (vicinity.xIndex.isOdd && vicinity.yIndex.isOdd
? Colors.blueAccent[100]
: null),
height: 200,
width: 200,
child: Center(child: Text('R${vicinity.xIndex}:C${vicinity.yIndex}')),
);
}
);
// Creates a simple 2D table of 200x200 squares with a builder delegate.
Widget simpleBuilderTest({
Axis mainAxis = Axis.vertical,
bool? primary,
ScrollableDetails? verticalDetails,
ScrollableDetails? horizontalDetails,
TwoDimensionalChildBuilderDelegate? delegate,
double? cacheExtent,
DiagonalDragBehavior? diagonalDrag,
Clip? clipBehavior,
String? restorationID,
bool useCacheExtent = false,
bool applyDimensions = true,
bool forgetToLayoutChild = false,
bool setLayoutOffset = true,
}) {
return MaterialApp(
theme: ThemeData(useMaterial3: false),
restorationScopeId: restorationID,
home: Scaffold(
body: SimpleBuilderTableView(
mainAxis: mainAxis,
verticalDetails: verticalDetails ?? const ScrollableDetails.vertical(),
horizontalDetails: horizontalDetails ?? const ScrollableDetails.horizontal(),
cacheExtent: cacheExtent,
useCacheExtent: useCacheExtent,
diagonalDragBehavior: diagonalDrag ?? DiagonalDragBehavior.none,
clipBehavior: clipBehavior ?? Clip.hardEdge,
delegate: delegate ?? builderDelegate,
applyDimensions: applyDimensions,
forgetToLayoutChild: forgetToLayoutChild,
setLayoutOffset: setLayoutOffset,
),
),
);
}
class SimpleBuilderTableView extends TwoDimensionalScrollView {
const SimpleBuilderTableView({
super.key,
super.primary,
super.mainAxis = Axis.vertical,
super.verticalDetails = const ScrollableDetails.vertical(),
super.horizontalDetails = const ScrollableDetails.horizontal(),
required TwoDimensionalChildBuilderDelegate delegate,
super.cacheExtent,
super.diagonalDragBehavior = DiagonalDragBehavior.none,
super.dragStartBehavior = DragStartBehavior.start,
super.keyboardDismissBehavior = ScrollViewKeyboardDismissBehavior.manual,
super.clipBehavior = Clip.hardEdge,
this.useCacheExtent = false,
this.applyDimensions = true,
this.forgetToLayoutChild = false,
this.setLayoutOffset = true,
}) : super(delegate: delegate);
// Piped through for testing in RenderTwoDimensionalViewport
final bool useCacheExtent;
final bool applyDimensions;
final bool forgetToLayoutChild;
final bool setLayoutOffset;
@override
Widget buildViewport(BuildContext context, ViewportOffset verticalOffset, ViewportOffset horizontalOffset) {
return SimpleBuilderTableViewport(
horizontalOffset: horizontalOffset,
horizontalAxisDirection: horizontalDetails.direction,
verticalOffset: verticalOffset,
verticalAxisDirection: verticalDetails.direction,
mainAxis: mainAxis,
delegate: delegate as TwoDimensionalChildBuilderDelegate,
cacheExtent: cacheExtent,
clipBehavior: clipBehavior,
useCacheExtent: useCacheExtent,
applyDimensions: applyDimensions,
forgetToLayoutChild: forgetToLayoutChild,
setLayoutOffset: setLayoutOffset,
);
}
}
class SimpleBuilderTableViewport extends TwoDimensionalViewport {
const SimpleBuilderTableViewport({
super.key,
required super.verticalOffset,
required super.verticalAxisDirection,
required super.horizontalOffset,
required super.horizontalAxisDirection,
required TwoDimensionalChildBuilderDelegate delegate,
required super.mainAxis,
super.cacheExtent,
super.clipBehavior = Clip.hardEdge,
this.useCacheExtent = false,
this.applyDimensions = true,
this.forgetToLayoutChild = false,
this.setLayoutOffset = true,
}) : super(delegate: delegate);
// Piped through for testing in RenderTwoDimensionalViewport
final bool useCacheExtent;
final bool applyDimensions;
final bool forgetToLayoutChild;
final bool setLayoutOffset;
@override
RenderTwoDimensionalViewport createRenderObject(BuildContext context) {
return RenderSimpleBuilderTableViewport(
horizontalOffset: horizontalOffset,
horizontalAxisDirection: horizontalAxisDirection,
verticalOffset: verticalOffset,
verticalAxisDirection: verticalAxisDirection,
mainAxis: mainAxis,
delegate: delegate as TwoDimensionalChildBuilderDelegate,
childManager: context as TwoDimensionalChildManager,
cacheExtent: cacheExtent,
clipBehavior: clipBehavior,
useCacheExtent: useCacheExtent,
applyDimensions: applyDimensions,
forgetToLayoutChild: forgetToLayoutChild,
setLayoutOffset: setLayoutOffset,
);
}
@override
void updateRenderObject(BuildContext context, RenderSimpleBuilderTableViewport renderObject) {
renderObject
..horizontalOffset = horizontalOffset
..horizontalAxisDirection = horizontalAxisDirection
..verticalOffset = verticalOffset
..verticalAxisDirection = verticalAxisDirection
..mainAxis = mainAxis
..delegate = delegate
..cacheExtent = cacheExtent
..clipBehavior = clipBehavior;
}
}
class RenderSimpleBuilderTableViewport extends RenderTwoDimensionalViewport {
RenderSimpleBuilderTableViewport({
required super.horizontalOffset,
required super.horizontalAxisDirection,
required super.verticalOffset,
required super.verticalAxisDirection,
required TwoDimensionalChildBuilderDelegate delegate,
required super.mainAxis,
required super.childManager,
super.cacheExtent,
super.clipBehavior = Clip.hardEdge,
this.applyDimensions = true,
this.setLayoutOffset = true,
this.useCacheExtent = false,
this.forgetToLayoutChild = false,
}) : super(delegate: delegate);
// These are to test conditions to validate subclass implementations after
// layoutChildSequence
final bool applyDimensions;
final bool setLayoutOffset;
final bool useCacheExtent;
final bool forgetToLayoutChild;
RenderBox? testGetChildFor(ChildVicinity vicinity) => getChildFor(vicinity);
@override
TestExtendedParentData parentDataOf(RenderBox child) {
return super.parentDataOf(child) as TestExtendedParentData;
}
@override
void setupParentData(RenderBox child) {
if (child.parentData is! TestExtendedParentData) {
child.parentData = TestExtendedParentData();
}
}
@override
void layoutChildSequence() {
// Really simple table implementation for testing.
// Every child is 200x200 square
final double horizontalPixels = horizontalOffset.pixels;
final double verticalPixels = verticalOffset.pixels;
final double viewportWidth = viewportDimension.width + (useCacheExtent ? cacheExtent : 0.0);
final double viewportHeight = viewportDimension.height + (useCacheExtent ? cacheExtent : 0.0);
final TwoDimensionalChildBuilderDelegate builderDelegate = delegate as TwoDimensionalChildBuilderDelegate;
final int maxRowIndex;
final int maxColumnIndex;
maxRowIndex = builderDelegate.maxYIndex ?? 5;
maxColumnIndex = builderDelegate.maxXIndex ?? 5;
final int leadingColumn = math.max((horizontalPixels / 200).floor(), 0);
final int leadingRow = math.max((verticalPixels / 200).floor(), 0);
final int trailingColumn = math.min(
((horizontalPixels + viewportWidth) / 200).ceil(),
maxColumnIndex,
);
final int trailingRow = math.min(
((verticalPixels + viewportHeight) / 200).ceil(),
maxRowIndex,
);
double xLayoutOffset = (leadingColumn * 200) - horizontalOffset.pixels;
for (int column = leadingColumn; column <= trailingColumn; column++) {
double yLayoutOffset = (leadingRow * 200) - verticalOffset.pixels;
for (int row = leadingRow; row <= trailingRow; row++) {
final ChildVicinity vicinity = ChildVicinity(xIndex: column, yIndex: row);
final RenderBox child = buildOrObtainChildFor(vicinity)!;
if (!forgetToLayoutChild) {
child.layout(constraints.tighten(width: 200.0, height: 200.0));
}
if (setLayoutOffset) {
parentDataOf(child).layoutOffset = Offset(xLayoutOffset, yLayoutOffset);
}
yLayoutOffset += 200;
}
xLayoutOffset += 200;
}
if (applyDimensions) {
final double verticalExtent = 200 * (maxRowIndex + 1);
verticalOffset.applyContentDimensions(
0.0,
clampDouble(verticalExtent - viewportDimension.height, 0.0, double.infinity),
);
final double horizontalExtent = 200 * (maxColumnIndex + 1);
horizontalOffset.applyContentDimensions(
0.0,
clampDouble(horizontalExtent - viewportDimension.width, 0.0, double.infinity),
);
}
}
}
// LIST DELEGATE ---
final List<List<Widget>> children = List<List<Widget>>.generate(
100,
(int xIndex) {
return List<Widget>.generate(
100,
(int yIndex) {
return Container(
color: xIndex.isEven && yIndex.isEven
? Colors.amber[100]
: (xIndex.isOdd && yIndex.isOdd
? Colors.blueAccent[100]
: null),
height: 200,
width: 200,
child: Center(child: Text('R$xIndex:C$yIndex')),
);
},
);
},
);
// Builds a simple 2D table of 200x200 squares with a list delegate.
Widget simpleListTest({
Axis mainAxis = Axis.vertical,
bool? primary,
ScrollableDetails? verticalDetails,
ScrollableDetails? horizontalDetails,
TwoDimensionalChildListDelegate? delegate,
double? cacheExtent,
DiagonalDragBehavior? diagonalDrag,
Clip? clipBehavior,
}) {
return MaterialApp(
theme: ThemeData(useMaterial3: true),
home: Scaffold(
body: SimpleListTableView(
mainAxis: mainAxis,
verticalDetails: verticalDetails ?? const ScrollableDetails.vertical(),
horizontalDetails: horizontalDetails ?? const ScrollableDetails.horizontal(),
cacheExtent: cacheExtent,
diagonalDragBehavior: diagonalDrag ?? DiagonalDragBehavior.none,
clipBehavior: clipBehavior ?? Clip.hardEdge,
delegate: delegate ?? TwoDimensionalChildListDelegate(children: children),
),
),
);
}
class SimpleListTableView extends TwoDimensionalScrollView {
const SimpleListTableView({
super.key,
super.primary,
super.mainAxis = Axis.vertical,
super.verticalDetails = const ScrollableDetails.vertical(),
super.horizontalDetails = const ScrollableDetails.horizontal(),
required TwoDimensionalChildListDelegate delegate,
super.cacheExtent,
super.diagonalDragBehavior = DiagonalDragBehavior.none,
super.dragStartBehavior = DragStartBehavior.start,
super.keyboardDismissBehavior = ScrollViewKeyboardDismissBehavior.manual,
super.clipBehavior = Clip.hardEdge,
}) : super(delegate: delegate);
@override
Widget buildViewport(BuildContext context, ViewportOffset verticalOffset, ViewportOffset horizontalOffset) {
return SimpleListTableViewport(
horizontalOffset: horizontalOffset,
horizontalAxisDirection: horizontalDetails.direction,
verticalOffset: verticalOffset,
verticalAxisDirection: verticalDetails.direction,
mainAxis: mainAxis,
delegate: delegate as TwoDimensionalChildListDelegate,
cacheExtent: cacheExtent,
clipBehavior: clipBehavior,
);
}
}
class SimpleListTableViewport extends TwoDimensionalViewport {
const SimpleListTableViewport({
super.key,
required super.verticalOffset,
required super.verticalAxisDirection,
required super.horizontalOffset,
required super.horizontalAxisDirection,
required TwoDimensionalChildListDelegate delegate,
required super.mainAxis,
super.cacheExtent,
super.clipBehavior = Clip.hardEdge,
}) : super(delegate: delegate);
@override
RenderTwoDimensionalViewport createRenderObject(BuildContext context) {
return RenderSimpleListTableViewport(
horizontalOffset: horizontalOffset,
horizontalAxisDirection: horizontalAxisDirection,
verticalOffset: verticalOffset,
verticalAxisDirection: verticalAxisDirection,
mainAxis: mainAxis,
delegate: delegate as TwoDimensionalChildListDelegate,
childManager: context as TwoDimensionalChildManager,
cacheExtent: cacheExtent,
clipBehavior: clipBehavior,
);
}
@override
void updateRenderObject(BuildContext context, RenderSimpleListTableViewport renderObject) {
renderObject
..horizontalOffset = horizontalOffset
..horizontalAxisDirection = horizontalAxisDirection
..verticalOffset = verticalOffset
..verticalAxisDirection = verticalAxisDirection
..mainAxis = mainAxis
..delegate = delegate
..cacheExtent = cacheExtent
..clipBehavior = clipBehavior;
}
}
class RenderSimpleListTableViewport extends RenderTwoDimensionalViewport {
RenderSimpleListTableViewport({
required super.horizontalOffset,
required super.horizontalAxisDirection,
required super.verticalOffset,
required super.verticalAxisDirection,
required TwoDimensionalChildListDelegate delegate,
required super.mainAxis,
required super.childManager,
super.cacheExtent,
super.clipBehavior = Clip.hardEdge,
}) : super(delegate: delegate);
@override
void layoutChildSequence() {
// Really simple table implementation for testing.
// Every child is 200x200 square
final double horizontalPixels = horizontalOffset.pixels;
final double verticalPixels = verticalOffset.pixels;
final TwoDimensionalChildListDelegate listDelegate = delegate as TwoDimensionalChildListDelegate;
final int rowCount;
final int columnCount;
rowCount = listDelegate.children.length;
columnCount = listDelegate.children[0].length;
final int leadingColumn = math.max((horizontalPixels / 200).floor(), 0);
final int leadingRow = math.max((verticalPixels / 200).floor(), 0);
final int trailingColumn = math.min(
((horizontalPixels + viewportDimension.width) / 200).ceil(),
columnCount - 1,
);
final int trailingRow = math.min(
((verticalPixels + viewportDimension.height) / 200).ceil(),
rowCount - 1,
);
double xLayoutOffset = (leadingColumn * 200) - horizontalOffset.pixels;
for (int column = leadingColumn; column <= trailingColumn; column++) {
double yLayoutOffset = (leadingRow * 200) - verticalOffset.pixels;
for (int row = leadingRow; row <= trailingRow; row++) {
final ChildVicinity vicinity = ChildVicinity(xIndex: column, yIndex: row);
final RenderBox child = buildOrObtainChildFor(vicinity)!;
child.layout(constraints.tighten(width: 200.0, height: 200.0));
parentDataOf(child).layoutOffset = Offset(xLayoutOffset, yLayoutOffset);
yLayoutOffset += 200;
}
xLayoutOffset += 200;
}
verticalOffset.applyContentDimensions(
0.0,
math.max(200 * rowCount - viewportDimension.height, 0.0),
);
horizontalOffset.applyContentDimensions(
0,
math.max(200 * columnCount - viewportDimension.width, 0.0),
);
}
}
class KeepAliveCheckBox extends StatefulWidget {
const KeepAliveCheckBox({ super.key });
@override
KeepAliveCheckBoxState createState() => KeepAliveCheckBoxState();
}
class KeepAliveCheckBoxState extends State<KeepAliveCheckBox> with AutomaticKeepAliveClientMixin {
bool checkValue = false;
@override
bool get wantKeepAlive => _wantKeepAlive;
bool _wantKeepAlive = false;
set wantKeepAlive(bool value) {
if (_wantKeepAlive != value) {
_wantKeepAlive = value;
updateKeepAlive();
}
}
@override
Widget build(BuildContext context) {
super.build(context);
return Checkbox(
value: checkValue,
onChanged: (bool? value) {
if (checkValue != value) {
setState(() {
checkValue = value!;
wantKeepAlive = value;
});
}
},
);
}
}
// TwoDimensionalViewportParentData already mixes in KeepAliveParentDataMixin,
// and so should be compatible with both the KeepAlive and
// TestParentDataWidget ParentDataWidgets.
// This ParentData is set up above as part of the
// RenderSimpleBuilderTableViewport for testing.
class TestExtendedParentData extends TwoDimensionalViewportParentData {
int? testValue;
}
class TestParentDataWidget extends ParentDataWidget<TestExtendedParentData> {
const TestParentDataWidget({
super.key,
required super.child,
this.testValue,
});
final int? testValue;
@override
void applyParentData(RenderObject renderObject) {
assert(renderObject.parentData is TestExtendedParentData);
final TestExtendedParentData parentData = renderObject.parentData! as TestExtendedParentData;
parentData.testValue = testValue;
}
@override
Type get debugTypicalAncestorWidgetClass => SimpleBuilderTableViewport;
}
| flutter/packages/flutter/test/widgets/two_dimensional_utils.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/two_dimensional_utils.dart",
"repo_id": "flutter",
"token_count": 6036
} | 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';
void main() {
// Generic reference variables.
BuildContext context;
RenderObjectWidget renderObjectWidget;
RenderObject renderObject;
Object object;
// Changes made in https://github.com/flutter/flutter/pull/26259
Scaffold scaffold = Scaffold(resizeToAvoidBottomInset: true);
scaffold = Scaffold(error: '');
final bool resize = scaffold.resizeToAvoidBottomInset;
// Change made in https://github.com/flutter/flutter/pull/15303
showDialog(builder: (context) => Text('Fix me.'));
showDialog(error: '');
// Changes made in https://github.com/flutter/flutter/pull/44189
const Element element = Element(myWidget);
element.dependOnInheritedElement(ancestor);
element.dependOnInheritedWidgetOfExactType<targetType>();
element.getElementForInheritedWidgetOfExactType<targetType>();
element.findAncestorWidgetOfExactType<targetType>();
element.findAncestorStateOfType<targetType>();
element.findRootAncestorStateOfType<targetType>();
element.findAncestorRenderObjectOfType<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.deferFirstFrame();
binding.allowFirstFrame();
// Changes made in https://github.com/flutter/flutter/pull/44189
const StatefulElement statefulElement = StatefulElement(myWidget);
statefulElement.dependOnInheritedElement(ancestor);
// Changes made in https://github.com/flutter/flutter/pull/44189
const BuildContext buildContext = Element(myWidget);
buildContext.dependOnInheritedElement(ancestor);
buildContext.dependOnInheritedWidgetOfExactType<targetType>();
buildContext.getElementForInheritedWidgetOfExactType<targetType>();
buildContext.findAncestorWidgetOfExactType<targetType>();
buildContext.findAncestorStateOfType<targetType>();
buildContext.findRootAncestorStateOfType<targetType>();
buildContext.findAncestorRenderObjectOfType<targetType>();
// Changes made in https://github.com/flutter/flutter/pull/66305
const Stack stack = Stack(clipBehavior: Clip.none);
const Stack stack = Stack(clipBehavior: Clip.hardEdge);
const Stack stack = Stack(error: '');
final behavior = stack.clipBehavior;
// Changes made in https://github.com/flutter/flutter/pull/61648
const Form form = Form(autovalidateMode: AutovalidateMode.always);
const Form form = Form(autovalidateMode: AutovalidateMode.disabled);
const Form form = Form(error: '');
final autoMode = form.autovalidateMode;
// Changes made in https://github.com/flutter/flutter/pull/61648
const FormField formField = FormField(autovalidateMode: AutovalidateMode.always);
const FormField formField = FormField(autovalidateMode: AutovalidateMode.disabled);
const FormField formField = FormField(error: '');
final autoMode = formField.autovalidateMode;
// Changes made in https://github.com/flutter/flutter/pull/61648
const TextFormField textFormField = TextFormField(autovalidateMode: AutovalidateMode.always);
const TextFormField textFormField = TextFormField(autovalidateMode: AutovalidateMode.disabled);
const TextFormField textFormField = TextFormField(error: '');
// Changes made in https://github.com/flutter/flutter/pull/61648
const DropdownButtonFormField dropDownButtonFormField = DropdownButtonFormField(autovalidateMode: AutovalidateMode.always);
const DropdownButtonFormField dropdownButtonFormField = DropdownButtonFormField(autovalidateMode: AutovalidateMode.disabled);
const DropdownButtonFormField dropdownButtonFormField = DropdownButtonFormField(error: '');
// Changes made in https://github.com/flutter/flutter/pull/68736
MediaQuery.maybeOf(context);
MediaQuery.of(context);
MediaQuery.of(error: '');
// Changes made in https://github.com/flutter/flutter/pull/70726
Navigator.maybeOf(context);
Navigator.of(context);
Navigator.of(error: '');
// Changes made in https://github.com/flutter/flutter/pull/68908
ScaffoldMessenger.maybeOf(context);
ScaffoldMessenger.of(context);
ScaffoldMessenger.of(error: '');
Scaffold.of(error: '');
Scaffold.maybeOf(context);
Scaffold.of(context);
// Changes made in https://github.com/flutter/flutter/pull/68910
Router.maybeOf(context);
Router.of(context);
Router.of(error: '');
// Changes made in https://github.com/flutter/flutter/pull/68911
Localizations.maybeLocaleOf(context);
Localizations.localeOf(context);
Localizations.localeOf(error: '');
// Changes made in https://github.com/flutter/flutter/pull/68917
FocusTraversalOrder.maybeOf(context);
FocusTraversalOrder.of(context);
FocusTraversalOrder.of(error: '');
FocusTraversalGroup.of(error: '');
FocusTraversalGroup.maybeOf(context);
FocusTraversalGroup.of(context);
Focus.maybeOf(context);
Focus.of(context);
Focus.of(error: '');
// Changes made in https://github.com/flutter/flutter/pull/68921
Shortcuts.maybeOf(context);
Shortcuts.of(context);
Shortcuts.of(error: '');
Actions.find(error: '');
Actions.maybeFind(context);
Actions.find(context);
Actions.handler(context);
Actions.handler(context);
Actions.handler(error: '');
Actions.invoke(error: '');
Actions.maybeInvoke(context);
Actions.invoke(context);
// Changes made in https://github.com/flutter/flutter/pull/68925
AnimatedList.maybeOf(context);
AnimatedList.of(context);
AnimatedList.of(error: '');
SliverAnimatedList.of(error: '');
SliverAnimatedList.maybeOf(context);
SliverAnimatedList.of(context);
// Changes made in https://github.com/flutter/flutter/pull/68905
MaterialBasedCupertinoThemeData.resolveFrom(context);
MaterialBasedCupertinoThemeData.resolveFrom(context);
MaterialBasedCupertinoThemeData.resolveFrom(error: '');
// Changes made in https://github.com/flutter/flutter/pull/72043
TextField(maxLengthEnforcement: MaxLengthEnforcement.enforce);
TextField(maxLengthEnforcement: MaxLengthEnforcement.none);
TextField(error: '');
final TextField textField;
textField.maxLengthEnforcement;
TextFormField(maxLengthEnforcement: MaxLengthEnforcement.enforce);
TextFormField(maxLengthEnforcement: MaxLengthEnforcement.none);
TextFormField(error: '');
// Changes made in https://github.com/flutter/flutter/pull/59127
const BottomNavigationBarItem bottomNavigationBarItem = BottomNavigationBarItem(label: myTitle);
const BottomNavigationBarItem bottomNavigationBarItem = BottomNavigationBarItem();
const BottomNavigationBarItem bottomNavigationBarItem = BottomNavigationBarItem(error: '');
bottomNavigationBarItem.label;
// Changes made in https://github.com/flutter/flutter/pull/65246
RectangularSliderTrackShape();
RectangularSliderTrackShape(error: '');
// Changes made in https://github.com/flutter/flutter/pull/46115
const InputDecoration inputDecoration = InputDecoration(floatingLabelBehavior: FloatingLabelBehavior.auto);
InputDecoration(floatingLabelBehavior: FloatingLabelBehavior.never);
InputDecoration();
InputDecoration(error: '');
InputDecoration.collapsed(floatingLabelBehavior: FloatingLabelBehavior.auto);
InputDecoration.collapsed(floatingLabelBehavior: FloatingLabelBehavior.never);
InputDecoration.collapsed();
InputDecoration.collapsed(error: '');
inputDecoration.floatingLabelBehavior;
const InputDecorationTheme inputDecorationTheme = InputDecorationTheme(floatingLabelBehavior: FloatingLabelBehavior.auto);
InputDecorationTheme(floatingLabelBehavior: FloatingLabelBehavior.never);
InputDecorationTheme();
InputDecorationTheme(error: '');
inputDecorationTheme.floatingLabelBehavior;
inputDecorationTheme.copyWith(floatingLabelBehavior: FloatingLabelBehavior.never);
inputDecorationTheme.copyWith(floatingLabelBehavior: FloatingLabelBehavior.auto);
inputDecorationTheme.copyWith();
inputDecorationTheme.copyWith(error: '');
// Changes made in https://github.com/flutter/flutter/pull/79160
Draggable draggable = Draggable();
draggable = Draggable(dragAnchorStrategy: childDragAnchorStrategy);
draggable = Draggable(dragAnchorStrategy: pointerDragAnchorStrategy);
draggable = Draggable(error: '');
draggable.dragAnchorStrategy;
// Changes made in https://github.com/flutter/flutter/pull/79160
LongPressDraggable longPressDraggable = LongPressDraggable();
longPressDraggable = LongPressDraggable(dragAnchorStrategy: childDragAnchorStrategy);
longPressDraggable = LongPressDraggable(dragAnchorStrategy: pointerDragAnchorStrategy);
longPressDraggable = LongPressDraggable(error: '');
longPressDraggable.dragAnchorStrategy;
// Changes made in https://github.com/flutter/flutter/pull/64254
final LeafRenderObjectElement leafElement = LeafRenderObjectElement();
leafElement.insertRenderObjectChild(renderObject, object);
leafElement.moveRenderObjectChild(renderObject, object);
leafElement.removeRenderObjectChild(renderObject);
final ListWheelElement listWheelElement = ListWheelElement();
listWheelElement.insertRenderObjectChild(renderObject, object);
listWheelElement.moveRenderObjectChild(renderObject, object);
listWheelElement.removeRenderObjectChild(renderObject);
final MultiChildRenderObjectElement multiChildRenderObjectElement = MultiChildRenderObjectElement();
multiChildRenderObjectElement.insertRenderObjectChild(renderObject, object);
multiChildRenderObjectElement.moveRenderObjectChild(renderObject, object);
multiChildRenderObjectElement.removeRenderObjectChild(renderObject);
final SingleChildRenderObjectElement singleChildRenderObjectElement = SingleChildRenderObjectElement();
singleChildRenderObjectElement.insertRenderObjectChild(renderObject, object);
singleChildRenderObjectElement.moveRenderObjectChild(renderObject, object);
singleChildRenderObjectElement.removeRenderObjectChild(renderObject);
final SliverMultiBoxAdaptorElement sliverMultiBoxAdaptorElement = SliverMultiBoxAdaptorElement();
sliverMultiBoxAdaptorElement.insertRenderObjectChild(renderObject, object);
sliverMultiBoxAdaptorElement.moveRenderObjectChild(renderObject, object);
sliverMultiBoxAdaptorElement.removeRenderObjectChild(renderObject);
final RenderObjectToWidgetElement renderObjectToWidgetElement = RenderObjectToWidgetElement(widget);
renderObjectToWidgetElement.insertRenderObjectChild(renderObject, object);
renderObjectToWidgetElement.moveRenderObjectChild(renderObject, object);
renderObjectToWidgetElement.removeRenderObjectChild(renderObject);
// Changes made in https://flutter.dev/docs/release/breaking-changes/clip-behavior
ListWheelScrollView listWheelScrollView = ListWheelScrollView();
listWheelScrollView = ListWheelScrollView(clipBehavior: Clip.hardEdge);
listWheelScrollView = ListWheelScrollView(clipBehavior: Clip.none);
listWheelScrollView = ListWheelScrollView(error: '');
listWheelScrollView = ListWheelScrollView.useDelegate(error: '');
listWheelScrollView = ListWheelScrollView.useDelegate();
listWheelScrollView = ListWheelScrollView.useDelegate(clipBehavior: Clip.hardEdge);
listWheelScrollView = ListWheelScrollView.useDelegate(clipBehavior: Clip.none);
listWheelScrollView.clipBehavior;
ListWheelViewport listWheelViewport = ListWheelViewport();
listWheelViewport = ListWheelViewport(clipBehavior: Clip.hardEdge);
listWheelViewport = ListWheelViewport(clipBehavior: Clip.none);
listWheelViewport = ListWheelViewport(error: '');
listWheelViewport.clipBehavior;
// Changes made in https://github.com/flutter/flutter/pull/87839
final OverscrollIndicatorNotification notification = OverscrollIndicatorNotification(leading: true);
final OverscrollIndicatorNotification notification = OverscrollIndicatorNotification(error: '');
notification.disallowIndicator();
// Changes made in https://github.com/flutter/flutter/pull/96115
Icon icon = Icons.pie_chart_outline;
// Changes made in https://github.com/flutter/flutter/pull/96957
Scrollbar scrollbar = Scrollbar(thumbVisibility: true);
bool nowShowing = scrollbar.thumbVisibility;
ScrollbarThemeData scrollbarTheme = ScrollbarThemeData(thumbVisibility: nowShowing);
scrollbarTheme.copyWith(thumbVisibility: nowShowing);
scrollbarTheme.thumbVisibility;
RawScrollbar rawScrollbar = RawScrollbar(thumbVisibility: true);
nowShowing = rawScrollbar.thumbVisibility;
// Changes made in https://github.com/flutter/flutter/pull/96174
Chip chip = Chip();
chip = Chip(deleteButtonTooltipMessage: '');
chip = Chip();
chip = Chip(deleteButtonTooltipMessage: 'Delete Tooltip');
chip.deleteButtonTooltipMessage;
// Changes made in https://github.com/flutter/flutter/pull/96174
InputChip inputChip = InputChip();
inputChip = InputChip(deleteButtonTooltipMessage: '');
inputChip = InputChip();
inputChip = InputChip(deleteButtonTooltipMessage: 'Delete Tooltip');
inputChip.deleteButtonTooltipMessage;
// Changes made in https://github.com/flutter/flutter/pull/96174
RawChip rawChip = Rawchip();
rawChip = RawChip(deleteButtonTooltipMessage: '');
rawChip = RawChip();
rawChip = RawChip(deleteButtonTooltipMessage: 'Delete Tooltip');
rawChip.deleteButtonTooltipMessage;
// Change made in https://github.com/flutter/flutter/pull/100381
SelectionOverlay.fadeDuration;
// Changes made in https://github.com/flutter/flutter/pull/105291
ButtonStyle elevationButtonStyle = ElevatedButton.styleFrom(
foregroundColor: Colors.white, backgroundColor: Colors.blue, disabledForegroundColor: Colors.grey.withOpacity(0.38), disabledBackgroundColor: Colors.grey.withOpacity(0.12),
);
ButtonStyle outlinedButtonStyle = OutlinedButton.styleFrom(
foregroundColor: Colors.blue, disabledForegroundColor: Colors.grey.withOpacity(0.38),
);
ButtonStyle textButtonStyle = TextButton.styleFrom(
foregroundColor: Colors.blue, disabledForegroundColor: Colors.grey.withOpacity(0.38),
);
// Changes made in https://github.com/flutter/flutter/pull/78588
final ScrollBehavior scrollBehavior = ScrollBehavior();
scrollBehavior.buildOverscrollIndicator(context, child, axisDirection);
final MaterialScrollBehavior materialScrollBehavior = MaterialScrollBehavior();
materialScrollBehavior.buildOverscrollIndicator(context, child, axisDirection);
// Changes made in https://github.com/flutter/flutter/pull/111706
Scrollbar scrollbar = Scrollbar(trackVisibility: true);
bool nowShowing = scrollbar.trackVisibility;
// The 3 expressions below have `bulkApply` set to true thus can't be tested yet.
//ScrollbarThemeData scrollbarTheme = ScrollbarThemeData(showTrackOnHover: nowShowing);
//scrollbarTheme.copyWith(showTrackOnHover: nowShowing);
//scrollbarTheme.showTrackOnHover;
// Changes made in https://github.com/flutter/flutter/pull/114459
MediaQuery.boldTextOf(context);
// Changes made in https://github.com/flutter/flutter/pull/122555
final ScrollableDetails details = ScrollableDetails(
direction: AxisDirection.down,
decorationClipBehavior: Clip.none,
);
final Clip clip = details.decorationClipBehavior;
// Changes made in https://github.com/flutter/flutter/pull/134417
const Curve curve = Easing.legacy;
const Curve curve = Easing.legacyAccelerate;
const Curve curve = Easing.legacyDecelerate;
final PlatformMenuBar platformMenuBar = PlatformMenuBar(menus: <PlatformMenuItem>[], child: const SizedBox());
final Widget bodyValue = platformMenuBar.child;
}
| flutter/packages/flutter/test_fixes/material/material.dart.expect/0 | {
"file_path": "flutter/packages/flutter/test_fixes/material/material.dart.expect",
"repo_id": "flutter",
"token_count": 4592
} | 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/widgets.dart';
void main() {
// Generic reference variables.
BuildContext context;
RenderObjectWidget renderObjectWidget;
RenderObject renderObject;
Object object;
TickerProvider vsync;
// Changes made in https://github.com/flutter/flutter/pull/123352
WidgetsBinding.instance.rootElement;
// Changes made in https://github.com/flutter/flutter/pull/119647
MediaQueryData.fromView(View.of(context));
// Changes made in https://github.com/flutter/flutter/pull/119186 and https://github.com/flutter/flutter/pull/81067
AnimatedSize(duration: Duration.zero);
// Changes made in https://github.com/flutter/flutter/pull/45941 and https://github.com/flutter/flutter/pull/83843
final WidgetsBinding binding = WidgetsBinding.instance;
binding.deferFirstFrame();
binding.allowFirstFrame();
// Changes made in https://github.com/flutter/flutter/pull/44189
const StatefulElement statefulElement = StatefulElement(myWidget);
statefulElement.dependOnInheritedElement(ancestor);
// Changes made in https://github.com/flutter/flutter/pull/61648
const Form form = Form(autovalidateMode: AutovalidateMode.always);
const Form form = Form(autovalidateMode: AutovalidateMode.disabled);
const Form form = Form(error: '');
final autoMode = form.autovalidateMode;
// Changes made in https://github.com/flutter/flutter/pull/61648
const FormField formField = FormField(autovalidateMode: AutovalidateMode.always);
const FormField formField = FormField(autovalidateMode: AutovalidateMode.disabled);
const FormField formField = FormField(error: '');
final autoMode = formField.autovalidateMode;
// Changes made in https://github.com/flutter/flutter/pull/66305
const Stack stack = Stack(clipBehavior: Clip.none);
const Stack stack = Stack(clipBehavior: Clip.hardEdge);
const Stack stack = Stack(error: '');
final behavior = stack.clipBehavior;
// Changes made in https://github.com/flutter/flutter/pull/68736
MediaQuery.maybeOf(context);
MediaQuery.of(context);
MediaQuery.of(error: '');
// Changes made in https://github.com/flutter/flutter/pull/70726
Navigator.maybeOf(context);
Navigator.of(context);
Navigator.of(error: '');
// Changes made in https://github.com/flutter/flutter/pull/68910
Router.maybeOf(context);
Router.of(context);
Router.of(error: '');
// Changes made in https://github.com/flutter/flutter/pull/68911
Localizations.maybeLocaleOf(context);
Localizations.localeOf(context);
Localizations.localeOf(error: '');
// Changes made in https://github.com/flutter/flutter/pull/68917
FocusTraversalOrder.maybeOf(context);
FocusTraversalOrder.of(context);
FocusTraversalOrder.of(error: '');
FocusTraversalGroup.of(error: '');
FocusTraversalGroup.maybeOf(context);
FocusTraversalGroup.of(context);
Focus.maybeOf(context);
Focus.of(context);
Focus.of(error: '');
// Changes made in https://github.com/flutter/flutter/pull/68921
Shortcuts.maybeOf(context);
Shortcuts.of(context);
Shortcuts.of(error: '');
// Changes made in https://github.com/flutter/flutter/pull/68925
AnimatedList.maybeOf(context);
AnimatedList.of(context);
AnimatedList.of(error: '');
SliverAnimatedList.of(error: '');
SliverAnimatedList.maybeOf(context);
SliverAnimatedList.of(context);
// Changes made in https://github.com/flutter/flutter/pull/59127
const BottomNavigationBarItem bottomNavigationBarItem = BottomNavigationBarItem(label: myTitle);
const BottomNavigationBarItem bottomNavigationBarItem = BottomNavigationBarItem();
const BottomNavigationBarItem bottomNavigationBarItem = BottomNavigationBarItem(error: '');
bottomNavigationBarItem.label;
// Changes made in https://github.com/flutter/flutter/pull/79160
Draggable draggable = Draggable();
draggable = Draggable(dragAnchorStrategy: childDragAnchorStrategy);
draggable = Draggable(dragAnchorStrategy: pointerDragAnchorStrategy);
draggable = Draggable(error: '');
draggable.dragAnchorStrategy;
// Changes made in https://github.com/flutter/flutter/pull/79160
LongPressDraggable longPressDraggable = LongPressDraggable();
longPressDraggable = LongPressDraggable(dragAnchorStrategy: childDragAnchorStrategy);
longPressDraggable = LongPressDraggable(dragAnchorStrategy: pointerDragAnchorStrategy);
longPressDraggable = LongPressDraggable(error: '');
longPressDraggable.dragAnchorStrategy;
// Changes made in https://github.com/flutter/flutter/pull/64254
final LeafRenderObjectElement leafElement = LeafRenderObjectElement();
leafElement.insertRenderObjectChild(renderObject, object);
leafElement.moveRenderObjectChild(renderObject, object);
leafElement.removeRenderObjectChild(renderObject);
final ListWheelElement listWheelElement = ListWheelElement();
listWheelElement.insertRenderObjectChild(renderObject, object);
listWheelElement.moveRenderObjectChild(renderObject, object);
listWheelElement.removeRenderObjectChild(renderObject);
final MultiChildRenderObjectElement multiChildRenderObjectElement = MultiChildRenderObjectElement();
multiChildRenderObjectElement.insertRenderObjectChild(renderObject, object);
multiChildRenderObjectElement.moveRenderObjectChild(renderObject, object);
multiChildRenderObjectElement.removeRenderObjectChild(renderObject);
final SingleChildRenderObjectElement singleChildRenderObjectElement = SingleChildRenderObjectElement();
singleChildRenderObjectElement.insertRenderObjectChild(renderObject, object);
singleChildRenderObjectElement.moveRenderObjectChild(renderObject, object);
singleChildRenderObjectElement.removeRenderObjectChild(renderObject);
final SliverMultiBoxAdaptorElement sliverMultiBoxAdaptorElement = SliverMultiBoxAdaptorElement();
sliverMultiBoxAdaptorElement.insertRenderObjectChild(renderObject, object);
sliverMultiBoxAdaptorElement.moveRenderObjectChild(renderObject, object);
sliverMultiBoxAdaptorElement.removeRenderObjectChild(renderObject);
final RenderObjectToWidgetElement renderObjectToWidgetElement = RenderObjectToWidgetElement(widget);
renderObjectToWidgetElement.insertRenderObjectChild(renderObject, object);
renderObjectToWidgetElement.moveRenderObjectChild(renderObject, object);
renderObjectToWidgetElement.removeRenderObjectChild(renderObject);
// Changes made in https://flutter.dev/docs/release/breaking-changes/clip-behavior
ListWheelViewport listWheelViewport = ListWheelViewport();
listWheelViewport = ListWheelViewport(clipBehavior: Clip.hardEdge);
listWheelViewport = ListWheelViewport(clipBehavior: Clip.none);
listWheelViewport = ListWheelViewport(error: '');
listWheelViewport.clipBehavior;
// Changes made in https://github.com/flutter/flutter/pull/87839
final OverscrollIndicatorNotification notification = OverscrollIndicatorNotification(leading: true);
final OverscrollIndicatorNotification notification = OverscrollIndicatorNotification(error: '');
notification.disallowIndicator();
// Changes made in https://github.com/flutter/flutter/pull/96957
RawScrollbar rawScrollbar = RawScrollbar(thumbVisibility: true);
nowShowing = rawScrollbar.thumbVisibility;
// Change made in https://github.com/flutter/flutter/pull/100381
SelectionOverlay.fadeDuration;
// Changes made in https://github.com/flutter/flutter/pull/78588
final ScrollBehavior scrollBehavior = ScrollBehavior();
scrollBehavior.buildOverscrollIndicator(context, child, axisDirection);
// Changes made in https://github.com/flutter/flutter/pull/114459
MediaQuery.boldTextOf(context);
// Changes made in https://github.com/flutter/flutter/pull/122555
final ScrollableDetails details = ScrollableDetails(
direction: AxisDirection.down,
decorationClipBehavior: Clip.none,
);
final Clip clip = details.decorationClipBehavior;
final PlatformMenuBar platformMenuBar = PlatformMenuBar(menus: <PlatformMenuItem>[], child: const SizedBox());
final Widget bodyValue = platformMenuBar.child;
// Changes made in TBD
final NavigatorState state = Navigator.of(context);
state.focusNode.enclosingScope!;
}
| flutter/packages/flutter/test_fixes/widgets/widgets.dart.expect/0 | {
"file_path": "flutter/packages/flutter/test_fixes/widgets/widgets.dart.expect",
"repo_id": "flutter",
"token_count": 2419
} | 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 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter_test/flutter_test.dart';
import '../../driver_extension.dart';
import '../extension/wait_conditions.dart';
import 'diagnostics_tree.dart';
import 'error.dart';
import 'find.dart';
import 'frame_sync.dart';
import 'geometry.dart';
import 'gesture.dart';
import 'health.dart';
import 'layer_tree.dart';
import 'message.dart';
import 'render_tree.dart';
import 'request_data.dart';
import 'semantics.dart';
import 'text.dart';
import 'text_input_action.dart' show SendTextInputAction;
import 'wait.dart';
/// A factory which creates [Finder]s from [SerializableFinder]s.
mixin CreateFinderFactory {
/// Creates the flutter widget finder from [SerializableFinder].
Finder createFinder(SerializableFinder finder) {
final String finderType = finder.finderType;
switch (finderType) {
case 'ByText':
return _createByTextFinder(finder as ByText);
case 'ByTooltipMessage':
return _createByTooltipMessageFinder(finder as ByTooltipMessage);
case 'BySemanticsLabel':
return _createBySemanticsLabelFinder(finder as BySemanticsLabel);
case 'ByValueKey':
return _createByValueKeyFinder(finder as ByValueKey);
case 'ByType':
return _createByTypeFinder(finder as ByType);
case 'PageBack':
return _createPageBackFinder();
case 'Ancestor':
return _createAncestorFinder(finder as Ancestor);
case 'Descendant':
return _createDescendantFinder(finder as Descendant);
default:
throw DriverError('Unsupported search specification type $finderType');
}
}
Finder _createByTextFinder(ByText arguments) {
return find.text(arguments.text);
}
Finder _createByTooltipMessageFinder(ByTooltipMessage arguments) {
return find.byElementPredicate((Element element) {
final Widget widget = element.widget;
if (widget is Tooltip) {
return widget.message == arguments.text;
}
return false;
}, description: 'widget with text tooltip "${arguments.text}"');
}
Finder _createBySemanticsLabelFinder(BySemanticsLabel arguments) {
return find.byElementPredicate((Element element) {
if (element is! RenderObjectElement) {
return false;
}
final String? semanticsLabel = element.renderObject.debugSemantics?.label;
if (semanticsLabel == null) {
return false;
}
final Pattern label = arguments.label;
return label is RegExp
? label.hasMatch(semanticsLabel)
: label == semanticsLabel;
}, description: 'widget with semantic label "${arguments.label}"');
}
Finder _createByValueKeyFinder(ByValueKey arguments) {
switch (arguments.keyValueType) {
case 'int':
return find.byKey(ValueKey<int>(arguments.keyValue as int));
case 'String':
return find.byKey(ValueKey<String>(arguments.keyValue as String));
default:
throw UnimplementedError('Unsupported ByValueKey type: ${arguments.keyValueType}');
}
}
Finder _createByTypeFinder(ByType arguments) {
return find.byElementPredicate((Element element) {
return element.widget.runtimeType.toString() == arguments.type;
}, description: 'widget with runtimeType "${arguments.type}"');
}
Finder _createPageBackFinder() {
return find.byElementPredicate((Element element) {
final Widget widget = element.widget;
if (widget is Tooltip) {
return widget.message == 'Back';
}
if (widget is CupertinoNavigationBarBackButton) {
return true;
}
return false;
}, description: 'Material or Cupertino back button');
}
Finder _createAncestorFinder(Ancestor arguments) {
final Finder finder = find.ancestor(
of: createFinder(arguments.of),
matching: createFinder(arguments.matching),
matchRoot: arguments.matchRoot,
);
return arguments.firstMatchOnly ? finder.first : finder;
}
Finder _createDescendantFinder(Descendant arguments) {
final Finder finder = find.descendant(
of: createFinder(arguments.of),
matching: createFinder(arguments.matching),
matchRoot: arguments.matchRoot,
);
return arguments.firstMatchOnly ? finder.first : finder;
}
}
/// A factory for [Command] handlers.
mixin CommandHandlerFactory {
/// With [_frameSync] enabled, Flutter Driver will wait to perform an action
/// until there are no pending frames in the app under test.
bool _frameSync = true;
/// Gets [DataHandler] for result delivery.
@protected
DataHandler? getDataHandler() => null;
/// Registers text input emulation.
@protected
void registerTextInput() {
_testTextInput.register();
}
final TestTextInput _testTextInput = TestTextInput();
/// Deserializes the finder from JSON generated by [Command.serialize] or [CommandWithTarget.serialize].
Future<Result> handleCommand(Command command, WidgetController prober, CreateFinderFactory finderFactory) {
switch (command.kind) {
case 'get_health': return _getHealth(command);
case 'get_layer_tree': return _getLayerTree(command);
case 'get_render_tree': return _getRenderTree(command);
case 'enter_text': return _enterText(command);
case 'send_text_input_action': return _sendTextInputAction(command);
case 'get_text': return _getText(command, finderFactory);
case 'request_data': return _requestData(command);
case 'scroll': return _scroll(command, prober, finderFactory);
case 'scrollIntoView': return _scrollIntoView(command, finderFactory);
case 'set_frame_sync': return _setFrameSync(command);
case 'set_semantics': return _setSemantics(command);
case 'set_text_entry_emulation': return _setTextEntryEmulation(command);
case 'tap': return _tap(command, prober, finderFactory);
case 'waitFor': return _waitFor(command, finderFactory);
case 'waitForAbsent': return _waitForAbsent(command, finderFactory);
case 'waitForTappable': return _waitForTappable(command, finderFactory);
case 'waitForCondition': return _waitForCondition(command);
case 'waitUntilNoTransientCallbacks': return _waitUntilNoTransientCallbacks(command);
case 'waitUntilNoPendingFrame': return _waitUntilNoPendingFrame(command);
case 'waitUntilFirstFrameRasterized': return _waitUntilFirstFrameRasterized(command);
case 'get_semantics_id': return _getSemanticsId(command, finderFactory);
case 'get_offset': return _getOffset(command, finderFactory);
case 'get_diagnostics_tree': return _getDiagnosticsTree(command, finderFactory);
}
throw DriverError('Unsupported command kind ${command.kind}');
}
Future<Health> _getHealth(Command command) async => const Health(HealthStatus.ok);
Future<LayerTree> _getLayerTree(Command command) async {
final String trees = <String>[
for (final RenderView renderView in RendererBinding.instance.renderViews)
if (renderView.debugLayer != null)
renderView.debugLayer!.toStringDeep(),
].join('\n\n');
return LayerTree(trees.isNotEmpty ? trees : null);
}
Future<RenderTree> _getRenderTree(Command command) async {
final String trees = <String>[
for (final RenderView renderView in RendererBinding.instance.renderViews)
renderView.toStringDeep(),
].join('\n\n');
return RenderTree(trees.isNotEmpty ? trees : null);
}
Future<Result> _enterText(Command command) async {
if (!_testTextInput.isRegistered) {
throw StateError(
'Unable to fulfill `FlutterDriver.enterText`. Text emulation is '
'disabled. You can enable it using `FlutterDriver.setTextEntryEmulation`.',
);
}
final EnterText enterTextCommand = command as EnterText;
_testTextInput.enterText(enterTextCommand.text);
return Result.empty;
}
Future<Result> _sendTextInputAction(Command command) async {
if (!_testTextInput.isRegistered) {
throw StateError('Unable to fulfill `FlutterDriver.sendTextInputAction`. Text emulation is '
'disabled. You can enable it using `FlutterDriver.setTextEntryEmulation`.');
}
final SendTextInputAction sendTextInputAction = command as SendTextInputAction;
_testTextInput.receiveAction(TextInputAction.values[sendTextInputAction.textInputAction.index]);
return Result.empty;
}
Future<RequestDataResult> _requestData(Command command) async {
final RequestData requestDataCommand = command as RequestData;
final DataHandler? dataHandler = getDataHandler();
return RequestDataResult(dataHandler == null
? 'No requestData Extension registered'
: await dataHandler(requestDataCommand.message));
}
Future<Result> _setFrameSync(Command command) async {
final SetFrameSync setFrameSyncCommand = command as SetFrameSync;
_frameSync = setFrameSyncCommand.enabled;
return Result.empty;
}
Future<Result> _tap(Command command, WidgetController prober, CreateFinderFactory finderFactory) async {
final Tap tapCommand = command as Tap;
final Finder computedFinder = await waitForElement(
finderFactory.createFinder(tapCommand.finder).hitTestable(),
);
await prober.tap(computedFinder);
return Result.empty;
}
Future<Result> _waitFor(Command command, CreateFinderFactory finderFactory) async {
final WaitFor waitForCommand = command as WaitFor;
await waitForElement(finderFactory.createFinder(waitForCommand.finder));
return Result.empty;
}
Future<Result> _waitForAbsent(Command command, CreateFinderFactory finderFactory) async {
final WaitForAbsent waitForAbsentCommand = command as WaitForAbsent;
await waitForAbsentElement(finderFactory.createFinder(waitForAbsentCommand.finder));
return Result.empty;
}
Future<Result> _waitForTappable(Command command, CreateFinderFactory finderFactory) async {
final WaitForTappable waitForTappableCommand = command as WaitForTappable;
await waitForElement(
finderFactory.createFinder(waitForTappableCommand.finder).hitTestable(),
);
return Result.empty;
}
Future<Result> _waitForCondition(Command command) async {
final WaitForCondition waitForConditionCommand = command as WaitForCondition;
final WaitCondition condition = deserializeCondition(waitForConditionCommand.condition);
await condition.wait();
return Result.empty;
}
@Deprecated(
'This method has been deprecated in favor of _waitForCondition. '
'This feature was deprecated after v1.9.3.'
)
Future<Result> _waitUntilNoTransientCallbacks(Command command) async {
if (SchedulerBinding.instance.transientCallbackCount != 0) {
await _waitUntilFrame(() => SchedulerBinding.instance.transientCallbackCount == 0);
}
return Result.empty;
}
/// Returns a future that waits until no pending frame is scheduled (frame is synced).
///
/// Specifically, it checks:
/// * Whether the count of transient callbacks is zero.
/// * Whether there's no pending request for scheduling a new frame.
///
/// We consider the frame is synced when both conditions are met.
///
/// This method relies on a Flutter Driver mechanism called "frame sync",
/// which waits for transient animations to finish. Persistent animations will
/// cause this to wait forever.
///
/// If a test needs to interact with the app while animations are running, it
/// should avoid this method and instead disable the frame sync using
/// `set_frame_sync` method. See [FlutterDriver.runUnsynchronized] for more
/// details on how to do this. Note, disabling frame sync will require the
/// test author to use some other method to avoid flakiness.
///
/// This method has been deprecated in favor of [_waitForCondition].
@Deprecated(
'This method has been deprecated in favor of _waitForCondition. '
'This feature was deprecated after v1.9.3.'
)
Future<Result> _waitUntilNoPendingFrame(Command command) async {
await _waitUntilFrame(() {
return SchedulerBinding.instance.transientCallbackCount == 0
&& !SchedulerBinding.instance.hasScheduledFrame;
});
return Result.empty;
}
Future<GetSemanticsIdResult> _getSemanticsId(Command command, CreateFinderFactory finderFactory) async {
final GetSemanticsId semanticsCommand = command as GetSemanticsId;
final Finder target = await waitForElement(finderFactory.createFinder(semanticsCommand.finder));
final Iterable<Element> elements = target.evaluate();
if (elements.length > 1) {
throw StateError('Found more than one element with the same ID: $elements');
}
final Element element = elements.single;
RenderObject? renderObject = element.renderObject;
SemanticsNode? node;
while (renderObject != null && node == null) {
node = renderObject.debugSemantics;
renderObject = renderObject.parent;
}
if (node == null) {
throw StateError('No semantics data found');
}
return GetSemanticsIdResult(node.id);
}
Future<GetOffsetResult> _getOffset(Command command, CreateFinderFactory finderFactory) async {
final GetOffset getOffsetCommand = command as GetOffset;
final Finder finder = await waitForElement(finderFactory.createFinder(getOffsetCommand.finder));
final Element element = finder.evaluate().single;
final RenderBox box = (element.renderObject as RenderBox?)!;
Offset localPoint;
switch (getOffsetCommand.offsetType) {
case OffsetType.topLeft:
localPoint = Offset.zero;
case OffsetType.topRight:
localPoint = box.size.topRight(Offset.zero);
case OffsetType.bottomLeft:
localPoint = box.size.bottomLeft(Offset.zero);
case OffsetType.bottomRight:
localPoint = box.size.bottomRight(Offset.zero);
case OffsetType.center:
localPoint = box.size.center(Offset.zero);
}
final Offset globalPoint = box.localToGlobal(localPoint);
return GetOffsetResult(dx: globalPoint.dx, dy: globalPoint.dy);
}
Future<DiagnosticsTreeResult> _getDiagnosticsTree(Command command, CreateFinderFactory finderFactory) async {
final GetDiagnosticsTree diagnosticsCommand = command as GetDiagnosticsTree;
final Finder finder = await waitForElement(finderFactory.createFinder(diagnosticsCommand.finder));
final Element element = finder.evaluate().single;
DiagnosticsNode diagnosticsNode;
switch (diagnosticsCommand.diagnosticsType) {
case DiagnosticsType.renderObject:
diagnosticsNode = element.renderObject!.toDiagnosticsNode();
case DiagnosticsType.widget:
diagnosticsNode = element.toDiagnosticsNode();
}
return DiagnosticsTreeResult(diagnosticsNode.toJsonMap(DiagnosticsSerializationDelegate(
subtreeDepth: diagnosticsCommand.subtreeDepth,
includeProperties: diagnosticsCommand.includeProperties,
)));
}
Future<Result> _scroll(Command command, WidgetController prober, CreateFinderFactory finderFactory) async {
final Scroll scrollCommand = command as Scroll;
final Finder target = await waitForElement(finderFactory.createFinder(scrollCommand.finder));
final int totalMoves = scrollCommand.duration.inMicroseconds * scrollCommand.frequency ~/ Duration.microsecondsPerSecond;
final Offset delta = Offset(scrollCommand.dx, scrollCommand.dy) / totalMoves.toDouble();
final Duration pause = scrollCommand.duration ~/ totalMoves;
final Offset startLocation = prober.getCenter(target);
Offset currentLocation = startLocation;
final TestPointer pointer = TestPointer();
prober.binding.handlePointerEvent(pointer.down(startLocation));
await Future<void>.value(); // so that down and move don't happen in the same microtask
for (int moves = 0; moves < totalMoves; moves += 1) {
currentLocation = currentLocation + delta;
prober.binding.handlePointerEvent(pointer.move(currentLocation));
await Future<void>.delayed(pause);
}
prober.binding.handlePointerEvent(pointer.up());
return Result.empty;
}
Future<Result> _scrollIntoView(Command command, CreateFinderFactory finderFactory) async {
final ScrollIntoView scrollIntoViewCommand = command as ScrollIntoView;
final Finder target = await waitForElement(finderFactory.createFinder(scrollIntoViewCommand.finder));
await Scrollable.ensureVisible(target.evaluate().single, duration: const Duration(milliseconds: 100), alignment: scrollIntoViewCommand.alignment);
return Result.empty;
}
Future<GetTextResult> _getText(Command command, CreateFinderFactory finderFactory) async {
final GetText getTextCommand = command as GetText;
final Finder target = await waitForElement(finderFactory.createFinder(getTextCommand.finder));
final Widget widget = target.evaluate().single.widget;
String? text;
if (widget.runtimeType == Text) {
text = (widget as Text).data;
} else if (widget.runtimeType == RichText) {
final RichText richText = widget as RichText;
text = richText.text.toPlainText(
includeSemanticsLabels: false,
includePlaceholders: false,
);
} else if (widget.runtimeType == TextField) {
text = (widget as TextField).controller?.text;
} else if (widget.runtimeType == TextFormField) {
text = (widget as TextFormField).controller?.text;
} else if (widget.runtimeType == EditableText) {
text = (widget as EditableText).controller.text;
}
if (text == null) {
throw UnsupportedError('Type ${widget.runtimeType} is currently not supported by getText');
}
return GetTextResult(text);
}
Future<Result> _setTextEntryEmulation(Command command) async {
final SetTextEntryEmulation setTextEntryEmulationCommand = command as SetTextEntryEmulation;
if (setTextEntryEmulationCommand.enabled) {
_testTextInput.register();
} else {
_testTextInput.unregister();
}
return Result.empty;
}
SemanticsHandle? _semantics;
bool get _semanticsIsEnabled => SemanticsBinding.instance.semanticsEnabled;
Future<SetSemanticsResult> _setSemantics(Command command) async {
final SetSemantics setSemanticsCommand = command as SetSemantics;
final bool semanticsWasEnabled = _semanticsIsEnabled;
if (setSemanticsCommand.enabled && _semantics == null) {
_semantics = SemanticsBinding.instance.ensureSemantics();
if (!semanticsWasEnabled) {
// wait for the first frame where semantics is enabled.
final Completer<void> completer = Completer<void>();
SchedulerBinding.instance.addPostFrameCallback((Duration d) {
completer.complete();
});
await completer.future;
}
} else if (!setSemanticsCommand.enabled && _semantics != null) {
_semantics!.dispose();
_semantics = null;
}
return SetSemanticsResult(semanticsWasEnabled != _semanticsIsEnabled);
}
// This can be used to wait for the first frame being rasterized during app launch.
@Deprecated(
'This method has been deprecated in favor of _waitForCondition. '
'This feature was deprecated after v1.9.3.'
)
Future<Result> _waitUntilFirstFrameRasterized(Command command) async {
await WidgetsBinding.instance.waitUntilFirstFrameRasterized;
return Result.empty;
}
/// Runs `finder` repeatedly until it finds one or more [Element]s.
Future<Finder> waitForElement(Finder finder) async {
if (_frameSync) {
await _waitUntilFrame(() => SchedulerBinding.instance.transientCallbackCount == 0);
}
await _waitUntilFrame(() => finder.evaluate().isNotEmpty);
if (_frameSync) {
await _waitUntilFrame(() => SchedulerBinding.instance.transientCallbackCount == 0);
}
return finder;
}
/// Runs `finder` repeatedly until it finds zero [Element]s.
Future<Finder> waitForAbsentElement(Finder finder) async {
if (_frameSync) {
await _waitUntilFrame(() => SchedulerBinding.instance.transientCallbackCount == 0);
}
await _waitUntilFrame(() => finder.evaluate().isEmpty);
if (_frameSync) {
await _waitUntilFrame(() => SchedulerBinding.instance.transientCallbackCount == 0);
}
return finder;
}
// Waits until at the end of a frame the provided [condition] is [true].
Future<void> _waitUntilFrame(bool Function() condition, [ Completer<void>? completer ]) {
completer ??= Completer<void>();
if (!condition()) {
SchedulerBinding.instance.addPostFrameCallback((Duration timestamp) {
_waitUntilFrame(condition, completer);
});
} else {
completer.complete();
}
return completer.future;
}
}
| flutter/packages/flutter_driver/lib/src/common/handler_factory.dart/0 | {
"file_path": "flutter/packages/flutter_driver/lib/src/common/handler_factory.dart",
"repo_id": "flutter",
"token_count": 6881
} | 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.
/// Returns the [p]-th percentile element from the [doubles].
/// `List<doubles>` will be sorted.
double findPercentile(List<double> doubles, double p) {
assert(doubles.isNotEmpty);
doubles.sort();
return doubles[((doubles.length - 1) * (p / 100)).round()];
}
| flutter/packages/flutter_driver/lib/src/driver/percentile_utils.dart/0 | {
"file_path": "flutter/packages/flutter_driver/lib/src/driver/percentile_utils.dart",
"repo_id": "flutter",
"token_count": 132
} | 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_driver/flutter_driver.dart';
import 'package:flutter_driver/src/driver/memory_summarizer.dart';
import '../common.dart';
TimelineEvent newGPUTraceEvent(double ms) => TimelineEvent(<String, dynamic>{
'name': 'AllocatorVK',
'ph': 'b',
'args': <String, String>{
'MemoryBudgetUsageMB': ms.toString()
},
});
void main() {
test('Can process GPU memory usage times.', () {
final GPUMemorySumarizer summarizer = GPUMemorySumarizer(<TimelineEvent>[
newGPUTraceEvent(1024),
newGPUTraceEvent(1024),
newGPUTraceEvent(512),
newGPUTraceEvent(2048),
]);
expect(summarizer.computeAverageMemoryUsage(), closeTo(1152, 0.1));
expect(summarizer.computePercentileMemoryUsage(50.0), closeTo(1024, 0.1));
expect(summarizer.computeWorstMemoryUsage(), 2048);
});
}
| flutter/packages/flutter_driver/test/src/gpu_memory_summarizer_test.dart/0 | {
"file_path": "flutter/packages/flutter_driver/test/src/gpu_memory_summarizer_test.dart",
"repo_id": "flutter",
"token_count": 355
} | 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 'dart:js' as js;
import 'package:flutter_driver/src/extension/_extension_web.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('test web_extension', () {
late Future<Map<String, dynamic>> Function(Map<String, String>) call;
setUp(() {
call = (Map<String, String> args) async {
return Future<Map<String, dynamic>>.value(args);
};
});
test('web_extension should register a function', () {
expect(() => registerWebServiceExtension(call),
returnsNormally);
expect(js.context.hasProperty(r'$flutterDriver'), true);
expect(js.context[r'$flutterDriver'], isNotNull);
expect(js.context.hasProperty(r'$flutterDriverResult'), true);
expect(js.context[r'$flutterDriverResult'], isNull);
});
});
}
| flutter/packages/flutter_driver/test/src/web_tests/web_extension_test.dart/0 | {
"file_path": "flutter/packages/flutter_driver/test/src/web_tests/web_extension_test.dart",
"repo_id": "flutter",
"token_count": 353
} | 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.
/// Json response template for the contents of the auth_opt.json file created by
/// goldctl.
String authTemplate({
bool gsutil = false,
}) {
return '''
{
"Luci":false,
"ServiceAccount":"${gsutil ? '' : '/packages/flutter/test/widgets/serviceAccount.json'}",
"GSUtil":$gsutil
}
''';
}
/// Json response template for Skia Gold image request:
/// https://flutter-gold.skia.org/img/images/[imageHash].png
List<List<int>> imageResponseTemplate() {
return <List<int>>[
<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,
],
<int>[
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,
],
];
}
| flutter/packages/flutter_goldens/test/json_templates.dart/0 | {
"file_path": "flutter/packages/flutter_goldens/test/json_templates.dart",
"repo_id": "flutter",
"token_count": 417
} | 710 |
{
"timerPickerHourLabelTwo": "awr",
"datePickerHourSemanticsLabelZero": "$hour o'r gloch",
"datePickerHourSemanticsLabelTwo": "$hour o'r gloch",
"datePickerHourSemanticsLabelFew": "$hour o'r gloch",
"datePickerHourSemanticsLabelMany": "$hour o'r gloch",
"timerPickerSecondLabelFew": "eiliad",
"timerPickerSecondLabelTwo": "eiliad",
"datePickerMinuteSemanticsLabelZero": "$minute munud",
"datePickerMinuteSemanticsLabelTwo": "$minute funud",
"datePickerMinuteSemanticsLabelFew": "$minute munud",
"datePickerMinuteSemanticsLabelMany": "$minute munud",
"timerPickerSecondLabelZero": "eiliad",
"timerPickerMinuteLabelMany": "munud",
"timerPickerMinuteLabelTwo": "funud",
"timerPickerMinuteLabelZero": "munud",
"timerPickerHourLabelMany": "awr",
"timerPickerHourLabelFew": "awr",
"timerPickerMinuteLabelFew": "munud",
"timerPickerSecondLabelMany": "eiliad",
"timerPickerHourLabelZero": "awr",
"datePickerHourSemanticsLabelOne": "$hour o'r gloch",
"datePickerHourSemanticsLabelOther": "$hour o'r gloch",
"datePickerMinuteSemanticsLabelOne": "1 funud",
"datePickerMinuteSemanticsLabelOther": "$minute munud",
"datePickerDateOrder": "dmy",
"datePickerDateTimeOrder": "date_time_dayPeriod",
"anteMeridiemAbbreviation": "AM",
"postMeridiemAbbreviation": "PM",
"todayLabel": "Heddiw",
"alertDialogLabel": "Rhybudd",
"tabSemanticsLabel": "Tab $tabIndex o $tabCount",
"timerPickerHourLabelOne": "awr",
"timerPickerHourLabelOther": "awr",
"timerPickerMinuteLabelOne": "funud",
"timerPickerMinuteLabelOther": "munud",
"timerPickerSecondLabelOne": "eiliad",
"timerPickerSecondLabelOther": "eiliad",
"cutButtonLabel": "Torri",
"copyButtonLabel": "Copïo",
"pasteButtonLabel": "Gludo",
"clearButtonLabel": "Clear",
"selectAllButtonLabel": "Dewis y Cyfan",
"searchTextFieldPlaceholderLabel": "Chwilio",
"modalBarrierDismissLabel": "Diystyru",
"noSpellCheckReplacementsLabel": "Dim Ailosodiadau wedi'u Canfod",
"menuDismissLabel": "Diystyru'r ddewislen",
"lookUpButtonLabel": "Chwilio",
"searchWebButtonLabel": "Chwilio'r We",
"shareButtonLabel": "Rhannu..."
}
| flutter/packages/flutter_localizations/lib/src/l10n/cupertino_cy.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_cy.arb",
"repo_id": "flutter",
"token_count": 782
} | 711 |
{
"datePickerHourSemanticsLabelOne": "$hour óra",
"datePickerHourSemanticsLabelOther": "$hour óra",
"datePickerMinuteSemanticsLabelOne": "1 perc",
"datePickerMinuteSemanticsLabelOther": "$minute perc",
"datePickerDateOrder": "ymd",
"datePickerDateTimeOrder": "date_dayPeriod_time",
"anteMeridiemAbbreviation": "de.",
"postMeridiemAbbreviation": "du.",
"todayLabel": "Ma",
"alertDialogLabel": "Értesítés",
"timerPickerHourLabelOne": "óra",
"timerPickerHourLabelOther": "óra",
"timerPickerMinuteLabelOne": "perc",
"timerPickerMinuteLabelOther": "perc",
"timerPickerSecondLabelOne": "mp",
"timerPickerSecondLabelOther": "mp",
"cutButtonLabel": "Kivágás",
"copyButtonLabel": "Másolás",
"pasteButtonLabel": "Beillesztés",
"selectAllButtonLabel": "Összes kijelölése",
"tabSemanticsLabel": "$tabCount/$tabIndex. lap",
"modalBarrierDismissLabel": "Elvetés",
"searchTextFieldPlaceholderLabel": "Keresés",
"noSpellCheckReplacementsLabel": "Nem található javítás",
"menuDismissLabel": "Menü bezárása",
"lookUpButtonLabel": "Felfelé nézés",
"searchWebButtonLabel": "Keresés az interneten",
"shareButtonLabel": "Megosztás…",
"clearButtonLabel": "Clear"
}
| flutter/packages/flutter_localizations/lib/src/l10n/cupertino_hu.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_hu.arb",
"repo_id": "flutter",
"token_count": 456
} | 712 |
{
"datePickerHourSemanticsLabelOne": "$hour മണി",
"datePickerHourSemanticsLabelOther": "$hour മണി",
"datePickerMinuteSemanticsLabelOne": "ഒരു മിനിറ്റ്",
"datePickerMinuteSemanticsLabelOther": "$minute മിനിറ്റ്",
"datePickerDateOrder": "dmy",
"datePickerDateTimeOrder": "date_time_dayPeriod",
"anteMeridiemAbbreviation": "AM",
"postMeridiemAbbreviation": "PM",
"todayLabel": "ഇന്ന്",
"alertDialogLabel": "മുന്നറിയിപ്പ്",
"timerPickerHourLabelOne": "മണിക്കൂർ",
"timerPickerHourLabelOther": "മണിക്കൂർ",
"timerPickerMinuteLabelOne": "മിനിറ്റ്",
"timerPickerMinuteLabelOther": "മിനിറ്റ്",
"timerPickerSecondLabelOne": "സെക്കൻഡ്",
"timerPickerSecondLabelOther": "സെക്കൻഡ്",
"cutButtonLabel": "മുറിക്കുക",
"copyButtonLabel": "പകർത്തുക",
"pasteButtonLabel": "ഒട്ടിക്കുക",
"selectAllButtonLabel": "എല്ലാം തിരഞ്ഞെടുക്കുക",
"tabSemanticsLabel": "$tabCount ടാബിൽ $tabIndex-ാമത്തേത്",
"modalBarrierDismissLabel": "നിരസിക്കുക",
"searchTextFieldPlaceholderLabel": "തിരയുക",
"noSpellCheckReplacementsLabel": "റീപ്ലേസ്മെന്റുകളൊന്നും കണ്ടെത്തിയില്ല",
"menuDismissLabel": "മെനു ഡിസ്മിസ് ചെയ്യുക",
"lookUpButtonLabel": "മുകളിലേക്ക് നോക്കുക",
"searchWebButtonLabel": "വെബിൽ തിരയുക",
"shareButtonLabel": "പങ്കിടുക...",
"clearButtonLabel": "Clear"
}
| flutter/packages/flutter_localizations/lib/src/l10n/cupertino_ml.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_ml.arb",
"repo_id": "flutter",
"token_count": 1151
} | 713 |
{
"datePickerHourSemanticsLabelOne": "$hourයි",
"datePickerHourSemanticsLabelOther": "$hourයි",
"datePickerMinuteSemanticsLabelOne": "මිනිත්තු 1",
"datePickerMinuteSemanticsLabelOther": "මිනිත්තු $minute",
"datePickerDateOrder": "ymd",
"datePickerDateTimeOrder": "date_dayPeriod_time",
"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_si.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_si.arb",
"repo_id": "flutter",
"token_count": 853
} | 714 |
{
"datePickerHourSemanticsLabelOne": "$hour giờ",
"datePickerHourSemanticsLabelOther": "$hour giờ",
"datePickerMinuteSemanticsLabelOne": "1 phút",
"datePickerMinuteSemanticsLabelOther": "$minute phút",
"datePickerDateOrder": "dmy",
"datePickerDateTimeOrder": "date_time_dayPeriod",
"anteMeridiemAbbreviation": "SÁNG",
"postMeridiemAbbreviation": "CHIỀU",
"todayLabel": "Hôm nay",
"alertDialogLabel": "Thông báo",
"timerPickerHourLabelOne": "giờ",
"timerPickerHourLabelOther": "giờ",
"timerPickerMinuteLabelOne": "phút",
"timerPickerMinuteLabelOther": "phút",
"timerPickerSecondLabelOne": "giây",
"timerPickerSecondLabelOther": "giây",
"cutButtonLabel": "Cắt",
"copyButtonLabel": "Sao chép",
"pasteButtonLabel": "Dán",
"selectAllButtonLabel": "Chọn tất cả",
"tabSemanticsLabel": "Thẻ $tabIndex/$tabCount",
"modalBarrierDismissLabel": "Bỏ qua",
"searchTextFieldPlaceholderLabel": "Tìm kiếm",
"noSpellCheckReplacementsLabel": "Không tìm thấy phương án thay thế",
"menuDismissLabel": "Đóng trình đơn",
"lookUpButtonLabel": "Tra cứu",
"searchWebButtonLabel": "Tìm kiếm trên web",
"shareButtonLabel": "Chia sẻ...",
"clearButtonLabel": "Clear"
}
| flutter/packages/flutter_localizations/lib/src/l10n/cupertino_vi.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_vi.arb",
"repo_id": "flutter",
"token_count": 526
} | 715 |
{
"scriptCategory": "tall",
"timeOfDayFormat": "H:mm",
"openAppDrawerTooltip": "নেভিগেশন মেনু খুলুন",
"backButtonTooltip": "ফিরে যান",
"closeButtonTooltip": "বন্ধ করুন",
"deleteButtonTooltip": "মুছে দিন",
"nextMonthTooltip": "পরের মাস",
"previousMonthTooltip": "আগের মাস",
"nextPageTooltip": "পরের পৃষ্ঠা",
"firstPageTooltip": "প্রথম পৃষ্ঠা",
"lastPageTooltip": "শেষ পৃষ্ঠা",
"previousPageTooltip": "আগের পৃষ্ঠা",
"showMenuTooltip": "মেনু দেখান",
"aboutListTileTitle": "$applicationName সম্পর্কে",
"licensesPageTitle": "লাইসেন্স",
"pageRowsInfoTitle": "$rowCountটির মধ্যে $firstRow-$lastRow",
"pageRowsInfoTitleApproximate": "প্রায় $rowCountটির মধ্যে $firstRow-$lastRow নম্বর",
"rowsPerPageTitle": "প্রতি পৃষ্ঠায় সারির সংখ্যা:",
"tabLabel": "$tabCount-এর মধ্যে $tabIndexটি ট্যাব",
"selectedRowCountTitleOne": "১টি আইটেম বেছে নেওয়া হয়েছে",
"selectedRowCountTitleOther": "$selectedRowCountটি আইটেম বেছে নেওয়া হয়েছে",
"cancelButtonLabel": "বাতিল করুন",
"closeButtonLabel": "বন্ধ করুন",
"continueButtonLabel": "চালিয়ে যান",
"copyButtonLabel": "কপি করুন",
"cutButtonLabel": "কাট করুন",
"scanTextButtonLabel": "টেক্সট স্ক্যান করুন",
"okButtonLabel": "ঠিক আছে",
"pasteButtonLabel": "পেস্ট করুন",
"selectAllButtonLabel": "সব বেছে নিন",
"viewLicensesButtonLabel": "লাইসেন্স দেখুন",
"anteMeridiemAbbreviation": "AM",
"postMeridiemAbbreviation": "PM",
"timePickerHourModeAnnouncement": "ঘণ্টা বেছে নিন",
"timePickerMinuteModeAnnouncement": "মিনিট বেছে নিন",
"modalBarrierDismissLabel": "খারিজ করুন",
"signedInLabel": "সাইন-ইন করা হয়েছে",
"hideAccountsLabel": "অ্যাকাউন্টগুলি লুকান",
"showAccountsLabel": "অ্যাকাউন্টগুলি দেখান",
"drawerLabel": "নেভিগেশান মেনু",
"popupMenuLabel": "পপ-আপ মেনু",
"dialogLabel": "ডায়ালগ",
"alertDialogLabel": "সতর্কতা",
"searchFieldLabel": "খুঁজুন",
"reorderItemToStart": "চালু করতে সরান",
"reorderItemToEnd": "একদম শেষের দিকে যান",
"reorderItemUp": "উপরের দিকে সরান",
"reorderItemDown": "নিচের দিকে সরান",
"reorderItemLeft": "বাঁদিকে সরান",
"reorderItemRight": "ডানদিকে সরান",
"expandedIconTapHint": "আড়াল করুন",
"collapsedIconTapHint": "বড় করুন",
"remainingTextFieldCharacterCountOne": "আর ১টি অক্ষর লেখা যাবে",
"remainingTextFieldCharacterCountOther": "আর $remainingCountটি অক্ষর লেখা যাবে",
"refreshIndicatorSemanticLabel": "রিফ্রেশ করুন",
"moreButtonTooltip": "আরও",
"dateSeparator": "/",
"dateHelpText": "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": "আগের চ্যানেলে যান",
"keyboardKeyChannelUp": "পরের চ্যানেলে যান",
"keyboardKeyControl": "Ctrl",
"keyboardKeyDelete": "Del",
"keyboardKeyEject": "ইজেক্ট করুন",
"keyboardKeyEnd": "End",
"keyboardKeyEscape": "Esc",
"keyboardKeyFn": "Fn",
"keyboardKeyHome": "Home",
"keyboardKeyInsert": "Insert",
"keyboardKeyMeta": "মেটা",
"keyboardKeyNumLock": "Num Lock",
"keyboardKeyNumpad1": "Num 1",
"keyboardKeyNumpad2": "Num 2",
"keyboardKeyNumpad3": "Num 3",
"keyboardKeyNumpad4": "Num 4",
"keyboardKeyNumpad5": "Num 5",
"keyboardKeyNumpad6": "Num 6",
"keyboardKeyNumpad7": "Num 7",
"keyboardKeyNumpad8": "Num 8",
"keyboardKeyNumpad9": "Num 9",
"keyboardKeyNumpad0": "Num 0",
"keyboardKeyNumpadAdd": "Num +",
"keyboardKeyNumpadComma": "Num ,",
"keyboardKeyNumpadDecimal": "Num .",
"keyboardKeyNumpadDivide": "Num /",
"keyboardKeyNumpadEnter": "Num Enter",
"keyboardKeyNumpadEqual": "Num =",
"keyboardKeyNumpadMultiply": "Num *",
"keyboardKeyNumpadParenLeft": "Num (",
"keyboardKeyNumpadParenRight": "Num )",
"keyboardKeyNumpadSubtract": "Num -",
"keyboardKeyPageDown": "PgDown",
"keyboardKeyPageUp": "PgUp",
"keyboardKeyPower": "Power",
"keyboardKeyPowerOff": "Power Off",
"keyboardKeyPrintScreen": "Print Screen",
"keyboardKeyScrollLock": "Scroll Lock",
"keyboardKeySelect": "বেছে নিন",
"keyboardKeySpace": "Space",
"keyboardKeyMetaMacOs": "Command",
"keyboardKeyMetaWindows": "Win",
"menuBarMenuLabel": "মেনু বার মেনু",
"currentDateLabel": "আজ",
"scrimLabel": "স্ক্রিম",
"bottomSheetLabel": "স্ক্রিনের নিচে অ্যাটাচ করা শিট",
"scrimOnTapHint": "$modalRouteContentName বন্ধ করুন",
"keyboardKeyShift": "Shift",
"expansionTileExpandedHint": "আড়াল করতে ডবল ট্যাপ করুন",
"expansionTileCollapsedHint": "বড় করে দেখতে ডবল ট্যাপ করুন",
"expansionTileExpandedTapHint": "আড়াল করুন",
"expansionTileCollapsedTapHint": "আরও বিবরণ পেতে বড় করে দেখুন",
"expandedHint": "আড়াল করা হয়েছে",
"collapsedHint": "বড় করা হয়েছে",
"menuDismissLabel": "বাতিল করার মেনু",
"lookUpButtonLabel": "লুক-আপ",
"searchWebButtonLabel": "ওয়েবে সার্চ করুন",
"shareButtonLabel": "শেয়ার করুন...",
"clearButtonTooltip": "Clear text",
"selectedDateLabel": "Selected"
}
| flutter/packages/flutter_localizations/lib/src/l10n/material_bn.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_bn.arb",
"repo_id": "flutter",
"token_count": 4497
} | 716 |
{
"scriptCategory": "tall",
"timeOfDayFormat": "H:mm",
"openAppDrawerTooltip": "નૅવિગેશન મેનૂ ખોલો",
"backButtonTooltip": "પાછળ",
"closeButtonTooltip": "બંધ કરો",
"deleteButtonTooltip": "ડિલીટ કરો",
"nextMonthTooltip": "આગલો મહિનો",
"previousMonthTooltip": "પાછલો મહિનો",
"nextPageTooltip": "આગલું પેજ",
"previousPageTooltip": "પાછલું પેજ",
"firstPageTooltip": "પહેલું પેજ",
"lastPageTooltip": "છેલ્લું પેજ",
"showMenuTooltip": "મેનૂ બતાવો",
"aboutListTileTitle": "$applicationName વિશે",
"licensesPageTitle": "લાઇસન્સ",
"pageRowsInfoTitle": "$rowCountમાંથી $firstRow–$lastRow",
"pageRowsInfoTitleApproximate": "આશરે $rowCountમાંથી $firstRow–$lastRow",
"rowsPerPageTitle": "પેજ દીઠ પંક્તિઓ:",
"tabLabel": "$tabCountમાંથી $tabIndex ટૅબ",
"selectedRowCountTitleOne": "1 આઇટમ પસંદ કરી",
"selectedRowCountTitleOther": "$selectedRowCount આઇટમ પસંદ કરી",
"cancelButtonLabel": "રદ કરો",
"closeButtonLabel": "બંધ કરો",
"continueButtonLabel": "ચાલુ રાખો",
"copyButtonLabel": "કૉપિ કરો",
"cutButtonLabel": "કાપો",
"scanTextButtonLabel": "ટેક્સ્ટ સ્કૅન કરો",
"okButtonLabel": "ઓકે",
"pasteButtonLabel": "પેસ્ટ કરો",
"selectAllButtonLabel": "બધા પસંદ કરો",
"viewLicensesButtonLabel": "લાઇસન્સ જુઓ",
"anteMeridiemAbbreviation": "AM",
"postMeridiemAbbreviation": "PM",
"timePickerHourModeAnnouncement": "કલાક પસંદ કરો",
"timePickerMinuteModeAnnouncement": "મિનિટ પસંદ કરો",
"modalBarrierDismissLabel": "છોડી દો",
"signedInLabel": "આમાં સાઇન ઇન કર્યું છે",
"hideAccountsLabel": "એકાઉન્ટ છુપાવો",
"showAccountsLabel": "એકાઉન્ટ બતાવો",
"drawerLabel": "નૅવિગેશન મેનૂ",
"popupMenuLabel": "પૉપઅપ મેનૂ",
"dialogLabel": "સંવાદ",
"alertDialogLabel": "અલર્ટ",
"searchFieldLabel": "શોધો",
"reorderItemToStart": "પ્રારંભમાં ખસેડો",
"reorderItemToEnd": "અંતમાં ખસેડો",
"reorderItemUp": "ઉપર ખસેડો",
"reorderItemDown": "નીચે ખસેડો",
"reorderItemLeft": "ડાબે ખસેડો",
"reorderItemRight": "જમણે ખસેડો",
"expandedIconTapHint": "સંકુચિત કરો",
"collapsedIconTapHint": "વિસ્તૃત કરો",
"remainingTextFieldCharacterCountOne": "1 અક્ષર બાકી",
"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": "1 લાઇસન્સ",
"licensesPackageDetailTextOther": "$licenseCount લાઇસન્સ",
"keyboardKeyAlt": "Alt",
"keyboardKeyAltGraph": "AltGr",
"keyboardKeyBackspace": "Backspace",
"keyboardKeyCapsLock": "Caps Lock",
"keyboardKeyChannelDown": "Channel Down",
"keyboardKeyChannelUp": "Channel Up",
"keyboardKeyControl": "Ctrl",
"keyboardKeyDelete": "Del",
"keyboardKeyEject": "Eject",
"keyboardKeyEnd": "End",
"keyboardKeyEscape": "Esc",
"keyboardKeyFn": "Fn",
"keyboardKeyHome": "Home",
"keyboardKeyInsert": "Insert",
"keyboardKeyMeta": "Meta",
"keyboardKeyNumLock": "Num Lock",
"keyboardKeyNumpad1": "Num 1",
"keyboardKeyNumpad2": "Num 2",
"keyboardKeyNumpad3": "Num 3",
"keyboardKeyNumpad4": "Num 4",
"keyboardKeyNumpad5": "Num 5",
"keyboardKeyNumpad6": "Num 6",
"keyboardKeyNumpad7": "Num 7",
"keyboardKeyNumpad8": "Num 8",
"keyboardKeyNumpad9": "Num 9",
"keyboardKeyNumpad0": "Num 0",
"keyboardKeyNumpadAdd": "Num +",
"keyboardKeyNumpadComma": "Num ,",
"keyboardKeyNumpadDecimal": "Num .",
"keyboardKeyNumpadDivide": "Num /",
"keyboardKeyNumpadEnter": "Num Enter",
"keyboardKeyNumpadEqual": "Num =",
"keyboardKeyNumpadMultiply": "Num *",
"keyboardKeyNumpadParenLeft": "Num (",
"keyboardKeyNumpadParenRight": "Num )",
"keyboardKeyNumpadSubtract": "Num -",
"keyboardKeyPageDown": "PgDown",
"keyboardKeyPageUp": "PgUp",
"keyboardKeyPower": "Power",
"keyboardKeyPowerOff": "Power Off",
"keyboardKeyPrintScreen": "Print Screen",
"keyboardKeyScrollLock": "Scroll Lock",
"keyboardKeySelect": "Select",
"keyboardKeySpace": "Space",
"keyboardKeyMetaMacOs": "Command",
"keyboardKeyMetaWindows": "Win",
"menuBarMenuLabel": "મેનૂ બાર મેનૂ",
"currentDateLabel": "આજે",
"scrimLabel": "સ્ક્રિમ",
"bottomSheetLabel": "બોટમ શીટ",
"scrimOnTapHint": "$modalRouteContentNameને બંધ કરો",
"keyboardKeyShift": "Shift",
"expansionTileExpandedHint": "નાની કરવા માટે બે વાર ટૅપ કરો",
"expansionTileCollapsedHint": "મોટી કરવા માટે બે વાર ટૅપ કરો",
"expansionTileExpandedTapHint": "નાની કરો",
"expansionTileCollapsedTapHint": "વધુ વિગતો માટે મોટી કરો",
"expandedHint": "નાની કરી",
"collapsedHint": "મોટી કરી",
"menuDismissLabel": "મેનૂ છોડી દો",
"lookUpButtonLabel": "શોધો",
"searchWebButtonLabel": "વેબ પર શોધો",
"shareButtonLabel": "શેર કરો…",
"clearButtonTooltip": "Clear text",
"selectedDateLabel": "Selected"
}
| flutter/packages/flutter_localizations/lib/src/l10n/material_gu.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_gu.arb",
"repo_id": "flutter",
"token_count": 4653
} | 717 |
{
"scriptCategory": "tall",
"timeOfDayFormat": "H:mm",
"openAppDrawerTooltip": "ເປີດເມນູການນຳທາງ",
"backButtonTooltip": "ກັບຄືນ",
"closeButtonTooltip": "ປິດ",
"deleteButtonTooltip": "ລຶບ",
"nextMonthTooltip": "ເດືອນໜ້າ",
"previousMonthTooltip": "ເດືອນແລ້ວ",
"nextPageTooltip": "ໜ້າຕໍ່ໄປ",
"previousPageTooltip": "ໜ້າກ່ອນໜ້າ",
"firstPageTooltip": "ໜ້າທຳອິດ",
"lastPageTooltip": "ໜ້າສຸດທ້າຍ",
"showMenuTooltip": "ສະແດງເມນູ",
"aboutListTileTitle": "ກ່ຽວກັບ $applicationName",
"licensesPageTitle": "ໃບອະນຸຍາດ",
"pageRowsInfoTitle": "$firstRow–$lastRow ຈາກທັງໝົດ $rowCount",
"pageRowsInfoTitleApproximate": "$firstRow–$lastRow ຈາກປະມານ $rowCount",
"rowsPerPageTitle": "ແຖວຕໍ່ໜ້າ:",
"tabLabel": "ແຖບທີ $tabIndex ຈາກທັງໝົດ $tabCount",
"selectedRowCountTitleOne": "ເລືອກ 1 ລາຍການແລ້ວ",
"selectedRowCountTitleOther": "ເລືອກ $selectedRowCount ລາຍການແລ້ວ",
"cancelButtonLabel": "ຍົກເລີກ",
"closeButtonLabel": "ປິດ",
"continueButtonLabel": "ສືບຕໍ່",
"copyButtonLabel": "ສຳເນົາ",
"cutButtonLabel": "ຕັດ",
"scanTextButtonLabel": "ສະແກນຂໍ້ຄວາມ",
"okButtonLabel": "ຕົກລົງ",
"pasteButtonLabel": "ວາງ",
"selectAllButtonLabel": "ເລືອກທັງໝົດ",
"viewLicensesButtonLabel": "ເບິ່ງໃບອະນຸຍາດ",
"anteMeridiemAbbreviation": "ກ່ອນທ່ຽງ",
"postMeridiemAbbreviation": "ຫຼັງທ່ຽງ",
"timePickerHourModeAnnouncement": "ເລືອກໂມງ",
"timePickerMinuteModeAnnouncement": "ເລືອກນາທີ",
"modalBarrierDismissLabel": "ປິດໄວ້",
"signedInLabel": "ເຂົ້າສູ່ລະບົບແລ້ວ",
"hideAccountsLabel": "ເຊື່ອງບັນຊີ",
"showAccountsLabel": "ສະແດງບັນຊີ",
"drawerLabel": "ເມນູນຳທາງ",
"popupMenuLabel": "ເມນູປັອບອັບ",
"dialogLabel": "ຂໍ້ຄວາມ",
"alertDialogLabel": "ການເຕືອນ",
"searchFieldLabel": "ຊອກຫາ",
"reorderItemToStart": "ຍ້າຍໄປເລີ່ມຕົ້ນ",
"reorderItemToEnd": "ຍ້າຍໄປສິ້ນສຸດ",
"reorderItemUp": "ຍ້າຍຂຶ້ນ",
"reorderItemDown": "ຍ້າຍລົງ",
"reorderItemLeft": "ຍ້າຍໄປຊ້າຍ",
"reorderItemRight": "ຍ້າຍໄປຂວາ",
"expandedIconTapHint": "ຫຍໍ້ເຂົ້າ",
"collapsedIconTapHint": "ຂະຫຍາຍ",
"remainingTextFieldCharacterCountOne": "ຍັງອີກ 1 ຕົວອັກສອນ",
"remainingTextFieldCharacterCountOther": "ຍັງອີກ $remainingCount ຕົວອັກສອນ",
"refreshIndicatorSemanticLabel": "ໂຫຼດຄືນໃໝ່",
"moreButtonTooltip": "ເພີ່ມເຕີມ",
"dateSeparator": "/",
"dateHelpText": "ດດ/ວວ/ປປປປ",
"selectYearSemanticsLabel": "ເລືອກປີ",
"unspecifiedDate": "ວັນທີ",
"unspecifiedDateRange": "ຊ່ວງວັນທີ",
"dateInputLabel": "ໃສ່ວັນທີ",
"dateRangeStartLabel": "ວັນທີເລີ່ມຕົ້ນ",
"dateRangeEndLabel": "ວັນທີສິ້ນສຸດ",
"dateRangeStartDateSemanticLabel": "ວັນທີເລີ່ມຕົ້ນ $fullDate",
"dateRangeEndDateSemanticLabel": "ວັນທີສິ້ນສຸດ $fullDate",
"invalidDateFormatLabel": "ຮູບແບບບໍ່ຖືກຕ້ອງ.",
"invalidDateRangeLabel": "ໄລຍະບໍ່ຖືກຕ້ອງ.",
"dateOutOfRangeLabel": "ຢູ່ນອກໄລຍະ.",
"saveButtonLabel": "ບັນທຶກ",
"datePickerHelpText": "ເລືອກວັນທີ",
"dateRangePickerHelpText": "ເລືອກໄລຍະ",
"calendarModeButtonLabel": "ສະຫຼັບໄປປະຕິທິນ",
"inputDateModeButtonLabel": "ສະຫຼັບໄປການປ້ອນຂໍ້ມູນ",
"timePickerDialHelpText": "ເລືອກເວລາ",
"timePickerInputHelpText": "ລະບຸເວລາ",
"timePickerHourLabel": "ຊົ່ວໂມງ",
"timePickerMinuteLabel": "ນາທີ",
"invalidTimeLabel": "ລະບຸເວລາທີ່ຖືກຕ້ອງ",
"dialModeButtonLabel": "ສະຫຼັບໄປໃຊ້ໂໝດເລືອກຕົວເລກ",
"inputTimeModeButtonLabel": "ສະຫຼັບໄປໃຊ້ໂໝດປ້ອນຂໍ້ຄວາມ",
"licensesPackageDetailTextZero": "No licenses",
"licensesPackageDetailTextOne": "1 ໃບອະນຸຍາດ",
"licensesPackageDetailTextOther": "$licenseCount ໃບອະນຸຍາດ",
"keyboardKeyAlt": "Alt",
"keyboardKeyAltGraph": "AltGr",
"keyboardKeyBackspace": "Backspace",
"keyboardKeyCapsLock": "Caps Lock",
"keyboardKeyChannelDown": "Channel Down",
"keyboardKeyChannelUp": "Channel Up",
"keyboardKeyControl": "Ctrl",
"keyboardKeyDelete": "Del",
"keyboardKeyEject": "Eject",
"keyboardKeyEnd": "End",
"keyboardKeyEscape": "Esc",
"keyboardKeyFn": "Fn",
"keyboardKeyHome": "Home",
"keyboardKeyInsert": "Insert",
"keyboardKeyMeta": "Meta",
"keyboardKeyNumLock": "Num Lock",
"keyboardKeyNumpad1": "ເລກ 1",
"keyboardKeyNumpad2": "ເລກ 2",
"keyboardKeyNumpad3": "ເລກ 3",
"keyboardKeyNumpad4": "ເລກ 4",
"keyboardKeyNumpad5": "ເລກ 5",
"keyboardKeyNumpad6": "ເລກ 6",
"keyboardKeyNumpad7": "ເລກ 7",
"keyboardKeyNumpad8": "ເລກ 8",
"keyboardKeyNumpad9": "ເລກ 9",
"keyboardKeyNumpad0": "ເລກ 0",
"keyboardKeyNumpadAdd": "ປຸ່ມ +",
"keyboardKeyNumpadComma": "ປຸ່ມ ,",
"keyboardKeyNumpadDecimal": "ປຸ່ມ .",
"keyboardKeyNumpadDivide": "ປຸ່ມ /",
"keyboardKeyNumpadEnter": "ປຸ່ມ Enter",
"keyboardKeyNumpadEqual": "ປຸ່ມ =",
"keyboardKeyNumpadMultiply": "ປຸ່ມ *",
"keyboardKeyNumpadParenLeft": "ປຸ່ມ (",
"keyboardKeyNumpadParenRight": "ປຸ່ມ )",
"keyboardKeyNumpadSubtract": "ປຸ່ມ -",
"keyboardKeyPageDown": "PgDown",
"keyboardKeyPageUp": "PgUp",
"keyboardKeyPower": "ເປີດປິດ",
"keyboardKeyPowerOff": "ປິດເຄື່ອງ",
"keyboardKeyPrintScreen": "Print Screen",
"keyboardKeyScrollLock": "Scroll Lock",
"keyboardKeySelect": "Select",
"keyboardKeySpace": "Space",
"keyboardKeyMetaMacOs": "Command",
"keyboardKeyMetaWindows": "Win",
"menuBarMenuLabel": "ເມນູແຖບເມນູ",
"currentDateLabel": "ມື້ນີ້",
"scrimLabel": "Scrim",
"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_lo.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_lo.arb",
"repo_id": "flutter",
"token_count": 4938
} | 718 |
{
"scriptCategory": "tall",
"timeOfDayFormat": "HH:mm",
"anteMeridiemAbbreviation": "AM",
"@anteMeridiemAbbreviation": {"notUsed":"Pashto time format does not use a.m. indicator"},
"postMeridiemAbbreviation": "PM",
"@postMeridiemAbbreviation": {"notUsed":"Pashto time format does not use p.m. indicator"},
"openAppDrawerTooltip": "د پرانیستی نیینګ مینو",
"backButtonTooltip": "شاته",
"closeButtonTooltip": "بنده",
"deleteButtonTooltip": "",
"nextMonthTooltip": "بله میاشت",
"previousMonthTooltip": "تیره میاشت",
"nextPageTooltip": "بله پاڼه",
"previousPageTooltip": "مخکینی مخ",
"firstPageTooltip": "First page",
"lastPageTooltip": "Last page",
"showMenuTooltip": "غورنۍ ښودل",
"aboutListTileTitle": "د $applicationName په اړه",
"licensesPageTitle": "جوازونه",
"pageRowsInfoTitle": "$firstRow–$lastRow د $rowCount",
"pageRowsInfoTitleApproximate": "$firstRow–$lastRow څخه $rowCount د",
"rowsPerPageTitle": "د هرې پاڼې پاڼې:",
"tabLabel": "$tabIndex د $tabCount",
"selectedRowCountTitleOther": "$selectedRowCount توکي غوره شوي",
"cancelButtonLabel": "لغوه کول",
"closeButtonLabel": "تړل",
"continueButtonLabel": "منځپانګې",
"copyButtonLabel": "کاپی",
"cutButtonLabel": "کم کړئ",
"scanTextButtonLabel": "متن سکین کړئ",
"okButtonLabel": "سمه ده",
"pasteButtonLabel": "پیټ کړئ",
"selectAllButtonLabel": "غوره کړئ",
"viewLicensesButtonLabel": "لیدلس وګورئ",
"timePickerHourModeAnnouncement": "وختونه وټاکئ",
"timePickerMinuteModeAnnouncement": "منې غوره کړئ",
"signedInLabel": "ننوتل",
"hideAccountsLabel": "حسابونه پټ کړئ",
"showAccountsLabel": "حسابونه ښکاره کړئ",
"modalBarrierDismissLabel": "رد کړه",
"drawerLabel": "د نیویگیشن مینو",
"popupMenuLabel": "د پاپ اپ مینو",
"dialogLabel": "خبرې اترې",
"alertDialogLabel": "خبرتیا",
"searchFieldLabel": "لټون",
"moreButtonTooltip": "More",
"reorderItemToStart": "Move to the start",
"reorderItemToEnd": "Move to the end",
"reorderItemUp": "Move up",
"reorderItemDown": "Move down",
"reorderItemLeft": "Move left",
"reorderItemRight": "Move right",
"expandedIconTapHint": "Collapse",
"collapsedIconTapHint": "Expand",
"remainingTextFieldCharacterCountZero": "No characters remaining",
"remainingTextFieldCharacterCountOne": "1 character remaining",
"remainingTextFieldCharacterCountOther": "$remainingCount characters remaining",
"refreshIndicatorSemanticLabel": "Refresh",
"dateSeparator": "/",
"dateHelpText": "mm/dd/yyyy",
"selectYearSemanticsLabel": "Select year",
"unspecifiedDate": "Date",
"unspecifiedDateRange": "Date Range",
"dateInputLabel": "Enter Date",
"dateRangeStartLabel": "Start Date",
"dateRangeEndLabel": "End Date",
"dateRangeStartDateSemanticLabel": "Start date $fullDate",
"dateRangeEndDateSemanticLabel": "End date $fullDate",
"invalidDateFormatLabel": "Invalid format.",
"invalidDateRangeLabel": "Invalid range.",
"dateOutOfRangeLabel": "Out of range.",
"saveButtonLabel": "SAVE",
"datePickerHelpText": "SELECT DATE",
"dateRangePickerHelpText": "SELECT RANGE",
"calendarModeButtonLabel": "Switch to calendar",
"inputDateModeButtonLabel": "Switch to input",
"timePickerDialHelpText": "SELECT TIME",
"timePickerInputHelpText": "ENTER TIME",
"timePickerHourLabel": "Hour",
"timePickerMinuteLabel": "Minute",
"invalidTimeLabel": "Enter a valid time",
"dialModeButtonLabel": "Switch to dial picker mode",
"inputTimeModeButtonLabel": "Switch to text input mode",
"licensesPackageDetailTextZero": "No licenses",
"licensesPackageDetailTextOne": "1 license",
"licensesPackageDetailTextOther": "$licenseCount licenses",
"keyboardKeyAlt": "Alt",
"keyboardKeyAltGraph": "AltGr",
"keyboardKeyBackspace": "Backspace",
"keyboardKeyCapsLock": "Caps Lock",
"keyboardKeyChannelDown": "Channel Down",
"keyboardKeyChannelUp": "Channel Up",
"keyboardKeyControl": "Ctrl",
"keyboardKeyDelete": "Del",
"keyboardKeyEject": "Eject",
"keyboardKeyEnd": "End",
"keyboardKeyEscape": "Esc",
"keyboardKeyFn": "Fn",
"keyboardKeyHome": "Home",
"keyboardKeyInsert": "Insert",
"keyboardKeyMeta": "Meta",
"keyboardKeyNumLock": "Num Lock",
"keyboardKeyNumpad1": "Num 1",
"keyboardKeyNumpad2": "Num 2",
"keyboardKeyNumpad3": "Num 3",
"keyboardKeyNumpad4": "Num 4",
"keyboardKeyNumpad5": "Num 5",
"keyboardKeyNumpad6": "Num 6",
"keyboardKeyNumpad7": "Num 7",
"keyboardKeyNumpad8": "Num 8",
"keyboardKeyNumpad9": "Num 9",
"keyboardKeyNumpad0": "Num 0",
"keyboardKeyNumpadAdd": "Num +",
"keyboardKeyNumpadComma": "Num ,",
"keyboardKeyNumpadDecimal": "Num .",
"keyboardKeyNumpadDivide": "Num /",
"keyboardKeyNumpadEnter": "Num Enter",
"keyboardKeyNumpadEqual": "Num =",
"keyboardKeyNumpadMultiply": "Num *",
"keyboardKeyNumpadParenLeft": "Num (",
"keyboardKeyNumpadParenRight": "Num )",
"keyboardKeyNumpadSubtract": "Num -",
"keyboardKeyPageDown": "PgDown",
"keyboardKeyPageUp": "PgUp",
"keyboardKeyPower": "Power",
"keyboardKeyPowerOff": "Power Off",
"keyboardKeyPrintScreen": "Print Screen",
"keyboardKeyScrollLock": "Scroll Lock",
"keyboardKeySelect": "Select",
"keyboardKeySpace": "Space",
"keyboardKeyMetaMacOs": "Command",
"keyboardKeyMetaWindows": "Win",
"menuBarMenuLabel": "Menu bar menu",
"currentDateLabel": "Date of today",
"scrimLabel": "Scrim",
"bottomSheetLabel": "Bottom Sheet",
"scrimOnTapHint": "Close $modalRouteName",
"keyboardKeyShift": "Shift",
"expansionTileExpandedHint": "double tap to collapse'",
"expansionTileCollapsedHint": "double tap to expand",
"expansionTileExpandedTapHint": "Collapse",
"expansionTileCollapsedTapHint": "Expand for more details",
"expandedHint": "Collapsed",
"collapsedHint": "Expanded",
"menuDismissLabel": "Dismiss menu",
"lookUpButtonLabel": "Look Up",
"searchWebButtonLabel": "Search Web",
"shareButtonLabel": "Share...",
"clearButtonTooltip": "Clear text",
"selectedDateLabel": "Selected"
}
| flutter/packages/flutter_localizations/lib/src/l10n/material_ps.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_ps.arb",
"repo_id": "flutter",
"token_count": 2393
} | 719 |
{
"reorderItemToStart": "Преместване в началото",
"reorderItemToEnd": "Преместване в края",
"reorderItemUp": "Преместване нагоре",
"reorderItemDown": "Преместване надолу",
"reorderItemLeft": "Преместване наляво",
"reorderItemRight": "Преместване надясно"
}
| flutter/packages/flutter_localizations/lib/src/l10n/widgets_bg.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_bg.arb",
"repo_id": "flutter",
"token_count": 187
} | 720 |
{
"reorderItemToStart": "Башына жылдыруу",
"reorderItemToEnd": "Аягына жылдыруу",
"reorderItemUp": "Жогору жылдыруу",
"reorderItemDown": "Төмөн жылдыруу",
"reorderItemLeft": "Солго жылдыруу",
"reorderItemRight": "Оңго жылдыруу"
}
| flutter/packages/flutter_localizations/lib/src/l10n/widgets_ky.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_ky.arb",
"repo_id": "flutter",
"token_count": 165
} | 721 |
{
"reorderItemToStart": "Przenieś na początek",
"reorderItemToEnd": "Przenieś na koniec",
"reorderItemUp": "Przenieś w górę",
"reorderItemDown": "Przenieś w dół",
"reorderItemLeft": "Przenieś w lewo",
"reorderItemRight": "Przenieś w prawo"
}
| flutter/packages/flutter_localizations/lib/src/l10n/widgets_pl.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_pl.arb",
"repo_id": "flutter",
"token_count": 125
} | 722 |
{
"reorderItemToStart": "ย้ายไปต้นรายการ",
"reorderItemToEnd": "ย้ายไปท้ายรายการ",
"reorderItemUp": "ย้ายขึ้น",
"reorderItemDown": "ย้ายลง",
"reorderItemLeft": "ย้ายไปทางซ้าย",
"reorderItemRight": "ย้ายไปทางขวา"
}
| flutter/packages/flutter_localizations/lib/src/l10n/widgets_th.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_th.arb",
"repo_id": "flutter",
"token_count": 206
} | 723 |
// 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';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Test correct month form for CupertinoDatePicker in monthYear mode', (WidgetTester tester) async {
await tester.pumpWidget(
CupertinoApp(
home: CupertinoPageScaffold(
child: Center(
child: CupertinoDatePicker(
initialDateTime: DateTime(2023, 5),
onDateTimeChanged: (_) {},
mode: CupertinoDatePickerMode.monthYear,
)),
),
supportedLocales: const <Locale>[Locale('ru', 'RU')],
localizationsDelegates: GlobalCupertinoLocalizations.delegates,
),
);
expect(find.text('Май'), findsWidgets);
});
testWidgets('Test correct month form for CupertinoDatePicker in date mode', (WidgetTester tester) async {
await tester.pumpWidget(
CupertinoApp(
home: CupertinoPageScaffold(
child: Center(
child: CupertinoDatePicker(
initialDateTime: DateTime(2023, 5),
onDateTimeChanged: (_) {},
mode: CupertinoDatePickerMode.date,
)),
),
supportedLocales: const <Locale>[Locale('ru', 'RU')],
localizationsDelegates: GlobalCupertinoLocalizations.delegates,
),
);
expect(find.text('мая'), findsWidgets);
});
}
| flutter/packages/flutter_localizations/test/cupertino/date_picker_test.dart/0 | {
"file_path": "flutter/packages/flutter_localizations/test/cupertino/date_picker_test.dart",
"repo_id": "flutter",
"token_count": 673
} | 724 |
// 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:clock/clock.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'event_simulation.dart';
import 'finders.dart' as finders;
import 'test_async_utils.dart';
import 'test_pointer.dart';
import 'tree_traversal.dart';
import 'window.dart';
/// The default drag touch slop used to break up a large drag into multiple
/// smaller moves.
///
/// This value must be greater than [kTouchSlop].
const double kDragSlopDefault = 20.0;
// Finds the end index (exclusive) of the span at `startIndex`, or `endIndex` if
// there are no other spans between `startIndex` and `endIndex`.
// The InlineSpan protocol doesn't expose the length of the span so we'll
// have to iterate through the whole range.
(InlineSpan, int)? _findEndOfSpan(InlineSpan rootSpan, int startIndex, int endIndex) {
assert(endIndex > startIndex);
final InlineSpan? subspan = rootSpan.getSpanForPosition(TextPosition(offset: startIndex));
if (subspan == null) {
return null;
}
int i = startIndex + 1;
while (i < endIndex && rootSpan.getSpanForPosition(TextPosition(offset: i)) == subspan) {
i += 1;
}
return (subspan, i);
}
// Examples can assume:
// typedef MyWidget = Placeholder;
/// Class that programmatically interacts with the [Semantics] tree.
///
/// Allows for testing of the [Semantics] tree, which is used by assistive
/// technology, search engines, and other analysis software to determine the
/// meaning of an application.
///
/// Should be accessed through [WidgetController.semantics]. If no custom
/// implementation is provided, a default [SemanticsController] will be created.
class SemanticsController {
/// Creates a [SemanticsController] that uses the given binding. Will be
/// automatically created as part of instantiating a [WidgetController], but
/// a custom implementation can be passed via the [WidgetController] constructor.
SemanticsController._(this._controller);
static final int _scrollingActions =
SemanticsAction.scrollUp.index |
SemanticsAction.scrollDown.index |
SemanticsAction.scrollLeft.index |
SemanticsAction.scrollRight.index;
/// Based on Android's FOCUSABLE_FLAGS. See [flutter/engine/AccessibilityBridge.java](https://github.com/flutter/engine/blob/main/shell/platform/android/io/flutter/view/AccessibilityBridge.java).
static final int _importantFlagsForAccessibility =
SemanticsFlag.hasCheckedState.index |
SemanticsFlag.hasToggledState.index |
SemanticsFlag.hasEnabledState.index |
SemanticsFlag.isButton.index |
SemanticsFlag.isTextField.index |
SemanticsFlag.isFocusable.index |
SemanticsFlag.isSlider.index |
SemanticsFlag.isInMutuallyExclusiveGroup.index;
final WidgetController _controller;
/// Attempts to find the [SemanticsNode] of first result from `finder`.
///
/// If the object identified by the finder doesn't own its semantic node,
/// this will return the semantics data of the first ancestor with semantics.
/// The ancestor's semantic data will include the child's as well as
/// other nodes that have been merged together.
///
/// If the [SemanticsNode] of the object identified by the finder is
/// force-merged into an ancestor (e.g. via the [MergeSemantics] widget)
/// the node into which it is merged is returned. That node will include
/// all the semantics information of the nodes merged into it.
///
/// Will throw a [StateError] if the finder returns more than one element or
/// if no semantics are found or are not enabled.
SemanticsNode find(finders.FinderBase<Element> finder) {
TestAsyncUtils.guardSync();
final Iterable<Element> candidates = finder.evaluate();
if (candidates.isEmpty) {
throw StateError('Finder returned no matching elements.');
}
if (candidates.length > 1) {
throw StateError('Finder returned more than one element.');
}
final Element element = candidates.single;
RenderObject? renderObject = element.findRenderObject();
SemanticsNode? result = renderObject?.debugSemantics;
while (renderObject != null && (result == null || result.isMergedIntoParent)) {
renderObject = renderObject.parent;
result = renderObject?.debugSemantics;
}
if (result == null) {
throw StateError('No Semantics data found.');
}
return result;
}
/// Simulates a traversal of the currently visible semantics tree as if by
/// assistive technologies.
///
/// Starts at the node for `startNode`. If `startNode` is not provided, then
/// the traversal begins with the first accessible node in the tree. If
/// `startNode` finds zero elements or more than one element, a [StateError]
/// will be thrown.
///
/// Ends at the node for `endNode`, inclusive. If `endNode` is not provided,
/// then the traversal ends with the last accessible node in the currently
/// available tree. If `endNode` finds zero elements or more than one element,
/// a [StateError] will be thrown.
///
/// If provided, the nodes for `endNode` and `startNode` must be part of the
/// same semantics tree, i.e. they must be part of the same view.
///
/// If neither `startNode` or `endNode` is provided, `view` can be provided to
/// specify the semantics tree to traverse. If `view` is left unspecified,
/// [WidgetTester.view] is traversed by default.
///
/// Since the order is simulated, edge cases that differ between platforms
/// (such as how the last visible item in a scrollable list is handled) may be
/// inconsistent with platform behavior, but are expected to be sufficient for
/// testing order, availability to assistive technologies, and interactions.
///
/// ## Sample Code
///
/// ```dart
/// testWidgets('MyWidget', (WidgetTester tester) async {
/// await tester.pumpWidget(const MyWidget());
///
/// expect(
/// tester.semantics.simulatedAccessibilityTraversal(),
/// containsAllInOrder(<Matcher>[
/// containsSemantics(label: 'My Widget'),
/// containsSemantics(label: 'is awesome!', isChecked: true),
/// ]),
/// );
/// });
/// ```
///
/// See also:
///
/// * [containsSemantics] and [matchesSemantics], which can be used to match
/// against a single node in the traversal.
/// * [containsAllInOrder], which can be given an [Iterable<Matcher>] to fuzzy
/// match the order allowing extra nodes before after and between matching
/// parts of the traversal.
/// * [orderedEquals], which can be given an [Iterable<Matcher>] to exactly
/// match the order of the traversal.
Iterable<SemanticsNode> simulatedAccessibilityTraversal({
@Deprecated(
'Use startNode instead. '
'This method was originally created before semantics finders were available. '
'Semantics finders avoid edge cases where some nodes are not discoverable by widget finders and should be preferred for semantics testing. '
'This feature was deprecated after v3.15.0-15.2.pre.'
)
finders.FinderBase<Element>? start,
@Deprecated(
'Use endNode instead. '
'This method was originally created before semantics finders were available. '
'Semantics finders avoid edge cases where some nodes are not discoverable by widget finders and should be preferred for semantics testing. '
'This feature was deprecated after v3.15.0-15.2.pre.'
)
finders.FinderBase<Element>? end,
finders.FinderBase<SemanticsNode>? startNode,
finders.FinderBase<SemanticsNode>? endNode,
FlutterView? view,
}) {
TestAsyncUtils.guardSync();
assert(
start == null || startNode == null,
'Cannot provide both start and startNode. Prefer startNode as start is deprecated.',
);
assert(
end == null || endNode == null,
'Cannot provide both end and endNode. Prefer endNode as end is deprecated.',
);
FlutterView? startView;
if (start != null) {
startView = _controller.viewOf(start);
if (view != null && startView != view) {
throw StateError(
'The start node is not part of the provided view.\n'
'Finder: ${start.toString(describeSelf: true)}\n'
'View of start node: $startView\n'
'Specified view: $view'
);
}
} else if (startNode != null) {
final SemanticsOwner owner = startNode.evaluate().single.owner!;
final RenderView renderView = _controller.binding.renderViews.firstWhere(
(RenderView render) => render.owner!.semanticsOwner == owner,
);
startView = renderView.flutterView;
if (view != null && startView != view) {
throw StateError(
'The start node is not part of the provided view.\n'
'Finder: ${startNode.toString(describeSelf: true)}\n'
'View of start node: $startView\n'
'Specified view: $view'
);
}
}
FlutterView? endView;
if (end != null) {
endView = _controller.viewOf(end);
if (view != null && endView != view) {
throw StateError(
'The end node is not part of the provided view.\n'
'Finder: ${end.toString(describeSelf: true)}\n'
'View of end node: $endView\n'
'Specified view: $view'
);
}
} else if (endNode != null) {
final SemanticsOwner owner = endNode.evaluate().single.owner!;
final RenderView renderView = _controller.binding.renderViews.firstWhere(
(RenderView render) => render.owner!.semanticsOwner == owner,
);
endView = renderView.flutterView;
if (view != null && endView != view) {
throw StateError(
'The end node is not part of the provided view.\n'
'Finder: ${endNode.toString(describeSelf: true)}\n'
'View of end node: $endView\n'
'Specified view: $view'
);
}
}
if (endView != null && startView != null && endView != startView) {
throw StateError(
'The start and end node are in different views.\n'
'Start finder: ${start!.toString(describeSelf: true)}\n'
'End finder: ${end!.toString(describeSelf: true)}\n'
'View of start node: $startView\n'
'View of end node: $endView'
);
}
final FlutterView actualView = view ?? startView ?? endView ?? _controller.view;
final RenderView renderView = _controller.binding.renderViews.firstWhere((RenderView r) => r.flutterView == actualView);
final List<SemanticsNode> traversal = <SemanticsNode>[];
_accessibilityTraversal(
renderView.owner!.semanticsOwner!.rootSemanticsNode!,
traversal,
);
// Setting the range
SemanticsNode? node;
String? errorString;
int startIndex;
if (start != null) {
node = find(start);
startIndex = traversal.indexOf(node);
errorString = start.toString(describeSelf: true);
} else if (startNode != null) {
node = startNode.evaluate().single;
startIndex = traversal.indexOf(node);
errorString = startNode.toString(describeSelf: true);
} else {
startIndex = 0;
}
if (startIndex == -1) {
throw StateError(
'The expected starting node was not found.\n'
'Finder: $errorString\n\n'
'Expected Start Node: $node\n\n'
'Traversal: [\n ${traversal.join('\n ')}\n]');
}
int? endIndex;
if (end != null) {
node = find(end);
endIndex = traversal.indexOf(node);
errorString = end.toString(describeSelf: true);
} else if (endNode != null) {
node = endNode.evaluate().single;
endIndex = traversal.indexOf(node);
errorString = endNode.toString(describeSelf: true);
}
if (endIndex == -1) {
throw StateError(
'The expected ending node was not found.\n'
'Finder: $errorString\n\n'
'Expected End Node: $node\n\n'
'Traversal: [\n ${traversal.join('\n ')}\n]');
}
endIndex ??= traversal.length - 1;
return traversal.getRange(startIndex, endIndex + 1);
}
/// Recursive depth first traversal of the specified `node`, adding nodes
/// that are important for semantics to the `traversal` list.
void _accessibilityTraversal(SemanticsNode node, List<SemanticsNode> traversal){
if (_isImportantForAccessibility(node)) {
traversal.add(node);
}
final List<SemanticsNode> children = node.debugListChildrenInOrder(DebugSemanticsDumpOrder.traversalOrder);
for (final SemanticsNode child in children) {
_accessibilityTraversal(child, traversal);
}
}
/// Whether or not the node is important for semantics. Should match most cases
/// on the platforms, but certain edge cases will be inconsistent.
///
/// Based on:
///
/// * [flutter/engine/AccessibilityBridge.java#SemanticsNode.isFocusable()](https://github.com/flutter/engine/blob/main/shell/platform/android/io/flutter/view/AccessibilityBridge.java#L2641)
/// * [flutter/engine/SemanticsObject.mm#SemanticsObject.isAccessibilityElement](https://github.com/flutter/engine/blob/main/shell/platform/darwin/ios/framework/Source/SemanticsObject.mm#L449)
bool _isImportantForAccessibility(SemanticsNode node) {
if (node.isMergedIntoParent) {
// If this node is merged, all its information are present on an ancestor
// node.
return false;
}
final SemanticsData data = node.getSemanticsData();
// If the node scopes a route, it doesn't matter what other flags/actions it
// has, it is _not_ important for accessibility, so we short circuit.
if (data.hasFlag(SemanticsFlag.scopesRoute)) {
return false;
}
final bool hasNonScrollingAction = data.actions & ~_scrollingActions != 0;
if (hasNonScrollingAction) {
return true;
}
final bool hasImportantFlag = data.flags & _importantFlagsForAccessibility != 0;
if (hasImportantFlag) {
return true;
}
final bool hasContent = data.label.isNotEmpty || data.value.isNotEmpty || data.hint.isNotEmpty;
if (hasContent) {
return true;
}
return false;
}
/// Performs the given [SemanticsAction] on the [SemanticsNode] found by `finder`.
///
/// If `args` are provided, they will be passed unmodified with the `action`.
/// The `checkForAction` argument allows for attempting to perform `action` on
/// `node` even if it doesn't report supporting that action. This is useful
/// for implicitly supported actions such as [SemanticsAction.showOnScreen].
void performAction(
finders.FinderBase<SemanticsNode> finder,
SemanticsAction action, {
Object? args,
bool checkForAction = true
}) {
final SemanticsNode node = finder.evaluate().single;
if (checkForAction && !node.getSemanticsData().hasAction(action)){
throw StateError(
'The given node does not support $action. If the action is implicitly '
'supported or an unsupported action is being tested for this node, '
'set `checkForAction` to false.\n'
'Node: $node'
);
}
node.owner!.performAction(node.id, action, args);
}
/// Performs a [SemanticsAction.tap] action on the [SemanticsNode] found
/// by `finder`.
///
/// Throws a [StateError] if:
/// * The given `finder` returns zero or more than one result.
/// * The [SemanticsNode] found with `finder` does not support
/// [SemanticsAction.tap].
void tap(finders.FinderBase<SemanticsNode> finder) {
performAction(finder, SemanticsAction.tap);
}
/// Performs a [SemanticsAction.longPress] action on the [SemanticsNode] found
/// by `finder`.
///
/// Throws a [StateError] if:
/// * The given `finder` returns zero or more than one result.
/// * The [SemanticsNode] found with `finder` does not support
/// [SemanticsAction.longPress].
void longPress(finders.FinderBase<SemanticsNode> finder) {
performAction(finder, SemanticsAction.longPress);
}
/// Performs a [SemanticsAction.scrollLeft] action on the [SemanticsNode]
/// found by `scrollable` or the first scrollable node in the default
/// semantics tree if no `scrollable` is provided.
///
/// Throws a [StateError] if:
/// * The given `scrollable` returns zero or more than one result.
/// * The [SemanticsNode] found with `scrollable` does not support
/// [SemanticsAction.scrollLeft].
void scrollLeft({finders.FinderBase<SemanticsNode>? scrollable}) {
performAction(scrollable ?? finders.find.semantics.scrollable(), SemanticsAction.scrollLeft);
}
/// Performs a [SemanticsAction.scrollRight] action on the [SemanticsNode]
/// found by `scrollable` or the first scrollable node in the default
/// semantics tree if no `scrollable` is provided.
///
/// Throws a [StateError] if:
/// * The given `scrollable` returns zero or more than one result.
/// * The [SemanticsNode] found with `scrollable` does not support
/// [SemanticsAction.scrollRight].
void scrollRight({finders.FinderBase<SemanticsNode>? scrollable}) {
performAction(scrollable ?? finders.find.semantics.scrollable(), SemanticsAction.scrollRight);
}
/// Performs a [SemanticsAction.scrollUp] action on the [SemanticsNode] found
/// by `scrollable` or the first scrollable node in the default semantics
/// tree if no `scrollable` is provided.
///
/// Throws a [StateError] if:
/// * The given `scrollable` returns zero or more than one result.
/// * The [SemanticsNode] found with `scrollable` does not support
/// [SemanticsAction.scrollUp].
void scrollUp({finders.FinderBase<SemanticsNode>? scrollable}) {
performAction(scrollable ?? finders.find.semantics.scrollable(), SemanticsAction.scrollUp);
}
/// Performs a [SemanticsAction.scrollDown] action on the [SemanticsNode]
/// found by `scrollable` or the first scrollable node in the default
/// semantics tree if no `scrollable` is provided.
///
/// Throws a [StateError] if:
/// * The given `scrollable` returns zero or more than one result.
/// * The [SemanticsNode] found with `scrollable` does not support
/// [SemanticsAction.scrollDown].
void scrollDown({finders.FinderBase<SemanticsNode>? scrollable}) {
performAction(scrollable ?? finders.find.semantics.scrollable(), SemanticsAction.scrollDown);
}
/// Performs a [SemanticsAction.increase] action on the [SemanticsNode]
/// found by `finder`.
///
/// Throws a [StateError] if:
/// * The given `finder` returns zero or more than one result.
/// * The [SemanticsNode] found with `finder` does not support
/// [SemanticsAction.increase].
void increase(finders.FinderBase<SemanticsNode> finder) {
performAction(finder, SemanticsAction.increase);
}
/// Performs a [SemanticsAction.decrease] action on the [SemanticsNode]
/// found by `finder`.
///
/// Throws a [StateError] if:
/// * The given `finder` returns zero or more than one result.
/// * The [SemanticsNode] found with `finder` does not support
/// [SemanticsAction.decrease].
void decrease(finders.FinderBase<SemanticsNode> finder) {
performAction(finder, SemanticsAction.decrease);
}
/// Performs a [SemanticsAction.showOnScreen] action on the [SemanticsNode]
/// found by `finder`.
///
/// Throws a [StateError] if:
/// * The given `finder` returns zero or more than one result.
/// * The [SemanticsNode] found with `finder` does not support
/// [SemanticsAction.showOnScreen].
void showOnScreen(finders.FinderBase<SemanticsNode> finder) {
performAction(
finder,
SemanticsAction.showOnScreen,
checkForAction: false,
);
}
/// Performs a [SemanticsAction.moveCursorForwardByCharacter] action on the
/// [SemanticsNode] found by `finder`.
///
/// If `shouldModifySelection` is true, then the cursor will begin or extend
/// a selection.
///
/// Throws a [StateError] if:
/// * The given `finder` returns zero or more than one result.
/// * The [SemanticsNode] found with `finder` does not support
/// [SemanticsAction.moveCursorForwardByCharacter].
void moveCursorForwardByCharacter(
finders.FinderBase<SemanticsNode> finder, {
bool shouldModifySelection = false
}) {
performAction(
finder,
SemanticsAction.moveCursorForwardByCharacter,
args: shouldModifySelection
);
}
/// Performs a [SemanticsAction.moveCursorForwardByWord] action on the
/// [SemanticsNode] found by `finder`.
///
/// Throws a [StateError] if:
/// * The given `finder` returns zero or more than one result.
/// * The [SemanticsNode] found with `finder` does not support
/// [SemanticsAction.moveCursorForwardByWord].
void moveCursorForwardByWord(
finders.FinderBase<SemanticsNode> finder, {
bool shouldModifySelection = false
}) {
performAction(
finder,
SemanticsAction.moveCursorForwardByWord,
args: shouldModifySelection
);
}
/// Performs a [SemanticsAction.moveCursorBackwardByCharacter] action on the
/// [SemanticsNode] found by `finder`.
///
/// If `shouldModifySelection` is true, then the cursor will begin or extend
/// a selection.
///
/// Throws a [StateError] if:
/// * The given `finder` returns zero or more than one result.
/// * The [SemanticsNode] found with `finder` does not support
/// [SemanticsAction.moveCursorBackwardByCharacter].
void moveCursorBackwardByCharacter(
finders.FinderBase<SemanticsNode> finder, {
bool shouldModifySelection = false
}) {
performAction(
finder,
SemanticsAction.moveCursorBackwardByCharacter,
args: shouldModifySelection
);
}
/// Performs a [SemanticsAction.moveCursorBackwardByWord] action on the
/// [SemanticsNode] found by `finder`.
///
/// Throws a [StateError] if:
/// * The given `finder` returns zero or more than one result.
/// * The [SemanticsNode] found with `finder` does not support
/// [SemanticsAction.moveCursorBackwardByWord].
void moveCursorBackwardByWord(
finders.FinderBase<SemanticsNode> finder, {
bool shouldModifySelection = false
}) {
performAction(
finder,
SemanticsAction.moveCursorBackwardByWord,
args: shouldModifySelection
);
}
/// Performs a [SemanticsAction.setText] action on the [SemanticsNode]
/// found by `finder` using the given `text`.
///
/// Throws a [StateError] if:
/// * The given `finder` returns zero or more than one result.
/// * The [SemanticsNode] found with `finder` does not support
/// [SemanticsAction.setText].
void setText(finders.FinderBase<SemanticsNode> finder, String text) {
performAction(finder, SemanticsAction.setText, args: text);
}
/// Performs a [SemanticsAction.setSelection] action on the [SemanticsNode]
/// found by `finder`.
///
/// The `base` parameter is the start index of selection, and the `extent`
/// parameter is the length of the selection. Each value should be limited
/// between 0 and the length of the found [SemanticsNode]'s `value`.
///
/// Throws a [StateError] if:
/// * The given `finder` returns zero or more than one result.
/// * The [SemanticsNode] found with `finder` does not support
/// [SemanticsAction.setSelection].
void setSelection(
finders.FinderBase<SemanticsNode> finder, {
required int base,
required int extent
}) {
performAction(
finder,
SemanticsAction.setSelection,
args: <String, int>{'base': base, 'extent': extent},
);
}
/// Performs a [SemanticsAction.copy] action on the [SemanticsNode]
/// found by `finder`.
///
/// Throws a [StateError] if:
/// * The given `finder` returns zero or more than one result.
/// * The [SemanticsNode] found with `finder` does not support
/// [SemanticsAction.copy].
void copy(finders.FinderBase<SemanticsNode> finder) {
performAction(finder, SemanticsAction.copy);
}
/// Performs a [SemanticsAction.cut] action on the [SemanticsNode]
/// found by `finder`.
///
/// Throws a [StateError] if:
/// * The given `finder` returns zero or more than one result.
/// * The [SemanticsNode] found with `finder` does not support
/// [SemanticsAction.cut].
void cut(finders.FinderBase<SemanticsNode> finder) {
performAction(finder, SemanticsAction.cut);
}
/// Performs a [SemanticsAction.paste] action on the [SemanticsNode]
/// found by `finder`.
///
/// Throws a [StateError] if:
/// * The given `finder` returns zero or more than one result.
/// * The [SemanticsNode] found with `finder` does not support
/// [SemanticsAction.paste].
void paste(finders.FinderBase<SemanticsNode> finder) {
performAction(finder, SemanticsAction.paste);
}
/// Performs a [SemanticsAction.didGainAccessibilityFocus] action on the
/// [SemanticsNode] found by `finder`.
///
/// Throws a [StateError] if:
/// * The given `finder` returns zero or more than one result.
/// * The [SemanticsNode] found with `finder` does not support
/// [SemanticsAction.didGainAccessibilityFocus].
void didGainAccessibilityFocus(finders.FinderBase<SemanticsNode> finder) {
performAction(finder, SemanticsAction.didGainAccessibilityFocus);
}
/// Performs a [SemanticsAction.didLoseAccessibilityFocus] action on the
/// [SemanticsNode] found by `finder`.
///
/// Throws a [StateError] if:
/// * The given `finder` returns zero or more than one result.
/// * The [SemanticsNode] found with `finder` does not support
/// [SemanticsAction.didLoseAccessibilityFocus].
void didLoseAccessibilityFocus(finders.FinderBase<SemanticsNode> finder) {
performAction(finder, SemanticsAction.didLoseAccessibilityFocus);
}
/// Performs a [SemanticsAction.customAction] action on the
/// [SemanticsNode] found by `finder`.
///
/// Throws a [StateError] if:
/// * The given `finder` returns zero or more than one result.
/// * The [SemanticsNode] found with `finder` does not support
/// [SemanticsAction.customAction].
void customAction(finders.FinderBase<SemanticsNode> finder, CustomSemanticsAction action) {
performAction(
finder,
SemanticsAction.customAction,
args: CustomSemanticsAction.getIdentifier(action)
);
}
/// Performs a [SemanticsAction.dismiss] action on the [SemanticsNode]
/// found by `finder`.
///
/// Throws a [StateError] if:
/// * The given `finder` returns zero or more than one result.
/// * The [SemanticsNode] found with `finder` does not support
/// [SemanticsAction.dismiss].
void dismiss(finders.FinderBase<SemanticsNode> finder) {
performAction(finder, SemanticsAction.dismiss);
}
}
/// Class that programmatically interacts with widgets.
///
/// For a variant of this class suited specifically for unit tests, see
/// [WidgetTester]. For one suitable for live tests on a device, consider
/// [LiveWidgetController].
///
/// Concrete subclasses must implement the [pump] method.
abstract class WidgetController {
/// Creates a widget controller that uses the given binding.
WidgetController(this.binding);
/// A reference to the current instance of the binding.
final WidgetsBinding binding;
/// The [TestPlatformDispatcher] that is being used in this test.
///
/// This will be injected into the framework such that calls to
/// [WidgetsBinding.platformDispatcher] will use this. This allows
/// users to change platform specific properties for testing.
///
/// See also:
///
/// * [TestFlutterView] which allows changing view specific properties
/// for testing
/// * [view] and [viewOf] which are used to find
/// [TestFlutterView]s from the widget tree
TestPlatformDispatcher get platformDispatcher => binding.platformDispatcher as TestPlatformDispatcher;
/// The [TestFlutterView] provided by default when testing with
/// [WidgetTester.pumpWidget].
///
/// If the test uses multiple views, this will return the view that is painted
/// into by [WidgetTester.pumpWidget]. If a different view needs to be
/// accessed use [viewOf] to ensure that the view related to the widget being
/// evaluated is the one that gets updated.
///
/// See also:
///
/// * [viewOf], which can find a [TestFlutterView] related to a given finder.
/// This is how to modify view properties for testing when dealing with
/// multiple views.
TestFlutterView get view => platformDispatcher.implicitView!;
/// Provides access to a [SemanticsController] for testing anything related to
/// the [Semantics] tree.
///
/// Assistive technologies, search engines, and other analysis tools all make
/// use of the [Semantics] tree to determine the meaning of an application.
/// If semantics has been disabled for the test, this will throw a [StateError].
SemanticsController get semantics {
if (!binding.semanticsEnabled) {
throw StateError(
'Semantics are not enabled. Enable them by passing '
'`semanticsEnabled: true` to `testWidgets`, or by manually creating a '
'`SemanticsHandle` with `WidgetController.ensureSemantics()`.');
}
return _semantics;
}
late final SemanticsController _semantics = SemanticsController._(this);
// FINDER API
// TODO(ianh): verify that the return values are of type T and throw
// a good message otherwise, in all the generic methods below
/// Finds the [TestFlutterView] that is the closest ancestor of the widget
/// found by [finder].
///
/// [TestFlutterView] can be used to modify view specific properties for testing.
///
/// See also:
///
/// * [view] which returns the [TestFlutterView] used when only a single
/// view is being used.
TestFlutterView viewOf(finders.FinderBase<Element> finder) {
return _viewOf(finder) as TestFlutterView;
}
FlutterView _viewOf(finders.FinderBase<Element> finder) {
return firstWidget<View>(
finders.find.ancestor(
of: finder,
matching: finders.find.byType(View),
),
).view;
}
/// Checks if `finder` exists in the tree.
bool any(finders.FinderBase<Element> finder) {
TestAsyncUtils.guardSync();
return finder.evaluate().isNotEmpty;
}
/// All widgets currently in the widget tree (lazy pre-order traversal).
///
/// Can contain duplicates, since widgets can be used in multiple
/// places in the widget tree.
Iterable<Widget> get allWidgets {
TestAsyncUtils.guardSync();
return allElements.map<Widget>((Element element) => element.widget);
}
/// The matching widget in the widget tree.
///
/// Throws a [StateError] if `finder` is empty or matches more than
/// one widget.
///
/// * Use [firstWidget] if you expect to match several widgets but only want the first.
/// * Use [widgetList] if you expect to match several widgets and want all of them.
T widget<T extends Widget>(finders.FinderBase<Element> finder) {
TestAsyncUtils.guardSync();
return finder.evaluate().single.widget as T;
}
/// The first matching widget according to a depth-first pre-order
/// traversal of the widget tree.
///
/// Throws a [StateError] if `finder` is empty.
///
/// * Use [widget] if you only expect to match one widget.
T firstWidget<T extends Widget>(finders.FinderBase<Element> finder) {
TestAsyncUtils.guardSync();
return finder.evaluate().first.widget as T;
}
/// The matching widgets in the widget tree.
///
/// * Use [widget] if you only expect to match one widget.
/// * Use [firstWidget] if you expect to match several but only want the first.
Iterable<T> widgetList<T extends Widget>(finders.FinderBase<Element> finder) {
TestAsyncUtils.guardSync();
return finder.evaluate().map<T>((Element element) {
final T result = element.widget as T;
return result;
});
}
/// Find all layers that are children of the provided [finder].
///
/// The [finder] must match exactly one element.
Iterable<Layer> layerListOf(finders.FinderBase<Element> finder) {
TestAsyncUtils.guardSync();
final Element element = finder.evaluate().single;
final RenderObject object = element.renderObject!;
RenderObject current = object;
while (current.debugLayer == null) {
current = current.parent!;
}
final ContainerLayer layer = current.debugLayer!;
return _walkLayers(layer);
}
/// All elements currently in the widget tree (lazy pre-order traversal).
///
/// The returned iterable is lazy. It does not walk the entire widget tree
/// immediately, but rather a chunk at a time as the iteration progresses
/// using [Iterator.moveNext].
Iterable<Element> get allElements {
TestAsyncUtils.guardSync();
return collectAllElementsFrom(binding.rootElement!, skipOffstage: false);
}
/// The matching element in the widget tree.
///
/// Throws a [StateError] if `finder` is empty or matches more than
/// one element.
///
/// * Use [firstElement] if you expect to match several elements but only want the first.
/// * Use [elementList] if you expect to match several elements and want all of them.
T element<T extends Element>(finders.FinderBase<Element> finder) {
TestAsyncUtils.guardSync();
return finder.evaluate().single as T;
}
/// The first matching element according to a depth-first pre-order
/// traversal of the widget tree.
///
/// Throws a [StateError] if `finder` is empty.
///
/// * Use [element] if you only expect to match one element.
T firstElement<T extends Element>(finders.FinderBase<Element> finder) {
TestAsyncUtils.guardSync();
return finder.evaluate().first as T;
}
/// The matching elements in the widget tree.
///
/// * Use [element] if you only expect to match one element.
/// * Use [firstElement] if you expect to match several but only want the first.
Iterable<T> elementList<T extends Element>(finders.FinderBase<Element> finder) {
TestAsyncUtils.guardSync();
return finder.evaluate().cast<T>();
}
/// All states currently in the widget tree (lazy pre-order traversal).
///
/// The returned iterable is lazy. It does not walk the entire widget tree
/// immediately, but rather a chunk at a time as the iteration progresses
/// using [Iterator.moveNext].
Iterable<State> get allStates {
TestAsyncUtils.guardSync();
return allElements.whereType<StatefulElement>().map<State>((StatefulElement element) => element.state);
}
/// The matching state in the widget tree.
///
/// Throws a [StateError] if `finder` is empty, matches more than
/// one state, or matches a widget that has no state.
///
/// * Use [firstState] if you expect to match several states but only want the first.
/// * Use [stateList] if you expect to match several states and want all of them.
T state<T extends State>(finders.FinderBase<Element> finder) {
TestAsyncUtils.guardSync();
return _stateOf<T>(finder.evaluate().single, finder);
}
/// The first matching state according to a depth-first pre-order
/// traversal of the widget tree.
///
/// Throws a [StateError] if `finder` is empty or if the first
/// matching widget has no state.
///
/// * Use [state] if you only expect to match one state.
T firstState<T extends State>(finders.FinderBase<Element> finder) {
TestAsyncUtils.guardSync();
return _stateOf<T>(finder.evaluate().first, finder);
}
/// The matching states in the widget tree.
///
/// Throws a [StateError] if any of the elements in `finder` match a widget
/// that has no state.
///
/// * Use [state] if you only expect to match one state.
/// * Use [firstState] if you expect to match several but only want the first.
Iterable<T> stateList<T extends State>(finders.FinderBase<Element> finder) {
TestAsyncUtils.guardSync();
return finder.evaluate().map<T>((Element element) => _stateOf<T>(element, finder));
}
T _stateOf<T extends State>(Element element, finders.FinderBase<Element> finder) {
TestAsyncUtils.guardSync();
if (element is StatefulElement) {
return element.state as T;
}
throw StateError('Widget of type ${element.widget.runtimeType}, with ${finder.describeMatch(finders.Plurality.many)}, is not a StatefulWidget.');
}
/// Render objects of all the widgets currently in the widget tree
/// (lazy pre-order traversal).
///
/// This will almost certainly include many duplicates since the
/// render object of a [StatelessWidget] or [StatefulWidget] is the
/// render object of its child; only [RenderObjectWidget]s have
/// their own render object.
Iterable<RenderObject> get allRenderObjects {
TestAsyncUtils.guardSync();
return allElements.map<RenderObject>((Element element) => element.renderObject!);
}
/// The render object of the matching widget in the widget tree.
///
/// Throws a [StateError] if `finder` is empty or matches more than
/// one widget (even if they all have the same render object).
///
/// * Use [firstRenderObject] if you expect to match several render objects but only want the first.
/// * Use [renderObjectList] if you expect to match several render objects and want all of them.
T renderObject<T extends RenderObject>(finders.FinderBase<Element> finder) {
TestAsyncUtils.guardSync();
return finder.evaluate().single.renderObject! as T;
}
/// The render object of the first matching widget according to a
/// depth-first pre-order traversal of the widget tree.
///
/// Throws a [StateError] if `finder` is empty.
///
/// * Use [renderObject] if you only expect to match one render object.
T firstRenderObject<T extends RenderObject>(finders.FinderBase<Element> finder) {
TestAsyncUtils.guardSync();
return finder.evaluate().first.renderObject! as T;
}
/// The render objects of the matching widgets in the widget tree.
///
/// * Use [renderObject] if you only expect to match one render object.
/// * Use [firstRenderObject] if you expect to match several but only want the first.
Iterable<T> renderObjectList<T extends RenderObject>(finders.FinderBase<Element> finder) {
TestAsyncUtils.guardSync();
return finder.evaluate().map<T>((Element element) {
final T result = element.renderObject! as T;
return result;
});
}
/// Returns a list of all the [Layer] objects in the rendering.
List<Layer> get layers {
return <Layer>[
for (final RenderView renderView in binding.renderViews)
..._walkLayers(renderView.debugLayer!)
];
}
Iterable<Layer> _walkLayers(Layer layer) sync* {
TestAsyncUtils.guardSync();
yield layer;
if (layer is ContainerLayer) {
final ContainerLayer root = layer;
Layer? child = root.firstChild;
while (child != null) {
yield* _walkLayers(child);
child = child.nextSibling;
}
}
}
// INTERACTION
/// Dispatch a pointer down / pointer up sequence at the center of
/// the given widget, assuming it is exposed.
///
/// {@template flutter.flutter_test.WidgetController.tap.warnIfMissed}
/// The `warnIfMissed` argument, if true (the default), causes a warning to be
/// displayed on the console if the specified [Finder] indicates a widget and
/// location that, were a pointer event to be sent to that location, would not
/// actually send any events to the widget (e.g. because the widget is
/// obscured, or the location is off-screen, or the widget is transparent to
/// pointer events).
///
/// Set the argument to false to silence that warning if you intend to not
/// actually hit the specified element.
/// {@endtemplate}
///
/// For example, a test that verifies that tapping a disabled button does not
/// trigger the button would set `warnIfMissed` to false, because the button
/// would ignore the tap.
Future<void> tap(
finders.FinderBase<Element> finder, {
int? pointer,
int buttons = kPrimaryButton,
bool warnIfMissed = true,
PointerDeviceKind kind = PointerDeviceKind.touch,
}) {
return tapAt(getCenter(finder, warnIfMissed: warnIfMissed, callee: 'tap'), pointer: pointer, buttons: buttons, kind: kind);
}
/// Dispatch a pointer down / pointer up sequence at a hit-testable
/// [InlineSpan] (typically a [TextSpan]) within the given text range.
///
/// This method performs a more spatially precise tap action on a piece of
/// static text, than the widget-based [tap] method.
///
/// The given [Finder] must find one and only one matching substring, and the
/// substring must be hit-testable (meaning, it must not be off-screen, or be
/// obscured by other widgets, or in a disabled widget). Otherwise this method
/// throws a [FlutterError].
///
/// If the target substring contains more than one hit-testable [InlineSpan]s,
/// [tapOnText] taps on one of them, but does not guarantee which.
///
/// The `pointer` and `button` arguments specify [PointerEvent.pointer] and
/// [PointerEvent.buttons] of the tap event.
Future<void> tapOnText(finders.FinderBase<finders.TextRangeContext> textRangeFinder, {int? pointer, int buttons = kPrimaryButton }) {
final Iterable<finders.TextRangeContext> ranges = textRangeFinder.evaluate();
if (ranges.isEmpty) {
throw FlutterError(textRangeFinder.toString());
}
if (ranges.length > 1) {
throw FlutterError(
'$textRangeFinder. The "tapOnText" method needs a single non-empty TextRange.',
);
}
final Offset? tapLocation = _findHitTestableOffsetIn(ranges.single);
if (tapLocation == null) {
final finders.TextRangeContext found = textRangeFinder.evaluate().single;
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('Finder specifies a TextRange that can not receive pointer events.'),
ErrorDescription('The finder used was: ${textRangeFinder.toString(describeSelf: true)}'),
ErrorDescription('Found a matching substring in a static text widget, within ${found.textRange}.'),
ErrorDescription('But the "tapOnText" method could not find a hit-testable Offset with in that text range.'),
found.renderObject.toDiagnosticsNode(name: 'The RenderBox of that static text widget was', style: DiagnosticsTreeStyle.shallow),
]
);
}
return tapAt(tapLocation, pointer: pointer, buttons: buttons);
}
/// Dispatch a pointer down / pointer up sequence at the given location.
Future<void> tapAt(
Offset location, {
int? pointer,
int buttons = kPrimaryButton,
PointerDeviceKind kind = PointerDeviceKind.touch,
}) {
return TestAsyncUtils.guard<void>(() async {
final TestGesture gesture = await startGesture(location, pointer: pointer, buttons: buttons, kind: kind);
await gesture.up();
});
}
/// Dispatch a pointer down at the center of the given widget, assuming it is
/// exposed.
///
/// {@macro flutter.flutter_test.WidgetController.tap.warnIfMissed}
///
/// The return value is a [TestGesture] object that can be used to continue the
/// gesture (e.g. moving the pointer or releasing it).
///
/// See also:
///
/// * [tap], which presses and releases a pointer at the given location.
/// * [longPress], which presses and releases a pointer with a gap in
/// between long enough to trigger the long-press gesture.
Future<TestGesture> press(
finders.FinderBase<Element> finder, {
int? pointer,
int buttons = kPrimaryButton,
bool warnIfMissed = true,
PointerDeviceKind kind = PointerDeviceKind.touch,
}) {
return TestAsyncUtils.guard<TestGesture>(() {
return startGesture(
getCenter(finder, warnIfMissed: warnIfMissed, callee: 'press'),
pointer: pointer,
buttons: buttons,
kind: kind,
);
});
}
/// Dispatch a pointer down / pointer up sequence (with a delay of
/// [kLongPressTimeout] + [kPressTimeout] between the two events) at the
/// center of the given widget, assuming it is exposed.
///
/// {@macro flutter.flutter_test.WidgetController.tap.warnIfMissed}
///
/// For example, consider a widget that, when long-pressed, shows an overlay
/// that obscures the original widget. A test for that widget might first
/// long-press that widget with `warnIfMissed` at its default value true, then
/// later verify that long-pressing the same location (using the same finder)
/// has no effect (since the widget is now obscured), setting `warnIfMissed`
/// to false on that second call.
Future<void> longPress(
finders.FinderBase<Element> finder, {
int? pointer,
int buttons = kPrimaryButton,
bool warnIfMissed = true,
PointerDeviceKind kind = PointerDeviceKind.touch,
}) {
return longPressAt(
getCenter(finder, warnIfMissed: warnIfMissed, callee: 'longPress'),
pointer: pointer,
buttons: buttons,
kind: kind,
);
}
/// Dispatch a pointer down / pointer up sequence at the given location with
/// a delay of [kLongPressTimeout] + [kPressTimeout] between the two events.
Future<void> longPressAt(
Offset location, {
int? pointer,
int buttons = kPrimaryButton,
PointerDeviceKind kind = PointerDeviceKind.touch,
}) {
return TestAsyncUtils.guard<void>(() async {
final TestGesture gesture = await startGesture(location, pointer: pointer, buttons: buttons, kind: kind);
await pump(kLongPressTimeout + kPressTimeout);
await gesture.up();
});
}
/// Attempts a fling gesture starting from the center of the given
/// widget, moving the given distance, reaching the given speed.
///
/// {@macro flutter.flutter_test.WidgetController.tap.warnIfMissed}
///
/// {@template flutter.flutter_test.WidgetController.fling.offset}
/// The `offset` represents a distance the pointer moves in the global
/// coordinate system of the screen.
///
/// Positive [Offset.dy] values mean the pointer moves downward. Negative
/// [Offset.dy] values mean the pointer moves upwards. Accordingly, positive
/// [Offset.dx] values mean the pointer moves towards the right. Negative
/// [Offset.dx] values mean the pointer moves towards left.
/// {@endtemplate}
///
/// {@template flutter.flutter_test.WidgetController.fling}
/// This can pump frames.
///
/// Exactly 50 pointer events are synthesized.
///
/// The `speed` is in pixels per second in the direction given by `offset`.
///
/// The `offset` and `speed` control the interval between each pointer event.
/// For example, if the `offset` is 200 pixels down, and the `speed` is 800
/// pixels per second, the pointer events will be sent for each increment
/// of 4 pixels (200/50), over 250ms (200/800), meaning events will be sent
/// every 1.25ms (250/200).
///
/// To make tests more realistic, frames may be pumped during this time (using
/// calls to [pump]). If the total duration is longer than `frameInterval`,
/// then one frame is pumped each time that amount of time elapses while
/// sending events, or each time an event is synthesized, whichever is rarer.
///
/// See [LiveTestWidgetsFlutterBindingFramePolicy.benchmarkLive] if the method
/// is used in a live environment and accurate time control is important.
///
/// The `initialOffset` argument, if non-zero, causes the pointer to first
/// apply that offset, then pump a delay of `initialOffsetDelay`. This can be
/// used to simulate a drag followed by a fling, including dragging in the
/// opposite direction of the fling (e.g. dragging 200 pixels to the right,
/// then fling to the left over 200 pixels, ending at the exact point that the
/// drag started).
/// {@endtemplate}
///
/// A fling is essentially a drag that ends at a particular speed. If you
/// just want to drag and end without a fling, use [drag].
Future<void> fling(
finders.FinderBase<Element> finder,
Offset offset,
double speed, {
int? pointer,
int buttons = kPrimaryButton,
Duration frameInterval = const Duration(milliseconds: 16),
Offset initialOffset = Offset.zero,
Duration initialOffsetDelay = const Duration(seconds: 1),
bool warnIfMissed = true,
PointerDeviceKind deviceKind = PointerDeviceKind.touch,
}) {
return flingFrom(
getCenter(finder, warnIfMissed: warnIfMissed, callee: 'fling'),
offset,
speed,
pointer: pointer,
buttons: buttons,
frameInterval: frameInterval,
initialOffset: initialOffset,
initialOffsetDelay: initialOffsetDelay,
deviceKind: deviceKind,
);
}
/// Attempts a fling gesture starting from the given location, moving the
/// given distance, reaching the given speed.
///
/// {@macro flutter.flutter_test.WidgetController.fling}
///
/// A fling is essentially a drag that ends at a particular speed. If you
/// just want to drag and end without a fling, use [dragFrom].
Future<void> flingFrom(
Offset startLocation,
Offset offset,
double speed, {
int? pointer,
int buttons = kPrimaryButton,
Duration frameInterval = const Duration(milliseconds: 16),
Offset initialOffset = Offset.zero,
Duration initialOffsetDelay = const Duration(seconds: 1),
PointerDeviceKind deviceKind = PointerDeviceKind.touch,
}) {
assert(offset.distance > 0.0);
assert(speed > 0.0); // speed is pixels/second
return TestAsyncUtils.guard<void>(() async {
final TestPointer testPointer = TestPointer(pointer ?? _getNextPointer(), deviceKind, null, buttons);
const int kMoveCount = 50; // Needs to be >= kHistorySize, see _LeastSquaresVelocityTrackerStrategy
final double timeStampDelta = 1000000.0 * offset.distance / (kMoveCount * speed);
double timeStamp = 0.0;
double lastTimeStamp = timeStamp;
await sendEventToBinding(testPointer.down(startLocation, timeStamp: Duration(microseconds: timeStamp.round())));
if (initialOffset.distance > 0.0) {
await sendEventToBinding(testPointer.move(startLocation + initialOffset, timeStamp: Duration(microseconds: timeStamp.round())));
timeStamp += initialOffsetDelay.inMicroseconds;
await pump(initialOffsetDelay);
}
for (int i = 0; i <= kMoveCount; i += 1) {
final Offset location = startLocation + initialOffset + Offset.lerp(Offset.zero, offset, i / kMoveCount)!;
await sendEventToBinding(testPointer.move(location, timeStamp: Duration(microseconds: timeStamp.round())));
timeStamp += timeStampDelta;
if (timeStamp - lastTimeStamp > frameInterval.inMicroseconds) {
await pump(Duration(microseconds: (timeStamp - lastTimeStamp).truncate()));
lastTimeStamp = timeStamp;
}
}
await sendEventToBinding(testPointer.up(timeStamp: Duration(microseconds: timeStamp.round())));
});
}
/// Attempts a trackpad fling gesture starting from the center of the given
/// widget, moving the given distance, reaching the given speed. A trackpad
/// fling sends PointerPanZoom events instead of a sequence of touch events.
///
/// {@macro flutter.flutter_test.WidgetController.tap.warnIfMissed}
///
/// {@macro flutter.flutter_test.WidgetController.fling}
///
/// A fling is essentially a drag that ends at a particular speed. If you
/// just want to drag and end without a fling, use [drag].
Future<void> trackpadFling(
finders.FinderBase<Element> finder,
Offset offset,
double speed, {
int? pointer,
int buttons = kPrimaryButton,
Duration frameInterval = const Duration(milliseconds: 16),
Offset initialOffset = Offset.zero,
Duration initialOffsetDelay = const Duration(seconds: 1),
bool warnIfMissed = true,
}) {
return trackpadFlingFrom(
getCenter(finder, warnIfMissed: warnIfMissed, callee: 'fling'),
offset,
speed,
pointer: pointer,
buttons: buttons,
frameInterval: frameInterval,
initialOffset: initialOffset,
initialOffsetDelay: initialOffsetDelay,
);
}
/// Attempts a fling gesture starting from the given location, moving the
/// given distance, reaching the given speed. A trackpad fling sends
/// PointerPanZoom events instead of a sequence of touch events.
///
/// {@macro flutter.flutter_test.WidgetController.fling}
///
/// A fling is essentially a drag that ends at a particular speed. If you
/// just want to drag and end without a fling, use [dragFrom].
Future<void> trackpadFlingFrom(
Offset startLocation,
Offset offset,
double speed, {
int? pointer,
int buttons = kPrimaryButton,
Duration frameInterval = const Duration(milliseconds: 16),
Offset initialOffset = Offset.zero,
Duration initialOffsetDelay = const Duration(seconds: 1),
}) {
assert(offset.distance > 0.0);
assert(speed > 0.0); // speed is pixels/second
return TestAsyncUtils.guard<void>(() async {
final TestPointer testPointer = TestPointer(pointer ?? _getNextPointer(), PointerDeviceKind.trackpad, null, buttons);
const int kMoveCount = 50; // Needs to be >= kHistorySize, see _LeastSquaresVelocityTrackerStrategy
final double timeStampDelta = 1000000.0 * offset.distance / (kMoveCount * speed);
double timeStamp = 0.0;
double lastTimeStamp = timeStamp;
await sendEventToBinding(testPointer.panZoomStart(startLocation, timeStamp: Duration(microseconds: timeStamp.round())));
if (initialOffset.distance > 0.0) {
await sendEventToBinding(testPointer.panZoomUpdate(startLocation, pan: initialOffset, timeStamp: Duration(microseconds: timeStamp.round())));
timeStamp += initialOffsetDelay.inMicroseconds;
await pump(initialOffsetDelay);
}
for (int i = 0; i <= kMoveCount; i += 1) {
final Offset pan = initialOffset + Offset.lerp(Offset.zero, offset, i / kMoveCount)!;
await sendEventToBinding(testPointer.panZoomUpdate(startLocation, pan: pan, timeStamp: Duration(microseconds: timeStamp.round())));
timeStamp += timeStampDelta;
if (timeStamp - lastTimeStamp > frameInterval.inMicroseconds) {
await pump(Duration(microseconds: (timeStamp - lastTimeStamp).truncate()));
lastTimeStamp = timeStamp;
}
}
await sendEventToBinding(testPointer.panZoomEnd(timeStamp: Duration(microseconds: timeStamp.round())));
});
}
/// A simulator of how the framework handles a series of [PointerEvent]s
/// received from the Flutter engine.
///
/// The [PointerEventRecord.timeDelay] is used as the time delay of the events
/// injection relative to the starting point of the method call.
///
/// Returns a list of the difference between the real delay time when the
/// [PointerEventRecord.events] are processed and
/// [PointerEventRecord.timeDelay].
/// - For [AutomatedTestWidgetsFlutterBinding] where the clock is fake, the
/// return value should be exact zeros.
/// - For [LiveTestWidgetsFlutterBinding], the values are typically small
/// positives, meaning the event happens a little later than the set time,
/// but a very small portion may have a tiny negative value for about tens of
/// microseconds. This is due to the nature of [Future.delayed].
///
/// The closer the return values are to zero the more faithful it is to the
/// `records`.
///
/// See [PointerEventRecord].
Future<List<Duration>> handlePointerEventRecord(List<PointerEventRecord> records);
/// Called to indicate that there should be a new frame after an optional
/// delay.
///
/// The frame is pumped after a delay of [duration] if [duration] is not null,
/// or immediately otherwise.
///
/// This is invoked by [flingFrom], for instance, so that the sequence of
/// pointer events occurs over time.
///
/// The [WidgetTester] subclass implements this by deferring to the [binding].
///
/// See also:
///
/// * [SchedulerBinding.endOfFrame], which returns a future that could be
/// appropriate to return in the implementation of this method.
Future<void> pump([Duration duration]);
/// Repeatedly calls [pump] with the given `duration` until there are no
/// longer any frames scheduled. This will call [pump] at least once, even if
/// no frames are scheduled when the function is called, to flush any pending
/// microtasks which may themselves schedule a frame.
///
/// This essentially waits for all animations to have completed.
///
/// If it takes longer that the given `timeout` to settle, then the test will
/// fail (this method will throw an exception). In particular, this means that
/// if there is an infinite animation in progress (for example, if there is an
/// indeterminate progress indicator spinning), this method will throw.
///
/// The default timeout is ten minutes, which is longer than most reasonable
/// finite animations would last.
///
/// If the function returns, it returns the number of pumps that it performed.
///
/// In general, it is better practice to figure out exactly why each frame is
/// needed, and then to [pump] exactly as many frames as necessary. This will
/// help catch regressions where, for instance, an animation is being started
/// one frame later than it should.
///
/// Alternatively, one can check that the return value from this function
/// matches the expected number of pumps.
Future<int> pumpAndSettle([
Duration duration = const Duration(milliseconds: 100),
]);
/// Attempts to drag the given widget by the given offset, by
/// starting a drag in the middle of the widget.
///
/// {@macro flutter.flutter_test.WidgetController.tap.warnIfMissed}
///
/// If you want the drag to end with a speed so that the gesture recognition
/// system identifies the gesture as a fling, consider using [fling] instead.
///
/// The operation happens at once. If you want the drag to last for a period
/// of time, consider using [timedDrag].
///
/// {@macro flutter.flutter_test.WidgetController.fling.offset}
///
/// {@template flutter.flutter_test.WidgetController.drag}
/// By default, if the x or y component of offset is greater than
/// [kDragSlopDefault], the gesture is broken up into two separate moves
/// calls. Changing `touchSlopX` or `touchSlopY` will change the minimum
/// amount of movement in the respective axis before the drag will be broken
/// into multiple calls. To always send the drag with just a single call to
/// [TestGesture.moveBy], `touchSlopX` and `touchSlopY` should be set to 0.
///
/// Breaking the drag into multiple moves is necessary for accurate execution
/// of drag update calls with a [DragStartBehavior] variable set to
/// [DragStartBehavior.start]. Without such a change, the dragUpdate callback
/// from a drag recognizer will never be invoked.
///
/// To force this function to a send a single move event, the `touchSlopX` and
/// `touchSlopY` variables should be set to 0. However, generally, these values
/// should be left to their default values.
/// {@endtemplate}
Future<void> drag(
finders.FinderBase<Element> finder,
Offset offset, {
int? pointer,
int buttons = kPrimaryButton,
double touchSlopX = kDragSlopDefault,
double touchSlopY = kDragSlopDefault,
bool warnIfMissed = true,
PointerDeviceKind kind = PointerDeviceKind.touch,
}) {
return dragFrom(
getCenter(finder, warnIfMissed: warnIfMissed, callee: 'drag'),
offset,
pointer: pointer,
buttons: buttons,
touchSlopX: touchSlopX,
touchSlopY: touchSlopY,
kind: kind,
);
}
/// Attempts a drag gesture consisting of a pointer down, a move by
/// the given offset, and a pointer up.
///
/// If you want the drag to end with a speed so that the gesture recognition
/// system identifies the gesture as a fling, consider using [flingFrom]
/// instead.
///
/// The operation happens at once. If you want the drag to last for a period
/// of time, consider using [timedDragFrom].
///
/// {@macro flutter.flutter_test.WidgetController.drag}
Future<void> dragFrom(
Offset startLocation,
Offset offset, {
int? pointer,
int buttons = kPrimaryButton,
double touchSlopX = kDragSlopDefault,
double touchSlopY = kDragSlopDefault,
PointerDeviceKind kind = PointerDeviceKind.touch,
}) {
assert(kDragSlopDefault > kTouchSlop);
return TestAsyncUtils.guard<void>(() async {
final TestGesture gesture = await startGesture(startLocation, pointer: pointer, buttons: buttons, kind: kind);
final double xSign = offset.dx.sign;
final double ySign = offset.dy.sign;
final double offsetX = offset.dx;
final double offsetY = offset.dy;
final bool separateX = offset.dx.abs() > touchSlopX && touchSlopX > 0;
final bool separateY = offset.dy.abs() > touchSlopY && touchSlopY > 0;
if (separateY || separateX) {
final double offsetSlope = offsetY / offsetX;
final double inverseOffsetSlope = offsetX / offsetY;
final double slopSlope = touchSlopY / touchSlopX;
final double absoluteOffsetSlope = offsetSlope.abs();
final double signedSlopX = touchSlopX * xSign;
final double signedSlopY = touchSlopY * ySign;
if (absoluteOffsetSlope != slopSlope) {
// The drag goes through one or both of the extents of the edges of the box.
if (absoluteOffsetSlope < slopSlope) {
assert(offsetX.abs() > touchSlopX);
// The drag goes through the vertical edge of the box.
// It is guaranteed that the |offsetX| > touchSlopX.
final double diffY = offsetSlope.abs() * touchSlopX * ySign;
// The vector from the origin to the vertical edge.
await gesture.moveBy(Offset(signedSlopX, diffY));
if (offsetY.abs() <= touchSlopY) {
// The drag ends on or before getting to the horizontal extension of the horizontal edge.
await gesture.moveBy(Offset(offsetX - signedSlopX, offsetY - diffY));
} else {
final double diffY2 = signedSlopY - diffY;
final double diffX2 = inverseOffsetSlope * diffY2;
// The vector from the edge of the box to the horizontal extension of the horizontal edge.
await gesture.moveBy(Offset(diffX2, diffY2));
await gesture.moveBy(Offset(offsetX - diffX2 - signedSlopX, offsetY - signedSlopY));
}
} else {
assert(offsetY.abs() > touchSlopY);
// The drag goes through the horizontal edge of the box.
// It is guaranteed that the |offsetY| > touchSlopY.
final double diffX = inverseOffsetSlope.abs() * touchSlopY * xSign;
// The vector from the origin to the vertical edge.
await gesture.moveBy(Offset(diffX, signedSlopY));
if (offsetX.abs() <= touchSlopX) {
// The drag ends on or before getting to the vertical extension of the vertical edge.
await gesture.moveBy(Offset(offsetX - diffX, offsetY - signedSlopY));
} else {
final double diffX2 = signedSlopX - diffX;
final double diffY2 = offsetSlope * diffX2;
// The vector from the edge of the box to the vertical extension of the vertical edge.
await gesture.moveBy(Offset(diffX2, diffY2));
await gesture.moveBy(Offset(offsetX - signedSlopX, offsetY - diffY2 - signedSlopY));
}
}
} else { // The drag goes through the corner of the box.
await gesture.moveBy(Offset(signedSlopX, signedSlopY));
await gesture.moveBy(Offset(offsetX - signedSlopX, offsetY - signedSlopY));
}
} else { // The drag ends inside the box.
await gesture.moveBy(offset);
}
await gesture.up();
});
}
/// Attempts to drag the given widget by the given offset in the `duration`
/// time, starting in the middle of the widget.
///
/// {@macro flutter.flutter_test.WidgetController.tap.warnIfMissed}
///
/// {@macro flutter.flutter_test.WidgetController.fling.offset}
///
/// This is the timed version of [drag]. This may or may not result in a
/// [fling] or ballistic animation, depending on the speed from
/// `offset/duration`.
///
/// {@template flutter.flutter_test.WidgetController.timedDrag}
/// The move events are sent at a given `frequency` in Hz (or events per
/// second). It defaults to 60Hz.
///
/// The movement is linear in time.
///
/// See also [LiveTestWidgetsFlutterBindingFramePolicy.benchmarkLive] for
/// more accurate time control.
/// {@endtemplate}
Future<void> timedDrag(
finders.FinderBase<Element> finder,
Offset offset,
Duration duration, {
int? pointer,
int buttons = kPrimaryButton,
double frequency = 60.0,
bool warnIfMissed = true,
}) {
return timedDragFrom(
getCenter(finder, warnIfMissed: warnIfMissed, callee: 'timedDrag'),
offset,
duration,
pointer: pointer,
buttons: buttons,
frequency: frequency,
);
}
/// Attempts a series of [PointerEvent]s to simulate a drag operation in the
/// `duration` time.
///
/// This is the timed version of [dragFrom]. This may or may not result in a
/// [flingFrom] or ballistic animation, depending on the speed from
/// `offset/duration`.
///
/// {@macro flutter.flutter_test.WidgetController.timedDrag}
Future<void> timedDragFrom(
Offset startLocation,
Offset offset,
Duration duration, {
int? pointer,
int buttons = kPrimaryButton,
double frequency = 60.0,
}) {
assert(frequency > 0);
final int intervals = duration.inMicroseconds * frequency ~/ 1E6;
assert(intervals > 1);
pointer ??= _getNextPointer();
final List<Duration> timeStamps = <Duration>[
for (int t = 0; t <= intervals; t += 1)
duration * t ~/ intervals,
];
final List<Offset> offsets = <Offset>[
startLocation,
for (int t = 0; t <= intervals; t += 1)
startLocation + offset * (t / intervals),
];
final List<PointerEventRecord> records = <PointerEventRecord>[
PointerEventRecord(Duration.zero, <PointerEvent>[
PointerAddedEvent(
position: startLocation,
),
PointerDownEvent(
position: startLocation,
pointer: pointer,
buttons: buttons,
),
]),
...<PointerEventRecord>[
for (int t = 0; t <= intervals; t += 1)
PointerEventRecord(timeStamps[t], <PointerEvent>[
PointerMoveEvent(
timeStamp: timeStamps[t],
position: offsets[t+1],
delta: offsets[t+1] - offsets[t],
pointer: pointer,
buttons: buttons,
),
]),
],
PointerEventRecord(duration, <PointerEvent>[
PointerUpEvent(
timeStamp: duration,
position: offsets.last,
pointer: pointer,
// The PointerData received from the engine with
// change = PointerChange.up, which translates to PointerUpEvent,
// doesn't provide the button field.
// buttons: buttons,
),
]),
];
return TestAsyncUtils.guard<void>(() async {
await handlePointerEventRecord(records);
});
}
/// The next available pointer identifier.
///
/// This is the default pointer identifier that will be used the next time the
/// [startGesture] method is called without an explicit pointer identifier.
int get nextPointer => _nextPointer;
static int _nextPointer = 1;
static int _getNextPointer() {
final int result = _nextPointer;
_nextPointer += 1;
return result;
}
TestGesture _createGesture({
int? pointer,
required PointerDeviceKind kind,
required int buttons,
}) {
return TestGesture(
dispatcher: sendEventToBinding,
kind: kind,
pointer: pointer ?? _getNextPointer(),
buttons: buttons,
);
}
/// Creates gesture and returns the [TestGesture] object which you can use
/// to continue the gesture using calls on the [TestGesture] object.
///
/// You can use [startGesture] instead if your gesture begins with a down
/// event.
Future<TestGesture> createGesture({
int? pointer,
PointerDeviceKind kind = PointerDeviceKind.touch,
int buttons = kPrimaryButton,
}) async {
return _createGesture(pointer: pointer, kind: kind, buttons: buttons);
}
/// Creates a gesture with an initial appropriate starting gesture at a
/// particular point, and returns the [TestGesture] object which you can use
/// to continue the gesture. Usually, the starting gesture will be a down event,
/// but if [kind] is set to [PointerDeviceKind.trackpad], the gesture will start
/// with a panZoomStart gesture.
///
/// You can use [createGesture] if your gesture doesn't begin with an initial
/// down or panZoomStart gesture.
///
/// See also:
/// * [WidgetController.drag], a method to simulate a drag.
/// * [WidgetController.timedDrag], a method to simulate the drag of a given
/// widget in a given duration. It sends move events at a given frequency and
/// it is useful when there are listeners involved.
/// * [WidgetController.fling], a method to simulate a fling.
Future<TestGesture> startGesture(
Offset downLocation, {
int? pointer,
PointerDeviceKind kind = PointerDeviceKind.touch,
int buttons = kPrimaryButton,
}) async {
final TestGesture result = _createGesture(pointer: pointer, kind: kind, buttons: buttons);
if (kind == PointerDeviceKind.trackpad) {
await result.panZoomStart(downLocation);
} else {
await result.down(downLocation);
}
return result;
}
/// Forwards the given location to the binding's hitTest logic.
HitTestResult hitTestOnBinding(Offset location, { int? viewId }) {
viewId ??= view.viewId;
final HitTestResult result = HitTestResult();
binding.hitTestInView(result, location, viewId);
return result;
}
/// Forwards the given pointer event to the binding.
Future<void> sendEventToBinding(PointerEvent event) {
return TestAsyncUtils.guard<void>(() async {
binding.handlePointerEvent(event);
});
}
/// Calls [debugPrint] with the given message.
///
/// This is overridden by the WidgetTester subclass to use the test binding's
/// [TestWidgetsFlutterBinding.debugPrintOverride], so that it appears on the
/// console even if the test is logging output from the application.
@protected
void printToConsole(String message) {
debugPrint(message);
}
// GEOMETRY
/// Returns the point at the center of the given widget.
///
/// {@template flutter.flutter_test.WidgetController.getCenter.warnIfMissed}
/// If `warnIfMissed` is true (the default is false), then the returned
/// coordinate is checked to see if a hit test at the returned location would
/// actually include the specified element in the [HitTestResult], and if not,
/// a warning is printed to the console.
///
/// The `callee` argument is used to identify the method that should be
/// referenced in messages regarding `warnIfMissed`. It can be ignored unless
/// this method is being called from another that is forwarding its own
/// `warnIfMissed` parameter (see e.g. the implementation of [tap]).
/// {@endtemplate}
Offset getCenter(finders.FinderBase<Element> finder, { bool warnIfMissed = false, String callee = 'getCenter' }) {
return _getElementPoint(finder, (Size size) => size.center(Offset.zero), warnIfMissed: warnIfMissed, callee: callee);
}
/// Returns the point at the top left of the given widget.
///
/// {@macro flutter.flutter_test.WidgetController.getCenter.warnIfMissed}
Offset getTopLeft(finders.FinderBase<Element> finder, { bool warnIfMissed = false, String callee = 'getTopLeft' }) {
return _getElementPoint(finder, (Size size) => Offset.zero, warnIfMissed: warnIfMissed, callee: callee);
}
/// Returns the point at the top right of the given widget. This
/// point is not inside the object's hit test area.
///
/// {@macro flutter.flutter_test.WidgetController.getCenter.warnIfMissed}
Offset getTopRight(finders.FinderBase<Element> finder, { bool warnIfMissed = false, String callee = 'getTopRight' }) {
return _getElementPoint(finder, (Size size) => size.topRight(Offset.zero), warnIfMissed: warnIfMissed, callee: callee);
}
/// Returns the point at the bottom left of the given widget. This
/// point is not inside the object's hit test area.
///
/// {@macro flutter.flutter_test.WidgetController.getCenter.warnIfMissed}
Offset getBottomLeft(finders.FinderBase<Element> finder, { bool warnIfMissed = false, String callee = 'getBottomLeft' }) {
return _getElementPoint(finder, (Size size) => size.bottomLeft(Offset.zero), warnIfMissed: warnIfMissed, callee: callee);
}
/// Returns the point at the bottom right of the given widget. This
/// point is not inside the object's hit test area.
///
/// {@macro flutter.flutter_test.WidgetController.getCenter.warnIfMissed}
Offset getBottomRight(finders.FinderBase<Element> finder, { bool warnIfMissed = false, String callee = 'getBottomRight' }) {
return _getElementPoint(finder, (Size size) => size.bottomRight(Offset.zero), warnIfMissed: warnIfMissed, callee: callee);
}
/// Whether warnings relating to hit tests not hitting their mark should be
/// fatal (cause the test to fail).
///
/// Some methods, e.g. [tap], have an argument `warnIfMissed` which causes a
/// warning to be displayed if the specified [Finder] indicates a widget and
/// location that, were a pointer event to be sent to that location, would not
/// actually send any events to the widget (e.g. because the widget is
/// obscured, or the location is off-screen, or the widget is transparent to
/// pointer events).
///
/// This warning was added in 2021. In ordinary operation this warning is
/// non-fatal since making it fatal would be a significantly breaking change
/// for anyone who already has tests relying on the ability to target events
/// using finders where the events wouldn't reach the widgets specified by the
/// finders in question.
///
/// However, doing this is usually unintentional. To make the warning fatal,
/// thus failing any tests where it occurs, this property can be set to true.
///
/// Typically this is done using a `flutter_test_config.dart` file, as described
/// in the documentation for the [flutter_test] library.
static bool hitTestWarningShouldBeFatal = false;
/// Finds one hit-testable Offset in the given `textRangeContext`'s render
/// object.
Offset? _findHitTestableOffsetIn(finders.TextRangeContext textRangeContext) {
TestAsyncUtils.guardSync();
final TextRange range = textRangeContext.textRange;
assert(range.isNormalized);
assert(range.isValid);
final Offset renderParagraphPaintOffset = textRangeContext.renderObject.localToGlobal(Offset.zero);
assert(renderParagraphPaintOffset.isFinite);
int spanStart = range.start;
while (spanStart < range.end) {
switch (_findEndOfSpan(textRangeContext.renderObject.text, spanStart, range.end)) {
case (final HitTestTarget target, final int endIndex):
// Uses BoxHeightStyle.tight in getBoxesForSelection to make sure the
// returned boxes don't extend outside of the hit-testable region.
final Iterable<Offset> testOffsets = textRangeContext.renderObject
.getBoxesForSelection(TextSelection(baseOffset: spanStart, extentOffset: endIndex))
// Try hit-testing the center of each TextBox.
.map((TextBox textBox) => textBox.toRect().center);
for (final Offset localOffset in testOffsets) {
final HitTestResult result = HitTestResult();
final Offset globalOffset = localOffset + renderParagraphPaintOffset;
binding.hitTestInView(result, globalOffset, textRangeContext.view.view.viewId);
if (result.path.any((HitTestEntry entry) => entry.target == target)) {
return globalOffset;
}
}
spanStart = endIndex;
case (_, final int endIndex):
spanStart = endIndex;
case null:
break;
}
}
return null;
}
Offset _getElementPoint(finders.FinderBase<Element> finder, Offset Function(Size size) sizeToPoint, { required bool warnIfMissed, required String callee }) {
TestAsyncUtils.guardSync();
final Iterable<Element> elements = finder.evaluate();
if (elements.isEmpty) {
throw FlutterError('The finder "$finder" (used in a call to "$callee()") could not find any matching widgets.');
}
if (elements.length > 1) {
throw FlutterError('The finder "$finder" (used in a call to "$callee()") ambiguously found multiple matching widgets. The "$callee()" method needs a single target.');
}
final Element element = elements.single;
final RenderObject? renderObject = element.renderObject;
if (renderObject == null) {
throw FlutterError(
'The finder "$finder" (used in a call to "$callee()") found an element, but it does not have a corresponding render object. '
'Maybe the element has not yet been rendered?'
);
}
if (renderObject is! RenderBox) {
throw FlutterError(
'The finder "$finder" (used in a call to "$callee()") found an element whose corresponding render object is not a RenderBox (it is a ${renderObject.runtimeType}: "$renderObject"). '
'Unfortunately "$callee()" only supports targeting widgets that correspond to RenderBox objects in the rendering.'
);
}
final RenderBox box = element.renderObject! as RenderBox;
final Offset location = box.localToGlobal(sizeToPoint(box.size));
if (warnIfMissed) {
final FlutterView view = _viewOf(finder);
final HitTestResult result = HitTestResult();
binding.hitTestInView(result, location, view.viewId);
final bool found = result.path.any((HitTestEntry entry) => entry.target == box);
if (!found) {
final RenderView renderView = binding.renderViews.firstWhere((RenderView r) => r.flutterView == view);
final bool outOfBounds = !(Offset.zero & renderView.size).contains(location);
if (hitTestWarningShouldBeFatal) {
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('Finder specifies a widget that would not receive pointer events.'),
ErrorDescription('A call to $callee() with finder "$finder" derived an Offset ($location) that would not hit test on the specified widget.'),
ErrorHint('Maybe the widget is actually off-screen, or another widget is obscuring it, or the widget cannot receive pointer events.'),
if (outOfBounds)
ErrorHint('Indeed, $location is outside the bounds of the root of the render tree, ${renderView.size}.'),
box.toDiagnosticsNode(name: 'The finder corresponds to this RenderBox', style: DiagnosticsTreeStyle.singleLine),
ErrorDescription('The hit test result at that offset is: $result'),
ErrorDescription('If you expected this target not to be able to receive pointer events, pass "warnIfMissed: false" to "$callee()".'),
ErrorDescription('To make this error into a non-fatal warning, set WidgetController.hitTestWarningShouldBeFatal to false.'),
]);
}
printToConsole(
'\n'
'Warning: A call to $callee() with finder "$finder" derived an Offset ($location) that would not hit test on the specified widget.\n'
'Maybe the widget is actually off-screen, or another widget is obscuring it, or the widget cannot receive pointer events.\n'
'${outOfBounds ? "Indeed, $location is outside the bounds of the root of the render tree, ${renderView.size}.\n" : ""}'
'The finder corresponds to this RenderBox: $box\n'
'The hit test result at that offset is: $result\n'
'${StackTrace.current}'
'To silence this warning, pass "warnIfMissed: false" to "$callee()".\n'
'To make this warning fatal, set WidgetController.hitTestWarningShouldBeFatal to true.\n',
);
}
}
return location;
}
/// Returns the size of the given widget. This is only valid once
/// the widget's render object has been laid out at least once.
Size getSize(finders.FinderBase<Element> finder) {
TestAsyncUtils.guardSync();
final Element element = finder.evaluate().single;
final RenderBox box = element.renderObject! as RenderBox;
return box.size;
}
/// Simulates sending physical key down and up events.
///
/// This only simulates key events coming from a physical keyboard, not from a
/// soft keyboard.
///
/// Specify `platform` as one of the platforms allowed in
/// [platform.Platform.operatingSystem] to make the event appear to be from
/// that type of system. If not specified, defaults to "web" on web, and the
/// operating system name based on [defaultTargetPlatform] everywhere else.
///
/// Specify the `physicalKey` for the event to override what is included in
/// the simulated event. If not specified, it uses a default from the US
/// keyboard layout for the corresponding logical `key`.
///
/// Specify the `character` for the event to override what is included in the
/// simulated event. If not specified, it uses a default derived from the
/// logical `key`.
///
/// Keys that are down when the test completes are cleared after each test.
///
/// This method sends both the key down and the key up events, to simulate a
/// key press. To simulate individual down and/or up events, see
/// [sendKeyDownEvent] and [sendKeyUpEvent].
///
/// Returns true if the key down event was handled by the framework.
///
/// See also:
///
/// - [sendKeyDownEvent] to simulate only a key down event.
/// - [sendKeyUpEvent] to simulate only a key up event.
Future<bool> sendKeyEvent(
LogicalKeyboardKey key, {
String? platform,
String? character,
PhysicalKeyboardKey? physicalKey
}) async {
final bool handled = await simulateKeyDownEvent(key, platform: platform, character: character, physicalKey: physicalKey);
// Internally wrapped in async guard.
await simulateKeyUpEvent(key, platform: platform, physicalKey: physicalKey);
return handled;
}
/// Simulates sending a physical key down event.
///
/// This only simulates key down events coming from a physical keyboard, not
/// from a soft keyboard.
///
/// Specify `platform` as one of the platforms allowed in
/// [platform.Platform.operatingSystem] to make the event appear to be from
/// that type of system. If not specified, defaults to "web" on web, and the
/// operating system name based on [defaultTargetPlatform] everywhere else.
///
/// Specify the `physicalKey` for the event to override what is included in
/// the simulated event. If not specified, it uses a default from the US
/// keyboard layout for the corresponding logical `key`.
///
/// Specify the `character` for the event to override what is included in the
/// simulated event. If not specified, it uses a default derived from the
/// logical `key`.
///
/// Keys that are down when the test completes are cleared after each test.
///
/// Returns true if the key event was handled by the framework.
///
/// See also:
///
/// - [sendKeyUpEvent] and [sendKeyRepeatEvent] to simulate the corresponding
/// key up and repeat event.
/// - [sendKeyEvent] to simulate both the key up and key down in the same call.
Future<bool> sendKeyDownEvent(
LogicalKeyboardKey key, {
String? platform,
String? character,
PhysicalKeyboardKey? physicalKey
}) async {
// Internally wrapped in async guard.
return simulateKeyDownEvent(key, platform: platform, character: character, physicalKey: physicalKey);
}
/// Simulates sending a physical key up event through the system channel.
///
/// This only simulates key up events coming from a physical keyboard,
/// not from a soft keyboard.
///
/// Specify `platform` as one of the platforms allowed in
/// [platform.Platform.operatingSystem] to make the event appear to be from
/// that type of system. If not specified, defaults to "web" on web, and the
/// operating system name based on [defaultTargetPlatform] everywhere else.
///
/// Specify the `physicalKey` for the event to override what is included in
/// the simulated event. If not specified, it uses a default from the US
/// keyboard layout for the corresponding logical `key`.
///
/// Returns true if the key event was handled by the framework.
///
/// See also:
///
/// - [sendKeyDownEvent] and [sendKeyRepeatEvent] to simulate the
/// corresponding key down and repeat event.
/// - [sendKeyEvent] to simulate both the key up and key down in the same call.
Future<bool> sendKeyUpEvent(
LogicalKeyboardKey key, {
String? platform,
PhysicalKeyboardKey? physicalKey
}) async {
// Internally wrapped in async guard.
return simulateKeyUpEvent(key, platform: platform, physicalKey: physicalKey);
}
/// Simulates sending a key repeat event from a physical keyboard.
///
/// This only simulates key repeat events coming from a physical keyboard, not
/// from a soft keyboard.
///
/// Specify `platform` as one of the platforms allowed in
/// [platform.Platform.operatingSystem] to make the event appear to be from
/// that type of system. If not specified, defaults to "web" on web, and the
/// operating system name based on [defaultTargetPlatform] everywhere else.
///
/// Specify the `physicalKey` for the event to override what is included in
/// the simulated event. If not specified, it uses a default from the US
/// keyboard layout for the corresponding logical `key`.
///
/// Specify the `character` for the event to override what is included in the
/// simulated event. If not specified, it uses a default derived from the
/// logical `key`.
///
/// Keys that are down when the test completes are cleared after each test.
///
/// Returns true if the key event was handled by the framework.
///
/// See also:
///
/// - [sendKeyDownEvent] and [sendKeyUpEvent] to simulate the corresponding
/// key down and up event.
/// - [sendKeyEvent] to simulate both the key up and key down in the same call.
Future<bool> sendKeyRepeatEvent(
LogicalKeyboardKey key, {
String? platform,
String? character,
PhysicalKeyboardKey? physicalKey
}) async {
// Internally wrapped in async guard.
return simulateKeyRepeatEvent(key, platform: platform, character: character, physicalKey: physicalKey);
}
/// Returns the rect of the given widget. This is only valid once
/// the widget's render object has been laid out at least once.
Rect getRect(finders.FinderBase<Element> finder) => Rect.fromPoints(getTopLeft(finder), getBottomRight(finder));
/// Attempts to find the [SemanticsNode] of first result from `finder`.
///
/// If the object identified by the finder doesn't own it's semantic node,
/// this will return the semantics data of the first ancestor with semantics.
/// The ancestor's semantic data will include the child's as well as
/// other nodes that have been merged together.
///
/// If the [SemanticsNode] of the object identified by the finder is
/// force-merged into an ancestor (e.g. via the [MergeSemantics] widget)
/// the node into which it is merged is returned. That node will include
/// all the semantics information of the nodes merged into it.
///
/// Will throw a [StateError] if the finder returns more than one element or
/// if no semantics are found or are not enabled.
// TODO(pdblasi-google): Deprecate this and point references to semantics.find. See https://github.com/flutter/flutter/issues/112670.
SemanticsNode getSemantics(finders.FinderBase<Element> finder) => semantics.find(finder);
/// Enable semantics in a test by creating a [SemanticsHandle].
///
/// The handle must be disposed at the end of the test.
SemanticsHandle ensureSemantics() {
return binding.ensureSemantics();
}
/// Given a widget `W` specified by [finder] and a [Scrollable] widget `S` in
/// its ancestry tree, this scrolls `S` so as to make `W` visible.
///
/// Usually the `finder` for this method should be labeled `skipOffstage:
/// false`, so that the [Finder] deals with widgets that are off the screen
/// correctly.
///
/// This does not work when `S` is long enough, and `W` far away enough from
/// the displayed part of `S`, that `S` has not yet cached `W`'s element.
/// Consider using [scrollUntilVisible] in such a situation.
///
/// See also:
///
/// * [Scrollable.ensureVisible], which is the production API used to
/// implement this method.
Future<void> ensureVisible(finders.FinderBase<Element> finder) => Scrollable.ensureVisible(element(finder));
/// Repeatedly scrolls a [Scrollable] by `delta` in the
/// [Scrollable.axisDirection] direction until a widget matching `finder` is
/// visible.
///
/// Between each scroll, advances the clock by `duration` time.
///
/// Scrolling is performed until the start of the `finder` is visible. This is
/// due to the default parameter values of the [Scrollable.ensureVisible] method.
///
/// If `scrollable` is `null`, a [Finder] that looks for a [Scrollable] is
/// used instead.
///
/// Throws a [StateError] if `finder` is not found after `maxScrolls` scrolls.
///
/// This is different from [ensureVisible] in that this allows looking for
/// `finder` that is not yet built. The caller must specify the scrollable
/// that will build child specified by `finder` when there are multiple
/// [Scrollable]s.
///
/// See also:
///
/// * [dragUntilVisible], which implements the body of this method.
Future<void> scrollUntilVisible(
finders.FinderBase<Element> finder,
double delta, {
finders.FinderBase<Element>? scrollable,
int maxScrolls = 50,
Duration duration = const Duration(milliseconds: 50),
}
) {
assert(maxScrolls > 0);
scrollable ??= finders.find.byType(Scrollable);
return TestAsyncUtils.guard<void>(() async {
Offset moveStep;
switch (widget<Scrollable>(scrollable!).axisDirection) {
case AxisDirection.up:
moveStep = Offset(0, delta);
case AxisDirection.down:
moveStep = Offset(0, -delta);
case AxisDirection.left:
moveStep = Offset(delta, 0);
case AxisDirection.right:
moveStep = Offset(-delta, 0);
}
await dragUntilVisible(
finder,
scrollable,
moveStep,
maxIteration: maxScrolls,
duration: duration,
);
});
}
/// Repeatedly drags `view` by `moveStep` until `finder` is visible.
///
/// Between each drag, advances the clock by `duration`.
///
/// Throws a [StateError] if `finder` is not found after `maxIteration`
/// drags.
///
/// See also:
///
/// * [scrollUntilVisible], which wraps this method with an API that is more
/// convenient when dealing with a [Scrollable].
Future<void> dragUntilVisible(
finders.FinderBase<Element> finder,
finders.FinderBase<Element> view,
Offset moveStep, {
int maxIteration = 50,
Duration duration = const Duration(milliseconds: 50),
}) {
return TestAsyncUtils.guard<void>(() async {
while (maxIteration > 0 && finder.evaluate().isEmpty) {
await drag(view, moveStep);
await pump(duration);
maxIteration -= 1;
}
await Scrollable.ensureVisible(element(finder));
});
}
}
/// Variant of [WidgetController] that can be used in tests running
/// on a device.
///
/// This is used, for instance, by [FlutterDriver].
class LiveWidgetController extends WidgetController {
/// Creates a widget controller that uses the given binding.
LiveWidgetController(super.binding);
@override
Future<void> pump([Duration? duration]) async {
if (duration != null) {
await Future<void>.delayed(duration);
}
binding.scheduleFrame();
await binding.endOfFrame;
}
@override
Future<int> pumpAndSettle([
Duration duration = const Duration(milliseconds: 100),
]) {
assert(duration > Duration.zero);
return TestAsyncUtils.guard<int>(() async {
int count = 0;
do {
await pump(duration);
count += 1;
} while (binding.hasScheduledFrame);
return count;
});
}
@override
Future<List<Duration>> handlePointerEventRecord(List<PointerEventRecord> records) {
assert(records.isNotEmpty);
return TestAsyncUtils.guard<List<Duration>>(() async {
final List<Duration> handleTimeStampDiff = <Duration>[];
DateTime? startTime;
for (final PointerEventRecord record in records) {
final DateTime now = clock.now();
startTime ??= now;
// So that the first event is promised to receive a zero timeDiff.
final Duration timeDiff = record.timeDelay - now.difference(startTime);
if (timeDiff.isNegative) {
// This happens when something (e.g. GC) takes a long time during the
// processing of the events.
// Flush all past events.
handleTimeStampDiff.add(-timeDiff);
record.events.forEach(binding.handlePointerEvent);
} else {
await Future<void>.delayed(timeDiff);
handleTimeStampDiff.add(
// Recalculating the time diff for getting exact time when the event
// packet is sent. For a perfect Future.delayed like the one in a
// fake async this new diff should be zero.
clock.now().difference(startTime) - record.timeDelay,
);
record.events.forEach(binding.handlePointerEvent);
}
}
return handleTimeStampDiff;
});
}
}
| flutter/packages/flutter_test/lib/src/controller.dart/0 | {
"file_path": "flutter/packages/flutter_test/lib/src/controller.dart",
"repo_id": "flutter",
"token_count": 30710
} | 725 |
// 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:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart';
import 'package:meta/meta.dart';
import 'package:test_api/scaffolding.dart' show Timeout;
import 'package:test_api/src/backend/declarer.dart'; // ignore: implementation_imports
import 'package:test_api/src/backend/group.dart'; // ignore: implementation_imports
import 'package:test_api/src/backend/group_entry.dart'; // ignore: implementation_imports
import 'package:test_api/src/backend/invoker.dart'; // ignore: implementation_imports
import 'package:test_api/src/backend/live_test.dart'; // ignore: implementation_imports
import 'package:test_api/src/backend/message.dart'; // ignore: implementation_imports
import 'package:test_api/src/backend/runtime.dart'; // ignore: implementation_imports
import 'package:test_api/src/backend/state.dart'; // ignore: implementation_imports
import 'package:test_api/src/backend/suite.dart'; // ignore: implementation_imports
import 'package:test_api/src/backend/suite_platform.dart'; // ignore: implementation_imports
import 'package:test_api/src/backend/test.dart'; // ignore: implementation_imports
export 'package:test_api/fake.dart' show Fake;
Declarer? _localDeclarer;
Declarer get _declarer {
final Declarer? declarer = Zone.current[#test.declarer] as Declarer?;
if (declarer != null) {
return declarer;
}
// If no declarer is defined, this test is being run via `flutter run -t test_file.dart`.
if (_localDeclarer == null) {
_localDeclarer = Declarer();
Future<void>(() {
Invoker.guard<Future<void>>(() async {
final _Reporter reporter = _Reporter(color: false); // disable color when run directly.
// ignore: recursive_getters, this self-call is safe since it will just fetch the declarer instance
final Group group = _declarer.build();
final Suite suite = Suite(group, SuitePlatform(Runtime.vm));
await _runGroup(suite, group, <Group>[], reporter);
reporter._onDone();
});
});
}
return _localDeclarer!;
}
Future<void> _runGroup(Suite suiteConfig, Group group, List<Group> parents, _Reporter reporter) async {
parents.add(group);
try {
final bool skipGroup = group.metadata.skip;
bool setUpAllSucceeded = true;
if (!skipGroup && group.setUpAll != null) {
final LiveTest liveTest = group.setUpAll!.load(suiteConfig, groups: parents);
await _runLiveTest(suiteConfig, liveTest, reporter, countSuccess: false);
setUpAllSucceeded = liveTest.state.result.isPassing;
}
if (setUpAllSucceeded) {
for (final GroupEntry entry in group.entries) {
if (entry is Group) {
await _runGroup(suiteConfig, entry, parents, reporter);
} else if (entry.metadata.skip) {
await _runSkippedTest(suiteConfig, entry as Test, parents, reporter);
} else {
final Test test = entry as Test;
await _runLiveTest(suiteConfig, test.load(suiteConfig, groups: parents), reporter);
}
}
}
// Even if we're closed or setUpAll failed, we want to run all the
// teardowns to ensure that any state is properly cleaned up.
if (!skipGroup && group.tearDownAll != null) {
final LiveTest liveTest = group.tearDownAll!.load(suiteConfig, groups: parents);
await _runLiveTest(suiteConfig, liveTest, reporter, countSuccess: false);
}
} finally {
parents.remove(group);
}
}
Future<void> _runLiveTest(Suite suiteConfig, LiveTest liveTest, _Reporter reporter, { bool countSuccess = true }) async {
reporter._onTestStarted(liveTest);
// Schedule a microtask to ensure that [onTestStarted] fires before the
// first [LiveTest.onStateChange] event.
await Future<void>.microtask(liveTest.run);
// Once the test finishes, use await null to do a coarse-grained event
// loop pump to avoid starving non-microtask events.
await null;
final bool isSuccess = liveTest.state.result.isPassing;
if (isSuccess) {
reporter.passed.add(liveTest);
} else {
reporter.failed.add(liveTest);
}
}
Future<void> _runSkippedTest(Suite suiteConfig, Test test, List<Group> parents, _Reporter reporter) async {
final LocalTest skipped = LocalTest(test.name, test.metadata, () { }, trace: test.trace);
if (skipped.metadata.skipReason != null) {
reporter.log('Skip: ${skipped.metadata.skipReason}');
}
final LiveTest liveTest = skipped.load(suiteConfig);
reporter._onTestStarted(liveTest);
reporter.skipped.add(skipped);
}
// TODO(nweiz): This and other top-level functions should throw exceptions if
// they're called after the declarer has finished declaring.
/// Creates a new test case with the given description (converted to a string)
/// and body.
///
/// The description will be added to the descriptions of any surrounding
/// [group]s. If [testOn] is passed, it's parsed as a [platform selector][]; the
/// test will only be run on matching platforms.
///
/// [platform selector]: https://github.com/dart-lang/test/tree/master/pkgs/test#platform-selectors
///
/// If [timeout] is passed, it's used to modify or replace the default timeout
/// of 30 seconds. Timeout modifications take precedence in suite-group-test
/// order, so [timeout] will also modify any timeouts set on the group or suite.
///
/// If [skip] is a String or `true`, the test is skipped. If it's a String, it
/// should explain why the test is skipped; this reason will be printed instead
/// of running the test.
///
/// If [tags] is passed, it declares user-defined tags that are applied to the
/// test. These tags can be used to select or skip the test on the command line,
/// or to do bulk test configuration. All tags should be declared in the
/// [package configuration file][configuring tags]. The parameter can be an
/// [Iterable] of tag names, or a [String] representing a single tag.
///
/// If [retry] is passed, the test will be retried the provided number of times
/// before being marked as a failure.
///
/// [configuring tags]: https://github.com/dart-lang/test/blob/44d6cb196f34a93a975ed5f3cb76afcc3a7b39b0/doc/package_config.md#configuring-tags
///
/// [onPlatform] allows tests to be configured on a platform-by-platform
/// basis. It's a map from strings that are parsed as [PlatformSelector]s to
/// annotation classes: [Timeout], [Skip], or lists of those. These
/// annotations apply only on the given platforms. For example:
///
/// test('potentially slow test', () {
/// // ...
/// }, onPlatform: {
/// // This test is especially slow on Windows.
/// 'windows': Timeout.factor(2),
/// 'browser': [
/// Skip('add browser support'),
/// // This will be slow on browsers once it works on them.
/// Timeout.factor(2)
/// ]
/// });
///
/// If multiple platforms match, the annotations apply in order as through
/// they were in nested groups.
@isTest
void test(
Object description,
dynamic Function() body, {
String? testOn,
Timeout? timeout,
dynamic skip,
dynamic tags,
Map<String, dynamic>? onPlatform,
int? retry,
}) {
_maybeConfigureTearDownForTestFile();
_declarer.test(
description.toString(),
body,
testOn: testOn,
timeout: timeout,
skip: skip,
onPlatform: onPlatform,
tags: tags,
retry: retry,
);
}
/// Creates a group of tests.
///
/// A group's description (converted to a string) is included in the descriptions
/// of any tests or sub-groups it contains. [setUp] and [tearDown] are also scoped
/// to the containing group.
///
/// If `skip` is a String or `true`, the group is skipped. If it's a String, it
/// should explain why the group is skipped; this reason will be printed instead
/// of running the group's tests.
@isTestGroup
void group(Object description, void Function() body, { dynamic skip, int? retry }) {
_maybeConfigureTearDownForTestFile();
_declarer.group(description.toString(), body, skip: skip, retry: retry);
}
/// Registers a function to be run before tests.
///
/// This function will be called before each test is run. The `body` may be
/// asynchronous; if so, it must return a [Future].
///
/// If this is called within a test group, it applies only to tests in that
/// group. The `body` will be run after any set-up callbacks in parent groups or
/// at the top level.
///
/// Each callback at the top level or in a given group will be run in the order
/// they were declared.
void setUp(dynamic Function() body) {
_maybeConfigureTearDownForTestFile();
_declarer.setUp(body);
}
/// Registers a function to be run after tests.
///
/// This function will be called after each test is run. The `body` may be
/// asynchronous; if so, it must return a [Future].
///
/// If this is called within a test group, it applies only to tests in that
/// group. The `body` will be run before any tear-down callbacks in parent
/// groups or at the top level.
///
/// Each callback at the top level or in a given group will be run in the
/// reverse of the order they were declared.
///
/// See also [addTearDown], which adds tear-downs to a running test.
void tearDown(dynamic Function() body) {
_maybeConfigureTearDownForTestFile();
_declarer.tearDown(body);
}
/// Registers a function to be run once before all tests.
///
/// The `body` may be asynchronous; if so, it must return a [Future].
///
/// If this is called within a test group, The `body` will run before all tests
/// in that group. It will be run after any [setUpAll] callbacks in parent
/// groups or at the top level. It won't be run if none of the tests in the
/// group are run.
///
/// **Note**: This function makes it very easy to accidentally introduce hidden
/// dependencies between tests that should be isolated. In general, you should
/// prefer [setUp], and only use [setUpAll] if the callback is prohibitively
/// slow.
void setUpAll(dynamic Function() body) {
_maybeConfigureTearDownForTestFile();
_declarer.setUpAll(body);
}
/// Registers a function to be run once after all tests.
///
/// If this is called within a test group, `body` will run after all tests
/// in that group. It will be run before any [tearDownAll] callbacks in parent
/// groups or at the top level. It won't be run if none of the tests in the
/// group are run.
///
/// **Note**: This function makes it very easy to accidentally introduce hidden
/// dependencies between tests that should be isolated. In general, you should
/// prefer [tearDown], and only use [tearDownAll] if the callback is
/// prohibitively slow.
void tearDownAll(dynamic Function() body) {
_maybeConfigureTearDownForTestFile();
_declarer.tearDownAll(body);
}
bool _isTearDownForTestFileConfigured = false;
/// If needed, configures `tearDownAll` after all user defined `tearDownAll` in the test file.
///
/// This function should be invoked in all functions, that may be invoked by user in the test file,
/// to be invoked before any other `tearDownAll`.
void _maybeConfigureTearDownForTestFile() {
if (_isTearDownForTestFileConfigured || !_shouldConfigureTearDownForTestFile()) {
return;
}
_declarer.tearDownAll(_tearDownForTestFile);
_isTearDownForTestFileConfigured = true;
}
/// Returns true if tear down for the test file needs to be configured.
bool _shouldConfigureTearDownForTestFile() {
return LeakTesting.enabled;
}
/// Tear down that should happen after all user defined tear down.
Future<void> _tearDownForTestFile() async {
await maybeTearDownLeakTrackingForAll();
}
/// A reporter that prints each test on its own line.
///
/// This is currently used in place of [CompactReporter] by `lib/test.dart`,
/// which can't transitively import `dart:io` but still needs access to a runner
/// so that test files can be run directly. This means that until issue 6943 is
/// fixed, this must not import `dart:io`.
class _Reporter {
_Reporter({bool color = true, bool printPath = true})
: _printPath = printPath,
_green = color ? '\u001b[32m' : '',
_red = color ? '\u001b[31m' : '',
_yellow = color ? '\u001b[33m' : '',
_bold = color ? '\u001b[1m' : '',
_noColor = color ? '\u001b[0m' : '';
final List<LiveTest> passed = <LiveTest>[];
final List<LiveTest> failed = <LiveTest>[];
final List<Test> skipped = <Test>[];
/// The terminal escape for green text, or the empty string if this is Windows
/// or not outputting to a terminal.
final String _green;
/// The terminal escape for red text, or the empty string if this is Windows
/// or not outputting to a terminal.
final String _red;
/// The terminal escape for yellow text, or the empty string if this is
/// Windows or not outputting to a terminal.
final String _yellow;
/// The terminal escape for bold text, or the empty string if this is
/// Windows or not outputting to a terminal.
final String _bold;
/// The terminal escape for removing test coloring, or the empty string if
/// this is Windows or not outputting to a terminal.
final String _noColor;
/// Whether the path to each test's suite should be printed.
final bool _printPath;
/// A stopwatch that tracks the duration of the full run.
final Stopwatch _stopwatch = Stopwatch(); // flutter_ignore: stopwatch (see analyze.dart)
// Ignore context: Used for logging of actual test runs, outside of FakeAsync.
/// The size of `_engine.passed` last time a progress notification was
/// printed.
int? _lastProgressPassed;
/// The size of `_engine.skipped` last time a progress notification was
/// printed.
int? _lastProgressSkipped;
/// The size of `_engine.failed` last time a progress notification was
/// printed.
int? _lastProgressFailed;
/// The message printed for the last progress notification.
String? _lastProgressMessage;
/// The suffix added to the last progress notification.
String? _lastProgressSuffix;
/// The set of all subscriptions to various streams.
final Set<StreamSubscription<void>> _subscriptions = <StreamSubscription<void>>{};
/// A callback called when the engine begins running [liveTest].
void _onTestStarted(LiveTest liveTest) {
if (!_stopwatch.isRunning) {
_stopwatch.start();
}
_progressLine(_description(liveTest));
_subscriptions.add(liveTest.onStateChange.listen((State state) => _onStateChange(liveTest, state)));
_subscriptions.add(liveTest.onError.listen((AsyncError error) => _onError(liveTest, error.error, error.stackTrace)));
_subscriptions.add(liveTest.onMessage.listen((Message message) {
_progressLine(_description(liveTest));
String text = message.text;
if (message.type == MessageType.skip) {
text = ' $_yellow$text$_noColor';
}
log(text);
}));
}
/// A callback called when [liveTest]'s state becomes [state].
void _onStateChange(LiveTest liveTest, State state) {
if (state.status != Status.complete) {
return;
}
}
/// A callback called when [liveTest] throws [error].
void _onError(LiveTest liveTest, Object error, StackTrace stackTrace) {
if (liveTest.state.status != Status.complete) {
return;
}
_progressLine(_description(liveTest), suffix: ' $_bold$_red[E]$_noColor');
log(_indent(error.toString()));
log(_indent('$stackTrace'));
}
/// A callback called when the engine is finished running tests.
void _onDone() {
final bool success = failed.isEmpty;
if (!success) {
_progressLine('Some tests failed.', color: _red);
} else if (passed.isEmpty) {
_progressLine('All tests skipped.');
} else {
_progressLine('All tests passed!');
}
}
/// Prints a line representing the current state of the tests.
///
/// [message] goes after the progress report. If [color] is passed, it's used
/// as the color for [message]. If [suffix] is passed, it's added to the end
/// of [message].
void _progressLine(String message, { String? color, String? suffix }) {
// Print nothing if nothing has changed since the last progress line.
if (passed.length == _lastProgressPassed &&
skipped.length == _lastProgressSkipped &&
failed.length == _lastProgressFailed &&
message == _lastProgressMessage &&
// Don't re-print just because a suffix was removed.
(suffix == null || suffix == _lastProgressSuffix)) {
return;
}
_lastProgressPassed = passed.length;
_lastProgressSkipped = skipped.length;
_lastProgressFailed = failed.length;
_lastProgressMessage = message;
_lastProgressSuffix = suffix;
if (suffix != null) {
message += suffix;
}
color ??= '';
final Duration duration = _stopwatch.elapsed;
final StringBuffer buffer = StringBuffer();
// \r moves back to the beginning of the current line.
buffer.write('${_timeString(duration)} ');
buffer.write(_green);
buffer.write('+');
buffer.write(passed.length);
buffer.write(_noColor);
if (skipped.isNotEmpty) {
buffer.write(_yellow);
buffer.write(' ~');
buffer.write(skipped.length);
buffer.write(_noColor);
}
if (failed.isNotEmpty) {
buffer.write(_red);
buffer.write(' -');
buffer.write(failed.length);
buffer.write(_noColor);
}
buffer.write(': ');
buffer.write(color);
buffer.write(message);
buffer.write(_noColor);
log(buffer.toString());
}
/// Returns a representation of [duration] as `MM:SS`.
String _timeString(Duration duration) {
final String minutes = duration.inMinutes.toString().padLeft(2, '0');
final String seconds = (duration.inSeconds % 60).toString().padLeft(2, '0');
return '$minutes:$seconds';
}
/// Returns a description of [liveTest].
///
/// This differs from the test's own description in that it may also include
/// the suite's name.
String _description(LiveTest liveTest) {
String name = liveTest.test.name;
if (_printPath && liveTest.suite.path != null) {
name = '${liveTest.suite.path}: $name';
}
return name;
}
/// Print the message to the console.
void log(String message) {
// We centralize all the prints in this file through this one method so that
// in principle we can reroute the output easily should we need to.
print(message); // ignore: avoid_print
}
}
String _indent(String string, { int? size, String? first }) {
size ??= first == null ? 2 : first.length;
return _prefixLines(string, ' ' * size, first: first);
}
String _prefixLines(String text, String prefix, { String? first, String? last, String? single }) {
first ??= prefix;
last ??= prefix;
single ??= first;
final List<String> lines = text.split('\n');
if (lines.length == 1) {
return '$single$text';
}
final StringBuffer buffer = StringBuffer('$first${lines.first}\n');
// Write out all but the first and last lines with [prefix].
for (final String line in lines.skip(1).take(lines.length - 2)) {
buffer.writeln('$prefix$line');
}
buffer.write('$last${lines.last}');
return buffer.toString();
}
| flutter/packages/flutter_test/lib/src/test_compat.dart/0 | {
"file_path": "flutter/packages/flutter_test/lib/src/test_compat.dart",
"repo_id": "flutter",
"token_count": 6135
} | 726 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('$WidgetsBinding initializes with $LiveTestWidgetsFlutterBinding when FLUTTER_TEST = "false"', () {
TestWidgetsFlutterBinding.ensureInitialized(<String, String>{'FLUTTER_TEST': 'false'});
expect(WidgetsBinding.instance, isA<LiveTestWidgetsFlutterBinding>());
}, onPlatform: const <String, dynamic>{
'browser': <Skip>[Skip('Browser will not use the live binding')],
});
}
| flutter/packages/flutter_test/test/bindings_environment/flutter_test_variable_is_false_test.dart/0 | {
"file_path": "flutter/packages/flutter_test/test/bindings_environment/flutter_test_variable_is_false_test.dart",
"repo_id": "flutter",
"token_count": 219
} | 727 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui';
import 'package:flutter_test/flutter_test.dart';
void main() {
group(FrameTimingSummarizer, () {
test('calculates all fields', () {
List<int> vsyncTimes = <int>[
for (int i = 0; i < 100; i += 1) 100 * (i + 1),
];
List<int> buildTimes = <int>[
for (int i = 0; i < 100; i += 1) vsyncTimes[i] + 1000 * (i + 1),
];
List<int> rasterTimes = <int>[
for (int i = 0; i < 100; i += 1) 1000 * (i + 1) + 1000,
];
// reversed to make sure sort is working.
buildTimes = buildTimes.reversed.toList();
rasterTimes = rasterTimes.reversed.toList();
vsyncTimes = vsyncTimes.reversed.toList();
final List<FrameTiming> inputData = <FrameTiming>[
for (int i = 0; i < 100; i += 1)
FrameTiming(
vsyncStart: 0,
buildStart: vsyncTimes[i],
buildFinish: buildTimes[i],
rasterStart: 500,
rasterFinish: rasterTimes[i],
// Wall time should not be used in any profiling metrics.
// It is primarily to correlate with external tools' measurement.
rasterFinishWallTime: 0,
),
];
final FrameTimingSummarizer summary = FrameTimingSummarizer(inputData);
expect(summary.averageFrameBuildTime.inMicroseconds, 50500);
expect(summary.p90FrameBuildTime.inMicroseconds, 90000);
expect(summary.p99FrameBuildTime.inMicroseconds, 99000);
expect(summary.worstFrameBuildTime.inMicroseconds, 100000);
expect(summary.missedFrameBuildBudget, 84);
expect(summary.averageFrameRasterizerTime.inMicroseconds, 51000);
expect(summary.p90FrameRasterizerTime.inMicroseconds, 90500);
expect(summary.p99FrameRasterizerTime.inMicroseconds, 99500);
expect(summary.worstFrameRasterizerTime.inMicroseconds, 100500);
expect(summary.missedFrameRasterizerBudget, 85);
expect(summary.frameBuildTime.length, 100);
expect(summary.averageVsyncOverhead.inMicroseconds, 5050);
expect(summary.p90VsyncOverhead.inMicroseconds, 9000);
expect(summary.p99VsyncOverhead.inMicroseconds, 9900);
expect(summary.worstVsyncOverhead.inMicroseconds, 10000);
});
group('missed budget count', () {
test('when single element missed budget', () {
final FrameTimingSummarizer summary = FrameTimingSummarizer(<FrameTiming>[
FrameTiming(
buildStart: 0,
buildFinish: (kBuildBudget + const Duration(microseconds: 1)).inMicroseconds,
vsyncStart: 0,
rasterStart: 0,
rasterFinish: 0,
rasterFinishWallTime: 0,
),
]);
expect(summary.missedFrameBuildBudget, 1);
});
test('when single element within budget', () {
final FrameTimingSummarizer summary = FrameTimingSummarizer(<FrameTiming>[
FrameTiming(
buildStart: 0,
buildFinish: 0,
vsyncStart: 0,
rasterStart: 0,
rasterFinish: 0,
rasterFinishWallTime: 0,
),
]);
expect(summary.missedFrameBuildBudget, 0);
});
test('when single element exactly within budget', () {
final FrameTimingSummarizer summary = FrameTimingSummarizer(<FrameTiming>[
FrameTiming(
buildStart: 0,
buildFinish: kBuildBudget.inMicroseconds,
vsyncStart: 0,
rasterStart: 0,
rasterFinish: 0,
rasterFinishWallTime: 0,
),
]);
expect(summary.missedFrameBuildBudget, 0);
});
test('when many missed budget', () {
final FrameTimingSummarizer summary = FrameTimingSummarizer(<FrameTiming>[
FrameTiming(
buildStart: 0,
buildFinish: 0,
vsyncStart: 0,
rasterStart: 0,
rasterFinish: 0,
rasterFinishWallTime: 0,
),
FrameTiming(
buildStart: 0,
buildFinish: kBuildBudget.inMicroseconds,
vsyncStart: 0,
rasterStart: 0,
rasterFinish: 0,
rasterFinishWallTime: 0,
),
FrameTiming(
buildStart: 0,
buildFinish: (kBuildBudget + const Duration(microseconds: 1)).inMicroseconds,
vsyncStart: 0,
rasterStart: 0,
rasterFinish: 0,
rasterFinishWallTime: 0,
),
FrameTiming(
buildStart: 0,
buildFinish: (kBuildBudget + const Duration(microseconds: 2)).inMicroseconds,
vsyncStart: 0,
rasterStart: 0,
rasterFinish: 0,
rasterFinishWallTime: 0,
),
]);
expect(summary.missedFrameBuildBudget, 2);
});
});
});
}
| flutter/packages/flutter_test/test/frame_timing_summarizer_test.dart/0 | {
"file_path": "flutter/packages/flutter_test/test/frame_timing_summarizer_test.dart",
"repo_id": "flutter",
"token_count": 2310
} | 728 |
// 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';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart';
/// Objects that should not be GCed during test run.
final List<InstrumentedDisposable> _retainer = <InstrumentedDisposable>[];
/// Test cases for memory leaks.
///
/// They are separate from test execution to allow
/// excluding them from test helpers.
final List<LeakTestCase> memoryLeakTests = <LeakTestCase>[
LeakTestCase(
name: 'no leaks',
body: (PumpWidgetsCallback? pumpWidgets,
RunAsyncCallback<dynamic>? runAsync) async {
await pumpWidgets!(Container());
},
),
LeakTestCase(
name: 'not disposed disposable',
body: (PumpWidgetsCallback? pumpWidgets,
RunAsyncCallback<dynamic>? runAsync) async {
InstrumentedDisposable();
},
notDisposedTotal: 1,
),
LeakTestCase(
name: 'not GCed disposable',
body: (PumpWidgetsCallback? pumpWidgets,
RunAsyncCallback<dynamic>? runAsync) async {
_retainer.add(InstrumentedDisposable()..dispose());
},
notGCedTotal: 1,
),
LeakTestCase(
name: 'leaking widget',
body: (PumpWidgetsCallback? pumpWidgets,
RunAsyncCallback<dynamic>? runAsync) async {
StatelessLeakingWidget();
},
notDisposedTotal: 1,
notGCedTotal: 1,
),
LeakTestCase(
name: 'dispose in tear down',
body: (PumpWidgetsCallback? pumpWidgets,
RunAsyncCallback<dynamic>? runAsync) async {
final InstrumentedDisposable myClass = InstrumentedDisposable();
addTearDown(myClass.dispose);
},
),
LeakTestCase(
name: 'pumped leaking widget',
body: (PumpWidgetsCallback? pumpWidgets,
RunAsyncCallback<dynamic>? runAsync) async {
await pumpWidgets!(StatelessLeakingWidget());
},
notDisposedTotal: 1,
notGCedTotal: 1,
),
LeakTestCase(
name: 'leaking widget in runAsync',
body: (PumpWidgetsCallback? pumpWidgets,
RunAsyncCallback<dynamic>? runAsync) async {
await runAsync!(() async {
StatelessLeakingWidget();
});
},
notDisposedTotal: 1,
notGCedTotal: 1,
),
LeakTestCase(
name: 'pumped in runAsync',
body: (PumpWidgetsCallback? pumpWidgets,
RunAsyncCallback<dynamic>? runAsync) async {
await runAsync!(() async {
await pumpWidgets!(StatelessLeakingWidget());
});
},
notDisposedTotal: 1,
notGCedTotal: 1,
),
];
String memoryLeakTestsFilePath() {
return RegExp(r'(\/[^\/]*.dart):')
.firstMatch(StackTrace.current.toString())!
.group(1).toString();
}
| flutter/packages/flutter_test/test/utils/memory_leak_tests.dart/0 | {
"file_path": "flutter/packages/flutter_test/test/utils/memory_leak_tests.dart",
"repo_id": "flutter",
"token_count": 1121
} | 729 |
// 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_test/flutter_test.dart';
void main() {
// Generic reference variables.
finders.FinderBase<Element> theStart;
finders.FinderBase<Element> theEnd;
testWidgets('simulatedAccessibilityTraversal', (WidgetTester tester) async {
// Changes made in https://github.com/flutter/flutter/pull/143386
tester.semantics.simulatedAccessibilityTraversal();
tester.semantics.simulatedAccessibilityTraversal(start: theStart);
tester.semantics.simulatedAccessibilityTraversal(end: theEnd);
tester.semantics.simulatedAccessibilityTraversal(start: theStart, end: theEnd);
});
}
| flutter/packages/flutter_test/test_fixes/flutter_test/semantics_controller.dart/0 | {
"file_path": "flutter/packages/flutter_test/test_fixes/flutter_test/semantics_controller.dart",
"repo_id": "flutter",
"token_count": 247
} | 730 |
#!/usr/bin/env bash
# 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.
# exit on error, or usage of unset var
set -euo pipefail
# Needed because if it is set, cd may print the path it changed to.
unset CDPATH
function follow_links() (
cd -P "$(dirname -- "$1")"
file="$PWD/$(basename -- "$1")"
while [[ -h "$file" ]]; do
cd -P "$(dirname -- "$file")"
file="$(readlink -- "$file")"
cd -P "$(dirname -- "$file")"
file="$PWD/$(basename -- "$file")"
done
echo "$file"
)
PROG_NAME="$(follow_links "${BASH_SOURCE[0]}")"
BIN_DIR="$(cd "${PROG_NAME%/*}" ; pwd -P)"
FLUTTER_ROOT="$BIN_DIR/../../.."
DART="$FLUTTER_ROOT/bin/dart"
"$DART" "$BIN_DIR/xcode_backend.dart" "$@"
| flutter/packages/flutter_tools/bin/xcode_backend.sh/0 | {
"file_path": "flutter/packages/flutter_tools/bin/xcode_backend.sh",
"repo_id": "flutter",
"token_count": 329
} | 731 |
include ':app'
| flutter/packages/flutter_tools/gradle/settings_aar.gradle.tmpl/0 | {
"file_path": "flutter/packages/flutter_tools/gradle/settings_aar.gradle.tmpl",
"repo_id": "flutter",
"token_count": 6
} | 732 |
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="flutter_gallery" type="FlutterRunConfigurationType" factoryName="Flutter">
<option name="filePath" value="$PROJECT_DIR$/examples/flutter_gallery/lib/main.dart" />
<method />
</configuration>
</component> | flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/flutter_gallery.xml.copy.tmpl/0 | {
"file_path": "flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/flutter_gallery.xml.copy.tmpl",
"repo_id": "flutter",
"token_count": 92
} | 733 |
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="manual_tests - drag_and_drop" type="FlutterRunConfigurationType" factoryName="Flutter">
<option name="filePath" value="$PROJECT_DIR$/dev/manual_tests/lib/drag_and_drop.dart" />
<method />
</configuration>
</component> | flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/manual_tests___drag_and_drop.xml.copy.tmpl/0 | {
"file_path": "flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/manual_tests___drag_and_drop.xml.copy.tmpl",
"repo_id": "flutter",
"token_count": 102
} | 734 |
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module> | flutter/packages/flutter_tools/ide_templates/intellij/flutter_root.iml.copy.tmpl/0 | {
"file_path": "flutter/packages/flutter_tools/ide_templates/intellij/flutter_root.iml.copy.tmpl",
"repo_id": "flutter",
"token_count": 106
} | 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 '../base/common.dart';
import '../base/config.dart';
import '../base/file_system.dart';
import '../base/platform.dart';
import '../base/process.dart';
import '../base/version.dart';
import '../convert.dart';
import '../globals.dart' as globals;
import 'java.dart';
// ANDROID_SDK_ROOT is deprecated.
// See https://developer.android.com/studio/command-line/variables.html#envar
const String kAndroidSdkRoot = 'ANDROID_SDK_ROOT';
const String kAndroidHome = 'ANDROID_HOME';
// No official environment variable for the NDK root is documented:
// https://developer.android.com/tools/variables#envar
// The follow three seem to be most commonly used.
const String kAndroidNdkHome = 'ANDROID_NDK_HOME';
const String kAndroidNdkPath = 'ANDROID_NDK_PATH';
const String kAndroidNdkRoot = 'ANDROID_NDK_ROOT';
final RegExp _numberedAndroidPlatformRe = RegExp(r'^android-([0-9]+)$');
final RegExp _sdkVersionRe = RegExp(r'^ro.build.version.sdk=([0-9]+)$');
// Android SDK layout:
// $ANDROID_HOME/platform-tools/adb
// $ANDROID_HOME/build-tools/19.1.0/aapt, dx, zipalign
// $ANDROID_HOME/build-tools/22.0.1/aapt
// $ANDROID_HOME/build-tools/23.0.2/aapt
// $ANDROID_HOME/build-tools/24.0.0-preview/aapt
// $ANDROID_HOME/build-tools/25.0.2/apksigner
// $ANDROID_HOME/platforms/android-22/android.jar
// $ANDROID_HOME/platforms/android-23/android.jar
// $ANDROID_HOME/platforms/android-N/android.jar
class AndroidSdk {
AndroidSdk(this.directory, {
Java? java,
FileSystem? fileSystem,
}): _java = java {
reinitialize(fileSystem: fileSystem);
}
/// The Android SDK root directory.
final Directory directory;
final Java? _java;
List<AndroidSdkVersion> _sdkVersions = <AndroidSdkVersion>[];
AndroidSdkVersion? _latestVersion;
/// Whether the `cmdline-tools` directory exists in the Android SDK.
///
/// This is required to use the newest SDK manager which only works with
/// the newer JDK.
bool get cmdlineToolsAvailable => directory.childDirectory('cmdline-tools').existsSync();
/// Whether the `platform-tools` or `cmdline-tools` directory exists in the Android SDK.
///
/// It is possible to have an Android SDK folder that is missing this with
/// the expectation that it will be downloaded later, e.g. by gradle or the
/// sdkmanager. The [licensesAvailable] property should be used to determine
/// whether the licenses are at least possibly accepted.
bool get platformToolsAvailable => cmdlineToolsAvailable
|| directory.childDirectory('platform-tools').existsSync();
/// Whether the `licenses` directory exists in the Android SDK.
///
/// The existence of this folder normally indicates that the SDK licenses have
/// been accepted, e.g. via the sdkmanager, Android Studio, or by copying them
/// from another workstation such as in CI scenarios. If these files are valid
/// gradle or the sdkmanager will be able to download and use other parts of
/// the SDK on demand.
bool get licensesAvailable => directory.childDirectory('licenses').existsSync();
static AndroidSdk? locateAndroidSdk() {
String? findAndroidHomeDir() {
String? androidHomeDir;
if (globals.config.containsKey('android-sdk')) {
androidHomeDir = globals.config.getValue('android-sdk') as String?;
} else if (globals.platform.environment.containsKey(kAndroidHome)) {
androidHomeDir = globals.platform.environment[kAndroidHome];
} else if (globals.platform.environment.containsKey(kAndroidSdkRoot)) {
androidHomeDir = globals.platform.environment[kAndroidSdkRoot];
} else if (globals.platform.isLinux) {
if (globals.fsUtils.homeDirPath != null) {
androidHomeDir = globals.fs.path.join(
globals.fsUtils.homeDirPath!,
'Android',
'Sdk',
);
}
} else if (globals.platform.isMacOS) {
if (globals.fsUtils.homeDirPath != null) {
androidHomeDir = globals.fs.path.join(
globals.fsUtils.homeDirPath!,
'Library',
'Android',
'sdk',
);
}
} else if (globals.platform.isWindows) {
if (globals.fsUtils.homeDirPath != null) {
androidHomeDir = globals.fs.path.join(
globals.fsUtils.homeDirPath!,
'AppData',
'Local',
'Android',
'sdk',
);
}
}
if (androidHomeDir != null) {
if (validSdkDirectory(androidHomeDir)) {
return androidHomeDir;
}
if (validSdkDirectory(globals.fs.path.join(androidHomeDir, 'sdk'))) {
return globals.fs.path.join(androidHomeDir, 'sdk');
}
}
// in build-tools/$version/aapt
final List<File> aaptBins = globals.os.whichAll('aapt');
for (File aaptBin in aaptBins) {
// Make sure we're using the aapt from the SDK.
aaptBin = globals.fs.file(aaptBin.resolveSymbolicLinksSync());
final String dir = aaptBin.parent.parent.parent.path;
if (validSdkDirectory(dir)) {
return dir;
}
}
// in platform-tools/adb
final List<File> adbBins = globals.os.whichAll('adb');
for (File adbBin in adbBins) {
// Make sure we're using the adb from the SDK.
adbBin = globals.fs.file(adbBin.resolveSymbolicLinksSync());
final String dir = adbBin.parent.parent.path;
if (validSdkDirectory(dir)) {
return dir;
}
}
return null;
}
final String? androidHomeDir = findAndroidHomeDir();
if (androidHomeDir == null) {
// No dice.
globals.printTrace('Unable to locate an Android SDK.');
return null;
}
return AndroidSdk(globals.fs.directory(androidHomeDir));
}
static bool validSdkDirectory(String dir) {
return sdkDirectoryHasLicenses(dir) || sdkDirectoryHasPlatformTools(dir);
}
static bool sdkDirectoryHasPlatformTools(String dir) {
return globals.fs.isDirectorySync(globals.fs.path.join(dir, 'platform-tools'));
}
static bool sdkDirectoryHasLicenses(String dir) {
return globals.fs.isDirectorySync(globals.fs.path.join(dir, 'licenses'));
}
List<AndroidSdkVersion> get sdkVersions => _sdkVersions;
AndroidSdkVersion? get latestVersion => _latestVersion;
late final String? adbPath = getPlatformToolsPath(globals.platform.isWindows ? 'adb.exe' : 'adb');
String? get emulatorPath => getEmulatorPath();
String? get avdManagerPath => getAvdManagerPath();
/// Locate the path for storing AVD emulator images. Returns null if none found.
String? getAvdPath() {
final String? avdHome = globals.platform.environment['ANDROID_AVD_HOME'];
final String? home = globals.platform.environment['HOME'];
final List<String> searchPaths = <String>[
if (avdHome != null)
avdHome,
if (home != null)
globals.fs.path.join(home, '.android', 'avd'),
];
if (globals.platform.isWindows) {
final String? homeDrive = globals.platform.environment['HOMEDRIVE'];
final String? homePath = globals.platform.environment['HOMEPATH'];
if (homeDrive != null && homePath != null) {
// Can't use path.join for HOMEDRIVE/HOMEPATH
// https://github.com/dart-lang/path/issues/37
final String home = homeDrive + homePath;
searchPaths.add(globals.fs.path.join(home, '.android', 'avd'));
}
}
for (final String searchPath in searchPaths) {
if (globals.fs.directory(searchPath).existsSync()) {
return searchPath;
}
}
return null;
}
Directory get _platformsDir => directory.childDirectory('platforms');
Iterable<Directory> get _platforms {
Iterable<Directory> platforms = <Directory>[];
if (_platformsDir.existsSync()) {
platforms = _platformsDir
.listSync()
.whereType<Directory>();
}
return platforms;
}
/// Validate the Android SDK. This returns an empty list if there are no
/// issues; otherwise, it returns a list of issues found.
List<String> validateSdkWellFormed() {
if (adbPath == null || !globals.processManager.canRun(adbPath)) {
return <String>['Android SDK file not found: ${adbPath ?? 'adb'}.'];
}
if (sdkVersions.isEmpty || latestVersion == null) {
final StringBuffer msg = StringBuffer('No valid Android SDK platforms found in ${_platformsDir.path}.');
if (_platforms.isEmpty) {
msg.write(' Directory was empty.');
} else {
msg.write(' Candidates were:\n');
msg.write(_platforms
.map((Directory dir) => ' - ${dir.basename}')
.join('\n'));
}
return <String>[msg.toString()];
}
return latestVersion!.validateSdkWellFormed();
}
String? getPlatformToolsPath(String binaryName) {
final File cmdlineToolsBinary = directory.childDirectory('cmdline-tools').childFile(binaryName);
if (cmdlineToolsBinary.existsSync()) {
return cmdlineToolsBinary.path;
}
final File platformToolBinary = directory.childDirectory('platform-tools').childFile(binaryName);
if (platformToolBinary.existsSync()) {
return platformToolBinary.path;
}
return null;
}
String? getEmulatorPath() {
final String binaryName = globals.platform.isWindows ? 'emulator.exe' : 'emulator';
// Emulator now lives inside "emulator" but used to live inside "tools" so
// try both.
final List<String> searchFolders = <String>['emulator', 'tools'];
for (final String folder in searchFolders) {
final File file = directory.childDirectory(folder).childFile(binaryName);
if (file.existsSync()) {
return file.path;
}
}
return null;
}
String? getCmdlineToolsPath(String binaryName, {bool skipOldTools = false}) {
// First look for the latest version of the command-line tools
final File cmdlineToolsLatestBinary = directory
.childDirectory('cmdline-tools')
.childDirectory('latest')
.childDirectory('bin')
.childFile(binaryName);
if (cmdlineToolsLatestBinary.existsSync()) {
return cmdlineToolsLatestBinary.path;
}
// Next look for the highest version of the command-line tools
final Directory cmdlineToolsDir = directory.childDirectory('cmdline-tools');
if (cmdlineToolsDir.existsSync()) {
final List<Version> cmdlineTools = cmdlineToolsDir
.listSync()
.whereType<Directory>()
.map((Directory subDirectory) {
try {
return Version.parse(subDirectory.basename);
} on Exception {
return null;
}
})
.whereType<Version>()
.toList();
cmdlineTools.sort();
for (final Version cmdlineToolsVersion in cmdlineTools.reversed) {
final File cmdlineToolsBinary = directory
.childDirectory('cmdline-tools')
.childDirectory(cmdlineToolsVersion.toString())
.childDirectory('bin')
.childFile(binaryName);
if (cmdlineToolsBinary.existsSync()) {
return cmdlineToolsBinary.path;
}
}
}
if (skipOldTools) {
return null;
}
// Finally fallback to the old SDK tools
final File toolsBinary = directory.childDirectory('tools').childDirectory('bin').childFile(binaryName);
if (toolsBinary.existsSync()) {
return toolsBinary.path;
}
return null;
}
String? getAvdManagerPath() => getCmdlineToolsPath(globals.platform.isWindows ? 'avdmanager.bat' : 'avdmanager');
/// From https://developer.android.com/ndk/guides/other_build_systems.
static const Map<String, String> _llvmHostDirectoryName = <String, String>{
'macos': 'darwin-x86_64',
'linux': 'linux-x86_64',
'windows': 'windows-x86_64',
};
/// Locates the binary path for an NDK binary.
///
/// The order of resolution is as follows:
///
/// 1. If [globals.config] defines an `'android-ndk'` use that.
/// 2. If the environment variable `ANDROID_NDK_HOME` is defined, use that.
/// 3. If the environment variable `ANDROID_NDK_PATH` is defined, use that.
/// 4. If the environment variable `ANDROID_NDK_ROOT` is defined, use that.
/// 5. Look for the default install location inside the Android SDK:
/// [directory]/ndk/\<version\>/. If multiple versions exist, use the
/// newest.
String? getNdkBinaryPath(
String binaryName, {
Platform? platform,
Config? config,
}) {
platform ??= globals.platform;
config ??= globals.config;
Directory? findAndroidNdkHomeDir() {
String? androidNdkHomeDir;
if (config!.containsKey('android-ndk')) {
androidNdkHomeDir = config.getValue('android-ndk') as String?;
} else if (platform!.environment.containsKey(kAndroidNdkHome)) {
androidNdkHomeDir = platform.environment[kAndroidNdkHome];
} else if (platform.environment.containsKey(kAndroidNdkPath)) {
androidNdkHomeDir = platform.environment[kAndroidNdkPath];
} else if (platform.environment.containsKey(kAndroidNdkRoot)) {
androidNdkHomeDir = platform.environment[kAndroidNdkRoot];
}
if (androidNdkHomeDir != null) {
return directory.fileSystem.directory(androidNdkHomeDir);
}
// Look for the default install location of the NDK inside the Android
// SDK when installed through `sdkmanager` or Android studio.
final Directory ndk = directory.childDirectory('ndk');
if (!ndk.existsSync()) {
return null;
}
final List<Version> ndkVersions = ndk
.listSync()
.map((FileSystemEntity entity) {
try {
return Version.parse(entity.basename);
} on Exception {
return null;
}
})
.whereType<Version>()
.toList()
// Use latest NDK first.
..sort((Version a, Version b) => -a.compareTo(b));
if (ndkVersions.isEmpty) {
return null;
}
return ndk.childDirectory(ndkVersions.first.toString());
}
final Directory? androidNdkHomeDir = findAndroidNdkHomeDir();
if (androidNdkHomeDir == null) {
return null;
}
final File executable = androidNdkHomeDir
.childDirectory('toolchains')
.childDirectory('llvm')
.childDirectory('prebuilt')
.childDirectory(_llvmHostDirectoryName[platform.operatingSystem]!)
.childDirectory('bin')
.childFile(binaryName);
if (executable.existsSync()) {
// LLVM missing in this NDK version.
return executable.path;
}
return null;
}
String? getNdkClangPath({Platform? platform, Config? config}) {
platform ??= globals.platform;
return getNdkBinaryPath(
platform.isWindows ? 'clang.exe' : 'clang',
platform: platform,
config: config,
);
}
String? getNdkArPath({Platform? platform, Config? config}) {
platform ??= globals.platform;
return getNdkBinaryPath(
platform.isWindows ? 'llvm-ar.exe' : 'llvm-ar',
platform: platform,
config: config,
);
}
String? getNdkLdPath({Platform? platform, Config? config}) {
platform ??= globals.platform;
return getNdkBinaryPath(
platform.isWindows ? 'ld.lld.exe' : 'ld.lld',
platform: platform,
config: config,
);
}
/// Sets up various paths used internally.
///
/// This method should be called in a case where the tooling may have updated
/// SDK artifacts, such as after running a gradle build.
void reinitialize({FileSystem? fileSystem}) {
List<Version> buildTools = <Version>[]; // 19.1.0, 22.0.1, ...
final Directory buildToolsDir = directory.childDirectory('build-tools');
if (buildToolsDir.existsSync()) {
buildTools = buildToolsDir
.listSync()
.map((FileSystemEntity entity) {
try {
return Version.parse(entity.basename);
} on Exception {
return null;
}
})
.whereType<Version>()
.toList();
}
// Match up platforms with the best corresponding build-tools.
_sdkVersions = _platforms.map<AndroidSdkVersion?>((Directory platformDir) {
final String platformName = platformDir.basename;
int platformVersion;
try {
final Match? numberedVersion = _numberedAndroidPlatformRe.firstMatch(platformName);
if (numberedVersion != null) {
platformVersion = int.parse(numberedVersion.group(1)!);
} else {
final String buildProps = platformDir.childFile('build.prop').readAsStringSync();
final Iterable<Match> versionMatches = const LineSplitter()
.convert(buildProps)
.map<RegExpMatch?>(_sdkVersionRe.firstMatch)
.whereType<Match>();
if (versionMatches.isEmpty) {
return null;
}
final String? versionString = versionMatches.first.group(1);
if (versionString == null) {
return null;
}
platformVersion = int.parse(versionString);
}
} on Exception {
return null;
}
Version? buildToolsVersion = Version.primary(buildTools.where((Version version) {
return version.major == platformVersion;
}).toList());
buildToolsVersion ??= Version.primary(buildTools);
if (buildToolsVersion == null) {
return null;
}
return AndroidSdkVersion._(
this,
sdkLevel: platformVersion,
platformName: platformName,
buildToolsVersion: buildToolsVersion,
fileSystem: fileSystem ?? globals.fs,
);
}).whereType<AndroidSdkVersion>().toList();
_sdkVersions.sort();
_latestVersion = _sdkVersions.isEmpty ? null : _sdkVersions.last;
}
/// Returns the filesystem path of the Android SDK manager tool.
String? get sdkManagerPath {
final String executable = globals.platform.isWindows
? 'sdkmanager.bat'
: 'sdkmanager';
return getCmdlineToolsPath(executable, skipOldTools: true);
}
/// Returns the version of the Android SDK manager tool or null if not found.
String? get sdkManagerVersion {
if (sdkManagerPath == null || !globals.processManager.canRun(sdkManagerPath)) {
throwToolExit(
'Android sdkmanager not found. Update to the latest Android SDK and ensure that '
'the cmdline-tools are installed to resolve this.'
);
}
final RunResult result = globals.processUtils.runSync(
<String>[sdkManagerPath!, '--version'],
environment: _java?.environment,
);
if (result.exitCode != 0) {
globals.printTrace('sdkmanager --version failed: exitCode: ${result.exitCode} stdout: ${result.stdout} stderr: ${result.stderr}');
return null;
}
return result.stdout.trim();
}
@override
String toString() => 'AndroidSdk: $directory';
}
class AndroidSdkVersion implements Comparable<AndroidSdkVersion> {
AndroidSdkVersion._(
this.sdk, {
required this.sdkLevel,
required this.platformName,
required this.buildToolsVersion,
required FileSystem fileSystem,
}) : _fileSystem = fileSystem;
final AndroidSdk sdk;
final int sdkLevel;
final String platformName;
final Version buildToolsVersion;
final FileSystem _fileSystem;
String get buildToolsVersionName => buildToolsVersion.toString();
String get androidJarPath => getPlatformsPath('android.jar');
/// Return the path to the android application package tool.
///
/// This is used to dump the xml in order to launch built android applications.
///
/// See also:
/// * [AndroidApk.fromApk], which depends on this to determine application identifiers.
String get aaptPath => getBuildToolsPath('aapt');
List<String> validateSdkWellFormed() {
final String? existsAndroidJarPath = _exists(androidJarPath);
if (existsAndroidJarPath != null) {
return <String>[existsAndroidJarPath];
}
final String? canRunAaptPath = _canRun(aaptPath);
if (canRunAaptPath != null) {
return <String>[canRunAaptPath];
}
return <String>[];
}
String getPlatformsPath(String itemName) {
return sdk.directory.childDirectory('platforms').childDirectory(platformName).childFile(itemName).path;
}
String getBuildToolsPath(String binaryName) {
return sdk.directory.childDirectory('build-tools').childDirectory(buildToolsVersionName).childFile(binaryName).path;
}
@override
int compareTo(AndroidSdkVersion other) => sdkLevel - other.sdkLevel;
@override
String toString() => '[${sdk.directory}, SDK version $sdkLevel, build-tools $buildToolsVersionName]';
String? _exists(String path) {
if (!_fileSystem.isFileSync(path)) {
return 'Android SDK file not found: $path.';
}
return null;
}
String? _canRun(String path) {
if (!globals.processManager.canRun(path)) {
return 'Android SDK file not found: $path.';
}
return null;
}
}
| flutter/packages/flutter_tools/lib/src/android/android_sdk.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/android/android_sdk.dart",
"repo_id": "flutter",
"token_count": 8012
} | 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 'base/context.dart';
import 'base/file_system.dart';
import 'build_info.dart';
abstract class ApplicationPackageFactory {
static ApplicationPackageFactory? get instance => context.get<ApplicationPackageFactory>();
/// Create an [ApplicationPackage] for the given platform.
Future<ApplicationPackage?> getPackageForPlatform(
TargetPlatform platform, {
BuildInfo? buildInfo,
File? applicationBinary,
});
}
abstract class ApplicationPackage {
ApplicationPackage({ required this.id });
/// Package ID from the Android Manifest or equivalent.
final String id;
String? get name;
String? get displayName => name;
@override
String toString() => displayName ?? id;
}
/// An interface for application package that is created from prebuilt binary.
abstract class PrebuiltApplicationPackage implements ApplicationPackage {
/// The application bundle of the prebuilt application.
///
/// The same ApplicationPackage should be able to be recreated by passing
/// the file to [FlutterApplicationPackageFactory.getPackageForPlatform].
FileSystemEntity get applicationPackage;
}
| flutter/packages/flutter_tools/lib/src/application_package.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/application_package.dart",
"repo_id": "flutter",
"token_count": 323
} | 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.
/// This file serves as the single point of entry into the `dart:io` APIs
/// within Flutter tools.
///
/// In order to make Flutter tools more testable, we use the `FileSystem` APIs
/// in `package:file` rather than using the `dart:io` file APIs directly (see
/// `file_system.dart`). Doing so allows us to swap out local file system
/// access with mockable (or in-memory) file systems, making our tests hermetic
/// vis-a-vis file system access.
///
/// We also use `package:platform` to provide an abstraction away from the
/// static methods in the `dart:io` `Platform` class (see `platform.dart`). As
/// such, do not export Platform from this file!
///
/// To ensure that all file system and platform API access within Flutter tools
/// goes through the proper APIs, we forbid direct imports of `dart:io` (via a
/// test), forcing all callers to instead import this file, which exports the
/// blessed subset of `dart:io` that is legal to use in Flutter tools.
///
/// Because of the nature of this file, it is important that **platform and file
/// APIs not be exported from `dart:io` in this file**! Moreover, be careful
/// about any additional exports that you add to this file, as doing so will
/// increase the API surface that we have to test in Flutter tools, and the APIs
/// in `dart:io` can sometimes be hard to use in tests.
library;
// We allow `print()` in this file as a fallback for writing to the terminal via
// regular stdout/stderr/stdio paths. Everything else in the flutter_tools
// library should route terminal I/O through the [Stdio] class defined below.
// ignore_for_file: avoid_print
import 'dart:async';
import 'dart:io' as io
show
IOSink,
InternetAddress,
InternetAddressType,
NetworkInterface,
Process,
ProcessInfo,
ProcessSignal,
Stdin,
StdinException,
Stdout,
StdoutException,
exit,
pid,
stderr,
stdin,
stdout;
import 'package:file/file.dart';
import 'package:meta/meta.dart';
import 'async_guard.dart';
import 'platform.dart';
import 'process.dart';
export 'dart:io'
show
BytesBuilder,
CompressionOptions,
// Directory, NO! Use `file_system.dart`
// File, NO! Use `file_system.dart`
// FileSystemEntity, NO! Use `file_system.dart`
GZipCodec,
HandshakeException,
HttpClient,
HttpClientRequest,
HttpClientResponse,
HttpClientResponseCompressionState,
HttpException,
HttpHeaders,
HttpRequest,
HttpResponse,
HttpServer,
HttpStatus,
IOException,
IOSink,
InternetAddress,
InternetAddressType,
// Link NO! Use `file_system.dart`
// NetworkInterface NO! Use `io.dart`
OSError,
// Platform NO! use `platform.dart`
Process,
ProcessException,
// ProcessInfo, NO! use `io.dart`
ProcessResult,
// ProcessSignal NO! Use [ProcessSignal] below.
ProcessStartMode,
// RandomAccessFile NO! Use `file_system.dart`
SecurityContext,
ServerSocket,
SignalException,
Socket,
SocketException,
Stdin,
StdinException,
Stdout,
WebSocket,
WebSocketException,
WebSocketTransformer,
ZLibEncoder,
exitCode,
gzip,
pid,
// stderr, NO! Use `io.dart`
// stdin, NO! Use `io.dart`
// stdout, NO! Use `io.dart`
systemEncoding;
/// Exits the process with the given [exitCode].
typedef ExitFunction = void Function(int exitCode);
const ExitFunction _defaultExitFunction = io.exit;
ExitFunction _exitFunction = _defaultExitFunction;
/// Exits the process.
///
/// Throws [AssertionError] if assertions are enabled and the dart:io exit
/// is still active when called. This may indicate exit was called in
/// a test without being configured correctly.
///
/// This is analogous to the `exit` function in `dart:io`, except that this
/// function may be set to a testing-friendly value by calling
/// [setExitFunctionForTests] (and then restored to its default implementation
/// with [restoreExitFunction]). The default implementation delegates to
/// `dart:io`.
ExitFunction get exit {
assert(
_exitFunction != io.exit || !_inUnitTest(),
'io.exit was called with assertions active in a unit test',
);
return _exitFunction;
}
// Whether the tool is executing in a unit test.
bool _inUnitTest() {
return Zone.current[#test.declarer] != null;
}
/// Sets the [exit] function to a function that throws an exception rather
/// than exiting the process; this is intended for testing purposes.
@visibleForTesting
void setExitFunctionForTests([ ExitFunction? exitFunction ]) {
_exitFunction = exitFunction ?? (int exitCode) {
throw ProcessExit(exitCode, immediate: true);
};
}
/// Restores the [exit] function to the `dart:io` implementation.
@visibleForTesting
void restoreExitFunction() {
_exitFunction = _defaultExitFunction;
}
/// A portable version of [io.ProcessSignal].
///
/// Listening on signals that don't exist on the current platform is just a
/// no-op. This is in contrast to [io.ProcessSignal], where listening to
/// non-existent signals throws an exception.
///
/// This class does NOT implement io.ProcessSignal, because that class uses
/// private fields. This means it cannot be used with, e.g., [Process.killPid].
/// Alternative implementations of the relevant methods that take
/// [ProcessSignal] instances are available on this class (e.g. "send").
class ProcessSignal {
@visibleForTesting
const ProcessSignal(this._delegate, {@visibleForTesting Platform platform = const LocalPlatform()})
: _platform = platform;
static const ProcessSignal sigwinch = PosixProcessSignal(io.ProcessSignal.sigwinch);
static const ProcessSignal sigterm = PosixProcessSignal(io.ProcessSignal.sigterm);
static const ProcessSignal sigusr1 = PosixProcessSignal(io.ProcessSignal.sigusr1);
static const ProcessSignal sigusr2 = PosixProcessSignal(io.ProcessSignal.sigusr2);
static const ProcessSignal sigint = ProcessSignal(io.ProcessSignal.sigint);
static const ProcessSignal sigkill = ProcessSignal(io.ProcessSignal.sigkill);
final io.ProcessSignal _delegate;
final Platform _platform;
Stream<ProcessSignal> watch() {
return _delegate.watch().map<ProcessSignal>((io.ProcessSignal signal) => this);
}
/// Sends the signal to the given process (identified by pid).
///
/// Returns true if the signal was delivered, false otherwise.
///
/// On Windows, this can only be used with [sigterm], which terminates the
/// process.
///
/// This is implemented by sending the signal using [io.Process.killPid] and
/// therefore cannot be faked in tests. To fake sending signals in tests, use
/// [kill] instead.
bool send(int pid) {
assert(!_platform.isWindows || this == ProcessSignal.sigterm);
return io.Process.killPid(pid, _delegate);
}
/// A more testable variant of [send].
///
/// Sends this signal to the given `process` by invoking [io.Process.kill].
///
/// In tests this method can be faked by passing a fake implementation of the
/// [io.Process] interface.
bool kill(io.Process process) {
return process.kill(_delegate);
}
@override
String toString() => _delegate.toString();
}
/// A [ProcessSignal] that is only available on Posix platforms.
///
/// Listening to a [_PosixProcessSignal] is a no-op on Windows.
@visibleForTesting
class PosixProcessSignal extends ProcessSignal {
const PosixProcessSignal(super.wrappedSignal, {@visibleForTesting super.platform});
@override
Stream<ProcessSignal> watch() {
// This uses the real platform since it invokes dart:io functionality directly.
if (_platform.isWindows) {
return const Stream<ProcessSignal>.empty();
}
return super.watch();
}
}
/// A class that wraps stdout, stderr, and stdin, and exposes the allowed
/// operations.
///
/// In particular, there are three ways that writing to stdout and stderr
/// can fail. A call to stdout.write() can fail:
/// * by throwing a regular synchronous exception,
/// * by throwing an exception asynchronously, and
/// * by completing the Future stdout.done with an error.
///
/// This class encapsulates all three so that we don't have to worry about it
/// anywhere else.
class Stdio {
Stdio();
/// Tests can provide overrides to use instead of the stdout and stderr from
/// dart:io.
@visibleForTesting
Stdio.test({
required io.Stdout stdout,
required io.IOSink stderr,
}) : _stdoutOverride = stdout, _stderrOverride = stderr;
io.Stdout? _stdoutOverride;
io.IOSink? _stderrOverride;
// These flags exist to remember when the done Futures on stdout and stderr
// complete to avoid trying to write to a closed stream sink, which would
// generate a [StateError].
bool _stdoutDone = false;
bool _stderrDone = false;
Stream<List<int>> get stdin => io.stdin;
io.Stdout get stdout {
if (_stdout != null) {
return _stdout!;
}
_stdout = _stdoutOverride ?? io.stdout;
_stdout!.done.then(
(void _) { _stdoutDone = true; },
onError: (Object err, StackTrace st) { _stdoutDone = true; },
);
return _stdout!;
}
io.Stdout? _stdout;
io.IOSink get stderr {
if (_stderr != null) {
return _stderr!;
}
_stderr = _stderrOverride ?? io.stderr;
_stderr!.done.then(
(void _) { _stderrDone = true; },
onError: (Object err, StackTrace st) { _stderrDone = true; },
);
return _stderr!;
}
io.IOSink? _stderr;
bool get hasTerminal => io.stdout.hasTerminal;
static bool? _stdinHasTerminal;
/// Determines whether there is a terminal attached.
///
/// [io.Stdin.hasTerminal] only covers a subset of cases. In this check the
/// echoMode is toggled on and off to catch cases where the tool running in
/// a docker container thinks there is an attached terminal. This can cause
/// runtime errors such as "inappropriate ioctl for device" if not handled.
bool get stdinHasTerminal {
if (_stdinHasTerminal != null) {
return _stdinHasTerminal!;
}
if (stdin is! io.Stdin) {
return _stdinHasTerminal = false;
}
final io.Stdin ioStdin = stdin as io.Stdin;
if (!ioStdin.hasTerminal) {
return _stdinHasTerminal = false;
}
try {
final bool currentEchoMode = ioStdin.echoMode;
ioStdin.echoMode = !currentEchoMode;
ioStdin.echoMode = currentEchoMode;
} on io.StdinException {
return _stdinHasTerminal = false;
}
return _stdinHasTerminal = true;
}
int? get terminalColumns => hasTerminal ? stdout.terminalColumns : null;
int? get terminalLines => hasTerminal ? stdout.terminalLines : null;
bool get supportsAnsiEscapes => hasTerminal && stdout.supportsAnsiEscapes;
/// Writes [message] to [stderr], falling back on [fallback] if the write
/// throws any exception. The default fallback calls [print] on [message].
void stderrWrite(
String message, {
void Function(String, dynamic, StackTrace)? fallback,
}) {
if (!_stderrDone) {
_stdioWrite(stderr, message, fallback: fallback);
return;
}
fallback == null ? print(message) : fallback(
message,
const io.StdoutException('stderr is done'),
StackTrace.current,
);
}
/// Writes [message] to [stdout], falling back on [fallback] if the write
/// throws any exception. The default fallback calls [print] on [message].
void stdoutWrite(
String message, {
void Function(String, dynamic, StackTrace)? fallback,
}) {
if (!_stdoutDone) {
_stdioWrite(stdout, message, fallback: fallback);
return;
}
fallback == null ? print(message) : fallback(
message,
const io.StdoutException('stdout is done'),
StackTrace.current,
);
}
// Helper for [stderrWrite] and [stdoutWrite].
void _stdioWrite(io.IOSink sink, String message, {
void Function(String, dynamic, StackTrace)? fallback,
}) {
asyncGuard<void>(() async {
sink.write(message);
}, onError: (Object error, StackTrace stackTrace) {
if (fallback == null) {
print(message);
} else {
fallback(message, error, stackTrace);
}
});
}
/// Adds [stream] to [stdout].
Future<void> addStdoutStream(Stream<List<int>> stream) => stdout.addStream(stream);
/// Adds [stream] to [stderr].
Future<void> addStderrStream(Stream<List<int>> stream) => stderr.addStream(stream);
}
/// An overridable version of io.ProcessInfo.
abstract class ProcessInfo {
factory ProcessInfo(FileSystem fs) = _DefaultProcessInfo;
factory ProcessInfo.test(FileSystem fs) = _TestProcessInfo;
int get currentRss;
int get maxRss;
File writePidFile(String pidFile);
}
/// The default implementation of [ProcessInfo], which uses [io.ProcessInfo].
class _DefaultProcessInfo implements ProcessInfo {
_DefaultProcessInfo(this._fileSystem);
final FileSystem _fileSystem;
@override
int get currentRss => io.ProcessInfo.currentRss;
@override
int get maxRss => io.ProcessInfo.maxRss;
@override
File writePidFile(String pidFile) {
return _fileSystem.file(pidFile)
..writeAsStringSync(io.pid.toString());
}
}
/// The test version of [ProcessInfo].
class _TestProcessInfo implements ProcessInfo {
_TestProcessInfo(this._fileSystem);
final FileSystem _fileSystem;
@override
int currentRss = 1000;
@override
int maxRss = 2000;
@override
File writePidFile(String pidFile) {
return _fileSystem.file(pidFile)
..writeAsStringSync('12345');
}
}
/// The return type for [listNetworkInterfaces].
class NetworkInterface implements io.NetworkInterface {
NetworkInterface(this._delegate);
final io.NetworkInterface _delegate;
@override
List<io.InternetAddress> get addresses => _delegate.addresses;
@override
int get index => _delegate.index;
@override
String get name => _delegate.name;
@override
String toString() => "NetworkInterface('$name', $addresses)";
}
typedef NetworkInterfaceLister = Future<List<NetworkInterface>> Function({
bool includeLoopback,
bool includeLinkLocal,
io.InternetAddressType type,
});
NetworkInterfaceLister? _networkInterfaceListerOverride;
// Tests can set up a non-default network interface lister.
@visibleForTesting
void setNetworkInterfaceLister(NetworkInterfaceLister lister) {
_networkInterfaceListerOverride = lister;
}
@visibleForTesting
void resetNetworkInterfaceLister() {
_networkInterfaceListerOverride = null;
}
/// This calls [NetworkInterface.list] from `dart:io` unless it is overridden by
/// [setNetworkInterfaceLister] for a test. If it is overridden for a test,
/// it should be reset with [resetNetworkInterfaceLister].
Future<List<NetworkInterface>> listNetworkInterfaces({
bool includeLoopback = false,
bool includeLinkLocal = false,
io.InternetAddressType type = io.InternetAddressType.any,
}) async {
if (_networkInterfaceListerOverride != null) {
return _networkInterfaceListerOverride!.call(
includeLoopback: includeLoopback,
includeLinkLocal: includeLinkLocal,
type: type,
);
}
final List<io.NetworkInterface> interfaces = await io.NetworkInterface.list(
includeLoopback: includeLoopback,
includeLinkLocal: includeLinkLocal,
type: type,
);
return interfaces.map(
(io.NetworkInterface interface) => NetworkInterface(interface),
).toList();
}
| flutter/packages/flutter_tools/lib/src/base/io.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/base/io.dart",
"repo_id": "flutter",
"token_count": 5384
} | 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 'package:meta/meta.dart' show immutable;
/// Data class that represents a range of versions in their String
/// representation.
///
/// Both the [versionMin] and [versionMax] are inclusive versions, and undefined
/// values represent an unknown minimum/maximum version.
@immutable
class VersionRange {
const VersionRange(
this.versionMin,
this.versionMax,
);
final String? versionMin;
final String? versionMax;
@override
bool operator ==(Object other) =>
other is VersionRange &&
other.versionMin == versionMin &&
other.versionMax == versionMax;
@override
int get hashCode => Object.hash(versionMin, versionMax);
}
| flutter/packages/flutter_tools/lib/src/base/version_range.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/base/version_range.dart",
"repo_id": "flutter",
"token_count": 237
} | 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 'package:meta/meta.dart';
import 'package:unified_analytics/unified_analytics.dart';
import '../../artifacts.dart';
import '../../base/build.dart';
import '../../base/common.dart';
import '../../base/file_system.dart';
import '../../base/io.dart';
import '../../base/process.dart';
import '../../build_info.dart';
import '../../globals.dart' as globals;
import '../../ios/mac.dart';
import '../../macos/xcode.dart';
import '../../project.dart';
import '../../reporting/reporting.dart';
import '../build_system.dart';
import '../depfile.dart';
import '../exceptions.dart';
import '../tools/shader_compiler.dart';
import 'assets.dart';
import 'common.dart';
import 'icon_tree_shaker.dart';
/// Supports compiling a dart kernel file to an assembly file.
///
/// If more than one iOS arch is provided, then this rule will
/// produce a universal binary.
abstract class AotAssemblyBase extends Target {
const AotAssemblyBase();
@override
String get analyticsName => 'ios_aot';
@override
Future<void> build(Environment environment) async {
final AOTSnapshotter snapshotter = AOTSnapshotter(
fileSystem: environment.fileSystem,
logger: environment.logger,
xcode: globals.xcode!,
artifacts: environment.artifacts,
processManager: environment.processManager,
);
final String buildOutputPath = environment.buildDir.path;
final String? environmentBuildMode = environment.defines[kBuildMode];
if (environmentBuildMode == null) {
throw MissingDefineException(kBuildMode, 'aot_assembly');
}
final String? environmentTargetPlatform = environment.defines[kTargetPlatform];
if (environmentTargetPlatform== null) {
throw MissingDefineException(kTargetPlatform, 'aot_assembly');
}
final String? sdkRoot = environment.defines[kSdkRoot];
if (sdkRoot == null) {
throw MissingDefineException(kSdkRoot, 'aot_assembly');
}
final List<String> extraGenSnapshotOptions = decodeCommaSeparated(environment.defines, kExtraGenSnapshotOptions);
final BuildMode buildMode = BuildMode.fromCliName(environmentBuildMode);
final TargetPlatform targetPlatform = getTargetPlatformForName(environmentTargetPlatform);
final String? splitDebugInfo = environment.defines[kSplitDebugInfo];
final bool dartObfuscation = environment.defines[kDartObfuscation] == 'true';
final List<DarwinArch> darwinArchs = environment.defines[kIosArchs]
?.split(' ')
.map(getIOSArchForName)
.toList()
?? <DarwinArch>[DarwinArch.arm64];
if (targetPlatform != TargetPlatform.ios) {
throw Exception('aot_assembly is only supported for iOS applications.');
}
final EnvironmentType? environmentType = environmentTypeFromSdkroot(sdkRoot, environment.fileSystem);
if (environmentType == EnvironmentType.simulator) {
throw Exception(
'release/profile builds are only supported for physical devices. '
'attempted to build for simulator.'
);
}
final String? codeSizeDirectory = environment.defines[kCodeSizeDirectory];
// If we're building multiple iOS archs the binaries need to be lipo'd
// together.
final List<Future<int>> pending = <Future<int>>[];
for (final DarwinArch darwinArch in darwinArchs) {
final List<String> archExtraGenSnapshotOptions = List<String>.of(extraGenSnapshotOptions);
if (codeSizeDirectory != null) {
final File codeSizeFile = environment.fileSystem
.directory(codeSizeDirectory)
.childFile('snapshot.${darwinArch.name}.json');
final File precompilerTraceFile = environment.fileSystem
.directory(codeSizeDirectory)
.childFile('trace.${darwinArch.name}.json');
archExtraGenSnapshotOptions.add('--write-v8-snapshot-profile-to=${codeSizeFile.path}');
archExtraGenSnapshotOptions.add('--trace-precompiler-to=${precompilerTraceFile.path}');
}
pending.add(snapshotter.build(
platform: targetPlatform,
buildMode: buildMode,
mainPath: environment.buildDir.childFile('app.dill').path,
outputPath: environment.fileSystem.path.join(buildOutputPath, darwinArch.name),
darwinArch: darwinArch,
sdkRoot: sdkRoot,
quiet: true,
splitDebugInfo: splitDebugInfo,
dartObfuscation: dartObfuscation,
extraGenSnapshotOptions: archExtraGenSnapshotOptions,
));
}
final List<int> results = await Future.wait(pending);
if (results.any((int result) => result != 0)) {
throw Exception('AOT snapshotter exited with code ${results.join()}');
}
// Combine the app lib into a fat framework.
await Lipo.create(
environment,
darwinArchs,
relativePath: 'App.framework/App',
inputDir: buildOutputPath,
);
// And combine the dSYM for each architecture too, if it was created.
await Lipo.create(
environment,
darwinArchs,
relativePath: 'App.framework.dSYM/Contents/Resources/DWARF/App',
inputDir: buildOutputPath,
// Don't fail if the dSYM wasn't created (i.e. during a debug build).
skipMissingInputs: true,
);
}
}
/// Generate an assembly target from a dart kernel file in release mode.
class AotAssemblyRelease extends AotAssemblyBase {
const AotAssemblyRelease();
@override
String get name => 'aot_assembly_release';
@override
List<Source> get inputs => const <Source>[
Source.pattern('{FLUTTER_ROOT}/packages/flutter_tools/lib/src/build_system/targets/ios.dart'),
Source.pattern('{BUILD_DIR}/app.dill'),
Source.artifact(Artifact.engineDartBinary),
Source.artifact(Artifact.skyEnginePath),
// TODO(zanderso): cannot reference gen_snapshot with artifacts since
// it resolves to a file (ios/gen_snapshot) that never exists. This was
// split into gen_snapshot_arm64 and gen_snapshot_armv7.
// Source.artifact(Artifact.genSnapshot,
// platform: TargetPlatform.ios,
// mode: BuildMode.release,
// ),
];
@override
List<Source> get outputs => const <Source>[
Source.pattern('{OUTPUT_DIR}/App.framework/App'),
];
@override
List<Target> get dependencies => const <Target>[
ReleaseUnpackIOS(),
KernelSnapshot(),
];
}
/// Generate an assembly target from a dart kernel file in profile mode.
class AotAssemblyProfile extends AotAssemblyBase {
const AotAssemblyProfile();
@override
String get name => 'aot_assembly_profile';
@override
List<Source> get inputs => const <Source>[
Source.pattern('{FLUTTER_ROOT}/packages/flutter_tools/lib/src/build_system/targets/ios.dart'),
Source.pattern('{BUILD_DIR}/app.dill'),
Source.artifact(Artifact.engineDartBinary),
Source.artifact(Artifact.skyEnginePath),
// TODO(zanderso): cannot reference gen_snapshot with artifacts since
// it resolves to a file (ios/gen_snapshot) that never exists. This was
// split into gen_snapshot_arm64 and gen_snapshot_armv7.
// Source.artifact(Artifact.genSnapshot,
// platform: TargetPlatform.ios,
// mode: BuildMode.profile,
// ),
];
@override
List<Source> get outputs => const <Source>[
Source.pattern('{OUTPUT_DIR}/App.framework/App'),
];
@override
List<Target> get dependencies => const <Target>[
ProfileUnpackIOS(),
KernelSnapshot(),
];
}
/// Create a trivial App.framework file for debug iOS builds.
class DebugUniversalFramework extends Target {
const DebugUniversalFramework();
@override
String get name => 'debug_universal_framework';
@override
List<Target> get dependencies => const <Target>[
DebugUnpackIOS(),
KernelSnapshot(),
];
@override
List<Source> get inputs => const <Source>[
Source.pattern('{FLUTTER_ROOT}/packages/flutter_tools/lib/src/build_system/targets/ios.dart'),
];
@override
List<Source> get outputs => const <Source>[
Source.pattern('{BUILD_DIR}/App.framework/App'),
];
@override
Future<void> build(Environment environment) async {
final String? sdkRoot = environment.defines[kSdkRoot];
if (sdkRoot == null) {
throw MissingDefineException(kSdkRoot, name);
}
// Generate a trivial App.framework.
final Set<String>? iosArchNames = environment.defines[kIosArchs]?.split(' ').toSet();
final File output = environment.buildDir
.childDirectory('App.framework')
.childFile('App');
environment.buildDir.createSync(recursive: true);
await _createStubAppFramework(
output,
environment,
iosArchNames,
sdkRoot,
);
}
}
/// Copy the iOS framework to the correct copy dir by invoking 'rsync'.
///
/// This class is abstract to share logic between the three concrete
/// implementations. The shelling out is done to avoid complications with
/// preserving special files (e.g., symbolic links) in the framework structure.
abstract class UnpackIOS extends Target {
const UnpackIOS();
@override
List<Source> get inputs => <Source>[
const Source.pattern(
'{FLUTTER_ROOT}/packages/flutter_tools/lib/src/build_system/targets/ios.dart'),
Source.artifact(
Artifact.flutterXcframework,
platform: TargetPlatform.ios,
mode: buildMode,
),
];
@override
List<Source> get outputs => const <Source>[
Source.pattern('{OUTPUT_DIR}/Flutter.framework/Flutter'),
];
@override
List<Target> get dependencies => <Target>[];
@visibleForOverriding
BuildMode get buildMode;
@override
Future<void> build(Environment environment) async {
final String? sdkRoot = environment.defines[kSdkRoot];
if (sdkRoot == null) {
throw MissingDefineException(kSdkRoot, name);
}
final String? archs = environment.defines[kIosArchs];
if (archs == null) {
throw MissingDefineException(kIosArchs, name);
}
await _copyFramework(environment, sdkRoot);
final File frameworkBinary = environment.outputDir.childDirectory('Flutter.framework').childFile('Flutter');
final String frameworkBinaryPath = frameworkBinary.path;
if (!await frameworkBinary.exists()) {
throw Exception('Binary $frameworkBinaryPath does not exist, cannot thin');
}
await _thinFramework(environment, frameworkBinaryPath, archs);
await _signFramework(environment, frameworkBinary, buildMode);
}
Future<void> _copyFramework(Environment environment, String sdkRoot) async {
final EnvironmentType? environmentType = environmentTypeFromSdkroot(sdkRoot, environment.fileSystem);
final String basePath = environment.artifacts.getArtifactPath(
Artifact.flutterFramework,
platform: TargetPlatform.ios,
mode: buildMode,
environmentType: environmentType,
);
final ProcessResult result = await environment.processManager.run(<String>[
'rsync',
'-av',
'--delete',
'--filter',
'- .DS_Store/',
basePath,
environment.outputDir.path,
]);
if (result.exitCode != 0) {
throw Exception(
'Failed to copy framework (exit ${result.exitCode}:\n'
'${result.stdout}\n---\n${result.stderr}',
);
}
}
/// Destructively thin Flutter.framework to include only the specified architectures.
Future<void> _thinFramework(
Environment environment,
String frameworkBinaryPath,
String archs,
) async {
final List<String> archList = archs.split(' ').toList();
final ProcessResult infoResult = await environment.processManager.run(<String>[
'lipo',
'-info',
frameworkBinaryPath,
]);
final String lipoInfo = infoResult.stdout as String;
final ProcessResult verifyResult = await environment.processManager.run(<String>[
'lipo',
frameworkBinaryPath,
'-verify_arch',
...archList,
]);
if (verifyResult.exitCode != 0) {
throw Exception('Binary $frameworkBinaryPath does not contain $archs. Running lipo -info:\n$lipoInfo');
}
// Skip thinning for non-fat executables.
if (lipoInfo.startsWith('Non-fat file:')) {
environment.logger.printTrace('Skipping lipo for non-fat file $frameworkBinaryPath');
return;
}
// Thin in-place.
final ProcessResult extractResult = await environment.processManager.run(<String>[
'lipo',
'-output',
frameworkBinaryPath,
for (final String arch in archList)
...<String>[
'-extract',
arch,
],
...<String>[frameworkBinaryPath],
]);
if (extractResult.exitCode != 0) {
throw Exception('Failed to extract $archs for $frameworkBinaryPath.\n${extractResult.stderr}\nRunning lipo -info:\n$lipoInfo');
}
}
}
/// Unpack the release prebuilt engine framework.
class ReleaseUnpackIOS extends UnpackIOS {
const ReleaseUnpackIOS();
@override
String get name => 'release_unpack_ios';
@override
BuildMode get buildMode => BuildMode.release;
}
/// Unpack the profile prebuilt engine framework.
class ProfileUnpackIOS extends UnpackIOS {
const ProfileUnpackIOS();
@override
String get name => 'profile_unpack_ios';
@override
BuildMode get buildMode => BuildMode.profile;
}
/// Unpack the debug prebuilt engine framework.
class DebugUnpackIOS extends UnpackIOS {
const DebugUnpackIOS();
@override
String get name => 'debug_unpack_ios';
@override
BuildMode get buildMode => BuildMode.debug;
}
/// The base class for all iOS bundle targets.
///
/// This is responsible for setting up the basic App.framework structure, including:
/// * Copying the app.dill/kernel_blob.bin from the build directory to assets (debug)
/// * Copying the precompiled isolate/vm data from the engine (debug)
/// * Copying the flutter assets to App.framework/flutter_assets
/// * Copying either the stub or real App assembly file to App.framework/App
abstract class IosAssetBundle extends Target {
const IosAssetBundle();
@override
List<Target> get dependencies => const <Target>[
KernelSnapshot(),
];
@override
List<Source> get inputs => const <Source>[
Source.pattern('{BUILD_DIR}/App.framework/App'),
Source.pattern('{PROJECT_DIR}/pubspec.yaml'),
...IconTreeShaker.inputs,
...ShaderCompiler.inputs,
];
@override
List<Source> get outputs => const <Source>[
Source.pattern('{OUTPUT_DIR}/App.framework/App'),
Source.pattern('{OUTPUT_DIR}/App.framework/Info.plist'),
];
@override
List<String> get depfiles => <String>[
'flutter_assets.d',
];
@override
Future<void> build(Environment environment) async {
final String? environmentBuildMode = environment.defines[kBuildMode];
if (environmentBuildMode == null) {
throw MissingDefineException(kBuildMode, name);
}
final BuildMode buildMode = BuildMode.fromCliName(environmentBuildMode);
final Directory frameworkDirectory = environment.outputDir.childDirectory('App.framework');
final File frameworkBinary = frameworkDirectory.childFile('App');
final Directory assetDirectory = frameworkDirectory.childDirectory('flutter_assets');
frameworkDirectory.createSync(recursive: true);
assetDirectory.createSync();
// Only copy the prebuilt runtimes and kernel blob in debug mode.
if (buildMode == BuildMode.debug) {
// Copy the App.framework to the output directory.
environment.buildDir
.childDirectory('App.framework')
.childFile('App')
.copySync(frameworkBinary.path);
final String vmSnapshotData = environment.artifacts.getArtifactPath(Artifact.vmSnapshotData, mode: BuildMode.debug);
final String isolateSnapshotData = environment.artifacts.getArtifactPath(Artifact.isolateSnapshotData, mode: BuildMode.debug);
environment.buildDir.childFile('app.dill')
.copySync(assetDirectory.childFile('kernel_blob.bin').path);
environment.fileSystem.file(vmSnapshotData)
.copySync(assetDirectory.childFile('vm_snapshot_data').path);
environment.fileSystem.file(isolateSnapshotData)
.copySync(assetDirectory.childFile('isolate_snapshot_data').path);
} else {
environment.buildDir.childDirectory('App.framework').childFile('App')
.copySync(frameworkBinary.path);
}
// Copy the dSYM
if (environment.buildDir.childDirectory('App.framework.dSYM').existsSync()) {
final File dsymOutputBinary = environment
.outputDir
.childDirectory('App.framework.dSYM')
.childDirectory('Contents')
.childDirectory('Resources')
.childDirectory('DWARF')
.childFile('App');
dsymOutputBinary.parent.createSync(recursive: true);
environment
.buildDir
.childDirectory('App.framework.dSYM')
.childDirectory('Contents')
.childDirectory('Resources')
.childDirectory('DWARF')
.childFile('App')
.copySync(dsymOutputBinary.path);
}
final FlutterProject flutterProject = FlutterProject.fromDirectory(environment.projectDir);
// Copy the assets.
final Depfile assetDepfile = await copyAssets(
environment,
assetDirectory,
targetPlatform: TargetPlatform.ios,
additionalInputs: <File>[
flutterProject.ios.infoPlist,
flutterProject.ios.appFrameworkInfoPlist,
],
flavor: environment.defines[kFlavor],
);
environment.depFileService.writeToFile(
assetDepfile,
environment.buildDir.childFile('flutter_assets.d'),
);
// Copy the plist from either the project or module.
flutterProject.ios.appFrameworkInfoPlist
.copySync(environment.outputDir
.childDirectory('App.framework')
.childFile('Info.plist').path);
await _signFramework(environment, frameworkBinary, buildMode);
}
}
/// Build a debug iOS application bundle.
class DebugIosApplicationBundle extends IosAssetBundle {
const DebugIosApplicationBundle();
@override
String get name => 'debug_ios_bundle_flutter_assets';
@override
List<Source> get inputs => <Source>[
const Source.artifact(Artifact.vmSnapshotData, mode: BuildMode.debug),
const Source.artifact(Artifact.isolateSnapshotData, mode: BuildMode.debug),
const Source.pattern('{BUILD_DIR}/app.dill'),
...super.inputs,
];
@override
List<Source> get outputs => <Source>[
const Source.pattern('{OUTPUT_DIR}/App.framework/flutter_assets/vm_snapshot_data'),
const Source.pattern('{OUTPUT_DIR}/App.framework/flutter_assets/isolate_snapshot_data'),
const Source.pattern('{OUTPUT_DIR}/App.framework/flutter_assets/kernel_blob.bin'),
...super.outputs,
];
@override
List<Target> get dependencies => <Target>[
const DebugUniversalFramework(),
...super.dependencies,
];
}
/// IosAssetBundle with debug symbols, used for Profile and Release builds.
abstract class _IosAssetBundleWithDSYM extends IosAssetBundle {
const _IosAssetBundleWithDSYM();
@override
List<Source> get inputs => <Source>[
...super.inputs,
const Source.pattern('{BUILD_DIR}/App.framework.dSYM/Contents/Resources/DWARF/App'),
];
@override
List<Source> get outputs => <Source>[
...super.outputs,
const Source.pattern('{OUTPUT_DIR}/App.framework.dSYM/Contents/Resources/DWARF/App'),
];
}
/// Build a profile iOS application bundle.
class ProfileIosApplicationBundle extends _IosAssetBundleWithDSYM {
const ProfileIosApplicationBundle();
@override
String get name => 'profile_ios_bundle_flutter_assets';
@override
List<Target> get dependencies => const <Target>[
AotAssemblyProfile(),
];
}
/// Build a release iOS application bundle.
class ReleaseIosApplicationBundle extends _IosAssetBundleWithDSYM {
const ReleaseIosApplicationBundle();
@override
String get name => 'release_ios_bundle_flutter_assets';
@override
List<Target> get dependencies => const <Target>[
AotAssemblyRelease(),
];
@override
Future<void> build(Environment environment) async {
bool buildSuccess = true;
try {
await super.build(environment);
} catch (_) { // ignore: avoid_catches_without_on_clauses
buildSuccess = false;
rethrow;
} finally {
// Send a usage event when the app is being archived.
// Since assemble is run during a `flutter build`/`run` as well as an out-of-band
// archive command from Xcode, this is a more accurate count than `flutter build ipa` alone.
if (environment.defines[kXcodeAction]?.toLowerCase() == 'install') {
environment.logger.printTrace('Sending archive event if usage enabled.');
UsageEvent(
'assemble',
'ios-archive',
label: buildSuccess ? 'success' : 'fail',
flutterUsage: environment.usage,
).send();
environment.analytics.send(Event.appleUsageEvent(
workflow: 'assemble',
parameter: 'ios-archive',
result: buildSuccess ? 'success' : 'fail',
));
}
}
}
}
/// Create an App.framework for debug iOS targets.
///
/// This framework needs to exist for the Xcode project to link/bundle,
/// but it isn't actually executed. To generate something valid, we compile a trivial
/// constant.
Future<void> _createStubAppFramework(File outputFile, Environment environment,
Set<String>? iosArchNames, String sdkRoot) async {
try {
outputFile.createSync(recursive: true);
} on Exception catch (e) {
throwToolExit('Failed to create App.framework stub at ${outputFile.path}: $e');
}
final FileSystem fileSystem = environment.fileSystem;
final Directory tempDir = fileSystem.systemTempDirectory
.createTempSync('flutter_tools_stub_source.');
try {
final File stubSource = tempDir.childFile('debug_app.cc')
..writeAsStringSync(r'''
static const int Moo = 88;
''');
final EnvironmentType? environmentType = environmentTypeFromSdkroot(sdkRoot, fileSystem);
await globals.xcode!.clang(<String>[
'-x',
'c',
for (final String arch in iosArchNames ?? <String>{}) ...<String>['-arch', arch],
stubSource.path,
'-dynamiclib',
// Keep version in sync with AOTSnapshotter flag
if (environmentType == EnvironmentType.physical)
'-miphoneos-version-min=12.0'
else
'-miphonesimulator-version-min=12.0',
'-Xlinker', '-rpath', '-Xlinker', '@executable_path/Frameworks',
'-Xlinker', '-rpath', '-Xlinker', '@loader_path/Frameworks',
'-fapplication-extension',
'-install_name', '@rpath/App.framework/App',
'-isysroot', sdkRoot,
'-o', outputFile.path,
]);
} finally {
try {
tempDir.deleteSync(recursive: true);
} on FileSystemException {
// Best effort. Sometimes we can't delete things from system temp.
} on Exception catch (e) {
throwToolExit('Failed to create App.framework stub at ${outputFile.path}: $e');
}
}
await _signFramework(environment, outputFile, BuildMode.debug);
}
Future<void> _signFramework(Environment environment, File binary, BuildMode buildMode) async {
await removeFinderExtendedAttributes(
binary,
ProcessUtils(processManager: environment.processManager, logger: environment.logger),
environment.logger,
);
String? codesignIdentity = environment.defines[kCodesignIdentity];
if (codesignIdentity == null || codesignIdentity.isEmpty) {
codesignIdentity = '-';
}
final ProcessResult result = environment.processManager.runSync(<String>[
'codesign',
'--force',
'--sign',
codesignIdentity,
if (buildMode != BuildMode.release) ...<String>[
// Mimic Xcode's timestamp codesigning behavior on non-release binaries.
'--timestamp=none',
],
binary.path,
]);
if (result.exitCode != 0) {
final String stdout = (result.stdout as String).trim();
final String stderr = (result.stderr as String).trim();
final StringBuffer output = StringBuffer();
output.writeln('Failed to codesign ${binary.path} with identity $codesignIdentity.');
if (stdout.isNotEmpty) {
output.writeln(stdout);
}
if (stderr.isNotEmpty) {
output.writeln(stderr);
}
throw Exception(output.toString());
}
}
| flutter/packages/flutter_tools/lib/src/build_system/targets/ios.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/build_system/targets/ios.dart",
"repo_id": "flutter",
"token_count": 8578
} | 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 'package:args/args.dart';
import 'package:meta/meta.dart';
import 'package:process/process.dart';
import 'package:yaml/yaml.dart' as yaml;
import '../artifacts.dart';
import '../base/common.dart';
import '../base/file_system.dart';
import '../base/logger.dart';
import '../base/platform.dart';
import '../base/terminal.dart';
import '../base/utils.dart';
import '../cache.dart';
import '../globals.dart' as globals;
/// Common behavior for `flutter analyze` and `flutter analyze --watch`
abstract class AnalyzeBase {
AnalyzeBase(this.argResults, {
required this.repoPackages,
required this.fileSystem,
required this.logger,
required this.platform,
required this.processManager,
required this.terminal,
required this.artifacts,
required this.suppressAnalytics,
});
/// The parsed argument results for execution.
final ArgResults argResults;
@protected
final List<Directory> repoPackages;
@protected
final FileSystem fileSystem;
@protected
final Logger logger;
@protected
final ProcessManager processManager;
@protected
final Platform platform;
@protected
final Terminal terminal;
@protected
final Artifacts artifacts;
@protected
final bool suppressAnalytics;
@protected
String get flutterRoot => globals.fs.path.absolute(Cache.flutterRoot!);
/// Called by [AnalyzeCommand] to start the analysis process.
Future<void> analyze();
void dumpErrors(Iterable<String> errors) {
if (argResults['write'] != null) {
try {
final RandomAccessFile resultsFile = fileSystem.file(argResults['write']).openSync(mode: FileMode.write);
try {
resultsFile.lockSync();
resultsFile.writeStringSync(errors.join('\n'));
} finally {
resultsFile.close();
}
} on Exception catch (e) {
logger.printError('Failed to save output to "${argResults['write']}": $e');
}
}
}
void writeBenchmark(Stopwatch stopwatch, int errorCount) {
const String benchmarkOut = 'analysis_benchmark.json';
final Map<String, dynamic> data = <String, dynamic>{
'time': stopwatch.elapsedMilliseconds / 1000.0,
'issues': errorCount,
};
fileSystem.file(benchmarkOut).writeAsStringSync(toPrettyJson(data));
logger.printStatus('Analysis benchmark written to $benchmarkOut ($data).');
}
bool get isFlutterRepo => argResults['flutter-repo'] as bool;
String get sdkPath {
final String? dartSdk = argResults['dart-sdk'] as String?;
return dartSdk ?? artifacts.getArtifactPath(Artifact.engineDartSdkPath);
}
bool get isBenchmarking => argResults['benchmark'] as bool;
String? get protocolTrafficLog => argResults['protocol-traffic-log'] as String?;
/// Generate an analysis summary for both [AnalyzeOnce], [AnalyzeContinuously].
static String generateErrorsMessage({
required int issueCount,
int? issueDiff,
int? files,
required String seconds,
}) {
final StringBuffer errorsMessage = StringBuffer(issueCount > 0
? '$issueCount ${pluralize('issue', issueCount)} found.'
: 'No issues found!');
// Only [AnalyzeContinuously] has issueDiff message.
if (issueDiff != null) {
if (issueDiff > 0) {
errorsMessage.write(' ($issueDiff new)');
} else if (issueDiff < 0) {
errorsMessage.write(' (${-issueDiff} fixed)');
}
}
// Only [AnalyzeContinuously] has files message.
if (files != null) {
errorsMessage.write(' • analyzed $files ${pluralize('file', files)}');
}
errorsMessage.write(' (ran in ${seconds}s)');
return errorsMessage.toString();
}
}
class PackageDependency {
// This is a map from dependency targets (lib directories) to a list
// of places that ask for that target (.packages or pubspec.yaml files)
Map<String, List<String>> values = <String, List<String>>{};
String? canonicalSource;
void addCanonicalCase(String packagePath, String pubSpecYamlPath) {
assert(canonicalSource == null);
add(packagePath, pubSpecYamlPath);
canonicalSource = pubSpecYamlPath;
}
void add(String packagePath, String sourcePath) {
values.putIfAbsent(packagePath, () => <String>[]).add(sourcePath);
}
bool get hasConflict => values.length > 1;
bool get hasConflictAffectingFlutterRepo {
final String? flutterRoot = Cache.flutterRoot;
assert(flutterRoot != null && globals.fs.path.isAbsolute(flutterRoot));
for (final List<String> targetSources in values.values) {
for (final String source in targetSources) {
assert(globals.fs.path.isAbsolute(source));
if (globals.fs.path.isWithin(flutterRoot!, source)) {
return true;
}
}
}
return false;
}
void describeConflict(StringBuffer result) {
assert(hasConflict);
final List<String> targets = values.keys.toList();
targets.sort((String a, String b) => values[b]!.length.compareTo(values[a]!.length));
for (final String target in targets) {
final List<String> targetList = values[target]!;
final int count = targetList.length;
result.writeln(' $count ${count == 1 ? 'source wants' : 'sources want'} "$target":');
bool canonical = false;
for (final String source in targetList) {
result.writeln(' $source');
if (source == canonicalSource) {
canonical = true;
}
}
if (canonical) {
result.writeln(' (This is the actual package definition, so it is considered the canonical "right answer".)');
}
}
}
String get target => values.keys.single;
}
class PackageDependencyTracker {
/// Packages whose source is defined in the vended SDK.
static const List<String> _vendedSdkPackages = <String>['analyzer', 'front_end', 'kernel'];
// This is a map from package names to objects that track the paths
// involved (sources and targets).
Map<String, PackageDependency> packages = <String, PackageDependency>{};
PackageDependency getPackageDependency(String packageName) {
return packages.putIfAbsent(packageName, () => PackageDependency());
}
/// Read the .packages file in [directory] and add referenced packages to [dependencies].
void addDependenciesFromPackagesFileIn(Directory directory) {
final String dotPackagesPath = globals.fs.path.join(directory.path, '.packages');
final File dotPackages = globals.fs.file(dotPackagesPath);
if (dotPackages.existsSync()) {
// this directory has opinions about what we should be using
final Iterable<String> lines = dotPackages
.readAsStringSync()
.split('\n')
.where((String line) => !line.startsWith(RegExp(r'^ *#')));
for (final String line in lines) {
final int colon = line.indexOf(':');
if (colon > 0) {
final String packageName = line.substring(0, colon);
final String packagePath = globals.fs.path.fromUri(line.substring(colon+1));
// Ensure that we only add `analyzer` and dependent packages defined in the vended SDK (and referred to with a local
// globals.fs.path. directive). Analyzer package versions reached via transitive dependencies (e.g., via `test`) are ignored
// since they would produce spurious conflicts.
if (!_vendedSdkPackages.contains(packageName) || packagePath.startsWith('..')) {
add(packageName, globals.fs.path.normalize(globals.fs.path.absolute(directory.path, packagePath)), dotPackagesPath);
}
}
}
}
}
void addCanonicalCase(String packageName, String packagePath, String pubSpecYamlPath) {
getPackageDependency(packageName).addCanonicalCase(packagePath, pubSpecYamlPath);
}
void add(String packageName, String packagePath, String dotPackagesPath) {
getPackageDependency(packageName).add(packagePath, dotPackagesPath);
}
void checkForConflictingDependencies(Iterable<Directory> pubSpecDirectories, PackageDependencyTracker dependencies) {
for (final Directory directory in pubSpecDirectories) {
final String pubSpecYamlPath = globals.fs.path.join(directory.path, 'pubspec.yaml');
final File pubSpecYamlFile = globals.fs.file(pubSpecYamlPath);
if (pubSpecYamlFile.existsSync()) {
// we are analyzing the actual canonical source for this package;
// make sure we remember that, in case all the packages are actually
// pointing elsewhere somehow.
final dynamic pubSpecYaml = yaml.loadYaml(globals.fs.file(pubSpecYamlPath).readAsStringSync());
if (pubSpecYaml is yaml.YamlMap) {
final dynamic packageName = pubSpecYaml['name'];
if (packageName is String) {
final String packagePath = globals.fs.path.normalize(globals.fs.path.absolute(globals.fs.path.join(directory.path, 'lib')));
dependencies.addCanonicalCase(packageName, packagePath, pubSpecYamlPath);
} else {
throwToolExit('pubspec.yaml is malformed. The name should be a String.');
}
} else {
throwToolExit('pubspec.yaml is malformed.');
}
}
dependencies.addDependenciesFromPackagesFileIn(directory);
}
// prepare a union of all the .packages files
if (dependencies.hasConflicts) {
final StringBuffer message = StringBuffer();
message.writeln(dependencies.generateConflictReport());
message.writeln('Make sure you have run "pub upgrade" in all the directories mentioned above.');
if (dependencies.hasConflictsAffectingFlutterRepo) {
message.writeln(
'For packages in the flutter repository, try using "flutter update-packages" to do all of them at once.\n'
'If you need to actually upgrade them, consider "flutter update-packages --force-upgrade". '
'(This will update your pubspec.yaml files as well, so you may wish to do this on a separate branch.)'
);
}
message.write(
'If this does not help, to track down the conflict you can use '
'"pub deps --style=list" and "pub upgrade --verbosity=solver" in the affected directories.'
);
throwToolExit(message.toString());
}
}
bool get hasConflicts {
return packages.values.any((PackageDependency dependency) => dependency.hasConflict);
}
bool get hasConflictsAffectingFlutterRepo {
return packages.values.any((PackageDependency dependency) => dependency.hasConflictAffectingFlutterRepo);
}
String generateConflictReport() {
assert(hasConflicts);
final StringBuffer result = StringBuffer();
packages.forEach((String package, PackageDependency dependency) {
if (dependency.hasConflict) {
result.writeln('Package "$package" has conflicts:');
dependency.describeConflict(result);
}
});
return result.toString();
}
Map<String, String> asPackageMap() {
final Map<String, String> result = <String, String>{};
packages.forEach((String package, PackageDependency dependency) {
result[package] = dependency.target;
});
return result;
}
}
/// Find directories or files from argResults.rest.
Set<String> findDirectories(ArgResults argResults, FileSystem fileSystem) {
final Set<String> items = Set<String>.of(argResults.rest
.map<String>((String path) => fileSystem.path.canonicalize(path)));
if (items.isNotEmpty) {
for (final String item in items) {
final FileSystemEntityType type = fileSystem.typeSync(item);
if (type == FileSystemEntityType.notFound) {
throwToolExit("You provided the path '$item', however it does not exist on disk");
}
}
}
return items;
}
| flutter/packages/flutter_tools/lib/src/commands/analyze_base.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/commands/analyze_base.dart",
"repo_id": "flutter",
"token_count": 4126
} | 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.
import 'package:file/file.dart';
import '../artifacts.dart';
import '../base/common.dart';
import '../base/io.dart';
import '../base/process.dart';
import '../build_info.dart';
import '../cache.dart';
import '../globals.dart' as globals;
import '../project.dart';
import '../runner/flutter_command.dart' show FlutterCommandResult;
import '../windows/build_windows.dart';
import 'build.dart';
class BuildPreviewCommand extends BuildSubCommand {
BuildPreviewCommand({
required super.logger,
required super.verboseHelp,
required this.fs,
required this.flutterRoot,
required this.processUtils,
required this.artifacts,
});
@override
final String name = '_preview';
@override
final bool hidden = true;
@override
Future<Set<DevelopmentArtifact>> get requiredArtifacts async => <DevelopmentArtifact>{
DevelopmentArtifact.windows,
};
@override
final String description = 'Build Flutter preview (desktop) app.';
final FileSystem fs;
final String flutterRoot;
final ProcessUtils processUtils;
final Artifacts artifacts;
static const BuildInfo buildInfo = BuildInfo(
BuildMode.debug,
null, // no flavor
// users may add icons later
treeShakeIcons: false,
);
@override
void requiresPubspecYaml() {}
static const String appName = 'flutter_preview';
@override
Future<FlutterCommandResult> runCommand() async {
if (!globals.platform.isWindows) {
throwToolExit('"build _preview" is currently only supported on Windows hosts.');
}
final Directory targetDir = fs.systemTempDirectory.createTempSync('flutter-build-preview');
try {
final FlutterProject flutterProject = await _createProject(targetDir);
// TODO(loic-sharma): Support windows-arm64 preview device, https://github.com/flutter/flutter/issues/139949.
await buildWindows(
flutterProject.windows,
buildInfo,
TargetPlatform.windows_x64,
);
final File previewDevice = targetDir
.childDirectory(getWindowsBuildDirectory(TargetPlatform.windows_x64))
.childDirectory('runner')
.childDirectory('Debug')
.childFile('$appName.exe');
if (!previewDevice.existsSync()) {
throw StateError('Preview device not found at ${previewDevice.absolute.path}');
}
final String newPath = artifacts.getArtifactPath(Artifact.flutterPreviewDevice);
fs.file(newPath).parent.createSync(recursive: true);
previewDevice.copySync(newPath);
return FlutterCommandResult.success();
} finally {
try {
targetDir.deleteSync(recursive: true);
} on FileSystemException catch (exception) {
logger.printError('Failed to delete ${targetDir.path}\n\n$exception');
}
}
}
Future<FlutterProject> _createProject(Directory targetDir) async {
final List<String> cmd = <String>[
fs.path.join(flutterRoot, 'bin', 'flutter.bat'),
'create',
'--empty',
'--project-name',
'flutter_preview',
targetDir.path,
];
final RunResult result = await processUtils.run(
cmd,
allowReentrantFlutter: true,
);
if (result.exitCode != 0) {
final StringBuffer buffer = StringBuffer('${cmd.join(' ')} exited with code ${result.exitCode}\n');
buffer.writeln('stdout:\n${result.stdout}\n');
buffer.writeln('stderr:\n${result.stderr}');
throw ProcessException(cmd.first, cmd.sublist(1), buffer.toString(), result.exitCode);
}
return FlutterProject.fromDirectory(targetDir);
}
}
| flutter/packages/flutter_tools/lib/src/commands/build_preview.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/commands/build_preview.dart",
"repo_id": "flutter",
"token_count": 1318
} | 742 |
// 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 '../globals.dart' as globals;
import '../runner/flutter_command.dart';
class GenerateCommand extends FlutterCommand {
GenerateCommand() {
usesTargetOption();
}
@override
String get description => 'run code generators.';
@override
String get name => 'generate';
@override
bool get hidden => true;
@override
Future<FlutterCommandResult> runCommand() async {
globals.printError(
'"flutter generate" is deprecated, use "dart pub run build_runner" instead. '
'The following dependencies must be added to dev_dependencies in pubspec.yaml:\n'
'build_runner: ^1.10.0\n'
'including all dependencies under the "builders" key'
);
return FlutterCommandResult.fail();
}
}
| flutter/packages/flutter_tools/lib/src/commands/generate.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/commands/generate.dart",
"repo_id": "flutter",
"token_count": 288
} | 743 |
// 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 '../base/file_system.dart';
import '../base/logger.dart';
import '../project.dart';
import '../project_validator.dart';
import '../project_validator_result.dart';
import '../runner/flutter_command.dart';
class ValidateProject {
ValidateProject({
required this.fileSystem,
required this.logger,
required this.allProjectValidators,
required this.userPath,
required this.processManager,
this.verbose = false,
this.machine = false,
});
final FileSystem fileSystem;
final Logger logger;
final bool verbose;
final bool machine;
final String userPath;
final List<ProjectValidator> allProjectValidators;
final ProcessManager processManager;
Future<FlutterCommandResult> run() async {
final Directory workingDirectory = userPath.isEmpty ? fileSystem.currentDirectory : fileSystem.directory(userPath);
final FlutterProject project = FlutterProject.fromDirectory(workingDirectory);
final Map<ProjectValidator, Future<List<ProjectValidatorResult>>> results = <ProjectValidator, Future<List<ProjectValidatorResult>>>{};
bool hasCrash = false;
for (final ProjectValidator validator in allProjectValidators) {
if (validator.machineOutput != machine) {
continue;
}
if (!results.containsKey(validator) && validator.supportsProject(project)) {
results[validator] = validator
.start(project)
.then(
(List<ProjectValidatorResult> results) => results,
onError: (Object exception, StackTrace trace) {
hasCrash = true;
return <ProjectValidatorResult>[
ProjectValidatorResult.crash(exception, trace),
];
},
);
}
}
final StringBuffer buffer = StringBuffer();
if (machine) {
// Print properties
buffer.write('{\n');
for (final Future<List<ProjectValidatorResult>> resultListFuture in results.values) {
final List<ProjectValidatorResult> resultList = await resultListFuture;
int count = 0;
for (final ProjectValidatorResult result in resultList) {
count++;
buffer.write(' "${result.name}": ${result.value}${count < resultList.length ? ',' : ''}\n');
}
}
buffer.write('}');
logger.printStatus(buffer.toString());
} else {
final List<String> resultsString = <String>[];
for (final ProjectValidator validator in results.keys) {
if (results[validator] != null) {
resultsString.add(validator.title);
addResultString(validator.title, await results[validator], resultsString);
}
}
buffer.writeAll(resultsString, '\n');
logger.printBox(buffer.toString());
}
if (hasCrash) {
return const FlutterCommandResult(ExitStatus.fail);
}
return const FlutterCommandResult(ExitStatus.success);
}
void addResultString(final String title, final List<ProjectValidatorResult>? results, final List<String> resultsString) {
if (results != null) {
for (final ProjectValidatorResult result in results) {
resultsString.add(getStringResult(result));
}
}
}
String getStringResult(ProjectValidatorResult result) {
final String icon;
switch (result.status) {
case StatusProjectValidator.error:
icon = '[✗]';
case StatusProjectValidator.info:
case StatusProjectValidator.success:
icon = '[✓]';
case StatusProjectValidator.warning:
icon = '[!]';
case StatusProjectValidator.crash:
icon = '[☠]';
}
return '$icon $result';
}
}
| flutter/packages/flutter_tools/lib/src/commands/validate_project.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/commands/validate_project.dart",
"repo_id": "flutter",
"token_count": 1424
} | 744 |
// 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;
typedef _OutputSender = void Function(String category, String message, {bool? parseStackFrames, int? variablesReference});
/// A formatter for improving the display of Flutter structured errors over DAP.
///
/// The formatter deserializes a `Flutter.Error` event and produces output
/// similar to the `renderedErrorText` field, but may include ansi color codes
/// to provide improved formatting (such as making stack frames from non-user
/// code faint) if the client indicated support.
///
/// Lines that look like stack frames will be marked so they can be parsed by
/// the base adapter and attached as [Source]s to allow them to be clickable
/// in the client.
class FlutterErrorFormatter {
final List<_BatchedOutput> batchedOutput = <_BatchedOutput>[];
/// Formats a Flutter error.
///
/// If this is not the first error since the reload, only a summary will be
/// included.
void formatError(Map<String, Object?> errorData) {
final _ErrorData data = _ErrorData(errorData);
const int assumedTerminalSize = 80;
const String barChar = '═';
final String headerPrefix = barChar * 8;
final String headerSuffix = barChar * math.max( assumedTerminalSize - (data.description?.length ?? 0) - 2 - headerPrefix.length, 0);
final String header = '$headerPrefix ${data.description} $headerSuffix';
_write('');
_write(header, isError: true);
if (data.errorsSinceReload == 0) {
data.properties.forEach(_writeNode);
data.children.forEach(_writeNode);
} else {
data.properties.forEach(_writeSummary);
}
_write(barChar * header.length, isError: true);
}
/// Sends all collected output through [sendOutput].
void sendOutput(_OutputSender sendOutput) {
for (final _BatchedOutput output in batchedOutput) {
sendOutput(
output.isError ? 'stderr' : 'stdout',
output.output,
parseStackFrames: output.parseStackFrames,
);
}
}
/// Writes [text] to the output.
///
/// If the last item in the batch has the same settings as this item, it will
/// be appended to the same item, otherwise a new item will be added to the
/// batch.
void _write(
String? text, {
int indent = 0,
bool isError = false,
bool parseStackFrames = false,
}) {
if (text != null) {
final String indentString = ' ' * indent;
final String message = '$indentString${text.trim()}';
_BatchedOutput? output = batchedOutput.lastOrNull;
if (output == null || output.isError != isError || output.parseStackFrames != parseStackFrames) {
batchedOutput.add(output = _BatchedOutput(isError, parseStackFrames: parseStackFrames));
}
output.writeln(message);
}
}
/// Writes [node] to the output using [indent], recursing unless [recursive]
/// is `false`.
void _writeNode(_ErrorNode node, {int indent = 0, bool recursive = true}) {
// Errors, summaries and lines starting "Exception:" are marked as errors so
// they go to stderr instead of stdout (this may cause the client to colour
// them like errors).
final bool showAsError = node.level == _DiagnosticsNodeLevel.error ||
node.level == _DiagnosticsNodeLevel.summary ||
(node.description?.startsWith('Exception: ') ?? false);
if (node.showName && node.name != null) {
_write('${node.name}: ${node.description}', indent: indent, isError: showAsError);
} else if (node.description?.startsWith('#') ?? false) {
// Possible stack frame.
_write(node.description, indent: indent, isError: showAsError, parseStackFrames: true);
} else {
_write(node.description, indent: indent, isError: showAsError);
}
if (recursive) {
if (node.style != _DiagnosticsNodeStyle.flat) {
indent++;
}
_writeNodes(node.properties, indent: indent);
_writeNodes(node.children, indent: indent);
}
}
/// Writes [nodes] to the output.
void _writeNodes(List<_ErrorNode> nodes, {int indent = 0, bool recursive = true}) {
for (final _ErrorNode child in nodes) {
_writeNode(child, indent: indent, recursive: recursive);
}
}
/// Writes a simple summary of [node] to the output.
void _writeSummary(_ErrorNode node) {
final bool allChildrenAreLeaf = node.children.isNotEmpty &&
!node.children.any((_ErrorNode child) => child.children.isNotEmpty);
if (node.level == _DiagnosticsNodeLevel.summary || allChildrenAreLeaf) {
_writeNode(node, recursive: false);
}
}
}
/// A container for output to be sent to the client.
///
/// When multiple lines are being sent, they may be written to the same batch
/// if the output options (error/stackFrame) are the same.
class _BatchedOutput {
_BatchedOutput(this.isError, {this.parseStackFrames = false});
final bool isError;
final bool parseStackFrames;
final StringBuffer _buffer = StringBuffer();
String get output => _buffer.toString();
void writeln(String output) => _buffer.writeln(output);
}
enum _DiagnosticsNodeLevel {
error,
summary,
}
enum _DiagnosticsNodeStyle {
flat,
}
class _ErrorData extends _ErrorNode {
_ErrorData(super.data);
int get errorsSinceReload => data['errorsSinceReload'] as int? ?? 0;
String get renderedErrorText => data['renderedErrorText'] as String? ?? '';
}
class _ErrorNode {
_ErrorNode(this.data);
final Map<Object, Object?> data;
List<_ErrorNode> get children => asList('children', _ErrorNode.new);
String? get description => asString('description');
_DiagnosticsNodeLevel? get level => asEnum('level', _DiagnosticsNodeLevel.values);
String? get name => asString('name');
List<_ErrorNode> get properties => asList('properties', _ErrorNode.new);
bool get showName => data['showName'] != false;
_DiagnosticsNodeStyle? get style => asEnum('style', _DiagnosticsNodeStyle.values);
String? asString(String field) {
final Object? value = data[field];
return value is String ? value : null;
}
T? asEnum<T extends Enum>(String field, Iterable<T> enumValues) {
final String? value = asString(field);
return value != null ? enumValues.asNameMap()[value] : null;
}
List<T> asList<T>(String field, T Function(Map<Object, Object?>) constructor) {
final Object? objects = data[field];
return objects is List && objects.every((Object? element) => element is Map<String, Object?>)
? objects.cast<Map<Object, Object?>>().map(constructor).toList()
: <T>[];
}
}
| flutter/packages/flutter_tools/lib/src/debug_adapters/error_formatter.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/debug_adapters/error_formatter.dart",
"repo_id": "flutter",
"token_count": 2186
} | 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 'dart:math' as math;
import 'package:meta/meta.dart';
import 'package:process/process.dart';
import 'android/android_emulator.dart';
import 'android/android_sdk.dart';
import 'android/android_workflow.dart';
import 'android/java.dart';
import 'base/context.dart';
import 'base/file_system.dart';
import 'base/logger.dart';
import 'base/process.dart';
import 'device.dart';
import 'ios/ios_emulators.dart';
EmulatorManager? get emulatorManager => context.get<EmulatorManager>();
/// A class to get all available emulators.
class EmulatorManager {
EmulatorManager({
required Java? java,
AndroidSdk? androidSdk,
required Logger logger,
required ProcessManager processManager,
required AndroidWorkflow androidWorkflow,
required FileSystem fileSystem,
}) : _java = java,
_androidSdk = androidSdk,
_processUtils = ProcessUtils(logger: logger, processManager: processManager),
_androidEmulators = AndroidEmulators(
androidSdk: androidSdk,
logger: logger,
processManager: processManager,
fileSystem: fileSystem,
androidWorkflow: androidWorkflow
) {
_emulatorDiscoverers.add(_androidEmulators);
}
final Java? _java;
final AndroidSdk? _androidSdk;
final AndroidEmulators _androidEmulators;
final ProcessUtils _processUtils;
// Constructing EmulatorManager is cheap; they only do expensive work if some
// of their methods are called.
final List<EmulatorDiscovery> _emulatorDiscoverers = <EmulatorDiscovery>[
IOSEmulators(),
];
Future<List<Emulator>> getEmulatorsMatching(String searchText) async {
final List<Emulator> emulators = await getAllAvailableEmulators();
searchText = searchText.toLowerCase();
bool exactlyMatchesEmulatorId(Emulator emulator) =>
emulator.id.toLowerCase() == searchText ||
emulator.name.toLowerCase() == searchText;
bool startsWithEmulatorId(Emulator emulator) =>
emulator.id.toLowerCase().startsWith(searchText) ||
emulator.name.toLowerCase().startsWith(searchText);
Emulator? exactMatch;
for (final Emulator emulator in emulators) {
if (exactlyMatchesEmulatorId(emulator)) {
exactMatch = emulator;
break;
}
}
if (exactMatch != null) {
return <Emulator>[exactMatch];
}
// Match on a id or name starting with [emulatorId].
return emulators.where(startsWithEmulatorId).toList();
}
Iterable<EmulatorDiscovery> get _platformDiscoverers {
return _emulatorDiscoverers.where((EmulatorDiscovery discoverer) => discoverer.supportsPlatform);
}
/// Return the list of all available emulators.
Future<List<Emulator>> getAllAvailableEmulators() async {
final List<Emulator> emulators = <Emulator>[];
await Future.forEach<EmulatorDiscovery>(_platformDiscoverers, (EmulatorDiscovery discoverer) async {
emulators.addAll(await discoverer.emulators);
});
return emulators;
}
/// Return the list of all available emulators.
Future<CreateEmulatorResult> createEmulator({ String? name }) async {
if (name == null || name.isEmpty) {
const String autoName = 'flutter_emulator';
// Don't use getEmulatorsMatching here, as it will only return one
// if there's an exact match and we need all those with this prefix
// so we can keep adding suffixes until we miss.
final List<Emulator> all = await getAllAvailableEmulators();
final Set<String> takenNames = all
.map<String>((Emulator e) => e.id)
.where((String id) => id.startsWith(autoName))
.toSet();
int suffix = 1;
name = autoName;
while (takenNames.contains(name)) {
name = '${autoName}_${++suffix}';
}
}
final String emulatorName = name!;
final String? avdManagerPath = _androidSdk?.avdManagerPath;
if (avdManagerPath == null || !_androidEmulators.canLaunchAnything) {
return CreateEmulatorResult(emulatorName,
success: false, error: 'avdmanager is missing from the Android SDK'
);
}
final String? device = await _getPreferredAvailableDevice(avdManagerPath);
if (device == null) {
return CreateEmulatorResult(emulatorName,
success: false, error: 'No device definitions are available');
}
final String? sdkId = await _getPreferredSdkId(avdManagerPath);
if (sdkId == null) {
return CreateEmulatorResult(emulatorName,
success: false,
error:
'No suitable Android AVD system images are available. You may need to install these'
' using sdkmanager, for example:\n'
' sdkmanager "system-images;android-27;google_apis_playstore;x86"');
}
// Cleans up error output from avdmanager to make it more suitable to show
// to flutter users. Specifically:
// - Removes lines that say "null" (!)
// - Removes lines that tell the user to use '--force' to overwrite emulators
String? cleanError(String? error) {
if (error == null || error.trim() == '') {
return null;
}
return error
.split('\n')
.where((String l) => l.trim() != 'null')
.where((String l) =>
l.trim() != 'Use --force if you want to replace it.')
.join('\n')
.trim();
}
final RunResult runResult = await _processUtils.run(<String>[
avdManagerPath,
'create',
'avd',
'-n', emulatorName,
'-k', sdkId,
'-d', device,
], environment: _java?.environment,
);
return CreateEmulatorResult(
emulatorName,
success: runResult.exitCode == 0,
output: runResult.stdout,
error: cleanError(runResult.stderr),
);
}
static const List<String> preferredDevices = <String>[
'pixel',
'pixel_xl',
];
Future<String?> _getPreferredAvailableDevice(String avdManagerPath) async {
final List<String> args = <String>[
avdManagerPath,
'list',
'device',
'-c',
];
final RunResult runResult = await _processUtils.run(args,
environment: _java?.environment);
if (runResult.exitCode != 0) {
return null;
}
final List<String> availableDevices = runResult.stdout
.split('\n')
.where((String l) => preferredDevices.contains(l.trim()))
.toList();
for (final String device in preferredDevices) {
if (availableDevices.contains(device)) {
return device;
}
}
return null;
}
static final RegExp _androidApiVersion = RegExp(r';android-(\d+);');
Future<String?> _getPreferredSdkId(String avdManagerPath) async {
// It seems that to get the available list of images, we need to send a
// request to create without the image and it'll provide us a list :-(
final List<String> args = <String>[
avdManagerPath,
'create',
'avd',
'-n', 'temp',
];
final RunResult runResult = await _processUtils.run(args,
environment: _java?.environment);
// Get the list of IDs that match our criteria
final List<String> availableIDs = runResult.stderr
.split('\n')
.where((String l) => _androidApiVersion.hasMatch(l))
.where((String l) => l.contains('system-images'))
.where((String l) => l.contains('google_apis_playstore'))
.toList();
final List<int> availableApiVersions = availableIDs
.map<String>((String id) => _androidApiVersion.firstMatch(id)!.group(1)!)
.map<int>((String apiVersion) => int.parse(apiVersion))
.toList();
// Get the highest Android API version or whats left
final int apiVersion = availableApiVersions.isNotEmpty
? availableApiVersions.reduce(math.max)
: -1; // Don't match below
// We're out of preferences, we just have to return the first one with the high
// API version.
for (final String id in availableIDs) {
if (id.contains(';android-$apiVersion;')) {
return id;
}
}
return null;
}
/// Whether we're capable of listing any emulators given the current environment configuration.
bool get canListAnything {
return _platformDiscoverers.any((EmulatorDiscovery discoverer) => discoverer.canListAnything);
}
}
/// An abstract class to discover and enumerate a specific type of emulators.
abstract class EmulatorDiscovery {
bool get supportsPlatform;
/// Whether this emulator discovery is capable of listing any emulators.
bool get canListAnything;
/// Whether this emulator discovery is capable of launching new emulators.
bool get canLaunchAnything;
Future<List<Emulator>> get emulators;
}
@immutable
abstract class Emulator {
const Emulator(this.id, this.hasConfig);
final String id;
final bool hasConfig;
String get name;
String? get manufacturer;
Category get category;
PlatformType get platformType;
@override
int get hashCode => id.hashCode;
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
return other is Emulator
&& other.id == id;
}
Future<void> launch({bool coldBoot});
@override
String toString() => name;
static List<String> descriptions(List<Emulator> emulators) {
if (emulators.isEmpty) {
return <String>[];
}
const List<String> tableHeader = <String>[
'Id',
'Name',
'Manufacturer',
'Platform',
];
// Extract emulators information
final List<List<String>> table = <List<String>>[
tableHeader,
for (final Emulator emulator in emulators)
<String>[
emulator.id,
emulator.name,
emulator.manufacturer ?? '',
emulator.platformType.toString(),
],
];
// Calculate column widths
final List<int> indices = List<int>.generate(table[0].length - 1, (int i) => i);
List<int> widths = indices.map<int>((int i) => 0).toList();
for (final List<String> row in table) {
widths = indices.map<int>((int i) => math.max(widths[i], row[i].length)).toList();
}
// Join columns into lines of text
final RegExp whiteSpaceAndDots = RegExp(r'[•\s]+$');
return table
.map<String>((List<String> row) {
return indices
.map<String>((int i) => row[i].padRight(widths[i]))
.followedBy(<String>[row.last])
.join(' • ');
})
.map<String>((String line) => line.replaceAll(whiteSpaceAndDots, ''))
.toList();
}
static void printEmulators(List<Emulator> emulators, Logger logger) {
final List<String> emulatorDescriptions = descriptions(emulators);
// Prints the first description as the table header, followed by a newline.
logger.printStatus('${emulatorDescriptions.first}\n');
emulatorDescriptions.sublist(1).forEach(logger.printStatus);
}
}
class CreateEmulatorResult {
CreateEmulatorResult(this.emulatorName, {required this.success, this.output, this.error});
final bool success;
final String emulatorName;
final String? output;
final String? error;
}
| flutter/packages/flutter_tools/lib/src/emulator.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/emulator.dart",
"repo_id": "flutter",
"token_count": 4182
} | 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 '../base/process.dart';
import 'fuchsia_device.dart';
import 'fuchsia_pm.dart';
/// Simple wrapper for interacting with the 'pkgctl' tool running on the
/// Fuchsia device.
class FuchsiaPkgctl {
/// Teaches pkgctl on [device] about the Fuchsia package server
Future<bool> addRepo(
FuchsiaDevice device, FuchsiaPackageServer server) async {
final String localIp = await device.hostAddress;
final String configUrl = 'http://[$localIp]:${server.port}/config.json';
final RunResult result =
await device.shell('pkgctl repo add url -n ${server.name} $configUrl');
return result.exitCode == 0;
}
/// Instructs pkgctl instance running on [device] to forget about the
/// Fuchsia package server with the given name
/// pkgctl repo rm fuchsia-pkg://mycorp.com
Future<bool> rmRepo(FuchsiaDevice device, FuchsiaPackageServer server) async {
final RunResult result = await device.shell(
'pkgctl repo rm fuchsia-pkg://${server.name}',
);
return result.exitCode == 0;
}
/// Instructs the pkgctl instance running on [device] to prefetch the package
/// with the given [packageUrl] hosted in the given [serverName].
Future<bool> resolve(
FuchsiaDevice device,
String serverName,
String packageName,
) async {
final String packageUrl = 'fuchsia-pkg://$serverName/$packageName';
final RunResult result = await device.shell('pkgctl resolve $packageUrl');
return result.exitCode == 0;
}
}
| flutter/packages/flutter_tools/lib/src/fuchsia/pkgctl.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/fuchsia/pkgctl.dart",
"repo_id": "flutter",
"token_count": 527
} | 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 '../../base/file_system.dart';
import '../../base/project_migrator.dart';
import '../../xcode_project.dart';
// The Runner target should inherit its build configuration from Generated.xcconfig.
// However the top-level Runner project should not inherit any build configuration so
// the Flutter build settings do not stomp on non-Flutter targets.
class ProjectBaseConfigurationMigration extends ProjectMigrator {
ProjectBaseConfigurationMigration(IosProject project, super.logger)
: _xcodeProjectInfoFile = project.xcodeProjectInfoFile;
final File _xcodeProjectInfoFile;
@override
void migrate() {
if (!_xcodeProjectInfoFile.existsSync()) {
logger.printTrace('Xcode project not found, skipping Runner project build settings and configuration migration');
return;
}
final String originalProjectContents = _xcodeProjectInfoFile.readAsStringSync();
// Example:
//
// 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = {
// isa = XCConfigurationList;
// buildConfigurations = (
// 97C147031CF9000F007C1171 /* Debug */,
// 97C147041CF9000F007C1171 /* Release */,
// 2436755321828D23008C7051 /* Profile */,
// );
final RegExp projectBuildConfigurationList = RegExp(
r'\/\* Build configuration list for PBXProject "Runner" \*\/ = {\s*isa = XCConfigurationList;\s*buildConfigurations = \(\s*(.*) \/\* Debug \*\/,\s*(.*) \/\* Release \*\/,\s*(.*) \/\* Profile \*\/,',
multiLine: true,
);
final RegExpMatch? match = projectBuildConfigurationList.firstMatch(originalProjectContents);
// If the PBXProject "Runner" build configuration identifiers can't be parsed, default to the generated template identifiers.
final String debugIdentifier = match?.group(1) ?? '97C147031CF9000F007C117D';
final String releaseIdentifier = match?.group(2) ?? '97C147041CF9000F007C117D';
final String profileIdentifier = match?.group(3) ?? '249021D3217E4FDB00AE95B9';
// Debug
final String debugBaseConfigurationOriginal = '''
$debugIdentifier /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */;
''';
final String debugBaseConfigurationReplacement = '''
$debugIdentifier /* Debug */ = {
isa = XCBuildConfiguration;
''';
String newProjectContents = originalProjectContents.replaceAll(debugBaseConfigurationOriginal, debugBaseConfigurationReplacement);
// Profile
final String profileBaseConfigurationOriginal = '''
$profileIdentifier /* Profile */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */;
''';
final String profileBaseConfigurationReplacement = '''
$profileIdentifier /* Profile */ = {
isa = XCBuildConfiguration;
''';
newProjectContents = newProjectContents.replaceAll(profileBaseConfigurationOriginal, profileBaseConfigurationReplacement);
// Release
final String releaseBaseConfigurationOriginal = '''
$releaseIdentifier /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */;
''';
final String releaseBaseConfigurationReplacement = '''
$releaseIdentifier /* Release */ = {
isa = XCBuildConfiguration;
''';
newProjectContents = newProjectContents.replaceAll(releaseBaseConfigurationOriginal, releaseBaseConfigurationReplacement);
if (originalProjectContents != newProjectContents) {
logger.printStatus('Project base configurations detected, removing.');
_xcodeProjectInfoFile.writeAsStringSync(newProjectContents);
}
}
}
| flutter/packages/flutter_tools/lib/src/ios/migrations/project_base_configuration_migration.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/ios/migrations/project_base_configuration_migration.dart",
"repo_id": "flutter",
"token_count": 1217
} | 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:native_assets_builder/native_assets_builder.dart'
hide NativeAssetsBuildRunner;
import 'package:native_assets_cli/native_assets_cli_internal.dart'
hide BuildMode;
import 'package:native_assets_cli/native_assets_cli_internal.dart'
as native_assets_cli;
import '../../../base/file_system.dart';
import '../../../build_info.dart';
import '../../../globals.dart' as globals;
import '../macos/native_assets_host.dart';
import '../native_assets.dart';
/// Dry run the native builds.
///
/// This does not build native assets, it only simulates what the final paths
/// of all assets will be so that this can be embedded in the kernel file and
/// the Xcode project.
Future<Uri?> dryRunNativeAssetsIOS({
required NativeAssetsBuildRunner buildRunner,
required Uri projectUri,
required FileSystem fileSystem,
}) async {
if (!await nativeBuildRequired(buildRunner)) {
return null;
}
final Uri buildUri = nativeAssetsBuildUri(projectUri, OS.iOS);
final Iterable<KernelAsset> assetTargetLocations = await dryRunNativeAssetsIOSInternal(
fileSystem,
projectUri,
buildRunner,
);
final Uri nativeAssetsUri = await writeNativeAssetsYaml(
KernelAssets(assetTargetLocations),
buildUri,
fileSystem,
);
return nativeAssetsUri;
}
Future<Iterable<KernelAsset>> dryRunNativeAssetsIOSInternal(
FileSystem fileSystem,
Uri projectUri,
NativeAssetsBuildRunner buildRunner,
) async {
const OS targetOS = OS.iOS;
globals.logger.printTrace('Dry running native assets for $targetOS.');
final DryRunResult dryRunResult = await buildRunner.dryRun(
linkModePreference: LinkModePreference.dynamic,
targetOS: targetOS,
workingDirectory: projectUri,
includeParentEnvironment: true,
);
ensureNativeAssetsBuildSucceed(dryRunResult);
final List<Asset> nativeAssets = dryRunResult.assets;
ensureNoLinkModeStatic(nativeAssets);
globals.logger.printTrace('Dry running native assets for $targetOS done.');
return _assetTargetLocations(nativeAssets).values;
}
/// Builds native assets.
Future<List<Uri>> buildNativeAssetsIOS({
required NativeAssetsBuildRunner buildRunner,
required List<DarwinArch> darwinArchs,
required EnvironmentType environmentType,
required Uri projectUri,
required BuildMode buildMode,
String? codesignIdentity,
required Uri yamlParentDirectory,
required FileSystem fileSystem,
}) async {
if (!await nativeBuildRequired(buildRunner)) {
await writeNativeAssetsYaml(KernelAssets(), yamlParentDirectory, fileSystem);
return <Uri>[];
}
final List<Target> targets = darwinArchs.map(_getNativeTarget).toList();
final native_assets_cli.BuildMode buildModeCli = nativeAssetsBuildMode(buildMode);
const OS targetOS = OS.iOS;
final Uri buildUri = nativeAssetsBuildUri(projectUri, targetOS);
final IOSSdk iosSdk = _getIOSSdk(environmentType);
globals.logger.printTrace('Building native assets for $targets $buildModeCli.');
final List<Asset> nativeAssets = <Asset>[];
final Set<Uri> dependencies = <Uri>{};
for (final Target target in targets) {
final BuildResult result = await buildRunner.build(
linkModePreference: LinkModePreference.dynamic,
target: target,
targetIOSSdk: iosSdk,
buildMode: buildModeCli,
workingDirectory: projectUri,
includeParentEnvironment: true,
cCompilerConfig: await buildRunner.cCompilerConfig,
);
ensureNativeAssetsBuildSucceed(result);
nativeAssets.addAll(result.assets);
dependencies.addAll(result.dependencies);
}
ensureNoLinkModeStatic(nativeAssets);
globals.logger.printTrace('Building native assets for $targets done.');
final Map<KernelAssetPath, List<Asset>> fatAssetTargetLocations = _fatAssetTargetLocations(nativeAssets);
await _copyNativeAssetsIOS(
buildUri,
fatAssetTargetLocations,
codesignIdentity,
buildMode,
fileSystem,
);
final Map<Asset, KernelAsset> assetTargetLocations = _assetTargetLocations(nativeAssets);
await writeNativeAssetsYaml(
KernelAssets(assetTargetLocations.values),
yamlParentDirectory,
fileSystem,
);
return dependencies.toList();
}
IOSSdk _getIOSSdk(EnvironmentType environmentType) {
switch (environmentType) {
case EnvironmentType.physical:
return IOSSdk.iPhoneOs;
case EnvironmentType.simulator:
return IOSSdk.iPhoneSimulator;
}
}
/// Extract the [Target] from a [DarwinArch].
Target _getNativeTarget(DarwinArch darwinArch) {
switch (darwinArch) {
case DarwinArch.armv7:
return Target.iOSArm;
case DarwinArch.arm64:
return Target.iOSArm64;
case DarwinArch.x86_64:
return Target.iOSX64;
}
}
Map<KernelAssetPath, List<Asset>> _fatAssetTargetLocations(List<Asset> nativeAssets) {
final Set<String> alreadyTakenNames = <String>{};
final Map<KernelAssetPath, List<Asset>> result = <KernelAssetPath, List<Asset>>{};
final Map<String, KernelAssetPath> idToPath = <String, KernelAssetPath>{};
for (final Asset asset in nativeAssets) {
// Use same target path for all assets with the same id.
final KernelAssetPath path = idToPath[asset.id] ??
_targetLocationIOS(
asset,
alreadyTakenNames,
).path;
idToPath[asset.id] = path;
result[path] ??= <Asset>[];
result[path]!.add(asset);
}
return result;
}
Map<Asset, KernelAsset> _assetTargetLocations(List<Asset> nativeAssets) {
final Set<String> alreadyTakenNames = <String>{};
return <Asset, KernelAsset>{
for (final Asset asset in nativeAssets)
asset: _targetLocationIOS(asset, alreadyTakenNames),
};
}
KernelAsset _targetLocationIOS(Asset asset, Set<String> alreadyTakenNames) {
final AssetPath path = asset.path;
final KernelAssetPath kernelAssetPath;
switch (path) {
case AssetSystemPath _:
kernelAssetPath = KernelAssetSystemPath(path.uri);
case AssetInExecutable _:
kernelAssetPath = KernelAssetInExecutable();
case AssetInProcess _:
kernelAssetPath = KernelAssetInProcess();
case AssetAbsolutePath _:
final String fileName = path.uri.pathSegments.last;
kernelAssetPath = KernelAssetAbsolutePath(frameworkUri(
fileName,
alreadyTakenNames,
));
default:
throw Exception(
'Unsupported asset path type ${path.runtimeType} in asset $asset',
);
}
return KernelAsset(
id: asset.id,
target: asset.target,
path: kernelAssetPath,
);
}
/// Copies native assets into a framework per dynamic library.
///
/// For `flutter run -release` a multi-architecture solution is needed. So,
/// `lipo` is used to combine all target architectures into a single file.
///
/// The install name is set so that it matches what the place it will
/// be bundled in the final app.
///
/// Code signing is also done here, so that it doesn't have to be done in
/// in xcode_backend.dart.
Future<void> _copyNativeAssetsIOS(
Uri buildUri,
Map<KernelAssetPath, List<Asset>> assetTargetLocations,
String? codesignIdentity,
BuildMode buildMode,
FileSystem fileSystem,
) async {
if (assetTargetLocations.isNotEmpty) {
globals.logger
.printTrace('Copying native assets to ${buildUri.toFilePath()}.');
for (final MapEntry<KernelAssetPath, List<Asset>> assetMapping
in assetTargetLocations.entries) {
final Uri target = (assetMapping.key as KernelAssetAbsolutePath).uri;
final List<Uri> sources = <Uri>[
for (final Asset source in assetMapping.value)
(source.path as AssetAbsolutePath).uri
];
final Uri targetUri = buildUri.resolveUri(target);
final File dylibFile = fileSystem.file(targetUri);
final Directory frameworkDir = dylibFile.parent;
if (!await frameworkDir.exists()) {
await frameworkDir.create(recursive: true);
}
await lipoDylibs(dylibFile, sources);
await setInstallNameDylib(dylibFile);
await createInfoPlist(targetUri.pathSegments.last, frameworkDir);
await codesignDylib(codesignIdentity, buildMode, frameworkDir);
}
globals.logger.printTrace('Copying native assets done.');
}
}
| flutter/packages/flutter_tools/lib/src/isolated/native_assets/ios/native_assets.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/isolated/native_assets/ios/native_assets.dart",
"repo_id": "flutter",
"token_count": 2844
} | 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 'package:intl/locale.dart';
import '../base/common.dart';
import '../base/file_system.dart';
import '../base/logger.dart';
import '../convert.dart';
import 'localizations_utils.dart';
import 'message_parser.dart';
// The set of date formats that can be automatically localized.
//
// The localizations generation tool makes use of the intl library's
// DateFormat class to properly format dates based on the locale, the
// desired format, as well as the passed in [DateTime]. For example, using
// DateFormat.yMMMMd("en_US").format(DateTime.utc(1996, 7, 10)) results
// in the string "July 10, 1996".
//
// Since the tool generates code that uses DateFormat's constructor, it is
// necessary to verify that the constructor exists, or the
// tool will generate code that may cause a compile-time error.
//
// See also:
//
// * <https://pub.dev/packages/intl>
// * <https://pub.dev/documentation/intl/latest/intl/DateFormat-class.html>
// * <https://api.dartlang.org/stable/2.7.0/dart-core/DateTime-class.html>
const Set<String> validDateFormats = <String>{
'd',
'E',
'EEEE',
'LLL',
'LLLL',
'M',
'Md',
'MEd',
'MMM',
'MMMd',
'MMMEd',
'MMMM',
'MMMMd',
'MMMMEEEEd',
'QQQ',
'QQQQ',
'y',
'yM',
'yMd',
'yMEd',
'yMMM',
'yMMMd',
'yMMMEd',
'yMMMM',
'yMMMMd',
'yMMMMEEEEd',
'yQQQ',
'yQQQQ',
'H',
'Hm',
'Hms',
'j',
'jm',
'jms',
'jmv',
'jmz',
'jv',
'jz',
'm',
'ms',
's',
};
// The set of number formats that can be automatically localized.
//
// The localizations generation tool makes use of the intl library's
// NumberFormat class to properly format numbers based on the locale and
// the desired format. For example, using
// NumberFormat.compactLong("en_US").format(1200000) results
// in the string "1.2 million".
//
// Since the tool generates code that uses NumberFormat's constructor, it is
// necessary to verify that the constructor exists, or the
// tool will generate code that may cause a compile-time error.
//
// See also:
//
// * <https://pub.dev/packages/intl>
// * <https://pub.dev/documentation/intl/latest/intl/NumberFormat-class.html>
const Set<String> _validNumberFormats = <String>{
'compact',
'compactCurrency',
'compactSimpleCurrency',
'compactLong',
'currency',
'decimalPattern',
'decimalPatternDigits',
'decimalPercentPattern',
'percentPattern',
'scientificPattern',
'simpleCurrency',
};
// The names of the NumberFormat factory constructors which have named
// parameters rather than positional parameters.
//
// This helps the tool correctly generate number formatting code correctly.
//
// Example of code that uses named parameters:
// final NumberFormat format = NumberFormat.compact(
// locale: localeName,
// );
//
// Example of code that uses positional parameters:
// final NumberFormat format = NumberFormat.scientificPattern(localeName);
const Set<String> _numberFormatsWithNamedParameters = <String>{
'compact',
'compactCurrency',
'compactSimpleCurrency',
'compactLong',
'currency',
'decimalPatternDigits',
'decimalPercentPattern',
'simpleCurrency',
};
class L10nException implements Exception {
L10nException(this.message);
final String message;
@override
String toString() => message;
}
class L10nParserException extends L10nException {
L10nParserException(
this.error,
this.fileName,
this.messageId,
this.messageString,
this.charNumber
): super('''
[$fileName:$messageId] $error
$messageString
${List<String>.filled(charNumber, ' ').join()}^''');
final String error;
final String fileName;
final String messageId;
final String messageString;
// Position of character within the "messageString" where the error is.
final int charNumber;
}
class L10nMissingPlaceholderException extends L10nParserException {
L10nMissingPlaceholderException(
super.error,
super.fileName,
super.messageId,
super.messageString,
super.charNumber,
this.placeholderName,
);
final String placeholderName;
}
// One optional named parameter to be used by a NumberFormat.
//
// Some of the NumberFormat factory constructors have optional named parameters.
// For example NumberFormat.compactCurrency has a decimalDigits parameter that
// specifies the number of decimal places to use when formatting.
//
// Optional parameters for NumberFormat placeholders are specified as a
// JSON map value for optionalParameters in a resource's "@" ARB file entry:
//
// "@myResourceId": {
// "placeholders": {
// "myNumberPlaceholder": {
// "type": "double",
// "format": "compactCurrency",
// "optionalParameters": {
// "decimalDigits": 2
// }
// }
// }
// }
class OptionalParameter {
const OptionalParameter(this.name, this.value);
final String name;
final Object value;
}
// One message parameter: one placeholder from an @foo entry in the template ARB file.
//
// Placeholders are specified as a JSON map with one entry for each placeholder.
// One placeholder must be specified for each message "{parameter}".
// Each placeholder entry is also a JSON map. If the map is empty, the placeholder
// is assumed to be an Object value whose toString() value will be displayed.
// For example:
//
// "greeting": "{hello} {world}",
// "@greeting": {
// "description": "A message with a two parameters",
// "placeholders": {
// "hello": {},
// "world": {}
// }
// }
//
// Each placeholder can optionally specify a valid Dart type. If the type
// is NumberFormat or DateFormat then a format which matches one of the
// type's factory constructors can also be specified. In this example the
// date placeholder is to be formatted with DateFormat.yMMMMd:
//
// "helloWorldOn": "Hello World on {date}",
// "@helloWorldOn": {
// "description": "A message with a date parameter",
// "placeholders": {
// "date": {
// "type": "DateTime",
// "format": "yMMMMd"
// }
// }
// }
//
class Placeholder {
Placeholder(this.resourceId, this.name, Map<String, Object?> attributes)
: example = _stringAttribute(resourceId, name, attributes, 'example'),
type = _stringAttribute(resourceId, name, attributes, 'type'),
format = _stringAttribute(resourceId, name, attributes, 'format'),
optionalParameters = _optionalParameters(resourceId, name, attributes),
isCustomDateFormat = _boolAttribute(resourceId, name, attributes, 'isCustomDateFormat');
final String resourceId;
final String name;
final String? example;
final String? format;
final List<OptionalParameter> optionalParameters;
final bool? isCustomDateFormat;
// The following will be initialized after all messages are parsed in the Message constructor.
String? type;
bool isPlural = false;
bool isSelect = false;
bool isDateTime = false;
bool requiresDateFormatting = false;
bool get requiresFormatting => requiresDateFormatting || requiresNumFormatting;
bool get requiresNumFormatting => <String>['int', 'num', 'double'].contains(type) && format != null;
bool get hasValidNumberFormat => _validNumberFormats.contains(format);
bool get hasNumberFormatWithParameters => _numberFormatsWithNamedParameters.contains(format);
bool get hasValidDateFormat => validDateFormats.contains(format);
static String? _stringAttribute(
String resourceId,
String name,
Map<String, Object?> attributes,
String attributeName,
) {
final Object? value = attributes[attributeName];
if (value == null) {
return null;
}
if (value is! String || value.isEmpty) {
throw L10nException(
'The "$attributeName" value of the "$name" placeholder in message $resourceId '
'must be a non-empty string.',
);
}
return value;
}
static bool? _boolAttribute(
String resourceId,
String name,
Map<String, Object?> attributes,
String attributeName,
) {
final Object? value = attributes[attributeName];
if (value == null) {
return null;
}
if (value != 'true' && value != 'false') {
throw L10nException(
'The "$attributeName" value of the "$name" placeholder in message $resourceId '
'must be a boolean value.',
);
}
return value == 'true';
}
static List<OptionalParameter> _optionalParameters(
String resourceId,
String name,
Map<String, Object?> attributes
) {
final Object? value = attributes['optionalParameters'];
if (value == null) {
return <OptionalParameter>[];
}
if (value is! Map<String, Object?>) {
throw L10nException(
'The "optionalParameters" value of the "$name" placeholder in message '
'$resourceId is not a properly formatted Map. Ensure that it is a map '
'with keys that are strings.'
);
}
final Map<String, Object?> optionalParameterMap = value;
return optionalParameterMap.keys.map<OptionalParameter>((String parameterName) {
return OptionalParameter(parameterName, optionalParameterMap[parameterName]!);
}).toList();
}
}
// All translations for a given message specified by a resource id.
//
// The template ARB file must contain an entry called @myResourceId for each
// message named myResourceId. The @ entry describes message parameters
// called "placeholders" and can include an optional description.
// Here's a simple example message with no parameters:
//
// "helloWorld": "Hello World",
// "@helloWorld": {
// "description": "The conventional newborn programmer greeting"
// }
//
// The value of this Message is "Hello World". The Message's value is the
// localized string to be shown for the template ARB file's locale.
// The docs for the Placeholder explain how placeholder entries are defined.
class Message {
Message(
AppResourceBundle templateBundle,
AppResourceBundleCollection allBundles,
this.resourceId,
bool isResourceAttributeRequired,
{
this.useRelaxedSyntax = false,
this.useEscaping = false,
this.logger,
}
) : assert(resourceId.isNotEmpty),
value = _value(templateBundle.resources, resourceId),
description = _description(templateBundle.resources, resourceId, isResourceAttributeRequired),
placeholders = _placeholders(templateBundle.resources, resourceId, isResourceAttributeRequired),
messages = <LocaleInfo, String?>{},
parsedMessages = <LocaleInfo, Node?>{} {
// Filenames for error handling.
final Map<LocaleInfo, String> filenames = <LocaleInfo, String>{};
// Collect all translations from allBundles and parse them.
for (final AppResourceBundle bundle in allBundles.bundles) {
filenames[bundle.locale] = bundle.file.basename;
final String? translation = bundle.translationFor(resourceId);
messages[bundle.locale] = translation;
List<String>? validPlaceholders;
if (useRelaxedSyntax) {
validPlaceholders = placeholders.entries.map((MapEntry<String, Placeholder> e) => e.key).toList();
}
try {
parsedMessages[bundle.locale] = translation == null ? null : Parser(
resourceId,
bundle.file.basename,
translation,
useEscaping: useEscaping,
placeholders: validPlaceholders,
logger: logger,
).parse();
} on L10nParserException catch (error) {
logger?.printError(error.toString());
// Treat it as an untranslated message in case we can't parse.
parsedMessages[bundle.locale] = null;
hadErrors = true;
}
}
// Infer the placeholders
_inferPlaceholders(filenames);
}
final String resourceId;
final String value;
final String? description;
late final Map<LocaleInfo, String?> messages;
final Map<LocaleInfo, Node?> parsedMessages;
final Map<String, Placeholder> placeholders;
final bool useEscaping;
final bool useRelaxedSyntax;
final Logger? logger;
bool hadErrors = false;
bool get placeholdersRequireFormatting => placeholders.values.any((Placeholder p) => p.requiresFormatting);
static String _value(Map<String, Object?> bundle, String resourceId) {
final Object? value = bundle[resourceId];
if (value == null) {
throw L10nException('A value for resource "$resourceId" was not found.');
}
if (value is! String) {
throw L10nException('The value of "$resourceId" is not a string.');
}
return value;
}
static Map<String, Object?>? _attributes(
Map<String, Object?> bundle,
String resourceId,
bool isResourceAttributeRequired,
) {
final Object? attributes = bundle['@$resourceId'];
if (isResourceAttributeRequired) {
if (attributes == null) {
throw L10nException(
'Resource attribute "@$resourceId" was not found. Please '
'ensure that each resource has a corresponding @resource.'
);
}
}
if (attributes != null && attributes is! Map<String, Object?>) {
throw L10nException(
'The resource attribute "@$resourceId" is not a properly formatted Map. '
'Ensure that it is a map with keys that are strings.'
);
}
return attributes as Map<String, Object?>?;
}
static String? _description(
Map<String, Object?> bundle,
String resourceId,
bool isResourceAttributeRequired,
) {
final Map<String, Object?>? resourceAttributes = _attributes(bundle, resourceId, isResourceAttributeRequired);
if (resourceAttributes == null) {
return null;
}
final Object? value = resourceAttributes['description'];
if (value == null) {
return null;
}
if (value is! String) {
throw L10nException(
'The description for "@$resourceId" is not a properly formatted String.'
);
}
return value;
}
static Map<String, Placeholder> _placeholders(
Map<String, Object?> bundle,
String resourceId,
bool isResourceAttributeRequired,
) {
final Map<String, Object?>? resourceAttributes = _attributes(bundle, resourceId, isResourceAttributeRequired);
if (resourceAttributes == null) {
return <String, Placeholder>{};
}
final Object? allPlaceholdersMap = resourceAttributes['placeholders'];
if (allPlaceholdersMap == null) {
return <String, Placeholder>{};
}
if (allPlaceholdersMap is! Map<String, Object?>) {
throw L10nException(
'The "placeholders" attribute for message $resourceId, is not '
'properly formatted. Ensure that it is a map with string valued keys.'
);
}
return Map<String, Placeholder>.fromEntries(
allPlaceholdersMap.keys.map((String placeholderName) {
final Object? value = allPlaceholdersMap[placeholderName];
if (value is! Map<String, Object?>) {
throw L10nException(
'The value of the "$placeholderName" placeholder attribute for message '
'"$resourceId", is not properly formatted. Ensure that it is a map '
'with string valued keys.'
);
}
return MapEntry<String, Placeholder>(placeholderName, Placeholder(resourceId, placeholderName, value));
}),
);
}
// Using parsed translations, attempt to infer types of placeholders used by plurals and selects.
// For undeclared placeholders, create a new placeholder.
void _inferPlaceholders(Map<LocaleInfo, String> filenames) {
// We keep the undeclared placeholders separate so that we can sort them alphabetically afterwards.
final Map<String, Placeholder> undeclaredPlaceholders = <String, Placeholder>{};
// Helper for getting placeholder by name.
Placeholder? getPlaceholder(String name) => placeholders[name] ?? undeclaredPlaceholders[name];
for (final LocaleInfo locale in parsedMessages.keys) {
if (parsedMessages[locale] == null) {
continue;
}
final List<Node> traversalStack = <Node>[parsedMessages[locale]!];
while (traversalStack.isNotEmpty) {
final Node node = traversalStack.removeLast();
if (<ST>[
ST.placeholderExpr,
ST.pluralExpr,
ST.selectExpr,
ST.argumentExpr
].contains(node.type)) {
final String identifier = node.children[1].value!;
Placeholder? placeholder = getPlaceholder(identifier);
if (placeholder == null) {
placeholder = Placeholder(resourceId, identifier, <String, Object?>{});
undeclaredPlaceholders[identifier] = placeholder;
}
if (node.type == ST.pluralExpr) {
placeholder.isPlural = true;
} else if (node.type == ST.selectExpr) {
placeholder.isSelect = true;
} else if (node.type == ST.argumentExpr) {
placeholder.isDateTime = true;
} else {
// Here the node type must be ST.placeholderExpr.
// A DateTime placeholder must require date formatting.
if (placeholder.type == 'DateTime') {
placeholder.requiresDateFormatting = true;
}
}
}
traversalStack.addAll(node.children);
}
}
placeholders.addEntries(
undeclaredPlaceholders.entries
.toList()
..sort((MapEntry<String, Placeholder> p1, MapEntry<String, Placeholder> p2) => p1.key.compareTo(p2.key))
);
bool atMostOneOf(bool x, bool y, bool z) {
return x && !y && !z
|| !x && y && !z
|| !x && !y && z
|| !x && !y && !z;
}
for (final Placeholder placeholder in placeholders.values) {
if (!atMostOneOf(placeholder.isPlural, placeholder.isDateTime, placeholder.isSelect)) {
throw L10nException('Placeholder is used as plural/select/datetime in certain languages.');
} else if (placeholder.isPlural) {
if (placeholder.type == null) {
placeholder.type = 'num';
}
else if (!<String>['num', 'int'].contains(placeholder.type)) {
throw L10nException("Placeholders used in plurals must be of type 'num' or 'int'");
}
} else if (placeholder.isSelect) {
if (placeholder.type == null) {
placeholder.type = 'String';
} else if (placeholder.type != 'String') {
throw L10nException("Placeholders used in selects must be of type 'String'");
}
} else if (placeholder.isDateTime) {
if (placeholder.type == null) {
placeholder.type = 'DateTime';
} else if (placeholder.type != 'DateTime') {
throw L10nException("Placeholders used in datetime expressions much be of type 'DateTime'");
}
}
placeholder.type ??= 'Object';
}
}
}
/// Represents the contents of one ARB file.
class AppResourceBundle {
/// Assuming that the caller has verified that the file exists and is readable.
factory AppResourceBundle(File file) {
final Map<String, Object?> resources;
try {
final String content = file.readAsStringSync().trim();
if (content.isEmpty) {
resources = <String, Object?>{};
} else {
resources = json.decode(content) as Map<String, Object?>;
}
} on FormatException catch (e) {
throw L10nException(
'The arb file ${file.path} has the following formatting issue: \n'
'$e',
);
}
String? localeString = resources['@@locale'] as String?;
// Look for the first instance of an ISO 639-1 language code, matching exactly.
final String fileName = file.fileSystem.path.basenameWithoutExtension(file.path);
for (int index = 0; index < fileName.length; index += 1) {
// If an underscore was found, check if locale string follows.
if (fileName[index] == '_') {
// If Locale.tryParse fails, it returns null.
final Locale? parserResult = Locale.tryParse(fileName.substring(index + 1));
// If the parserResult is not an actual locale identifier, end the loop.
if (parserResult != null && _iso639Languages.contains(parserResult.languageCode)) {
// The parsed result uses dashes ('-'), but we want underscores ('_').
final String parserLocaleString = parserResult.toString().replaceAll('-', '_');
if (localeString == null) {
// If @@locale was not defined, use the filename locale suffix.
localeString = parserLocaleString;
} else {
// If the localeString was defined in @@locale and in the filename, verify to
// see if the parsed locale matches, throw an error if it does not. This
// prevents developers from confusing issues when both @@locale and
// "_{locale}" is specified in the filename.
if (localeString != parserLocaleString) {
throw L10nException(
'The locale specified in @@locale and the arb filename do not match. \n'
'Please make sure that they match, since this prevents any confusion \n'
'with which locale to use. Otherwise, specify the locale in either the \n'
'filename of the @@locale key only.\n'
'Current @@locale value: $localeString\n'
'Current filename extension: $parserLocaleString'
);
}
}
break;
}
}
}
if (localeString == null) {
throw L10nException(
"The following .arb file's locale could not be determined: \n"
'${file.path} \n'
"Make sure that the locale is specified in the file's '@@locale' "
'property or as part of the filename (e.g. file_en.arb)'
);
}
final Iterable<String> ids = resources.keys.where((String key) => !key.startsWith('@'));
return AppResourceBundle._(file, LocaleInfo.fromString(localeString), resources, ids);
}
const AppResourceBundle._(this.file, this.locale, this.resources, this.resourceIds);
final File file;
final LocaleInfo locale;
/// JSON representation of the contents of the ARB file.
final Map<String, Object?> resources;
final Iterable<String> resourceIds;
String? translationFor(String resourceId) {
final Object? result = resources[resourceId];
if (result is! String?) {
throwToolExit('Localized message for key "$resourceId" in "${file.path}" '
'is not a string.');
}
return result;
}
@override
String toString() {
return 'AppResourceBundle($locale, ${file.path})';
}
}
// Represents all of the ARB files in [directory] as [AppResourceBundle]s.
class AppResourceBundleCollection {
factory AppResourceBundleCollection(Directory directory) {
// Assuming that the caller has verified that the directory is readable.
final RegExp filenameRE = RegExp(r'(\w+)\.arb$');
final Map<LocaleInfo, AppResourceBundle> localeToBundle = <LocaleInfo, AppResourceBundle>{};
final Map<String, List<LocaleInfo>> languageToLocales = <String, List<LocaleInfo>>{};
// We require the list of files to be sorted so that
// "languageToLocales[bundle.locale.languageCode]" is not null
// by the time we handle locales with country codes.
final List<File> files = directory
.listSync()
.whereType<File>()
.where((File e) => filenameRE.hasMatch(e.path))
.toList()
..sort(sortFilesByPath);
for (final File file in files) {
final AppResourceBundle bundle = AppResourceBundle(file);
if (localeToBundle[bundle.locale] != null) {
throw L10nException(
"Multiple arb files with the same '${bundle.locale}' locale detected. \n"
'Ensure that there is exactly one arb file for each locale.'
);
}
localeToBundle[bundle.locale] = bundle;
languageToLocales[bundle.locale.languageCode] ??= <LocaleInfo>[];
languageToLocales[bundle.locale.languageCode]!.add(bundle.locale);
}
languageToLocales.forEach((String language, List<LocaleInfo> listOfCorrespondingLocales) {
final List<String> localeStrings = listOfCorrespondingLocales.map((LocaleInfo locale) {
return locale.toString();
}).toList();
if (!localeStrings.contains(language)) {
throw L10nException(
'Arb file for a fallback, $language, does not exist, even though \n'
'the following locale(s) exist: $listOfCorrespondingLocales. \n'
'When locales specify a script code or country code, a \n'
'base locale (without the script code or country code) should \n'
'exist as the fallback. Please create a {fileName}_$language.arb \n'
'file.'
);
}
});
return AppResourceBundleCollection._(directory, localeToBundle, languageToLocales);
}
const AppResourceBundleCollection._(this._directory, this._localeToBundle, this._languageToLocales);
final Directory _directory;
final Map<LocaleInfo, AppResourceBundle> _localeToBundle;
final Map<String, List<LocaleInfo>> _languageToLocales;
Iterable<LocaleInfo> get locales => _localeToBundle.keys;
Iterable<AppResourceBundle> get bundles => _localeToBundle.values;
AppResourceBundle? bundleFor(LocaleInfo locale) => _localeToBundle[locale];
Iterable<String> get languages => _languageToLocales.keys;
Iterable<LocaleInfo> localesForLanguage(String language) => _languageToLocales[language] ?? <LocaleInfo>[];
@override
String toString() {
return 'AppResourceBundleCollection(${_directory.path}, ${locales.length} locales)';
}
}
// A set containing all the ISO630-1 languages. This list was pulled from https://datahub.io/core/language-codes.
final Set<String> _iso639Languages = <String>{
'aa',
'ab',
'ae',
'af',
'ak',
'am',
'an',
'ar',
'as',
'av',
'ay',
'az',
'ba',
'be',
'bg',
'bh',
'bi',
'bm',
'bn',
'bo',
'br',
'bs',
'ca',
'ce',
'ch',
'co',
'cr',
'cs',
'cu',
'cv',
'cy',
'da',
'de',
'dv',
'dz',
'ee',
'el',
'en',
'eo',
'es',
'et',
'eu',
'fa',
'ff',
'fi',
'fil',
'fj',
'fo',
'fr',
'fy',
'ga',
'gd',
'gl',
'gn',
'gsw',
'gu',
'gv',
'ha',
'he',
'hi',
'ho',
'hr',
'ht',
'hu',
'hy',
'hz',
'ia',
'id',
'ie',
'ig',
'ii',
'ik',
'io',
'is',
'it',
'iu',
'ja',
'jv',
'ka',
'kg',
'ki',
'kj',
'kk',
'kl',
'km',
'kn',
'ko',
'kr',
'ks',
'ku',
'kv',
'kw',
'ky',
'la',
'lb',
'lg',
'li',
'ln',
'lo',
'lt',
'lu',
'lv',
'mg',
'mh',
'mi',
'mk',
'ml',
'mn',
'mr',
'ms',
'mt',
'my',
'na',
'nb',
'nd',
'ne',
'ng',
'nl',
'nn',
'no',
'nr',
'nv',
'ny',
'oc',
'oj',
'om',
'or',
'os',
'pa',
'pi',
'pl',
'ps',
'pt',
'qu',
'rm',
'rn',
'ro',
'ru',
'rw',
'sa',
'sc',
'sd',
'se',
'sg',
'si',
'sk',
'sl',
'sm',
'sn',
'so',
'sq',
'sr',
'ss',
'st',
'su',
'sv',
'sw',
'ta',
'te',
'tg',
'th',
'ti',
'tk',
'tl',
'tn',
'to',
'tr',
'ts',
'tt',
'tw',
'ty',
'ug',
'uk',
'ur',
'uz',
've',
'vi',
'vo',
'wa',
'wo',
'xh',
'yi',
'yo',
'za',
'zh',
'zu',
};
| flutter/packages/flutter_tools/lib/src/localizations/gen_l10n_types.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/localizations/gen_l10n_types.dart",
"repo_id": "flutter",
"token_count": 10105
} | 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 'dart:async';
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/io.dart';
import '../base/logger.dart';
import '../base/platform.dart';
import '../base/process.dart';
import '../base/user_messages.dart';
import '../base/version.dart';
import '../build_info.dart';
import '../cache.dart';
import '../ios/xcodeproj.dart';
Version get xcodeRequiredVersion => Version(14, null, null);
/// Diverging this number from the minimum required version will provide a doctor
/// warning, not error, that users should upgrade Xcode.
Version get xcodeRecommendedVersion => xcodeRequiredVersion;
/// SDK name passed to `xcrun --sdk`. Corresponds to undocumented Xcode
/// SUPPORTED_PLATFORMS values.
///
/// Usage: xcrun [options] <tool name> ... arguments ...
/// ...
/// --sdk <sdk name> find the tool for the given SDK name.
String getSDKNameForIOSEnvironmentType(EnvironmentType environmentType) {
return (environmentType == EnvironmentType.simulator)
? 'iphonesimulator'
: 'iphoneos';
}
/// A utility class for interacting with Xcode command line tools.
class Xcode {
Xcode({
required Platform platform,
required ProcessManager processManager,
required Logger logger,
required FileSystem fileSystem,
required XcodeProjectInterpreter xcodeProjectInterpreter,
required UserMessages userMessages,
String? flutterRoot,
}) : _platform = platform,
_fileSystem = fileSystem,
_xcodeProjectInterpreter = xcodeProjectInterpreter,
_userMessage = userMessages,
_flutterRoot = flutterRoot,
_processUtils =
ProcessUtils(logger: logger, processManager: processManager),
_logger = logger;
/// Create an [Xcode] for testing.
///
/// Defaults to a memory file system, fake platform,
/// buffer logger, and test [XcodeProjectInterpreter].
@visibleForTesting
factory Xcode.test({
required ProcessManager processManager,
XcodeProjectInterpreter? xcodeProjectInterpreter,
Platform? platform,
FileSystem? fileSystem,
String? flutterRoot,
Logger? logger,
}) {
platform ??= FakePlatform(
operatingSystem: 'macos',
environment: <String, String>{},
);
logger ??= BufferLogger.test();
return Xcode(
platform: platform,
processManager: processManager,
fileSystem: fileSystem ?? MemoryFileSystem.test(),
userMessages: UserMessages(),
flutterRoot: flutterRoot,
logger: logger,
xcodeProjectInterpreter: xcodeProjectInterpreter ?? XcodeProjectInterpreter.test(processManager: processManager),
);
}
final Platform _platform;
final ProcessUtils _processUtils;
final FileSystem _fileSystem;
final XcodeProjectInterpreter _xcodeProjectInterpreter;
final UserMessages _userMessage;
final String? _flutterRoot;
final Logger _logger;
bool get isInstalledAndMeetsVersionCheck => _platform.isMacOS && isInstalled && isRequiredVersionSatisfactory;
String? _xcodeSelectPath;
String? get xcodeSelectPath {
if (_xcodeSelectPath == null) {
try {
_xcodeSelectPath = _processUtils.runSync(
<String>['/usr/bin/xcode-select', '--print-path'],
).stdout.trim();
} on ProcessException {
// Ignored, return null below.
} on ArgumentError {
// Ignored, return null below.
}
}
return _xcodeSelectPath;
}
String get xcodeAppPath {
// If the Xcode Select Path is /Applications/Xcode.app/Contents/Developer,
// the path to Xcode App is /Applications/Xcode.app
final String? pathToXcode = xcodeSelectPath;
if (pathToXcode == null || pathToXcode.isEmpty) {
throwToolExit(_userMessage.xcodeMissing);
}
final int index = pathToXcode.indexOf('.app');
if (index == -1) {
throwToolExit(_userMessage.xcodeMissing);
}
return pathToXcode.substring(0, index + 4);
}
/// Path to script to automate debugging through Xcode. Used in xcode_debug.dart.
/// Located in this file to make it easily overrideable in google3.
String get xcodeAutomationScriptPath {
final String flutterRoot = _flutterRoot ?? Cache.flutterRoot!;
final String flutterToolsAbsolutePath = _fileSystem.path.join(
flutterRoot,
'packages',
'flutter_tools',
);
final String filePath = '$flutterToolsAbsolutePath/bin/xcode_debug.js';
if (!_fileSystem.file(filePath).existsSync()) {
throwToolExit('Unable to find Xcode automation script at $filePath');
}
return filePath;
}
bool get isInstalled => _xcodeProjectInterpreter.isInstalled;
Version? get currentVersion => _xcodeProjectInterpreter.version;
String? get buildVersion => _xcodeProjectInterpreter.build;
String? get versionText => _xcodeProjectInterpreter.versionText;
bool? _eulaSigned;
/// Has the EULA been signed?
bool get eulaSigned {
if (_eulaSigned == null) {
try {
final RunResult result = _processUtils.runSync(
<String>[...xcrunCommand(), 'clang'],
);
if (result.stdout.contains('license')) {
_eulaSigned = false;
} else if (result.stderr.contains('license')) {
_eulaSigned = false;
} else {
_eulaSigned = true;
}
} on ProcessException {
_eulaSigned = false;
}
}
return _eulaSigned ?? false;
}
bool? _isSimctlInstalled;
/// Verifies that simctl is installed by trying to run it.
bool get isSimctlInstalled {
if (_isSimctlInstalled == null) {
try {
// This command will error if additional components need to be installed in
// xcode 9.2 and above.
final RunResult result = _processUtils.runSync(
<String>[...xcrunCommand(), 'simctl', 'list', 'devices', 'booted'],
);
_isSimctlInstalled = result.exitCode == 0;
} on ProcessException {
_isSimctlInstalled = false;
}
}
return _isSimctlInstalled ?? false;
}
bool? _isDevicectlInstalled;
/// Verifies that `devicectl` is installed by checking Xcode version and trying
/// to run it. `devicectl` is made available in Xcode 15.
bool get isDevicectlInstalled {
if (_isDevicectlInstalled == null) {
try {
if (currentVersion == null || currentVersion!.major < 15) {
_isDevicectlInstalled = false;
return _isDevicectlInstalled!;
}
final RunResult result = _processUtils.runSync(
<String>[...xcrunCommand(), 'devicectl', '--version'],
);
_isDevicectlInstalled = result.exitCode == 0;
} on ProcessException {
_isDevicectlInstalled = false;
}
}
return _isDevicectlInstalled ?? false;
}
bool get isRequiredVersionSatisfactory {
final Version? version = currentVersion;
if (version == null) {
return false;
}
return version >= xcodeRequiredVersion;
}
bool get isRecommendedVersionSatisfactory {
final Version? version = currentVersion;
if (version == null) {
return false;
}
return version >= xcodeRecommendedVersion;
}
/// See [XcodeProjectInterpreter.xcrunCommand].
List<String> xcrunCommand() => _xcodeProjectInterpreter.xcrunCommand();
Future<RunResult> cc(List<String> args) => _run('cc', args);
Future<RunResult> clang(List<String> args) => _run('clang', args);
Future<RunResult> dsymutil(List<String> args) => _run('dsymutil', args);
Future<RunResult> strip(List<String> args) => _run('strip', args);
Future<RunResult> _run(String command, List<String> args) {
return _processUtils.run(
<String>[...xcrunCommand(), command, ...args],
throwOnError: true,
);
}
Future<String> sdkLocation(EnvironmentType environmentType) async {
final RunResult runResult = await _processUtils.run(
<String>[...xcrunCommand(), '--sdk', getSDKNameForIOSEnvironmentType(environmentType), '--show-sdk-path'],
);
if (runResult.exitCode != 0) {
throwToolExit('Could not find SDK location: ${runResult.stderr}');
}
return runResult.stdout.trim();
}
String? getSimulatorPath() {
final String? selectPath = xcodeSelectPath;
if (selectPath == null) {
return null;
}
final String appPath = _fileSystem.path.join(selectPath, 'Applications', 'Simulator.app');
return _fileSystem.directory(appPath).existsSync() ? appPath : null;
}
/// Gets the version number of the platform for the selected SDK.
Future<Version?> sdkPlatformVersion(EnvironmentType environmentType) async {
final RunResult runResult = await _processUtils.run(
<String>[...xcrunCommand(), '--sdk', getSDKNameForIOSEnvironmentType(environmentType), '--show-sdk-platform-version'],
);
if (runResult.exitCode != 0) {
_logger.printError('Could not find SDK Platform Version: ${runResult.stderr}');
return null;
}
final String versionString = runResult.stdout.trim();
return Version.parse(versionString);
}
}
EnvironmentType? environmentTypeFromSdkroot(String sdkroot, FileSystem fileSystem) {
// iPhoneSimulator.sdk or iPhoneOS.sdk
final String sdkName = fileSystem.path.basename(sdkroot).toLowerCase();
if (sdkName.contains('iphone')) {
return sdkName.contains('simulator') ? EnvironmentType.simulator : EnvironmentType.physical;
}
assert(false);
return null;
}
| flutter/packages/flutter_tools/lib/src/macos/xcode.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/macos/xcode.dart",
"repo_id": "flutter",
"token_count": 3475
} | 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 'package:meta/meta.dart';
import 'package:xml/xml.dart';
import 'package:yaml/yaml.dart';
import '../src/convert.dart';
import 'android/android_builder.dart';
import 'android/gradle_utils.dart' as gradle;
import 'base/common.dart';
import 'base/error_handling_io.dart';
import 'base/file_system.dart';
import 'base/logger.dart';
import 'base/utils.dart';
import 'base/version.dart';
import 'bundle.dart' as bundle;
import 'cmake_project.dart';
import 'features.dart';
import 'flutter_manifest.dart';
import 'flutter_plugins.dart';
import 'globals.dart' as globals;
import 'platform_plugins.dart';
import 'project_validator_result.dart';
import 'template.dart';
import 'xcode_project.dart';
export 'cmake_project.dart';
export 'xcode_project.dart';
/// Enum for each officially supported platform.
enum SupportedPlatform {
android,
ios,
linux,
macos,
web,
windows,
fuchsia,
root, // Special platform to represent the root project directory
}
class FlutterProjectFactory {
FlutterProjectFactory({
required Logger logger,
required FileSystem fileSystem,
}) : _logger = logger,
_fileSystem = fileSystem;
final Logger _logger;
final FileSystem _fileSystem;
@visibleForTesting
final Map<String, FlutterProject> projects =
<String, FlutterProject>{};
/// Returns a [FlutterProject] view of the given directory or a ToolExit error,
/// if `pubspec.yaml` or `example/pubspec.yaml` is invalid.
FlutterProject fromDirectory(Directory directory) {
return projects.putIfAbsent(directory.path, () {
final FlutterManifest manifest = FlutterProject._readManifest(
directory.childFile(bundle.defaultManifestPath).path,
logger: _logger,
fileSystem: _fileSystem,
);
final FlutterManifest exampleManifest = FlutterProject._readManifest(
FlutterProject._exampleDirectory(directory)
.childFile(bundle.defaultManifestPath)
.path,
logger: _logger,
fileSystem: _fileSystem,
);
return FlutterProject(directory, manifest, exampleManifest);
});
}
}
/// Represents the contents of a Flutter project at the specified [directory].
///
/// [FlutterManifest] information is read from `pubspec.yaml` and
/// `example/pubspec.yaml` files on construction of a [FlutterProject] instance.
/// The constructed instance carries an immutable snapshot representation of the
/// presence and content of those files. Accordingly, [FlutterProject] instances
/// should be discarded upon changes to the `pubspec.yaml` files, but can be
/// used across changes to other files, as no other file-level information is
/// cached.
class FlutterProject {
@visibleForTesting
FlutterProject(this.directory, this.manifest, this._exampleManifest);
/// Returns a [FlutterProject] view of the given directory or a ToolExit error,
/// if `pubspec.yaml` or `example/pubspec.yaml` is invalid.
static FlutterProject fromDirectory(Directory directory) => globals.projectFactory.fromDirectory(directory);
/// Returns a [FlutterProject] view of the current directory or a ToolExit error,
/// if `pubspec.yaml` or `example/pubspec.yaml` is invalid.
static FlutterProject current() => globals.projectFactory.fromDirectory(globals.fs.currentDirectory);
/// Create a [FlutterProject] and bypass the project caching.
@visibleForTesting
static FlutterProject fromDirectoryTest(Directory directory, [Logger? logger]) {
final FileSystem fileSystem = directory.fileSystem;
logger ??= BufferLogger.test();
final FlutterManifest manifest = FlutterProject._readManifest(
directory.childFile(bundle.defaultManifestPath).path,
logger: logger,
fileSystem: fileSystem,
);
final FlutterManifest exampleManifest = FlutterProject._readManifest(
FlutterProject._exampleDirectory(directory)
.childFile(bundle.defaultManifestPath)
.path,
logger: logger,
fileSystem: fileSystem,
);
return FlutterProject(directory, manifest, exampleManifest);
}
/// The location of this project.
final Directory directory;
/// The location of the build folder.
Directory get buildDirectory => directory.childDirectory('build');
/// The manifest of this project.
final FlutterManifest manifest;
/// The manifest of the example sub-project of this project.
final FlutterManifest _exampleManifest;
/// The set of organization names found in this project as
/// part of iOS product bundle identifier, Android application ID, or
/// Gradle group ID.
Future<Set<String>> get organizationNames async {
final List<String> candidates = <String>[];
if (ios.existsSync()) {
// Don't require iOS build info, this method is only
// used during create as best-effort, use the
// default target bundle identifier.
try {
final String? bundleIdentifier = await ios.productBundleIdentifier(null);
if (bundleIdentifier != null) {
candidates.add(bundleIdentifier);
}
} on ToolExit {
// It's possible that while parsing the build info for the ios project
// that the bundleIdentifier can't be resolve. However, we would like
// skip parsing that id in favor of searching in other place. We can
// consider a tool exit in this case to be non fatal for the program.
}
}
if (android.existsSync()) {
final String? applicationId = android.applicationId;
final String? group = android.group;
candidates.addAll(<String>[
if (applicationId != null)
applicationId,
if (group != null)
group,
]);
}
if (example.android.existsSync()) {
final String? applicationId = example.android.applicationId;
if (applicationId != null) {
candidates.add(applicationId);
}
}
if (example.ios.existsSync()) {
final String? bundleIdentifier = await example.ios.productBundleIdentifier(null);
if (bundleIdentifier != null) {
candidates.add(bundleIdentifier);
}
}
return Set<String>.of(candidates.map<String?>(_organizationNameFromPackageName).whereType<String>());
}
String? _organizationNameFromPackageName(String packageName) {
if (0 <= packageName.lastIndexOf('.')) {
return packageName.substring(0, packageName.lastIndexOf('.'));
}
return null;
}
/// The iOS sub project of this project.
late final IosProject ios = IosProject.fromFlutter(this);
/// The Android sub project of this project.
late final AndroidProject android = AndroidProject._(this);
/// The web sub project of this project.
late final WebProject web = WebProject._(this);
/// The MacOS sub project of this project.
late final MacOSProject macos = MacOSProject.fromFlutter(this);
/// The Linux sub project of this project.
late final LinuxProject linux = LinuxProject.fromFlutter(this);
/// The Windows sub project of this project.
late final WindowsProject windows = WindowsProject.fromFlutter(this);
/// The Fuchsia sub project of this project.
late final FuchsiaProject fuchsia = FuchsiaProject._(this);
/// The `pubspec.yaml` file of this project.
File get pubspecFile => directory.childFile('pubspec.yaml');
/// The `.packages` file of this project.
File get packagesFile => directory.childFile('.packages');
/// The `package_config.json` file of the project.
///
/// This is the replacement for .packages which contains language
/// version information.
File get packageConfigFile => directory.childDirectory('.dart_tool').childFile('package_config.json');
/// The `.metadata` file of this project.
File get metadataFile => directory.childFile('.metadata');
/// The `.flutter-plugins` file of this project.
File get flutterPluginsFile => directory.childFile('.flutter-plugins');
/// The `.flutter-plugins-dependencies` file of this project,
/// which contains the dependencies each plugin depends on.
File get flutterPluginsDependenciesFile => directory.childFile('.flutter-plugins-dependencies');
/// The `.dart-tool` directory of this project.
Directory get dartTool => directory.childDirectory('.dart_tool');
/// The directory containing the generated code for this project.
Directory get generated => directory
.absolute
.childDirectory('.dart_tool')
.childDirectory('build')
.childDirectory('generated')
.childDirectory(manifest.appName);
/// The generated Dart plugin registrant for non-web platforms.
File get dartPluginRegistrant => dartTool
.childDirectory('flutter_build')
.childFile('dart_plugin_registrant.dart');
/// The example sub-project of this project.
FlutterProject get example => FlutterProject(
_exampleDirectory(directory),
_exampleManifest,
FlutterManifest.empty(logger: globals.logger),
);
/// True if this project is a Flutter module project.
bool get isModule => manifest.isModule;
/// True if this project is a Flutter plugin project.
bool get isPlugin => manifest.isPlugin;
/// True if the Flutter project is using the AndroidX support library.
bool get usesAndroidX => manifest.usesAndroidX;
/// True if this project has an example application.
bool get hasExampleApp => _exampleDirectory(directory).existsSync();
/// Returns a list of platform names that are supported by the project.
List<SupportedPlatform> getSupportedPlatforms({bool includeRoot = false}) {
final List<SupportedPlatform> platforms = includeRoot ? <SupportedPlatform>[SupportedPlatform.root] : <SupportedPlatform>[];
if (android.existsSync()) {
platforms.add(SupportedPlatform.android);
}
if (ios.exists) {
platforms.add(SupportedPlatform.ios);
}
if (web.existsSync()) {
platforms.add(SupportedPlatform.web);
}
if (macos.existsSync()) {
platforms.add(SupportedPlatform.macos);
}
if (linux.existsSync()) {
platforms.add(SupportedPlatform.linux);
}
if (windows.existsSync()) {
platforms.add(SupportedPlatform.windows);
}
if (fuchsia.existsSync()) {
platforms.add(SupportedPlatform.fuchsia);
}
return platforms;
}
/// The directory that will contain the example if an example exists.
static Directory _exampleDirectory(Directory directory) => directory.childDirectory('example');
/// Reads and validates the `pubspec.yaml` file at [path], asynchronously
/// returning a [FlutterManifest] representation of the contents.
///
/// Completes with an empty [FlutterManifest], if the file does not exist.
/// Completes with a ToolExit on validation error.
static FlutterManifest _readManifest(String path, {
required Logger logger,
required FileSystem fileSystem,
}) {
FlutterManifest? manifest;
try {
manifest = FlutterManifest.createFromPath(
path,
logger: logger,
fileSystem: fileSystem,
);
} on YamlException catch (e) {
logger.printStatus('Error detected in pubspec.yaml:', emphasis: true);
logger.printError('$e');
} on FormatException catch (e) {
logger.printError('Error detected while parsing pubspec.yaml:', emphasis: true);
logger.printError('$e');
} on FileSystemException catch (e) {
logger.printError('Error detected while reading pubspec.yaml:', emphasis: true);
logger.printError('$e');
}
if (manifest == null) {
throwToolExit('Please correct the pubspec.yaml file at $path');
}
return manifest;
}
/// Reapplies template files and regenerates project files and plugin
/// registrants for app and module projects only.
///
/// Will not create project platform directories if they do not already exist.
///
/// If [allowedPlugins] is non-null, all plugins with method channels in the
/// project's pubspec.yaml will be validated to be in that set, or else a
/// [ToolExit] will be thrown.
Future<void> regeneratePlatformSpecificTooling({
DeprecationBehavior deprecationBehavior = DeprecationBehavior.none,
Iterable<String>? allowedPlugins,
}) async {
return ensureReadyForPlatformSpecificTooling(
androidPlatform: android.existsSync(),
iosPlatform: ios.existsSync(),
// TODO(stuartmorgan): Revisit the conditions here once the plans for handling
// desktop in existing projects are in place.
linuxPlatform: featureFlags.isLinuxEnabled && linux.existsSync(),
macOSPlatform: featureFlags.isMacOSEnabled && macos.existsSync(),
windowsPlatform: featureFlags.isWindowsEnabled && windows.existsSync(),
webPlatform: featureFlags.isWebEnabled && web.existsSync(),
deprecationBehavior: deprecationBehavior,
allowedPlugins: allowedPlugins,
);
}
/// Applies template files and generates project files and plugin
/// registrants for app and module projects only for the specified platforms.
Future<void> ensureReadyForPlatformSpecificTooling({
bool androidPlatform = false,
bool iosPlatform = false,
bool linuxPlatform = false,
bool macOSPlatform = false,
bool windowsPlatform = false,
bool webPlatform = false,
DeprecationBehavior deprecationBehavior = DeprecationBehavior.none,
Iterable<String>? allowedPlugins,
}) async {
if (!directory.existsSync() || isPlugin) {
return;
}
await refreshPluginsList(this, iosPlatform: iosPlatform, macOSPlatform: macOSPlatform);
if (androidPlatform) {
await android.ensureReadyForPlatformSpecificTooling(deprecationBehavior: deprecationBehavior);
}
if (iosPlatform) {
await ios.ensureReadyForPlatformSpecificTooling();
}
if (linuxPlatform) {
await linux.ensureReadyForPlatformSpecificTooling();
}
if (macOSPlatform) {
await macos.ensureReadyForPlatformSpecificTooling();
}
if (windowsPlatform) {
await windows.ensureReadyForPlatformSpecificTooling();
}
if (webPlatform) {
await web.ensureReadyForPlatformSpecificTooling();
}
await injectPlugins(
this,
androidPlatform: androidPlatform,
iosPlatform: iosPlatform,
linuxPlatform: linuxPlatform,
macOSPlatform: macOSPlatform,
windowsPlatform: windowsPlatform,
allowedPlugins: allowedPlugins,
);
}
void checkForDeprecation({DeprecationBehavior deprecationBehavior = DeprecationBehavior.none}) {
if (android.existsSync() && pubspecFile.existsSync()) {
android.checkForDeprecation(deprecationBehavior: deprecationBehavior);
}
}
/// Returns a json encoded string containing the [appName], [version], and [buildNumber] that is used to generate version.json
String getVersionInfo() {
final String? buildName = manifest.buildName;
final String? buildNumber = manifest.buildNumber;
final Map<String, String> versionFileJson = <String, String>{
'app_name': manifest.appName,
if (buildName != null)
'version': buildName,
if (buildNumber != null)
'build_number': buildNumber,
'package_name': manifest.appName,
};
return jsonEncode(versionFileJson);
}
}
/// Base class for projects per platform.
abstract class FlutterProjectPlatform {
/// Plugin's platform config key, e.g., "macos", "ios".
String get pluginConfigKey;
/// Whether the platform exists in the project.
bool existsSync();
}
/// Represents the Android sub-project of a Flutter project.
///
/// Instances will reflect the contents of the `android/` sub-folder of
/// Flutter applications and the `.android/` sub-folder of Flutter module projects.
class AndroidProject extends FlutterProjectPlatform {
AndroidProject._(this.parent);
// User facing string when java/gradle/agp versions are compatible.
@visibleForTesting
static const String validJavaGradleAgpString = 'compatible java/gradle/agp';
// User facing link that describes compatibility between gradle and
// android gradle plugin.
static const String gradleAgpCompatUrl =
'https://developer.android.com/studio/releases/gradle-plugin#updating-gradle';
// User facing link that describes compatibility between java and the first
// version of gradle to support it.
static const String javaGradleCompatUrl =
'https://docs.gradle.org/current/userguide/compatibility.html#java';
/// The parent of this project.
final FlutterProject parent;
@override
String get pluginConfigKey => AndroidPlugin.kConfigKey;
static final RegExp _androidNamespacePattern = RegExp('android {[\\S\\s]+namespace\\s*=?\\s*[\'"](.+)[\'"]');
static final RegExp _applicationIdPattern = RegExp('^\\s*applicationId\\s*=?\\s*[\'"](.*)[\'"]\\s*\$');
static final RegExp _imperativeKotlinPluginPattern = RegExp('^\\s*apply plugin\\:\\s+[\'"]kotlin-android[\'"]\\s*\$');
static final RegExp _declarativeKotlinPluginPattern = RegExp('^\\s*id\\s+[\'"]kotlin-android[\'"]\\s*\$');
/// Pattern used to find the assignment of the "group" property in Gradle.
/// Expected example: `group "dev.flutter.plugin"`
/// Regex is used in both Groovy and Kotlin Gradle files.
static final RegExp _groupPattern = RegExp('^\\s*group\\s*=?\\s*[\'"](.*)[\'"]\\s*\$');
/// The Gradle root directory of the Android host app. This is the directory
/// containing the `app/` subdirectory and the `settings.gradle` file that
/// includes it in the overall Gradle project.
Directory get hostAppGradleRoot {
if (!isModule || _editableHostAppDirectory.existsSync()) {
return _editableHostAppDirectory;
}
return ephemeralDirectory;
}
/// The Gradle root directory of the Android wrapping of Flutter and plugins.
/// This is the same as [hostAppGradleRoot] except when the project is
/// a Flutter module with an editable host app.
Directory get _flutterLibGradleRoot => isModule ? ephemeralDirectory : _editableHostAppDirectory;
Directory get ephemeralDirectory => parent.directory.childDirectory('.android');
Directory get _editableHostAppDirectory => parent.directory.childDirectory('android');
/// True if the parent Flutter project is a module.
bool get isModule => parent.isModule;
/// True if the parent Flutter project is a plugin.
bool get isPlugin => parent.isPlugin;
/// True if the Flutter project is using the AndroidX support library.
bool get usesAndroidX => parent.usesAndroidX;
/// Returns true if the current version of the Gradle plugin is supported.
late final bool isSupportedVersion = _computeSupportedVersion();
/// Gets all build variants of this project.
Future<List<String>> getBuildVariants() async {
if (!existsSync() || androidBuilder == null) {
return const <String>[];
}
return androidBuilder!.getBuildVariants(project: parent);
}
/// Outputs app link related settings into a json file.
///
/// The return future resolves to the path of the json file.
///
/// The future resolves to null if it fails to retrieve app link settings.
Future<String> outputsAppLinkSettings({required String variant}) async {
if (!existsSync() || androidBuilder == null) {
throwToolExit('Target directory $hostAppGradleRoot is not an Android project');
}
return androidBuilder!.outputsAppLinkSettings(variant, project: parent);
}
bool _computeSupportedVersion() {
final FileSystem fileSystem = hostAppGradleRoot.fileSystem;
final File plugin = hostAppGradleRoot.childFile(
fileSystem.path.join('buildSrc', 'src', 'main', 'groovy', 'FlutterPlugin.groovy'));
if (plugin.existsSync()) {
return false;
}
try {
for (final String line in appGradleFile.readAsLinesSync()) {
// This syntax corresponds to applying the Flutter Gradle Plugin with a
// script.
// See https://docs.gradle.org/current/userguide/plugins.html#sec:script_plugins.
final bool fileBasedApply = line.contains(RegExp(r'apply from: .*/flutter.gradle'));
// This syntax corresponds to applying the Flutter Gradle Plugin using
// the declarative "plugins {}" block after including it in the
// pluginManagement block of the settings.gradle file.
// See https://docs.gradle.org/current/userguide/composite_builds.html#included_plugin_builds,
// as well as the settings.gradle and build.gradle templates.
final bool declarativeApply = line.contains('dev.flutter.flutter-gradle-plugin');
// This case allows for flutter run/build to work for modules. It does
// not guarantee the Flutter Gradle Plugin is applied.
final bool managed = line.contains(RegExp('def flutterPluginVersion = [\'"]managed[\'"]'));
if (fileBasedApply || declarativeApply || managed) {
return true;
}
}
} on FileSystemException {
return false;
}
return false;
}
/// True, if the app project is using Kotlin.
bool get isKotlin {
final bool imperativeMatch = firstMatchInFile(appGradleFile, _imperativeKotlinPluginPattern) != null;
final bool declarativeMatch = firstMatchInFile(appGradleFile, _declarativeKotlinPluginPattern) != null;
return imperativeMatch || declarativeMatch;
}
/// Gets top-level Gradle build file.
/// See https://developer.android.com/build#top-level.
///
/// The file must exist and it must be written in either Groovy (build.gradle)
/// or Kotlin (build.gradle.kts).
File get hostAppGradleFile {
final File buildGroovy = hostAppGradleRoot.childFile('build.gradle');
final File buildKotlin = hostAppGradleRoot.childFile('build.gradle.kts');
if (buildGroovy.existsSync() && buildKotlin.existsSync()) {
// We mimic Gradle's behavior of preferring Groovy over Kotlin when both files exist.
return buildGroovy;
}
if (buildKotlin.existsSync()) {
return buildKotlin;
}
// TODO(bartekpacia): An exception should be thrown when neither
// build.gradle nor build.gradle.kts exist, instead of falling back to the
// Groovy file. See #141180.
return buildGroovy;
}
/// Gets the module-level build.gradle file.
/// See https://developer.android.com/build#module-level.
///
/// The file must exist and it must be written in either Groovy (build.gradle)
/// or Kotlin (build.gradle.kts).
File get appGradleFile {
final Directory appDir = hostAppGradleRoot.childDirectory('app');
final File buildGroovy = appDir.childFile('build.gradle');
final File buildKotlin = appDir.childFile('build.gradle.kts');
if (buildGroovy.existsSync() && buildKotlin.existsSync()) {
// We mimic Gradle's behavior of preferring Groovy over Kotlin when both files exist.
return buildGroovy;
}
if (buildKotlin.existsSync()) {
return buildKotlin;
}
// TODO(bartekpacia): An exception should be thrown when neither
// build.gradle nor build.gradle.kts exist, instead of falling back to the
// Groovy file. See #141180.
return buildGroovy;
}
File get appManifestFile {
if (isUsingGradle) {
return hostAppGradleRoot
.childDirectory('app')
.childDirectory('src')
.childDirectory('main')
.childFile('AndroidManifest.xml');
}
return hostAppGradleRoot.childFile('AndroidManifest.xml');
}
File get gradleAppOutV1File => gradleAppOutV1Directory.childFile('app-debug.apk');
Directory get gradleAppOutV1Directory {
return globals.fs.directory(globals.fs.path.join(hostAppGradleRoot.path, 'app', 'build', 'outputs', 'apk'));
}
/// Whether the current flutter project has an Android sub-project.
@override
bool existsSync() {
return parent.isModule || _editableHostAppDirectory.existsSync();
}
/// Check if the versions of Java, Gradle and AGP are compatible.
///
/// This is expected to be called from
/// flutter_tools/lib/src/project_validator.dart.
Future<ProjectValidatorResult> validateJavaAndGradleAgpVersions() async {
// Constructing ProjectValidatorResult happens here and not in
// flutter_tools/lib/src/project_validator.dart because of the additional
// Complexity of variable status values and error string formatting.
const String visibleName = 'Java/Gradle/Android Gradle Plugin';
final CompatibilityResult validJavaGradleAgpVersions =
await hasValidJavaGradleAgpVersions();
return ProjectValidatorResult(
name: visibleName,
value: validJavaGradleAgpVersions.description,
status: validJavaGradleAgpVersions.success
? StatusProjectValidator.success
: StatusProjectValidator.error,
);
}
/// Ensures Java SDK is compatible with the project's Gradle version and
/// the project's Gradle version is compatible with the AGP version used
/// in build.gradle.
Future<CompatibilityResult> hasValidJavaGradleAgpVersions() async {
final String? gradleVersion = await gradle.getGradleVersion(
hostAppGradleRoot, globals.logger, globals.processManager);
final String? agpVersion =
gradle.getAgpVersion(hostAppGradleRoot, globals.logger);
final String? javaVersion = versionToParsableString(globals.java?.version);
// Assume valid configuration.
String description = validJavaGradleAgpString;
final bool compatibleGradleAgp = gradle.validateGradleAndAgp(globals.logger,
gradleV: gradleVersion, agpV: agpVersion);
final bool compatibleJavaGradle = gradle.validateJavaAndGradle(
globals.logger,
javaV: javaVersion,
gradleV: gradleVersion);
// Begin description formatting.
if (!compatibleGradleAgp) {
final String gradleDescription = agpVersion != null
? 'Update Gradle to at least "${gradle.getGradleVersionFor(agpVersion)}".'
: '';
description = '''
Incompatible Gradle/AGP versions. \n
Gradle Version: $gradleVersion, AGP Version: $agpVersion
$gradleDescription\n
See the link below for more information:
$gradleAgpCompatUrl
''';
}
if (!compatibleJavaGradle) {
// Should contain the agp error (if present) but not the valid String.
description = '''
${compatibleGradleAgp ? '' : description}
Incompatible Java/Gradle versions.
Java Version: $javaVersion, Gradle Version: $gradleVersion\n
See the link below for more information:
$javaGradleCompatUrl
''';
}
return CompatibilityResult(
compatibleJavaGradle && compatibleGradleAgp, description);
}
bool get isUsingGradle {
return hostAppGradleFile.existsSync();
}
String? get applicationId {
return firstMatchInFile(appGradleFile, _applicationIdPattern)?.group(1);
}
/// Get the namespace for newer Android projects,
/// which replaces the `package` attribute in the Manifest.xml.
String? get namespace {
try {
// firstMatchInFile() reads per line but `_androidNamespacePattern` matches a multiline pattern.
return _androidNamespacePattern.firstMatch(appGradleFile.readAsStringSync())?.group(1);
} on FileSystemException {
return null;
}
}
String? get group {
return firstMatchInFile(hostAppGradleFile, _groupPattern)?.group(1);
}
/// The build directory where the Android artifacts are placed.
Directory get buildDirectory {
return parent.buildDirectory;
}
Future<void> ensureReadyForPlatformSpecificTooling({DeprecationBehavior deprecationBehavior = DeprecationBehavior.none}) async {
if (isModule && _shouldRegenerateFromTemplate()) {
await _regenerateLibrary();
// Add ephemeral host app, if an editable host app does not already exist.
if (!_editableHostAppDirectory.existsSync()) {
await _overwriteFromTemplate(globals.fs.path.join('module', 'android', 'host_app_common'), ephemeralDirectory);
await _overwriteFromTemplate(globals.fs.path.join('module', 'android', 'host_app_ephemeral'), ephemeralDirectory);
}
}
if (!hostAppGradleRoot.existsSync()) {
return;
}
gradle.updateLocalProperties(project: parent, requireAndroidSdk: false);
}
bool _shouldRegenerateFromTemplate() {
return globals.fsUtils.isOlderThanReference(
entity: ephemeralDirectory,
referenceFile: parent.pubspecFile,
) || globals.cache.isOlderThanToolsStamp(ephemeralDirectory);
}
File get localPropertiesFile => _flutterLibGradleRoot.childFile('local.properties');
Directory get pluginRegistrantHost => _flutterLibGradleRoot.childDirectory(isModule ? 'Flutter' : 'app');
Future<void> _regenerateLibrary() async {
ErrorHandlingFileSystem.deleteIfExists(ephemeralDirectory, recursive: true);
await _overwriteFromTemplate(
globals.fs.path.join(
'module',
'android',
'library_new_embedding',
),
ephemeralDirectory);
await _overwriteFromTemplate(globals.fs.path.join(
'module',
'android',
'gradle'), ephemeralDirectory);
globals.gradleUtils?.injectGradleWrapperIfNeeded(ephemeralDirectory);
}
Future<void> _overwriteFromTemplate(String path, Directory target) async {
final Template template = await Template.fromName(
path,
fileSystem: globals.fs,
templateManifest: null,
logger: globals.logger,
templateRenderer: globals.templateRenderer,
);
final String androidIdentifier = parent.manifest.androidPackage ?? 'com.example.${parent.manifest.appName}';
template.render(
target,
<String, Object>{
'android': true,
'projectName': parent.manifest.appName,
'androidIdentifier': androidIdentifier,
'androidX': usesAndroidX,
'agpVersion': gradle.templateAndroidGradlePluginVersion,
'agpVersionForModule': gradle.templateAndroidGradlePluginVersionForModule,
'kotlinVersion': gradle.templateKotlinGradlePluginVersion,
'gradleVersion': gradle.templateDefaultGradleVersion,
'compileSdkVersion': gradle.compileSdkVersion,
'minSdkVersion': gradle.minSdkVersion,
'ndkVersion': gradle.ndkVersion,
'targetSdkVersion': gradle.targetSdkVersion,
},
printStatusWhenWriting: false,
);
}
void checkForDeprecation({DeprecationBehavior deprecationBehavior = DeprecationBehavior.none}) {
if (deprecationBehavior == DeprecationBehavior.none) {
return;
}
final AndroidEmbeddingVersionResult result = computeEmbeddingVersion();
if (result.version != AndroidEmbeddingVersion.v1) {
return;
}
// The v1 android embedding has been deleted.
throwToolExit(
'Build failed due to use of deleted Android v1 embedding.',
exitCode: 1,
);
}
AndroidEmbeddingVersion getEmbeddingVersion() {
final AndroidEmbeddingVersion androidEmbeddingVersion = computeEmbeddingVersion().version;
if (androidEmbeddingVersion == AndroidEmbeddingVersion.v1) {
throwToolExit(
'Build failed due to use of deleted Android v1 embedding.',
exitCode: 1,
);
}
return androidEmbeddingVersion;
}
AndroidEmbeddingVersionResult computeEmbeddingVersion() {
if (isModule) {
// A module type's Android project is used in add-to-app scenarios and
// only supports the V2 embedding.
return AndroidEmbeddingVersionResult(AndroidEmbeddingVersion.v2, 'Is add-to-app module');
}
if (isPlugin) {
// Plugins do not use an appManifest, so we stop here.
//
// TODO(garyq): This method does not currently check for code references to
// the v1 embedding, we should check for this once removal is further along.
return AndroidEmbeddingVersionResult(AndroidEmbeddingVersion.v2, 'Is plugin');
}
if (!appManifestFile.existsSync()) {
return AndroidEmbeddingVersionResult(AndroidEmbeddingVersion.v1, 'No `${appManifestFile.absolute.path}` file');
}
XmlDocument document;
try {
document = XmlDocument.parse(appManifestFile.readAsStringSync());
} on XmlException {
throwToolExit('Error parsing $appManifestFile '
'Please ensure that the android manifest is a valid XML document and try again.');
} on FileSystemException {
throwToolExit('Error reading $appManifestFile even though it exists. '
'Please ensure that you have read permission to this file and try again.');
}
for (final XmlElement application in document.findAllElements('application')) {
final String? applicationName = application.getAttribute('android:name');
if (applicationName == 'io.flutter.app.FlutterApplication') {
return AndroidEmbeddingVersionResult(AndroidEmbeddingVersion.v1, '${appManifestFile.absolute.path} uses `android:name="io.flutter.app.FlutterApplication"`');
}
}
for (final XmlElement metaData in document.findAllElements('meta-data')) {
final String? name = metaData.getAttribute('android:name');
if (name == 'flutterEmbedding') {
final String? embeddingVersionString = metaData.getAttribute('android:value');
if (embeddingVersionString == '1') {
return AndroidEmbeddingVersionResult(AndroidEmbeddingVersion.v1, '${appManifestFile.absolute.path} `<meta-data android:name="flutterEmbedding"` has value 1');
}
if (embeddingVersionString == '2') {
return AndroidEmbeddingVersionResult(AndroidEmbeddingVersion.v2, '${appManifestFile.absolute.path} `<meta-data android:name="flutterEmbedding"` has value 2');
}
}
}
return AndroidEmbeddingVersionResult(AndroidEmbeddingVersion.v1, 'No `<meta-data android:name="flutterEmbedding" android:value="2"/>` in ${appManifestFile.absolute.path}');
}
}
/// Iteration of the embedding Java API in the engine used by the Android project.
enum AndroidEmbeddingVersion {
/// V1 APIs based on io.flutter.app.FlutterActivity.
v1,
/// V2 APIs based on io.flutter.embedding.android.FlutterActivity.
v2,
}
/// Data class that holds the results of checking for embedding version.
///
/// This class includes the reason why a particular embedding was selected.
class AndroidEmbeddingVersionResult {
AndroidEmbeddingVersionResult(this.version, this.reason);
/// The embedding version.
AndroidEmbeddingVersion version;
/// The reason why the embedding version was selected.
String reason;
}
// What the tool should do when encountering deprecated API in applications.
enum DeprecationBehavior {
// The command being run does not care about deprecation status.
none,
// The command should continue and ignore the deprecation warning.
ignore,
// The command should exit the tool.
exit,
}
/// Represents the web sub-project of a Flutter project.
class WebProject extends FlutterProjectPlatform {
WebProject._(this.parent);
final FlutterProject parent;
@override
String get pluginConfigKey => WebPlugin.kConfigKey;
/// Whether this flutter project has a web sub-project.
@override
bool existsSync() {
return parent.directory.childDirectory('web').existsSync()
&& indexFile.existsSync();
}
/// The 'lib' directory for the application.
Directory get libDirectory => parent.directory.childDirectory('lib');
/// The directory containing additional files for the application.
Directory get directory => parent.directory.childDirectory('web');
/// The html file used to host the flutter web application.
File get indexFile => parent.directory
.childDirectory('web')
.childFile('index.html');
/// The .dart_tool/dartpad directory
Directory get dartpadToolDirectory => parent.directory
.childDirectory('.dart_tool')
.childDirectory('dartpad');
Future<void> ensureReadyForPlatformSpecificTooling() async {
/// Create .dart_tool/dartpad/web_plugin_registrant.dart.
/// See: https://github.com/dart-lang/dart-services/pull/874
await injectBuildTimePluginFiles(
parent,
destination: dartpadToolDirectory,
webPlatform: true,
);
}
}
/// The Fuchsia sub project.
class FuchsiaProject {
FuchsiaProject._(this.project);
final FlutterProject project;
Directory? _editableHostAppDirectory;
Directory get editableHostAppDirectory =>
_editableHostAppDirectory ??= project.directory.childDirectory('fuchsia');
bool existsSync() => editableHostAppDirectory.existsSync();
Directory? _meta;
Directory get meta =>
_meta ??= editableHostAppDirectory.childDirectory('meta');
}
// Combines success and a description into one object that can be returned
// together.
@visibleForTesting
class CompatibilityResult {
CompatibilityResult(this.success, this.description);
final bool success;
final String description;
}
/// Converts a [Version] to a string that can be parsed by [Version.parse].
String? versionToParsableString(Version? version) {
if (version == null) {
return null;
}
return '${version.major}.${version.minor}.${version.patch}';
}
| flutter/packages/flutter_tools/lib/src/project.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/project.dart",
"repo_id": "flutter",
"token_count": 12047
} | 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:unified_analytics/unified_analytics.dart';
import '../base/config.dart';
import '../base/io.dart';
import '../features.dart';
import '../globals.dart' as globals;
import '../version.dart';
/// This function is called from within the context runner to perform
/// checks that are necessary for determining if a no-op version of
/// [Analytics] gets returned.
///
/// When [enableAsserts] is set to `true`, various assert statements
/// will be enabled to ensure usage of this class is within GA4 limitations.
///
/// For testing purposes, pass in a [FakeAnalytics] instance initialized with
/// an in-memory [FileSystem] to prevent writing to disk.
Analytics getAnalytics({
required bool runningOnBot,
required FlutterVersion flutterVersion,
required Map<String, String> environment,
required String? clientIde,
required Config config,
bool enableAsserts = false,
FakeAnalytics? analyticsOverride,
}) {
final String version = flutterVersion.getVersionString(redactUnknownBranches: true);
final bool suppressEnvFlag = environment['FLUTTER_SUPPRESS_ANALYTICS']?.toLowerCase() == 'true';
if (// 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) {
return const NoOpAnalytics();
}
// Providing an override of the [Analytics] instance is preferred when
// running tests for this function to prevent writing to the filesystem
if (analyticsOverride != null) {
return analyticsOverride;
}
return Analytics(
tool: DashTool.flutterTool,
flutterChannel: flutterVersion.channel,
flutterVersion: flutterVersion.frameworkVersion,
dartVersion: flutterVersion.dartSdkVersion,
enableAsserts: enableAsserts,
clientIde: clientIde,
enabledFeatures: getEnabledFeatures(config),
);
}
/// Uses the [Config] object to get enabled features.
String? getEnabledFeatures(Config config) {
// Create string with all enabled features to send as user property
final Iterable<Feature> enabledFeatures = allFeatures.where((Feature feature) {
final String? configSetting = feature.configSetting;
return configSetting != null && config.getValue(configSetting) == true;
});
return enabledFeatures.isNotEmpty
? enabledFeatures
.map((Feature feature) => feature.configSetting)
.join(',')
: null;
}
/// Function to safely grab the max rss from [ProcessInfo].
int? getMaxRss(ProcessInfo processInfo) {
try {
return globals.processInfo.maxRss;
} on Exception catch (error) {
globals.printTrace('Querying maxRss failed with error: $error');
}
return null;
}
| flutter/packages/flutter_tools/lib/src/reporting/unified_analytics.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/reporting/unified_analytics.dart",
"repo_id": "flutter",
"token_count": 905
} | 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:process/process.dart';
import '../base/file_system.dart';
import '../base/io.dart';
import '../base/logger.dart';
import '../convert.dart';
import '../web/compile.dart';
import 'test_compiler.dart';
import 'test_config.dart';
/// Helper class to start golden file comparison in a separate process.
///
/// The golden file comparator is configured using flutter_test_config.dart and that
/// file can contain arbitrary Dart code that depends on dart:ui. Thus it has to
/// be executed in a `flutter_tester` environment. This helper class generates a
/// Dart file configured with flutter_test_config.dart to perform the comparison
/// of golden files.
class TestGoldenComparator {
/// Creates a [TestGoldenComparator] instance.
TestGoldenComparator(this.shellPath, this.compilerFactory, {
required Logger logger,
required FileSystem fileSystem,
required ProcessManager processManager,
required this.webRenderer,
}) : tempDir = fileSystem.systemTempDirectory.createTempSync('flutter_web_platform.'),
_logger = logger,
_fileSystem = fileSystem,
_processManager = processManager;
final String? shellPath;
final Directory tempDir;
final TestCompiler Function() compilerFactory;
final Logger _logger;
final FileSystem _fileSystem;
final ProcessManager _processManager;
final WebRendererMode webRenderer;
TestCompiler? _compiler;
TestGoldenComparatorProcess? _previousComparator;
Uri? _previousTestUri;
Future<void> close() async {
tempDir.deleteSync(recursive: true);
await _compiler?.dispose();
await _previousComparator?.close();
}
/// Start golden comparator in a separate process. Start one file per test file
/// to reduce the overhead of starting `flutter_tester`.
Future<TestGoldenComparatorProcess?> _processForTestFile(Uri testUri) async {
if (testUri == _previousTestUri) {
return _previousComparator!;
}
final String bootstrap = TestGoldenComparatorProcess.generateBootstrap(_fileSystem.file(testUri), testUri, logger: _logger);
final Process? process = await _startProcess(bootstrap);
if (process == null) {
return null;
}
unawaited(_previousComparator?.close());
_previousComparator = TestGoldenComparatorProcess(process, logger: _logger);
_previousTestUri = testUri;
return _previousComparator!;
}
Future<Process?> _startProcess(String testBootstrap) async {
// Prepare the Dart file that will talk to us and start the test.
final File listenerFile = (await tempDir.createTemp('listener')).childFile('listener.dart');
await listenerFile.writeAsString(testBootstrap);
// Lazily create the compiler
_compiler = _compiler ?? compilerFactory();
final String? output = await _compiler!.compile(listenerFile.uri);
if (output == null) {
return null;
}
final List<String> command = <String>[
shellPath!,
'--disable-vm-service',
'--non-interactive',
'--packages=${_fileSystem.path.join('.dart_tool', 'package_config.json')}',
output,
];
final Map<String, String> environment = <String, String>{
// Chrome is the only supported browser currently.
'FLUTTER_TEST_BROWSER': 'chrome',
'FLUTTER_WEB_RENDERER': webRenderer == WebRendererMode.html ? 'html' : 'canvaskit',
};
return _processManager.start(command, environment: environment);
}
Future<String?> compareGoldens(Uri testUri, Uint8List bytes, Uri goldenKey, bool? updateGoldens) async {
final File imageFile = await (await tempDir.createTemp('image')).childFile('image').writeAsBytes(bytes);
final TestGoldenComparatorProcess? process = await _processForTestFile(testUri);
if (process == null) {
return 'process was null';
}
process.sendCommand(imageFile, goldenKey, updateGoldens);
final Map<String, dynamic> result = await process.getResponse();
return (result['success'] as bool) ? null : ((result['message'] as String?) ?? 'does not match');
}
}
/// Represents a `flutter_tester` process started for golden comparison. Also
/// handles communication with the child process.
class TestGoldenComparatorProcess {
/// Creates a [TestGoldenComparatorProcess] backed by [process].
TestGoldenComparatorProcess(this.process, {required Logger logger}) : _logger = logger {
// Pipe stdout and stderr to printTrace and printError.
// Also parse stdout as a stream of JSON objects.
streamIterator = StreamIterator<Map<String, dynamic>>(
process.stdout
.transform<String>(utf8.decoder)
.transform<String>(const LineSplitter())
.where((String line) {
logger.printTrace('<<< $line');
return line.isNotEmpty && line[0] == '{';
})
.map<dynamic>(jsonDecode)
.cast<Map<String, dynamic>>());
process.stderr
.transform<String>(utf8.decoder)
.transform<String>(const LineSplitter())
.forEach((String line) {
logger.printError('<<< $line');
});
}
final Logger _logger;
final Process process;
late StreamIterator<Map<String, dynamic>> streamIterator;
Future<void> close() async {
process.kill();
await process.exitCode;
}
void sendCommand(File imageFile, Uri? goldenKey, bool? updateGoldens) {
final Object command = jsonEncode(<String, dynamic>{
'imageFile': imageFile.path,
'key': goldenKey.toString(),
'update': updateGoldens,
});
_logger.printTrace('Preparing to send command: $command');
process.stdin.writeln(command);
}
Future<Map<String, dynamic>> getResponse() async {
final bool available = await streamIterator.moveNext();
assert(available);
return streamIterator.current;
}
static String generateBootstrap(File testFile, Uri testUri, {required Logger logger}) {
final File? testConfigFile = findTestConfigFile(testFile, logger);
// Generate comparator process for the file.
return '''
import 'dart:convert'; // flutter_ignore: dart_convert_import
import 'dart:io'; // flutter_ignore: dart_io_import
import 'package:flutter_test/flutter_test.dart';
${testConfigFile != null ? "import '${Uri.file(testConfigFile.path)}' as test_config;" : ""}
void main() async {
LocalFileComparator comparator = LocalFileComparator(Uri.parse('$testUri'));
goldenFileComparator = comparator;
${testConfigFile != null ? 'test_config.testExecutable(() async {' : ''}
final commands = stdin
.transform<String>(utf8.decoder)
.transform<String>(const LineSplitter())
.map<dynamic>(jsonDecode);
await for (final dynamic command in commands) {
if (command is Map<String, dynamic>) {
File imageFile = File(command['imageFile'] as String);
Uri goldenKey = Uri.parse(command['key'] as String);
bool update = command['update'] as bool;
final bytes = await File(imageFile.path).readAsBytes();
if (update) {
await goldenFileComparator.update(goldenKey, bytes);
print(jsonEncode({'success': true}));
} else {
try {
bool success = await goldenFileComparator.compare(bytes, goldenKey);
print(jsonEncode({'success': success}));
} on Exception catch (ex) {
print(jsonEncode({'success': false, 'message': '\$ex'}));
}
}
} else {
print('object type is not right');
}
}
${testConfigFile != null ? '});' : ''}
}
''';
}
}
| flutter/packages/flutter_tools/lib/src/test/flutter_web_goldens.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/test/flutter_web_goldens.dart",
"repo_id": "flutter",
"token_count": 2616
} | 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 'package:meta/meta.dart' show visibleForTesting;
import 'package:vm_service/vm_service.dart' as vm_service;
import 'base/common.dart';
import 'base/context.dart';
import 'base/io.dart' as io;
import 'base/logger.dart';
import 'base/utils.dart';
import 'cache.dart';
import 'convert.dart';
import 'device.dart';
import 'globals.dart' as globals;
import 'project.dart';
import 'version.dart';
const String kResultType = 'type';
const String kResultTypeSuccess = 'Success';
const String kGetSkSLsMethod = '_flutter.getSkSLs';
const String kSetAssetBundlePathMethod = '_flutter.setAssetBundlePath';
const String kFlushUIThreadTasksMethod = '_flutter.flushUIThreadTasks';
const String kRunInViewMethod = '_flutter.runInView';
const String kListViewsMethod = '_flutter.listViews';
const String kScreenshotSkpMethod = '_flutter.screenshotSkp';
const String kRenderFrameWithRasterStatsMethod = '_flutter.renderFrameWithRasterStats';
const String kReloadAssetFonts = '_flutter.reloadAssetFonts';
const String kFlutterToolAlias = 'Flutter Tools';
const String kReloadSourcesServiceName = 'reloadSources';
const String kHotRestartServiceName = 'hotRestart';
const String kFlutterVersionServiceName = 'flutterVersion';
const String kCompileExpressionServiceName = 'compileExpression';
const String kFlutterMemoryInfoServiceName = 'flutterMemoryInfo';
const String kFlutterGetSkSLServiceName = 'flutterGetSkSL';
/// The error response code from an unrecoverable compilation failure.
const int kIsolateReloadBarred = 1005;
/// Override `WebSocketConnector` in [context] to use a different constructor
/// for [WebSocket]s (used by tests).
typedef WebSocketConnector = Future<io.WebSocket> Function(String url, {io.CompressionOptions compression, required Logger logger});
typedef PrintStructuredErrorLogMethod = void Function(vm_service.Event);
WebSocketConnector _openChannel = _defaultOpenChannel;
/// A testing only override of the WebSocket connector.
///
/// Provide a `null` value to restore the original connector.
@visibleForTesting
set openChannelForTesting(WebSocketConnector? connector) {
_openChannel = connector ?? _defaultOpenChannel;
}
/// The error codes for the JSON-RPC standard, including VM service specific
/// error codes.
///
/// See also: https://www.jsonrpc.org/specification#error_object
abstract class RPCErrorCodes {
/// The method does not exist or is not available.
static const int kMethodNotFound = -32601;
/// Invalid method parameter(s), such as a mismatched type.
static const int kInvalidParams = -32602;
/// Internal JSON-RPC error.
static const int kInternalError = -32603;
/// Application specific error codes.
static const int kServerError = -32000;
/// Non-standard JSON-RPC error codes:
/// The VM service or extension service has disappeared.
static const int kServiceDisappeared = 112;
}
/// A function that reacts to the invocation of the 'reloadSources' service.
///
/// The VM Service Protocol allows clients to register custom services that
/// can be invoked by other clients through the service protocol itself.
///
/// Clients like VmService use external 'reloadSources' services,
/// when available, instead of the VM internal one. This allows these clients to
/// invoke Flutter HotReload when connected to a Flutter Application started in
/// hot mode.
///
/// See: https://github.com/dart-lang/sdk/issues/30023
typedef ReloadSources = Future<void> Function(
String isolateId, {
bool force,
bool pause,
});
typedef Restart = Future<void> Function({ bool pause });
typedef CompileExpression = Future<String> Function(
String isolateId,
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,
);
/// A method that pulls an SkSL shader from the device and writes it to a file.
///
/// The name of the file returned as a result.
typedef GetSkSLMethod = Future<String?> Function();
Future<io.WebSocket> _defaultOpenChannel(String url, {
io.CompressionOptions compression = io.CompressionOptions.compressionDefault,
required Logger logger,
}) async {
Duration delay = const Duration(milliseconds: 100);
int attempts = 0;
io.WebSocket? socket;
Future<void> handleError(Object? e) async {
void Function(String) printVisibleTrace = logger.printTrace;
if (attempts == 10) {
logger.printStatus('Connecting to the VM Service is taking longer than expected...');
} else if (attempts == 20) {
logger.printStatus('Still attempting to connect to the VM Service...');
logger.printStatus(
'If you do NOT see the Flutter application running, it might have '
'crashed. The device logs (e.g. from adb or XCode) might have more '
'details.');
logger.printStatus(
'If you do see the Flutter application running on the device, try '
're-running with --host-vmservice-port to use a specific port known to '
'be available.');
} else if (attempts % 50 == 0) {
printVisibleTrace = logger.printStatus;
}
printVisibleTrace('Exception attempting to connect to the VM Service: $e');
printVisibleTrace('This was attempt #$attempts. Will retry in $delay.');
// Delay next attempt.
await Future<void>.delayed(delay);
// Back off exponentially, up to 1600ms per attempt.
if (delay < const Duration(seconds: 1)) {
delay *= 2;
}
}
final WebSocketConnector constructor = context.get<WebSocketConnector>() ?? (String url, {
io.CompressionOptions compression = io.CompressionOptions.compressionDefault,
Logger? logger,
}) => io.WebSocket.connect(url, compression: compression);
while (socket == null) {
attempts += 1;
try {
socket = await constructor(url, compression: compression, logger: logger);
} on io.WebSocketException catch (e) {
await handleError(e);
} on io.SocketException catch (e) {
await handleError(e);
}
}
return socket;
}
/// Override `VMServiceConnector` in [context] to return a different VMService
/// from [VMService.connect] (used by tests).
typedef VMServiceConnector = Future<FlutterVmService> Function(Uri httpUri, {
ReloadSources? reloadSources,
Restart? restart,
CompileExpression? compileExpression,
GetSkSLMethod? getSkSLMethod,
FlutterProject? flutterProject,
PrintStructuredErrorLogMethod? printStructuredErrorLogMethod,
io.CompressionOptions compression,
Device? device,
required Logger logger,
});
/// Set up the VM Service client by attaching services for each of the provided
/// callbacks.
///
/// All parameters besides [vmService] may be null.
Future<vm_service.VmService> setUpVmService({
ReloadSources? reloadSources,
Restart? restart,
CompileExpression? compileExpression,
Device? device,
GetSkSLMethod? skSLMethod,
FlutterProject? flutterProject,
PrintStructuredErrorLogMethod? printStructuredErrorLogMethod,
required vm_service.VmService vmService,
}) async {
// Each service registration requires a request to the attached VM service. Since the
// order of these requests does not matter, store each future in a list and await
// all at the end of this method.
final List<Future<vm_service.Success?>> registrationRequests = <Future<vm_service.Success?>>[];
if (reloadSources != null) {
vmService.registerServiceCallback(kReloadSourcesServiceName, (Map<String, Object?> params) async {
final String isolateId = _validateRpcStringParam('reloadSources', params, 'isolateId');
final bool force = _validateRpcBoolParam('reloadSources', params, 'force');
final bool pause = _validateRpcBoolParam('reloadSources', params, 'pause');
await reloadSources(isolateId, force: force, pause: pause);
return <String, Object>{
'result': <String, Object>{
kResultType: kResultTypeSuccess,
},
};
});
registrationRequests.add(vmService.registerService(kReloadSourcesServiceName, kFlutterToolAlias));
}
if (restart != null) {
vmService.registerServiceCallback(kHotRestartServiceName, (Map<String, Object?> params) async {
final bool pause = _validateRpcBoolParam('compileExpression', params, 'pause');
await restart(pause: pause);
return <String, Object>{
'result': <String, Object>{
kResultType: kResultTypeSuccess,
},
};
});
registrationRequests.add(vmService.registerService(kHotRestartServiceName, kFlutterToolAlias));
}
vmService.registerServiceCallback(kFlutterVersionServiceName, (Map<String, Object?> params) async {
final FlutterVersion version = context.get<FlutterVersion>() ?? FlutterVersion(
fs: globals.fs,
flutterRoot: Cache.flutterRoot!,
);
final Map<String, Object> versionJson = version.toJson();
versionJson['frameworkRevisionShort'] = version.frameworkRevisionShort;
versionJson['engineRevisionShort'] = version.engineRevisionShort;
return <String, Object>{
'result': <String, Object>{
kResultType: kResultTypeSuccess,
...versionJson,
},
};
});
registrationRequests.add(vmService.registerService(kFlutterVersionServiceName, kFlutterToolAlias));
if (compileExpression != null) {
vmService.registerServiceCallback(kCompileExpressionServiceName, (Map<String, Object?> params) async {
final String isolateId = _validateRpcStringParam('compileExpression', params, 'isolateId');
final String expression = _validateRpcStringParam('compileExpression', params, 'expression');
final List<String> definitions = List<String>.from(params['definitions']! as List<Object?>);
final List<String> definitionTypes = List<String>.from(params['definitionTypes']! as List<Object?>);
final List<String> typeDefinitions = List<String>.from(params['typeDefinitions']! as List<Object?>);
final List<String> typeBounds = List<String>.from(params['typeBounds']! as List<Object?>);
final List<String> typeDefaults = List<String>.from(params['typeDefaults']! as List<Object?>);
final String libraryUri = params['libraryUri']! as String;
final String? klass = params['klass'] as String?;
final String? method = params['method'] as String?;
final bool isStatic = _validateRpcBoolParam('compileExpression', params, 'isStatic');
final String kernelBytesBase64 = await compileExpression(isolateId,
expression, definitions, definitionTypes, typeDefinitions, typeBounds, typeDefaults,
libraryUri, klass, method, isStatic);
return <String, Object>{
kResultType: kResultTypeSuccess,
'result': <String, String>{'kernelBytes': kernelBytesBase64},
};
});
registrationRequests.add(vmService.registerService(kCompileExpressionServiceName, kFlutterToolAlias));
}
if (device != null) {
vmService.registerServiceCallback(kFlutterMemoryInfoServiceName, (Map<String, Object?> params) async {
final MemoryInfo result = await device.queryMemoryInfo();
return <String, Object>{
'result': <String, Object>{
kResultType: kResultTypeSuccess,
...result.toJson(),
},
};
});
registrationRequests.add(vmService.registerService(kFlutterMemoryInfoServiceName, kFlutterToolAlias));
}
if (skSLMethod != null) {
vmService.registerServiceCallback(kFlutterGetSkSLServiceName, (Map<String, Object?> params) async {
final String? filename = await skSLMethod();
if (filename == null) {
return <String, Object>{
'result': <String, Object>{
kResultType: kResultTypeSuccess,
},
};
}
return <String, Object>{
'result': <String, Object>{
kResultType: kResultTypeSuccess,
'filename': filename,
},
};
});
registrationRequests.add(vmService.registerService(kFlutterGetSkSLServiceName, kFlutterToolAlias));
}
if (printStructuredErrorLogMethod != null) {
vmService.onExtensionEvent.listen(printStructuredErrorLogMethod);
registrationRequests.add(vmService
.streamListen(vm_service.EventStreams.kExtension)
.then<vm_service.Success?>(
(vm_service.Success success) => success,
// It is safe to ignore this error because we expect an error to be
// thrown if we're already subscribed.
onError: (Object error, StackTrace stackTrace) {
if (error is vm_service.RPCError) {
return null;
}
return Future<vm_service.Success?>.error(error, stackTrace);
},
),
);
}
try {
await Future.wait(registrationRequests);
} on vm_service.RPCError catch (e) {
throwToolExit('Failed to register service methods on attached VM Service: $e');
}
return vmService;
}
/// Connect to a Dart VM Service at [httpUri].
///
/// If the [reloadSources] parameter is not null, the 'reloadSources' service
/// will be registered. The VM Service Protocol allows clients to register
/// custom services that can be invoked by other clients through the service
/// protocol itself.
///
/// See: https://github.com/dart-lang/sdk/commit/df8bf384eb815cf38450cb50a0f4b62230fba217
Future<FlutterVmService> connectToVmService(
Uri httpUri, {
ReloadSources? reloadSources,
Restart? restart,
CompileExpression? compileExpression,
GetSkSLMethod? getSkSLMethod,
FlutterProject? flutterProject,
PrintStructuredErrorLogMethod? printStructuredErrorLogMethod,
io.CompressionOptions compression = io.CompressionOptions.compressionDefault,
Device? device,
required Logger logger,
}) async {
final VMServiceConnector connector = context.get<VMServiceConnector>() ?? _connect;
return connector(httpUri,
reloadSources: reloadSources,
restart: restart,
compileExpression: compileExpression,
compression: compression,
device: device,
getSkSLMethod: getSkSLMethod,
flutterProject: flutterProject,
printStructuredErrorLogMethod: printStructuredErrorLogMethod,
logger: logger,
);
}
Future<vm_service.VmService> createVmServiceDelegate(
Uri wsUri, {
io.CompressionOptions compression = io.CompressionOptions.compressionDefault,
required Logger logger,
}) async {
final io.WebSocket channel = await _openChannel(wsUri.toString(), compression: compression, logger: logger);
return vm_service.VmService(
channel,
channel.add,
disposeHandler: () async {
await channel.close();
},
);
}
Future<FlutterVmService> _connect(
Uri httpUri, {
ReloadSources? reloadSources,
Restart? restart,
CompileExpression? compileExpression,
GetSkSLMethod? getSkSLMethod,
FlutterProject? flutterProject,
PrintStructuredErrorLogMethod? printStructuredErrorLogMethod,
io.CompressionOptions compression = io.CompressionOptions.compressionDefault,
Device? device,
required Logger logger,
}) async {
final Uri wsUri = httpUri.replace(scheme: 'ws', path: urlContext.join(httpUri.path, 'ws'));
final vm_service.VmService delegateService = await createVmServiceDelegate(
wsUri, compression: compression, logger: logger,
);
final vm_service.VmService service = await setUpVmService(
reloadSources: reloadSources,
restart: restart,
compileExpression: compileExpression,
device: device,
skSLMethod: getSkSLMethod,
flutterProject: flutterProject,
printStructuredErrorLogMethod: printStructuredErrorLogMethod,
vmService: delegateService,
);
// This call is to ensure we are able to establish a connection instead of
// keeping on trucking and failing farther down the process.
await delegateService.getVersion();
return FlutterVmService(service, httpAddress: httpUri, wsAddress: wsUri);
}
String _validateRpcStringParam(String methodName, Map<String, Object?> params, String paramName) {
final Object? value = params[paramName];
if (value is! String || value.isEmpty) {
throw vm_service.RPCError(
methodName,
RPCErrorCodes.kInvalidParams,
"Invalid '$paramName': $value",
);
}
return value;
}
bool _validateRpcBoolParam(String methodName, Map<String, Object?> params, String paramName) {
final Object? value = params[paramName];
if (value != null && value is! bool) {
throw vm_service.RPCError(
methodName,
RPCErrorCodes.kInvalidParams,
"Invalid '$paramName': $value",
);
}
return (value as bool?) ?? false;
}
/// Peered to an Android/iOS FlutterView widget on a device.
class FlutterView {
FlutterView({
required this.id,
required this.uiIsolate,
});
factory FlutterView.parse(Map<String, Object?> json) {
final Map<String, Object?>? rawIsolate = json['isolate'] as Map<String, Object?>?;
vm_service.IsolateRef? isolate;
if (rawIsolate != null) {
rawIsolate['number'] = rawIsolate['number']?.toString();
isolate = vm_service.IsolateRef.parse(rawIsolate);
}
return FlutterView(
id: json['id']! as String,
uiIsolate: isolate,
);
}
final vm_service.IsolateRef? uiIsolate;
final String id;
bool get hasIsolate => uiIsolate != null;
@override
String toString() => id;
Map<String, Object?> toJson() {
return <String, Object?>{
'id': id,
'isolate': uiIsolate?.toJson(),
};
}
}
/// Flutter specific VM Service functionality.
class FlutterVmService {
FlutterVmService(
this.service, {
this.wsAddress,
this.httpAddress,
});
final vm_service.VmService service;
final Uri? wsAddress;
final Uri? httpAddress;
Future<vm_service.Response?> callMethodWrapper(
String method, {
String? isolateId,
Map<String, Object?>? args
}) async {
try {
return await service.callMethod(method, isolateId: isolateId, args: args);
} on vm_service.RPCError catch (e) {
// If the service disappears mid-request the tool is unable to recover
// and should begin to shutdown due to the service connection closing.
// Swallow the exception here and let the shutdown logic elsewhere deal
// with cleaning up.
if (e.code == RPCErrorCodes.kServiceDisappeared) {
return null;
}
rethrow;
}
}
/// Set the asset directory for the an attached Flutter view.
Future<void> setAssetDirectory({
required Uri assetsDirectory,
required String? viewId,
required String? uiIsolateId,
required bool windows,
}) async {
await callMethodWrapper(kSetAssetBundlePathMethod,
isolateId: uiIsolateId,
args: <String, Object?>{
'viewId': viewId,
'assetDirectory': assetsDirectory.toFilePath(windows: windows),
});
}
/// Retrieve the cached SkSL shaders from an attached Flutter view.
///
/// This method will only return data if `--cache-sksl` was provided as a
/// flutter run argument, and only then on physical devices.
Future<Map<String, Object?>?> getSkSLs({
required String viewId,
}) async {
final vm_service.Response? response = await callMethodWrapper(
kGetSkSLsMethod,
args: <String, String>{
'viewId': viewId,
},
);
if (response == null) {
return null;
}
return response.json?['SkSLs'] as Map<String, Object?>?;
}
/// Flush all tasks on the UI thread for an attached Flutter view.
///
/// This method is currently used only for benchmarking.
Future<void> flushUIThreadTasks({
required String uiIsolateId,
}) async {
await callMethodWrapper(
kFlushUIThreadTasksMethod,
args: <String, String>{
'isolateId': uiIsolateId,
},
);
}
/// Launch the Dart isolate with entrypoint [main] in the Flutter engine [viewId]
/// with [assetsDirectory] as the devFS.
///
/// This method is used by the tool to hot restart an already running Flutter
/// engine.
Future<void> runInView({
required String viewId,
required Uri main,
required Uri assetsDirectory,
}) async {
try {
await service.streamListen(vm_service.EventStreams.kIsolate);
} on vm_service.RPCError {
// Do nothing, since the tool is already subscribed.
}
final Future<void> onRunnable = service.onIsolateEvent.firstWhere((vm_service.Event event) {
return event.kind == vm_service.EventKind.kIsolateRunnable;
});
await callMethodWrapper(
kRunInViewMethod,
args: <String, Object>{
'viewId': viewId,
'mainScript': main.toString(),
'assetDirectory': assetsDirectory.toString(),
},
);
await onRunnable;
}
/// Renders the last frame with additional raster tracing enabled.
///
/// When a frame is rendered using this method it will incur additional cost
/// for rasterization which is not reflective of how long the frame takes in
/// production. This is primarily intended to be used to identify the layers
/// that result in the most raster perf degradation.
Future<Map<String, Object?>?> renderFrameWithRasterStats({
required String? viewId,
required String? uiIsolateId,
}) async {
final vm_service.Response? response = await callMethodWrapper(
kRenderFrameWithRasterStatsMethod,
isolateId: uiIsolateId,
args: <String, String?>{
'viewId': viewId,
},
);
return response?.json;
}
Future<String> flutterDebugDumpApp({
required String isolateId,
}) async {
final Map<String, Object?>? response = await invokeFlutterExtensionRpcRaw(
'ext.flutter.debugDumpApp',
isolateId: isolateId,
);
return response?['data']?.toString() ?? '';
}
Future<String> flutterDebugDumpRenderTree({
required String isolateId,
}) async {
final Map<String, Object?>? response = await invokeFlutterExtensionRpcRaw(
'ext.flutter.debugDumpRenderTree',
isolateId: isolateId,
args: <String, Object>{}
);
return response?['data']?.toString() ?? '';
}
Future<String> flutterDebugDumpLayerTree({
required String isolateId,
}) async {
final Map<String, Object?>? response = await invokeFlutterExtensionRpcRaw(
'ext.flutter.debugDumpLayerTree',
isolateId: isolateId,
);
return response?['data']?.toString() ?? '';
}
Future<String> flutterDebugDumpFocusTree({
required String isolateId,
}) async {
final Map<String, Object?>? response = await invokeFlutterExtensionRpcRaw(
'ext.flutter.debugDumpFocusTree',
isolateId: isolateId,
);
return response?['data']?.toString() ?? '';
}
Future<String> flutterDebugDumpSemanticsTreeInTraversalOrder({
required String isolateId,
}) async {
final Map<String, Object?>? response = await invokeFlutterExtensionRpcRaw(
'ext.flutter.debugDumpSemanticsTreeInTraversalOrder',
isolateId: isolateId,
);
return response?['data']?.toString() ?? '';
}
Future<String> flutterDebugDumpSemanticsTreeInInverseHitTestOrder({
required String isolateId,
}) async {
final Map<String, Object?>? response = await invokeFlutterExtensionRpcRaw(
'ext.flutter.debugDumpSemanticsTreeInInverseHitTestOrder',
isolateId: isolateId,
);
if (response != null) {
return response['data']?.toString() ?? '';
}
return '';
}
Future<Map<String, Object?>?> _flutterToggle(String name, {
required String isolateId,
}) async {
Map<String, Object?>? state = await invokeFlutterExtensionRpcRaw(
'ext.flutter.$name',
isolateId: isolateId,
);
if (state != null && state.containsKey('enabled') && state['enabled'] is String) {
state = await invokeFlutterExtensionRpcRaw(
'ext.flutter.$name',
isolateId: isolateId,
args: <String, Object>{
'enabled': state['enabled'] == 'true' ? 'false' : 'true',
},
);
}
return state;
}
Future<Map<String, Object?>?> flutterToggleDebugPaintSizeEnabled({
required String isolateId,
}) => _flutterToggle('debugPaint', isolateId: isolateId);
Future<Map<String, Object?>?> flutterTogglePerformanceOverlayOverride({
required String isolateId,
}) => _flutterToggle('showPerformanceOverlay', isolateId: isolateId);
Future<Map<String, Object?>?> flutterToggleWidgetInspector({
required String isolateId,
}) => _flutterToggle('inspector.show', isolateId: isolateId);
Future<Map<String, Object?>?> flutterToggleInvertOversizedImages({
required String isolateId,
}) => _flutterToggle('invertOversizedImages', isolateId: isolateId);
Future<Map<String, Object?>?> flutterToggleProfileWidgetBuilds({
required String isolateId,
}) => _flutterToggle('profileWidgetBuilds', isolateId: isolateId);
Future<Map<String, Object?>?> flutterDebugAllowBanner(bool show, {
required String isolateId,
}) {
return invokeFlutterExtensionRpcRaw(
'ext.flutter.debugAllowBanner',
isolateId: isolateId,
args: <String, Object>{'enabled': show ? 'true' : 'false'},
);
}
Future<Map<String, Object?>?> flutterReassemble({
required String isolateId,
}) {
return invokeFlutterExtensionRpcRaw(
'ext.flutter.reassemble',
isolateId: isolateId,
);
}
Future<bool> flutterAlreadyPaintedFirstUsefulFrame({
required String isolateId,
}) async {
final Map<String, Object?>? result = await invokeFlutterExtensionRpcRaw(
'ext.flutter.didSendFirstFrameRasterizedEvent',
isolateId: isolateId,
);
// result might be null when the service extension is not initialized
return result?['enabled'] == 'true';
}
Future<Map<String, Object?>?> uiWindowScheduleFrame({
required String isolateId,
}) {
return invokeFlutterExtensionRpcRaw(
'ext.ui.window.scheduleFrame',
isolateId: isolateId,
);
}
Future<Map<String, Object?>?> flutterEvictAsset(String assetPath, {
required String isolateId,
}) {
return invokeFlutterExtensionRpcRaw(
'ext.flutter.evict',
isolateId: isolateId,
args: <String, Object?>{
'value': assetPath,
},
);
}
Future<Map<String, Object?>?> flutterEvictShader(String assetPath, {
required String isolateId,
}) {
return invokeFlutterExtensionRpcRaw(
'ext.ui.window.reinitializeShader',
isolateId: isolateId,
args: <String, Object?>{
'assetKey': assetPath,
},
);
}
Future<Map<String, Object?>?> flutterEvictScene(String assetPath, {
required String isolateId,
}) {
return invokeFlutterExtensionRpcRaw(
'ext.ui.window.reinitializeScene',
isolateId: isolateId,
args: <String, Object?>{
'assetKey': assetPath,
},
);
}
/// Exit the application by calling [exit] from `dart:io`.
///
/// This method is only supported by certain embedders. This is
/// described by [Device.supportsFlutterExit].
Future<bool> flutterExit({
required String isolateId,
}) async {
try {
final Map<String, Object?>? result = await invokeFlutterExtensionRpcRaw(
'ext.flutter.exit',
isolateId: isolateId,
);
// A response of `null` indicates that `invokeFlutterExtensionRpcRaw` caught an RPCError
// with a missing method code. This can happen when attempting to quit a Flutter app
// that never registered the methods in the bindings.
if (result == null) {
return false;
}
} on vm_service.SentinelException {
// Do nothing on sentinel, the isolate already exited.
} on vm_service.RPCError {
// Do nothing on RPCError, the isolate already exited.
}
return true;
}
/// Return the current platform override for the flutter view running with
/// the main isolate [isolateId].
///
/// If a non-null value is provided for [platform], the platform override
/// is updated with this value.
Future<String> flutterPlatformOverride({
String? platform,
required String isolateId,
}) async {
final Map<String, Object?>? result = await invokeFlutterExtensionRpcRaw(
'ext.flutter.platformOverride',
isolateId: isolateId,
args: platform != null
? <String, Object>{'value': platform}
: <String, String>{},
);
if (result != null && result['value'] is String) {
return result['value']! as String;
}
return 'unknown';
}
/// Return the current brightness value for the flutter view running with
/// the main isolate [isolateId].
///
/// If a non-null value is provided for [brightness], the brightness override
/// is updated with this value.
Future<Brightness?> flutterBrightnessOverride({
Brightness? brightness,
required String isolateId,
}) async {
final Map<String, Object?>? result = await invokeFlutterExtensionRpcRaw(
'ext.flutter.brightnessOverride',
isolateId: isolateId,
args: brightness != null
? <String, String>{'value': brightness.toString()}
: <String, String>{},
);
if (result != null && result['value'] is String) {
return result['value'] == 'Brightness.light'
? Brightness.light
: Brightness.dark;
}
return null;
}
Future<vm_service.Response?> _checkedCallServiceExtension(
String method, {
Map<String, Object?>? args,
}) async {
try {
return await service.callServiceExtension(method, args: args);
} on vm_service.RPCError catch (err) {
// If an application is not using the framework or the VM service
// disappears while handling a request, return null.
if ((err.code == RPCErrorCodes.kMethodNotFound)
|| (err.code == RPCErrorCodes.kServiceDisappeared)) {
return null;
}
rethrow;
}
}
/// Invoke a flutter extension method, if the flutter extension is not
/// available, returns null.
Future<Map<String, Object?>?> invokeFlutterExtensionRpcRaw(
String method, {
required String isolateId,
Map<String, Object?>? args,
}) async {
final vm_service.Response? response = await _checkedCallServiceExtension(
method,
args: <String, Object?>{
'isolateId': isolateId,
...?args,
},
);
return response?.json;
}
/// List all [FlutterView]s attached to the current VM.
///
/// If this returns an empty list, it will poll forever unless [returnEarly]
/// is set to true.
///
/// By default, the poll duration is 50 milliseconds.
Future<List<FlutterView>> getFlutterViews({
bool returnEarly = false,
Duration delay = const Duration(milliseconds: 50),
}) async {
while (true) {
final vm_service.Response? response = await callMethodWrapper(
kListViewsMethod,
);
if (response == null) {
// The service may have disappeared mid-request.
// Return an empty list now, and let the shutdown logic elsewhere deal
// with cleaning up.
return <FlutterView>[];
}
final List<Object?>? rawViews = response.json?['views'] as List<Object?>?;
final List<FlutterView> views = <FlutterView>[
if (rawViews != null)
for (final Map<String, Object?> rawView in rawViews.whereType<Map<String, Object?>>())
FlutterView.parse(rawView),
];
if (views.isNotEmpty || returnEarly) {
return views;
}
await Future<void>.delayed(delay);
}
}
/// Tell the provided flutter view that the font manifest has been updated
/// and asset fonts should be reloaded.
Future<void> reloadAssetFonts({
required String isolateId,
required String viewId,
}) async {
await callMethodWrapper(
kReloadAssetFonts,
isolateId: isolateId, args: <String, Object?>{
'viewId': viewId,
},
);
}
/// Waits for a signal from the VM service that [extensionName] is registered.
///
/// Looks at the list of loaded extensions for first Flutter view, as well as
/// the stream of added extensions to avoid races.
///
/// If [webIsolate] is true, this uses the VM Service isolate list instead of
/// the `_flutter.listViews` method, which is not implemented by DWDS.
///
/// Throws a [VmServiceDisappearedException] should the VM Service disappear
/// while making calls to it.
Future<vm_service.IsolateRef> findExtensionIsolate(String extensionName) async {
try {
await service.streamListen(vm_service.EventStreams.kIsolate);
} on vm_service.RPCError {
// Do nothing, since the tool is already subscribed.
}
final Completer<vm_service.IsolateRef> extensionAdded = Completer<vm_service.IsolateRef>();
late final StreamSubscription<vm_service.Event> isolateEvents;
isolateEvents = service.onIsolateEvent.listen((vm_service.Event event) {
if (event.kind == vm_service.EventKind.kServiceExtensionAdded
&& event.extensionRPC == extensionName) {
isolateEvents.cancel();
extensionAdded.complete(event.isolate!);
}
});
try {
final List<vm_service.IsolateRef> refs = await _getIsolateRefs();
for (final vm_service.IsolateRef ref in refs) {
final vm_service.Isolate? isolate = await getIsolateOrNull(ref.id!);
if (isolate != null && (isolate.extensionRPCs?.contains(extensionName) ?? false)) {
return ref;
}
}
return await extensionAdded.future;
} finally {
await isolateEvents.cancel();
try {
await service.streamCancel(vm_service.EventStreams.kIsolate);
} on vm_service.RPCError {
// It's ok for cleanup to fail, such as when the service disappears.
}
}
}
Future<List<vm_service.IsolateRef>> _getIsolateRefs() async {
final List<FlutterView> flutterViews = await getFlutterViews();
if (flutterViews.isEmpty) {
throw VmServiceDisappearedException();
}
final List<vm_service.IsolateRef> refs = <vm_service.IsolateRef>[];
for (final FlutterView flutterView in flutterViews) {
final vm_service.IsolateRef? uiIsolate = flutterView.uiIsolate;
if (uiIsolate != null) {
refs.add(uiIsolate);
}
}
return refs;
}
/// Attempt to retrieve the isolate with id [isolateId], or `null` if it has
/// been collected.
Future<vm_service.Isolate?> getIsolateOrNull(String isolateId) async {
return service.getIsolate(isolateId)
.then<vm_service.Isolate?>(
(vm_service.Isolate isolate) => isolate,
onError: (Object? error, StackTrace stackTrace) {
if (error is vm_service.SentinelException ||
error == null ||
(error is vm_service.RPCError && error.code == RPCErrorCodes.kServiceDisappeared)) {
return null;
}
return Future<vm_service.Isolate?>.error(error, stackTrace);
});
}
/// Attempt to retrieve the isolate pause event with id [isolateId], or `null` if it has
/// been collected.
Future<vm_service.Event?> getIsolatePauseEventOrNull(String isolateId) async {
return service.getIsolatePauseEvent(isolateId)
.then<vm_service.Event?>(
(vm_service.Event event) => event,
onError: (Object? error, StackTrace stackTrace) {
if (error is vm_service.SentinelException ||
error == null ||
(error is vm_service.RPCError && error.code == RPCErrorCodes.kServiceDisappeared)) {
return null;
}
return Future<vm_service.Event?>.error(error, stackTrace);
});
}
/// Create a new development file system on the device.
Future<vm_service.Response> createDevFS(String fsName) {
// Call the unchecked version of `callServiceExtension` because the caller
// has custom handling of certain RPCErrors.
return service.callServiceExtension(
'_createDevFS',
args: <String, Object?>{'fsName': fsName},
);
}
/// Delete an existing file system.
Future<void> deleteDevFS(String fsName) async {
await _checkedCallServiceExtension(
'_deleteDevFS',
args: <String, Object?>{'fsName': fsName},
);
}
Future<vm_service.Response?> screenshotSkp() {
return _checkedCallServiceExtension(kScreenshotSkpMethod);
}
/// Set the VM timeline flags.
Future<void> setTimelineFlags(List<String> recordedStreams) async {
await _checkedCallServiceExtension(
'setVMTimelineFlags',
args: <String, Object?>{
'recordedStreams': recordedStreams,
},
);
}
Future<vm_service.Response?> getTimeline() {
return _checkedCallServiceExtension('getVMTimeline');
}
Future<void> dispose() async {
await service.dispose();
}
}
/// Thrown when the VM Service disappears while calls are being made to it.
class VmServiceDisappearedException implements Exception { }
/// Whether the event attached to an [Isolate.pauseEvent] should be considered
/// a "pause" event.
bool isPauseEvent(String kind) {
return kind == vm_service.EventKind.kPauseStart ||
kind == vm_service.EventKind.kPauseExit ||
kind == vm_service.EventKind.kPauseBreakpoint ||
kind == vm_service.EventKind.kPauseInterrupted ||
kind == vm_service.EventKind.kPauseException ||
kind == vm_service.EventKind.kPausePostRequest ||
kind == vm_service.EventKind.kNone;
}
/// A brightness enum that matches the values https://github.com/flutter/engine/blob/3a96741247528133c0201ab88500c0c3c036e64e/lib/ui/window.dart#L1328
/// Describes the contrast of a theme or color palette.
enum Brightness {
/// The color is dark and will require a light text color to achieve readable
/// contrast.
///
/// For example, the color might be dark grey, requiring white text.
dark,
/// The color is light and will require a dark text color to achieve readable
/// contrast.
///
/// For example, the color might be bright white, requiring black text.
light,
}
/// Process a VM service log event into a string message.
String processVmServiceMessage(vm_service.Event event) {
final String message = utf8.decode(base64.decode(event.bytes!));
// Remove extra trailing newlines appended by the vm service.
if (message.endsWith('\n')) {
return message.substring(0, message.length - 1);
}
return message;
}
| flutter/packages/flutter_tools/lib/src/vmservice.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/vmservice.dart",
"repo_id": "flutter",
"token_count": 13390
} | 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/platform.dart';
import '../doctor_validator.dart';
import '../features.dart';
class WebWorkflow extends Workflow {
const WebWorkflow({
required Platform platform,
required FeatureFlags featureFlags,
}) : _platform = platform,
_featureFlags = featureFlags;
final Platform _platform;
final FeatureFlags _featureFlags;
@override
bool get appliesToHostPlatform => _featureFlags.isWebEnabled &&
(_platform.isWindows ||
_platform.isMacOS ||
_platform.isLinux);
@override
bool get canLaunchDevices => _featureFlags.isWebEnabled;
@override
bool get canListDevices => _featureFlags.isWebEnabled;
@override
bool get canListEmulators => false;
}
| flutter/packages/flutter_tools/lib/src/web/workflow.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/web/workflow.dart",
"repo_id": "flutter",
"token_count": 269
} | 756 |
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://raw.githubusercontent.com/flutter/flutter/stable/packages/flutter_tools/static/custom-devices.schema.json",
"title": "Flutter Custom Devices",
"description": "The schema for the flutter custom devices config file.",
"type": "object",
"properties": {
"custom-devices": {
"description": "The actual list of custom devices.",
"type": "array",
"items": {
"description": "A single custom device to be configured.",
"type": "object",
"properties": {
"id": {
"description": "A unique, short identification string for this device. Used for example as an argument to the flutter run command.",
"type": "string"
},
"label": {
"description": "A more descriptive, user-friendly label for the device.",
"type": "string",
"default": "",
"required": false
},
"sdkNameAndVersion": {
"description": "Additional information about the device. For other devices, this is the SDK (for example Android SDK, Windows SDK) name and version.",
"type": "string",
"default": "",
"required": false
},
"enabled": {
"description": "If false, this device will be ignored completely by the flutter SDK and none of the commands configured will be called. You can use this as a way to comment out device configs you're still working on, for example.",
"type": "boolean",
"default": true,
"required": false
},
"platform": {
"description": "The platform of the target device.",
"enum": ["linux-arm64", "linux-x64"],
"default": "linux-arm64",
"required": false
},
"ping": {
"description": "The command to be invoked to ping the device. Used to find out whether its available or not. Every exit code unequal 0 will be treated as \"unavailable\". On Windows, consider providing a \"pingSuccessRegex\" since Windows' ping will also return 0 on failure. Make sure the command times out internally since it's not guaranteed the flutter SDK will enforce a timeout itself.",
"type": "array",
"items": {
"type": "string"
},
"minItems": 1,
"default": [
"ping", "-w", "500", "-n", "1", "raspberrypi"
]
},
"pingSuccessRegex": {
"description": "When the output of the ping command matches this regex (and the ping command finished with exit code 0), the ping will be considered successful and the pinged device reachable. If this regex is not provided the ping command will be considered successful when it returned with exit code 0. The regex syntax is the standard dart syntax.",
"type": ["string", "null"],
"format": "regex",
"default": "[<=]\\d+ms",
"required": false
},
"postBuild": {
"description": "The command to be invoked after the build process is done, to do any additional packaging for example.",
"type": ["array", "null"],
"items": {
"type": "string"
},
"minItems": 1,
"default": null,
"required": false
},
"install": {
"description": "The command to be invoked to install the app on the device. The path to the directory / file to be installed (copied over) to the device is available via the ${localPath} string interpolation and the name of the app to be installed via the ${appName} string interpolation.",
"type": "array",
"items": {
"type": "string"
},
"minItems": 1,
"default": [
"scp", "-r", "${localPath}", "pi@raspberrypi:/tmp/${appName}"
]
},
"uninstall": {
"description": "The command to be invoked to remove the app from the device. Invoked before every invocation of the app install command. The name of the app to be removed is available via the ${appName} string interpolation.",
"type": "array",
"items": {
"type": "string"
},
"minItems": 1,
"default": [
"ssh", "pi@raspberrypi", "rm -rf \"/tmp/${appName}\""
]
},
"runDebug": {
"description": "The command to be invoked to run the app in debug mode. The name of the app to be started is available via the ${appName} string interpolation. Make sure the flutter cmdline output is available via this commands stdout/stderr since the SDK needs the \"VM Service is now listening on ...\" message to function. If the forwardPort command is not specified, the VM Service URL will be connected to as-is, without any port forwarding. In that case you need to make sure it is reachable from your host device, possibly via the \"--vm-service-host=<ip>\" engine flag.",
"type": "array",
"items": {
"type": "string"
},
"minItems": 1,
"default": [
"ssh", "pi@raspberrypi", "flutter-pi /tmp/${appName} --vm-service-host=192.168.178.123"
]
},
"forwardPort": {
"description": "The command to be invoked to forward a specific device port to a port on the host device. The host port is available via ${hostPort} and the device port via ${devicePort}. On success, the command should stay running for the duration of the forwarding. The command will be terminated using SIGTERM when the forwarding should be stopped. When using ssh, make sure ssh quits when the forwarding fails since that's not the default behaviour.",
"type": ["array", "null"],
"items": {
"type": "string"
},
"minItems": 1,
"default": [
"ssh", "-o", "ExitOnForwardFailure=yes", "-L", "127.0.0.1:${hostPort}:127.0.0.1:${devicePort}", "pi@raspberrypi"
],
"required": false
},
"forwardPortSuccessRegex": {
"description": "A regular expression to be used to classify a successful port forwarding. As soon as any line of stdout or stderr of the forward port command matches this regex, the port forwarding is considered successful. The regex syntax is the standard dart syntax. This value needs to be present & non-null when \"forwardPort\" specified.",
"type": ["string", "null"],
"format": "regex",
"default": "Linux",
"required": false
},
"screenshot": {
"description": "Take a screenshot of the app as a png image. This command should take the screenshot, convert it to png, then base64 encode it and echo to stdout. Any stderr output will be ignored. If this command is not given, screenshotting will be disabled for this device.",
"type": ["array", "null"],
"items": {
"type": "string"
},
"minItems": 1,
"default": [
"ssh", "pi@raspberrypi", "fbgrab /tmp/screenshot.png && cat /tmp/screenshot.png | base64 | tr -d ' \\n\\t'"
],
"required": false
}
}
}
}
}
}
| flutter/packages/flutter_tools/static/custom-devices.schema.json/0 | {
"file_path": "flutter/packages/flutter_tools/static/custom-devices.schema.json",
"repo_id": "flutter",
"token_count": 3069
} | 757 |
import Flutter
import UIKit
import XCTest
{{#withPlatformChannelPluginHook}}
@testable import {{pluginProjectName}}
// This demonstrates a simple unit test of the Swift portion of this plugin's implementation.
//
// See https://developer.apple.com/documentation/xctest for more information about using XCTest.
{{/withPlatformChannelPluginHook}}
class RunnerTests: XCTestCase {
{{#withPlatformChannelPluginHook}}
func testGetPlatformVersion() {
let plugin = {{pluginClass}}()
let call = FlutterMethodCall(methodName: "getPlatformVersion", arguments: [])
let resultExpectation = expectation(description: "result block must be called.")
plugin.handle(call) { result in
XCTAssertEqual(result as! String, "iOS " + UIDevice.current.systemVersion)
resultExpectation.fulfill()
}
waitForExpectations(timeout: 1)
}
{{/withPlatformChannelPluginHook}}
{{^withPlatformChannelPluginHook}}
func testExample() {
// If you add code to the Runner application, consider adding tests here.
// See https://developer.apple.com/documentation/xctest for more information about using XCTest.
}
{{/withPlatformChannelPluginHook}}
}
| flutter/packages/flutter_tools/templates/app_shared/ios-swift.tmpl/RunnerTests/RunnerTests.swift.tmpl/0 | {
"file_path": "flutter/packages/flutter_tools/templates/app_shared/ios-swift.tmpl/RunnerTests/RunnerTests.swift.tmpl",
"repo_id": "flutter",
"token_count": 353
} | 758 |
def localProperties = new Properties()
def localPropertiesFile = rootProject.file("local.properties")
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader("UTF-8") { reader ->
localProperties.load(reader)
}
}
def flutterVersionCode = localProperties.getProperty("flutter.versionCode")
if (flutterVersionCode == null) {
flutterVersionCode = "1"
}
def flutterVersionName = localProperties.getProperty("flutter.versionName")
if (flutterVersionName == null) {
flutterVersionName = "1.0"
}
apply plugin: "com.android.dynamic-feature"
android {
compileSdk = flutter.compileSdkVersion
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
sourceSets {
applicationVariants.all { variant ->
main.assets.srcDirs += "${project.buildDir}/intermediates/flutter/${variant.name}/deferred_assets"
main.jniLibs.srcDirs += "${project.buildDir}/intermediates/flutter/${variant.name}/deferred_libs"
}
}
defaultConfig {
minSdk = flutter.minSdkVersion
targetSdk = flutter.targetSdkVersion
versionCode = flutterVersionCode.toInteger()
versionName = flutterVersionName
}
}
dependencies {
implementation(project(":app"))
}
| flutter/packages/flutter_tools/templates/module/android/deferred_component/build.gradle.tmpl/0 | {
"file_path": "flutter/packages/flutter_tools/templates/module/android/deferred_component/build.gradle.tmpl",
"repo_id": "flutter",
"token_count": 500
} | 759 |
<!-- Generated file. Do not edit. -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="{{androidIdentifier}}"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.INTERNET"/>
<application
tools:node="merge">
<meta-data
android:name="flutterProjectType"
android:value="module" />
<!-- Don't delete the meta-data below.
It is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
android:name="flutterEmbedding"
android:value="2" />
</application>
</manifest>
| flutter/packages/flutter_tools/templates/module/android/library_new_embedding/Flutter.tmpl/src/main/AndroidManifest.xml.tmpl/0 | {
"file_path": "flutter/packages/flutter_tools/templates/module/android/library_new_embedding/Flutter.tmpl/src/main/AndroidManifest.xml.tmpl",
"repo_id": "flutter",
"token_count": 244
} | 760 |
#include "../Flutter/Generated.xcconfig"
| flutter/packages/flutter_tools/templates/module/ios/host_app_ephemeral/Config.tmpl/Flutter.xcconfig/0 | {
"file_path": "flutter/packages/flutter_tools/templates/module/ios/host_app_ephemeral/Config.tmpl/Flutter.xcconfig",
"repo_id": "flutter",
"token_count": 16
} | 761 |
#include "include/{{projectName}}/{{pluginClassSnakeCase}}.h"
#include <flutter_linux/flutter_linux.h>
#include <gtk/gtk.h>
#include <sys/utsname.h>
#include <cstring>
#include "{{pluginClassSnakeCase}}_private.h"
#define {{pluginClassCapitalSnakeCase}}(obj) \
(G_TYPE_CHECK_INSTANCE_CAST((obj), {{pluginClassSnakeCase}}_get_type(), \
{{pluginClass}}))
struct _{{pluginClass}} {
GObject parent_instance;
};
G_DEFINE_TYPE({{pluginClass}}, {{pluginClassSnakeCase}}, g_object_get_type())
// Called when a method call is received from Flutter.
static void {{pluginClassSnakeCase}}_handle_method_call(
{{pluginClass}}* self,
FlMethodCall* method_call) {
g_autoptr(FlMethodResponse) response = nullptr;
const gchar* method = fl_method_call_get_name(method_call);
if (strcmp(method, "getPlatformVersion") == 0) {
response = get_platform_version();
} else {
response = FL_METHOD_RESPONSE(fl_method_not_implemented_response_new());
}
fl_method_call_respond(method_call, response, nullptr);
}
FlMethodResponse* get_platform_version() {
struct utsname uname_data = {};
uname(&uname_data);
g_autofree gchar *version = g_strdup_printf("Linux %s", uname_data.version);
g_autoptr(FlValue) result = fl_value_new_string(version);
return FL_METHOD_RESPONSE(fl_method_success_response_new(result));
}
static void {{pluginClassSnakeCase}}_dispose(GObject* object) {
G_OBJECT_CLASS({{pluginClassSnakeCase}}_parent_class)->dispose(object);
}
static void {{pluginClassSnakeCase}}_class_init({{pluginClass}}Class* klass) {
G_OBJECT_CLASS(klass)->dispose = {{pluginClassSnakeCase}}_dispose;
}
static void {{pluginClassSnakeCase}}_init({{pluginClass}}* self) {}
static void method_call_cb(FlMethodChannel* channel, FlMethodCall* method_call,
gpointer user_data) {
{{pluginClass}}* plugin = {{pluginClassCapitalSnakeCase}}(user_data);
{{pluginClassSnakeCase}}_handle_method_call(plugin, method_call);
}
void {{pluginClassSnakeCase}}_register_with_registrar(FlPluginRegistrar* registrar) {
{{pluginClass}}* plugin = {{pluginClassCapitalSnakeCase}}(
g_object_new({{pluginClassSnakeCase}}_get_type(), nullptr));
g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new();
g_autoptr(FlMethodChannel) channel =
fl_method_channel_new(fl_plugin_registrar_get_messenger(registrar),
"{{projectName}}",
FL_METHOD_CODEC(codec));
fl_method_channel_set_method_call_handler(channel, method_call_cb,
g_object_ref(plugin),
g_object_unref);
g_object_unref(plugin);
}
| flutter/packages/flutter_tools/templates/plugin/linux.tmpl/pluginClassSnakeCase.cc.tmpl/0 | {
"file_path": "flutter/packages/flutter_tools/templates/plugin/linux.tmpl/pluginClassSnakeCase.cc.tmpl",
"repo_id": "flutter",
"token_count": 1087
} | 762 |
rootProject.name = '{{projectName}}'
| flutter/packages/flutter_tools/templates/plugin_shared/android.tmpl/settings.gradle.tmpl/0 | {
"file_path": "flutter/packages/flutter_tools/templates/plugin_shared/android.tmpl/settings.gradle.tmpl",
"repo_id": "flutter",
"token_count": 12
} | 763 |
import 'package:flutter/material.dart';
import '../settings/settings_view.dart';
import 'sample_item.dart';
import 'sample_item_details_view.dart';
/// Displays a list of SampleItems.
class SampleItemListView extends StatelessWidget {
const SampleItemListView({
super.key,
this.items = const [SampleItem(1), SampleItem(2), SampleItem(3)],
});
static const routeName = '/';
final List<SampleItem> items;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Sample Items'),
actions: [
IconButton(
icon: const Icon(Icons.settings),
onPressed: () {
// Navigate to the settings page. If the user leaves and returns
// to the app after it has been killed while running in the
// background, the navigation stack is restored.
Navigator.restorablePushNamed(context, SettingsView.routeName);
},
),
],
),
// To work with lists that may contain a large number of items, it’s best
// to use the ListView.builder constructor.
//
// In contrast to the default ListView constructor, which requires
// building all Widgets up front, the ListView.builder constructor lazily
// builds Widgets as they’re scrolled into view.
body: ListView.builder(
// Providing a restorationId allows the ListView to restore the
// scroll position when a user leaves and returns to the app after it
// has been killed while running in the background.
restorationId: 'sampleItemListView',
itemCount: items.length,
itemBuilder: (BuildContext context, int index) {
final item = items[index];
return ListTile(
title: Text('SampleItem ${item.id}'),
leading: const CircleAvatar(
// Display the Flutter Logo image asset.
foregroundImage: AssetImage('assets/images/flutter_logo.png'),
),
onTap: () {
// Navigate to the details page. If the user leaves and returns to
// the app after it has been killed while running in the
// background, the navigation stack is restored.
Navigator.restorablePushNamed(
context,
SampleItemDetailsView.routeName,
);
}
);
},
),
);
}
}
| flutter/packages/flutter_tools/templates/skeleton/lib/src/sample_feature/sample_item_list_view.dart.tmpl/0 | {
"file_path": "flutter/packages/flutter_tools/templates/skeleton/lib/src/sample_feature/sample_item_list_view.dart.tmpl",
"repo_id": "flutter",
"token_count": 1004
} | 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:args/command_runner.dart';
import 'package:file/memory.dart';
import 'package:file_testing/file_testing.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/os.dart';
import 'package:flutter_tools/src/base/platform.dart';
import 'package:flutter_tools/src/base/process.dart';
import 'package:flutter_tools/src/base/utils.dart';
import 'package:flutter_tools/src/build_system/build_system.dart';
import 'package:flutter_tools/src/cache.dart';
import 'package:flutter_tools/src/cmake.dart';
import 'package:flutter_tools/src/commands/build.dart';
import 'package:flutter_tools/src/commands/build_linux.dart';
import 'package:flutter_tools/src/features.dart';
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/common.dart';
import '../../src/context.dart';
import '../../src/fakes.dart';
import '../../src/test_build_system.dart';
import '../../src/test_flutter_command_runner.dart';
const String _kTestFlutterRoot = '/flutter';
final Platform linuxPlatform = FakePlatform(
environment: <String, String>{
'FLUTTER_ROOT': _kTestFlutterRoot,
'HOME': '/',
}
);
final Platform notLinuxPlatform = FakePlatform(
operatingSystem: 'macos',
environment: <String, String>{
'FLUTTER_ROOT': _kTestFlutterRoot,
}
);
void main() {
setUpAll(() {
Cache.disableLocking();
});
late MemoryFileSystem fileSystem;
late FakeProcessManager processManager;
late ProcessUtils processUtils;
late Logger logger;
late TestUsage usage;
late Artifacts artifacts;
late FakeAnalytics fakeAnalytics;
setUp(() {
fileSystem = MemoryFileSystem.test();
artifacts = Artifacts.test(fileSystem: fileSystem);
Cache.flutterRoot = _kTestFlutterRoot;
usage = TestUsage();
logger = BufferLogger.test();
processManager = FakeProcessManager.empty();
processUtils = ProcessUtils(
logger: logger,
processManager: processManager,
);
fakeAnalytics = getInitializedFakeAnalyticsInstance(
fs: fileSystem,
fakeFlutterVersion: FakeFlutterVersion(),
);
});
// Creates the mock files necessary to look like a Flutter project.
void setUpMockCoreProjectFiles() {
fileSystem.file('pubspec.yaml').createSync();
fileSystem.file('.packages').createSync();
fileSystem.file(fileSystem.path.join('lib', 'main.dart')).createSync(recursive: true);
}
// Creates the mock files necessary to run a build.
void setUpMockProjectFilesForBuild() {
setUpMockCoreProjectFiles();
fileSystem.file(fileSystem.path.join('linux', 'CMakeLists.txt')).createSync(recursive: true);
}
// Returns the command matching the build_linux call to cmake.
FakeCommand cmakeCommand(String buildMode, {
String target = 'x64',
void Function(List<String> command)? onRun,
}) {
return FakeCommand(
command: <String>[
'cmake',
'-G',
'Ninja',
'-DCMAKE_BUILD_TYPE=${sentenceCase(buildMode)}',
'-DFLUTTER_TARGET_PLATFORM=linux-$target',
'/linux',
],
workingDirectory: 'build/linux/$target/$buildMode',
onRun: onRun,
);
}
// Returns the command matching the build_linux call to ninja.
FakeCommand ninjaCommand(String buildMode, {
Map<String, String>? environment,
String target = 'x64',
void Function(List<String> command)? onRun,
String stdout = '',
}) {
return FakeCommand(
command: <String>[
'ninja',
'-C',
'build/linux/$target/$buildMode',
'install',
],
environment: environment,
onRun: onRun,
stdout: stdout,
);
}
testUsingContext('Linux build fails when there is no linux project', () async {
final BuildCommand command = BuildCommand(
artifacts: artifacts,
androidSdk: FakeAndroidSdk(),
buildSystem: TestBuildSystem.all(BuildResult(success: true)),
fileSystem: fileSystem,
logger: logger,
processUtils: processUtils,
osUtils: FakeOperatingSystemUtils(),
);
setUpMockCoreProjectFiles();
expect(createTestCommandRunner(command).run(
const <String>['build', 'linux', '--no-pub']
), throwsToolExit(message: 'No Linux desktop project configured. See '
'https://docs.flutter.dev/desktop#add-desktop-support-to-an-existing-flutter-app '
'to learn about adding Linux support to a project.'));
}, overrides: <Type, Generator>{
Platform: () => linuxPlatform,
FileSystem: () => fileSystem,
ProcessManager: () => processManager,
FeatureFlags: () => TestFeatureFlags(isLinuxEnabled: true),
});
testUsingContext('Linux build fails on non-linux platform', () async {
final BuildCommand command = BuildCommand(
artifacts: artifacts,
androidSdk: FakeAndroidSdk(),
buildSystem: TestBuildSystem.all(BuildResult(success: true)),
fileSystem: fileSystem,
logger: logger,
processUtils: processUtils,
osUtils: FakeOperatingSystemUtils(),
);
setUpMockProjectFilesForBuild();
expect(createTestCommandRunner(command).run(
const <String>['build', 'linux', '--no-pub']
), throwsToolExit(message: '"build linux" only supported on Linux hosts.'));
}, overrides: <Type, Generator>{
Platform: () => notLinuxPlatform,
FileSystem: () => fileSystem,
ProcessManager: () => processManager,
FeatureFlags: () => TestFeatureFlags(isLinuxEnabled: true),
});
testUsingContext('Linux 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(),
);
setUpMockProjectFilesForBuild();
expect(createTestCommandRunner(command).run(
const <String>['build', 'linux', '--no-pub']
), throwsToolExit(message: '"build linux" is not currently supported. To enable, run "flutter config --enable-linux-desktop".'));
}, overrides: <Type, Generator>{
Platform: () => linuxPlatform,
FileSystem: () => fileSystem,
ProcessManager: () => processManager,
FeatureFlags: () => TestFeatureFlags(),
});
testUsingContext('Linux build invokes CMake and ninja, and writes temporary files', () async {
final BuildCommand command = BuildCommand(
artifacts: artifacts,
androidSdk: FakeAndroidSdk(),
buildSystem: TestBuildSystem.all(BuildResult(success: true)),
fileSystem: fileSystem,
logger: logger,
processUtils: processUtils,
osUtils: FakeOperatingSystemUtils(),
);
processManager.addCommands(<FakeCommand>[
cmakeCommand('release'),
ninjaCommand('release'),
]);
setUpMockProjectFilesForBuild();
await createTestCommandRunner(command).run(
const <String>['build', 'linux', '--no-pub']
);
expect(fileSystem.file('linux/flutter/ephemeral/generated_config.cmake'), exists);
expect(
analyticsTimingEventExists(
sentEvents: fakeAnalytics.sentEvents,
workflow: 'build',
variableName: 'cmake-linux',
),
true,
);
expect(
analyticsTimingEventExists(
sentEvents: fakeAnalytics.sentEvents,
workflow: 'build',
variableName: 'linux-ninja',
),
true,
);
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
ProcessManager: () => processManager,
Platform: () => linuxPlatform,
FeatureFlags: () => TestFeatureFlags(isLinuxEnabled: true),
OperatingSystemUtils: () => FakeOperatingSystemUtils(),
Analytics: () => fakeAnalytics,
});
testUsingContext('Handles missing cmake', () async {
final BuildCommand command = BuildCommand(
artifacts: artifacts,
androidSdk: FakeAndroidSdk(),
buildSystem: TestBuildSystem.all(BuildResult(success: true)),
fileSystem: fileSystem,
logger: logger,
processUtils: processUtils,
osUtils: FakeOperatingSystemUtils(),
);
setUpMockProjectFilesForBuild();
processManager = FakeProcessManager.empty()
..excludedExecutables.add('cmake');
expect(createTestCommandRunner(command).run(
const <String>['build', 'linux', '--no-pub']
), throwsToolExit(message: 'CMake is required for Linux development.'));
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
ProcessManager: () => processManager,
Platform: () => linuxPlatform,
FeatureFlags: () => TestFeatureFlags(isLinuxEnabled: true),
OperatingSystemUtils: () => FakeOperatingSystemUtils(),
});
testUsingContext('Handles argument error from missing ninja', () async {
final BuildCommand command = BuildCommand(
artifacts: artifacts,
androidSdk: FakeAndroidSdk(),
buildSystem: TestBuildSystem.all(BuildResult(success: true)),
fileSystem: fileSystem,
logger: logger,
processUtils: processUtils,
osUtils: FakeOperatingSystemUtils(),
);
setUpMockProjectFilesForBuild();
processManager.addCommands(<FakeCommand>[
cmakeCommand('release'),
ninjaCommand('release', onRun: (_) {
throw ArgumentError();
}),
]);
expect(createTestCommandRunner(command).run(
const <String>['build', 'linux', '--no-pub']
), throwsToolExit(message: "ninja not found. Run 'flutter doctor' for more information."));
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
ProcessManager: () => processManager,
Platform: () => linuxPlatform,
FeatureFlags: () => TestFeatureFlags(isLinuxEnabled: true),
OperatingSystemUtils: () => FakeOperatingSystemUtils(),
});
testUsingContext('Linux build does not spew stdout to status logger', () async {
final BuildCommand command = BuildCommand(
artifacts: artifacts,
androidSdk: FakeAndroidSdk(),
buildSystem: TestBuildSystem.all(BuildResult(success: true)),
fileSystem: fileSystem,
logger: logger,
processUtils: processUtils,
osUtils: FakeOperatingSystemUtils(),
);
setUpMockProjectFilesForBuild();
processManager.addCommands(<FakeCommand>[
cmakeCommand('debug'),
ninjaCommand('debug',
stdout: 'STDOUT STUFF',
),
]);
await createTestCommandRunner(command).run(
const <String>['build', 'linux', '--debug', '--no-pub']
);
expect(testLogger.statusText, isNot(contains('STDOUT STUFF')));
expect(testLogger.warningText, isNot(contains('STDOUT STUFF')));
expect(testLogger.errorText, isNot(contains('STDOUT STUFF')));
expect(testLogger.traceText, contains('STDOUT STUFF'));
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
ProcessManager: () => processManager,
Platform: () => linuxPlatform,
FeatureFlags: () => TestFeatureFlags(isLinuxEnabled: true),
OperatingSystemUtils: () => FakeOperatingSystemUtils(),
});
testUsingContext('Linux build extracts errors from stdout', () async {
final BuildCommand command = BuildCommand(
artifacts: artifacts,
androidSdk: FakeAndroidSdk(),
buildSystem: TestBuildSystem.all(BuildResult(success: true)),
fileSystem: fileSystem,
logger: logger,
processUtils: processUtils,
osUtils: FakeOperatingSystemUtils(),
);
setUpMockProjectFilesForBuild();
// This contains a mix of routine build output and various types of errors
// (Dart error, compile error, link error), edited down for compactness.
const String stdout = r'''
ninja: Entering directory `build/linux/x64/release'
[1/6] Generating /foo/linux/flutter/ephemeral/libflutter_linux_gtk.so, /foo/linux/flutter/ephemeral/flutter_linux/flutter_linux.h, _phony
lib/main.dart:4:3: Error: Method not found: 'foo'.
[2/6] Building CXX object CMakeFiles/foo.dir/main.cc.o
/foo/linux/main.cc:6:2: error: expected ';' after class
/foo/linux/main.cc:9:7: warning: unused variable 'unused_variable' [-Wunused-variable]
/foo/linux/main.cc:10:3: error: unknown type name 'UnknownType'
/foo/linux/main.cc:12:7: error: 'bar' is a private member of 'Foo'
/foo/linux/my_application.h:4:10: fatal error: 'gtk/gtk.h' file not found
[3/6] Building CXX object CMakeFiles/foo_bar.dir/flutter/generated_plugin_registrant.cc.o
[4/6] Building CXX object CMakeFiles/foo_bar.dir/my_application.cc.o
[5/6] Linking CXX executable intermediates_do_not_run/foo_bar
main.cc:(.text+0x13): undefined reference to `Foo::bar()'
clang: error: linker command failed with exit code 1 (use -v to see invocation)
ninja: build stopped: subcommand failed.
ERROR: No file or variants found for asset: images/a_dot_burr.jpeg
''';
processManager.addCommands(<FakeCommand>[
cmakeCommand('release'),
ninjaCommand('release',
stdout: stdout,
),
]);
await createTestCommandRunner(command).run(
const <String>['build', 'linux', '--no-pub']
);
// Just the warnings and errors should be surfaced.
expect(testLogger.errorText, r'''
lib/main.dart:4:3: Error: Method not found: 'foo'.
/foo/linux/main.cc:6:2: error: expected ';' after class
/foo/linux/main.cc:9:7: warning: unused variable 'unused_variable' [-Wunused-variable]
/foo/linux/main.cc:10:3: error: unknown type name 'UnknownType'
/foo/linux/main.cc:12:7: error: 'bar' is a private member of 'Foo'
/foo/linux/my_application.h:4:10: fatal error: 'gtk/gtk.h' file not found
clang: error: linker command failed with exit code 1 (use -v to see invocation)
ERROR: No file or variants found for asset: images/a_dot_burr.jpeg
''');
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
ProcessManager: () => processManager,
Platform: () => linuxPlatform,
FeatureFlags: () => TestFeatureFlags(isLinuxEnabled: true),
OperatingSystemUtils: () => FakeOperatingSystemUtils(),
});
testUsingContext('Linux verbose build sets VERBOSE_SCRIPT_LOGGING', () async {
final BuildCommand command = BuildCommand(
artifacts: artifacts,
androidSdk: FakeAndroidSdk(),
buildSystem: TestBuildSystem.all(BuildResult(success: true)),
fileSystem: fileSystem,
logger: logger,
processUtils: processUtils,
osUtils: FakeOperatingSystemUtils(),
);
setUpMockProjectFilesForBuild();
processManager.addCommands(<FakeCommand>[
cmakeCommand('debug'),
ninjaCommand('debug',
environment: const <String, String>{
'VERBOSE_SCRIPT_LOGGING': 'true',
},
stdout: 'STDOUT STUFF',
),
]);
await createTestCommandRunner(command).run(
const <String>['build', 'linux', '--debug', '-v', '--no-pub']
);
expect(testLogger.statusText, contains('STDOUT STUFF'));
expect(testLogger.traceText, isNot(contains('STDOUT STUFF')));
expect(testLogger.warningText, isNot(contains('STDOUT STUFF')));
expect(testLogger.errorText, isNot(contains('STDOUT STUFF')));
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
Logger: () => logger,
ProcessManager: () => processManager,
Platform: () => linuxPlatform,
FeatureFlags: () => TestFeatureFlags(isLinuxEnabled: true),
OperatingSystemUtils: () => FakeOperatingSystemUtils(),
});
testUsingContext('Linux on x64 build --debug passes debug mode to cmake and ninja', () async {
final BuildCommand command = BuildCommand(
artifacts: artifacts,
androidSdk: FakeAndroidSdk(),
buildSystem: TestBuildSystem.all(BuildResult(success: true)),
fileSystem: fileSystem,
logger: logger,
processUtils: processUtils,
osUtils: FakeOperatingSystemUtils(),
);
setUpMockProjectFilesForBuild();
processManager.addCommands(<FakeCommand>[
cmakeCommand('debug'),
ninjaCommand('debug'),
]);
await createTestCommandRunner(command).run(
const <String>['build', 'linux', '--debug', '--no-pub']
);
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
Logger: () => logger,
ProcessManager: () => processManager,
Platform: () => linuxPlatform,
FeatureFlags: () => TestFeatureFlags(isLinuxEnabled: true),
OperatingSystemUtils: () => FakeOperatingSystemUtils(),
});
testUsingContext('Linux on ARM64 build --debug passes debug mode to cmake and ninja', () async {
final BuildCommand command = BuildCommand(
artifacts: artifacts,
androidSdk: FakeAndroidSdk(),
buildSystem: TestBuildSystem.all(BuildResult(success: true)),
fileSystem: fileSystem,
logger: logger,
processUtils: processUtils,
osUtils: CustomFakeOperatingSystemUtils(hostPlatform: HostPlatform.linux_arm64),
);
setUpMockProjectFilesForBuild();
processManager.addCommands(<FakeCommand>[
cmakeCommand('debug', target: 'arm64'),
ninjaCommand('debug', target: 'arm64'),
]);
await createTestCommandRunner(command).run(
const <String>['build', 'linux', '--debug', '--no-pub']
);
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
ProcessManager: () => processManager,
Platform: () => linuxPlatform,
FeatureFlags: () => TestFeatureFlags(isLinuxEnabled: true),
});
testUsingContext('Linux on x64 build --profile passes profile mode to make', () async {
final BuildCommand command = BuildCommand(
artifacts: artifacts,
androidSdk: FakeAndroidSdk(),
buildSystem: TestBuildSystem.all(BuildResult(success: true)),
fileSystem: fileSystem,
logger: logger,
processUtils: processUtils,
osUtils: FakeOperatingSystemUtils(),
);
setUpMockProjectFilesForBuild();
processManager.addCommands(<FakeCommand>[
cmakeCommand('profile'),
ninjaCommand('profile'),
]);
await createTestCommandRunner(command).run(
const <String>['build', 'linux', '--profile', '--no-pub']
);
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
ProcessManager: () => processManager,
Platform: () => linuxPlatform,
FeatureFlags: () => TestFeatureFlags(isLinuxEnabled: true),
OperatingSystemUtils: () => FakeOperatingSystemUtils(),
});
testUsingContext('Linux on ARM64 build --profile passes profile mode to make', () async {
final BuildCommand command = BuildCommand(
artifacts: artifacts,
androidSdk: FakeAndroidSdk(),
buildSystem: TestBuildSystem.all(BuildResult(success: true)),
fileSystem: fileSystem,
logger: logger,
processUtils: processUtils,
osUtils: CustomFakeOperatingSystemUtils(hostPlatform: HostPlatform.linux_arm64),
);
setUpMockProjectFilesForBuild();
processManager.addCommands(<FakeCommand>[
cmakeCommand('profile', target: 'arm64'),
ninjaCommand('profile', target: 'arm64'),
]);
await createTestCommandRunner(command).run(
const <String>['build', 'linux', '--profile', '--no-pub']
);
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
ProcessManager: () => processManager,
Platform: () => linuxPlatform,
FeatureFlags: () => TestFeatureFlags(isLinuxEnabled: true),
});
testUsingContext('Not support Linux cross-build for x64 on arm64', () async {
final BuildCommand command = BuildCommand(
artifacts: artifacts,
androidSdk: FakeAndroidSdk(),
buildSystem: TestBuildSystem.all(BuildResult(success: true)),
fileSystem: fileSystem,
logger: logger,
processUtils: processUtils,
osUtils: CustomFakeOperatingSystemUtils(hostPlatform: HostPlatform.linux_arm64),
);
expect(createTestCommandRunner(command).run(
const <String>['build', 'linux', '--no-pub', '--target-platform=linux-x64']
), throwsToolExit());
}, overrides: <Type, Generator>{
Platform: () => linuxPlatform,
FeatureFlags: () => TestFeatureFlags(isLinuxEnabled: true),
});
testUsingContext('Linux build configures CMake exports', () async {
final BuildCommand command = BuildCommand(
artifacts: artifacts,
androidSdk: FakeAndroidSdk(),
buildSystem: TestBuildSystem.all(BuildResult(success: true)),
fileSystem: fileSystem,
logger: logger,
processUtils: processUtils,
osUtils: FakeOperatingSystemUtils(),
);
setUpMockProjectFilesForBuild();
processManager.addCommands(<FakeCommand>[
cmakeCommand('release'),
ninjaCommand('release'),
]);
fileSystem.file('lib/other.dart')
.createSync(recursive: true);
fileSystem.file('foo/bar.sksl.json')
.createSync(recursive: true);
await createTestCommandRunner(command).run(
const <String>[
'build',
'linux',
'--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 File cmakeConfig = fileSystem.currentDirectory
.childDirectory('linux')
.childDirectory('flutter')
.childDirectory('ephemeral')
.childFile('generated_config.cmake');
expect(cmakeConfig, exists);
final List<String> configLines = cmakeConfig.readAsLinesSync();
expect(configLines, containsAll(<String>[
'file(TO_CMAKE_PATH "$_kTestFlutterRoot" FLUTTER_ROOT)',
'file(TO_CMAKE_PATH "${fileSystem.currentDirectory.path}" PROJECT_DIR)',
'set(FLUTTER_VERSION "1.0.0" PARENT_SCOPE)',
'set(FLUTTER_VERSION_MAJOR 1 PARENT_SCOPE)',
'set(FLUTTER_VERSION_MINOR 0 PARENT_SCOPE)',
'set(FLUTTER_VERSION_PATCH 0 PARENT_SCOPE)',
'set(FLUTTER_VERSION_BUILD 0 PARENT_SCOPE)',
' "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"',
' "FLUTTER_ROOT=$_kTestFlutterRoot"',
' "PROJECT_DIR=${fileSystem.currentDirectory.path}"',
' "FLUTTER_TARGET=lib/other.dart"',
' "BUNDLE_SKSL_PATH=foo/bar.sksl.json"',
]));
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
ProcessManager: () => processManager,
Platform: () => linuxPlatform,
FeatureFlags: () => TestFeatureFlags(isLinuxEnabled: true),
OperatingSystemUtils: () => FakeOperatingSystemUtils(),
});
testUsingContext('linux can extract binary name from CMake file', () async {
fileSystem.file('linux/CMakeLists.txt')
..createSync(recursive: true)
..writeAsStringSync(r'''
cmake_minimum_required(VERSION 3.10)
project(runner LANGUAGES CXX)
set(BINARY_NAME "fizz_bar")
''');
fileSystem.file('pubspec.yaml').createSync();
fileSystem.file('.packages').createSync();
final FlutterProject flutterProject = FlutterProject.fromDirectoryTest(fileSystem.currentDirectory);
expect(getCmakeExecutableName(flutterProject.linux), 'fizz_bar');
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
ProcessManager: () => processManager,
FeatureFlags: () => TestFeatureFlags(isLinuxEnabled: true),
});
testUsingContext('Refuses to build for Linux 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(),
));
expect(
() => runner.run(<String>['build', 'linux', '--no-pub']),
throwsToolExit(),
);
}, overrides: <Type, Generator>{
FeatureFlags: () => TestFeatureFlags(),
});
testUsingContext('hidden when not enabled on Linux host', () {
expect(BuildLinuxCommand(logger: BufferLogger.test(), operatingSystemUtils: FakeOperatingSystemUtils()).hidden, true);
}, overrides: <Type, Generator>{
FeatureFlags: () => TestFeatureFlags(),
Platform: () => notLinuxPlatform,
});
testUsingContext('Not hidden when enabled and on Linux host', () {
expect(BuildLinuxCommand(logger: BufferLogger.test(), operatingSystemUtils: FakeOperatingSystemUtils()).hidden, false);
}, overrides: <Type, Generator>{
FeatureFlags: () => TestFeatureFlags(isLinuxEnabled: true),
Platform: () => linuxPlatform,
});
testUsingContext('Performs code size analysis and sends analytics', () async {
final BuildCommand command = BuildCommand(
artifacts: artifacts,
androidSdk: FakeAndroidSdk(),
buildSystem: TestBuildSystem.all(BuildResult(success: true)),
fileSystem: fileSystem,
logger: logger,
processUtils: processUtils,
osUtils: FakeOperatingSystemUtils(),
);
setUpMockProjectFilesForBuild();
processManager.addCommands(<FakeCommand>[
cmakeCommand('release'),
ninjaCommand('release', onRun: (_) {
fileSystem.file('build/flutter_size_01/snapshot.linux-x64.json')
..createSync(recursive: true)
..writeAsStringSync('''
[
{
"l": "dart:_internal",
"c": "SubListIterable",
"n": "[Optimized] skip",
"s": 2400
}
]''');
fileSystem.file('build/flutter_size_01/trace.linux-x64.json')
..createSync(recursive: true)
..writeAsStringSync('{}');
}),
]);
fileSystem.file('build/linux/x64/release/bundle/libapp.so')
..createSync(recursive: true)
..writeAsBytesSync(List<int>.filled(10000, 0));
await createTestCommandRunner(command).run(
const <String>['build', 'linux', '--no-pub', '--analyze-size']
);
expect(testLogger.statusText, contains('A summary of your Linux bundle analysis can be found at'));
expect(testLogger.statusText, contains('dart devtools --appSizeBase='));
expect(usage.events, contains(
const TestUsageEvent('code-size-analysis', 'linux'),
));
expect(fakeAnalytics.sentEvents, contains(
Event.codeSizeAnalysis(platform: 'linux')
));
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
ProcessManager: () => processManager,
Platform: () => linuxPlatform,
FeatureFlags: () => TestFeatureFlags(isLinuxEnabled: true),
Usage: () => usage,
OperatingSystemUtils: () => FakeOperatingSystemUtils(),
Analytics: () => fakeAnalytics,
});
testUsingContext('Linux on ARM64 build --release passes, and check if the LinuxBuildDirectory for arm64 can be referenced correctly by using analytics', () async {
final BuildCommand command = BuildCommand(
artifacts: artifacts,
androidSdk: FakeAndroidSdk(),
buildSystem: TestBuildSystem.all(BuildResult(success: true)),
fileSystem: fileSystem,
logger: logger,
processUtils: processUtils,
osUtils: CustomFakeOperatingSystemUtils(hostPlatform: HostPlatform.linux_arm64),
);
setUpMockProjectFilesForBuild();
processManager.addCommands(<FakeCommand>[
cmakeCommand('release', target: 'arm64'),
ninjaCommand('release', target: 'arm64', onRun: (_) {
fileSystem.file('build/flutter_size_01/snapshot.linux-arm64.json')
..createSync(recursive: true)
..writeAsStringSync('''
[
{
"l": "dart:_internal",
"c": "SubListIterable",
"n": "[Optimized] skip",
"s": 2400
}
]''');
fileSystem.file('build/flutter_size_01/trace.linux-arm64.json')
..createSync(recursive: true)
..writeAsStringSync('{}');
}),
]);
fileSystem.file('build/linux/arm64/release/bundle/libapp.so')
..createSync(recursive: true)
..writeAsBytesSync(List<int>.filled(10000, 0));
await createTestCommandRunner(command).run(
const <String>['build', 'linux', '--no-pub', '--analyze-size']
);
// check if libapp.so of "build/linux/arm64/release" directory can be referenced.
expect(testLogger.statusText, contains('libapp.so (Dart AOT)'));
expect(usage.events, contains(
const TestUsageEvent('code-size-analysis', 'linux'),
));
expect(fakeAnalytics.sentEvents, contains(
Event.codeSizeAnalysis(platform: 'linux')
));
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
ProcessManager: () => processManager,
Platform: () => linuxPlatform,
FeatureFlags: () => TestFeatureFlags(isLinuxEnabled: true),
Usage: () => usage,
OperatingSystemUtils: () => CustomFakeOperatingSystemUtils(hostPlatform: HostPlatform.linux_arm64),
Analytics: () => fakeAnalytics,
});
}
class CustomFakeOperatingSystemUtils extends Fake implements OperatingSystemUtils {
CustomFakeOperatingSystemUtils({
HostPlatform hostPlatform = HostPlatform.linux_x64
}) : _hostPlatform = hostPlatform;
final HostPlatform _hostPlatform;
@override
String get name => 'Linux';
@override
HostPlatform get hostPlatform => _hostPlatform;
@override
List<File> whichAll(String execName) => <File>[];
}
| flutter/packages/flutter_tools/test/commands.shard/hermetic/build_linux_test.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/commands.shard/hermetic/build_linux_test.dart",
"repo_id": "flutter",
"token_count": 10738
} | 765 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io';
import 'package:flutter_tools/src/base/platform.dart';
import 'package:flutter_tools/src/doctor_validator.dart';
import 'package:flutter_tools/src/http_host_validator.dart';
import '../../src/common.dart';
import '../../src/fake_http_client.dart';
import '../../src/fakes.dart';
// The environment variables used to override some URLs
const String kTestEnvPubHost = 'https://pub.flutter-io.cn';
const String kTestEnvGCloudHost = 'https://storage.flutter-io.cn';
const Map<String, String> kTestEnvironment = <String, String>{
'PUB_HOSTED_URL': kTestEnvPubHost,
'FLUTTER_STORAGE_BASE_URL': kTestEnvGCloudHost,
};
void main() {
group('http host validator', () {
const List<String> osTested = <String>['windows', 'macos', 'linux'];
group('no env variables', () {
testWithoutContext('all http hosts are available', () async {
final FakeHttpClient mockClient = FakeHttpClient.any();
// Run the check for all operating systems one by one
for (final String os in osTested) {
final HttpHostValidator httpHostValidator = HttpHostValidator(
platform: FakePlatform(operatingSystem: os),
featureFlags: TestFeatureFlags(),
httpClient: mockClient,
);
// Run the validation check and get the results
final ValidationResult result = await httpHostValidator.validate();
// Check for a ValidationType.success result
expect(result.type, equals(ValidationType.success));
}
});
testWithoutContext('all http hosts are not available', () async {
// Run the check for all operating systems one by one
for (final String os in osTested) {
final Platform platform = FakePlatform(operatingSystem: os);
final HttpHostValidator httpHostValidator = HttpHostValidator(
platform: platform,
featureFlags: TestFeatureFlags(),
httpClient: FakeHttpClient.list(<FakeRequest>[
FakeRequest(Uri.parse(kCloudHost), method: HttpMethod.head, responseError: const OSError('Name or service not known', -2)),
FakeRequest(Uri.parse(kCocoaPods), method: HttpMethod.head, responseError: const OSError('Name or service not known', -2)),
FakeRequest(Uri.parse(kGitHub), method: HttpMethod.head, responseError: const OSError('Name or service not known', -2)),
FakeRequest(Uri.parse(kMaven), method: HttpMethod.head, responseError: const OSError('Name or service not known', -2)),
FakeRequest(Uri.parse(kPubDev), method: HttpMethod.head, responseError: const OSError('Name or service not known', -2)),
]),
);
// Run the validation check and get the results
final ValidationResult result = await httpHostValidator.validate();
// Check for a ValidationType.notAvailable result
expect(result.type, equals(ValidationType.notAvailable));
}
});
testWithoutContext('one http host is not available', () async {
// Run the check for all operating systems one by one
for (final String os in osTested) {
final Platform platform = FakePlatform(operatingSystem: os);
final HttpHostValidator httpHostValidator = HttpHostValidator(
platform: platform,
featureFlags: TestFeatureFlags(),
httpClient: FakeHttpClient.list(<FakeRequest>[
FakeRequest(Uri.parse(kCloudHost), method: HttpMethod.head, responseError: const OSError('Name or service not known', -2)),
FakeRequest(Uri.parse(kCocoaPods), method: HttpMethod.head),
FakeRequest(Uri.parse(kGitHub), method: HttpMethod.head),
FakeRequest(Uri.parse(kMaven), method: HttpMethod.head),
FakeRequest(Uri.parse(kPubDev), method: HttpMethod.head),
]),
);
// Run the validation check and get the results
final ValidationResult result = await httpHostValidator.validate();
// Check for a ValidationType.partial result
expect(result.type, equals(ValidationType.partial));
}
});
});
group('with env variables', () {
testWithoutContext('all http hosts are available', () async {
final FakeHttpClient mockClient = FakeHttpClient.any();
// Run the check for all operating systems one by one
for (final String os in osTested) {
final HttpHostValidator httpHostValidator = HttpHostValidator(
platform: FakePlatform(operatingSystem: os, environment: kTestEnvironment),
featureFlags: TestFeatureFlags(),
httpClient: mockClient,
);
// Run the validation check and get the results
final ValidationResult result = await httpHostValidator.validate();
// Check for a ValidationType.success result
expect(result.type, equals(ValidationType.success));
}
});
testWithoutContext('all http hosts are not available', () async {
// Run the check for all operating systems one by one
for (final String os in osTested) {
final Platform platform = FakePlatform(operatingSystem: os, environment: kTestEnvironment);
final HttpHostValidator httpHostValidator = HttpHostValidator(
platform: platform,
featureFlags: TestFeatureFlags(),
httpClient: FakeHttpClient.list(<FakeRequest>[
FakeRequest(Uri.parse(kCocoaPods), method: HttpMethod.head, responseError: const OSError('Name or service not known', -2)),
FakeRequest(Uri.parse(kGitHub), method: HttpMethod.head, responseError: const OSError('Name or service not known', -2)),
FakeRequest(Uri.parse(kTestEnvGCloudHost), method: HttpMethod.head, responseError: const OSError('Name or service not known', -2)),
FakeRequest(Uri.parse(kTestEnvPubHost), method: HttpMethod.head, responseError: const OSError('Name or service not known', -2)),
]),
);
// Run the validation check and get the results
final ValidationResult result = await httpHostValidator.validate();
// Check for a ValidationType.notAvailable result
expect(result.type, equals(ValidationType.notAvailable));
}
});
testWithoutContext('one http host is not available', () async {
// Run the check for all operating systems one by one
for (final String os in osTested) {
final Platform platform = FakePlatform(operatingSystem: os, environment: kTestEnvironment);
final HttpHostValidator httpHostValidator = HttpHostValidator(
platform: platform,
featureFlags: TestFeatureFlags(),
httpClient: FakeHttpClient.list(<FakeRequest>[
FakeRequest(Uri.parse(kCocoaPods), method: HttpMethod.head),
FakeRequest(Uri.parse(kGitHub), method: HttpMethod.head, responseError: const OSError('Name or service not known', -2)),
FakeRequest(Uri.parse(kTestEnvGCloudHost), method: HttpMethod.head, responseError: const OSError('Name or service not known', -2)),
FakeRequest(Uri.parse(kTestEnvPubHost), method: HttpMethod.head),
]),
);
// Run the validation check and get the results
final ValidationResult result = await httpHostValidator.validate();
// Check for a ValidationType.partial result
expect(result.type, equals(ValidationType.partial));
}
});
testWithoutContext('does not throw on unparseable user-defined host uri', () async {
final HttpHostValidator httpHostValidator = HttpHostValidator(
platform: FakePlatform(
environment: <String,String> {
'PUB_HOSTED_URL': '::Not A Uri::',
'FLUTTER_STORAGE_BASE_URL': kTestEnvGCloudHost,
},
),
featureFlags: TestFeatureFlags(isAndroidEnabled: false),
httpClient: FakeHttpClient.any(),
);
// Run the validation check and get the results
final ValidationResult result = await httpHostValidator.validate();
expect(result.type, equals(ValidationType.partial));
expect(
result.messages,
contains(const ValidationMessage.error(
'Environment variable PUB_HOSTED_URL does not specify a valid URL: "::Not A Uri::"\n'
'Please see https://flutter.dev/community/china for an example of how to use it.',
)),
);
});
testWithoutContext('does not throw on invalid user-defined host', () async {
final HttpHostValidator httpHostValidator = HttpHostValidator(
platform: FakePlatform(
environment: <String,String> {
'PUB_HOSTED_URL': kTestEnvPubHost,
'FLUTTER_STORAGE_BASE_URL': '',
},
),
featureFlags: TestFeatureFlags(isAndroidEnabled: false),
httpClient: FakeHttpClient.any(),
);
// Run the validation check and get the results
final ValidationResult result = await httpHostValidator.validate();
expect(result.type, equals(ValidationType.partial));
expect(
result.messages,
contains(const ValidationMessage.error(
'Environment variable FLUTTER_STORAGE_BASE_URL does not specify a valid URL: ""\n'
'Please see https://flutter.dev/community/china for an example of how to use it.'
)),
);
});
});
group('specific os disabled', () {
testWithoutContext('all http hosts are available - android disabled', () async {
// Run the check for all operating systems one by one
for (final String os in osTested) {
final HttpHostValidator httpHostValidator = HttpHostValidator(
platform: FakePlatform(operatingSystem: os),
featureFlags: TestFeatureFlags(isAndroidEnabled: false),
httpClient: FakeHttpClient.list(<FakeRequest>[
FakeRequest(Uri.parse(kCloudHost), method: HttpMethod.head),
FakeRequest(Uri.parse(kCocoaPods), method: HttpMethod.head),
FakeRequest(Uri.parse(kGitHub), method: HttpMethod.head),
FakeRequest(Uri.parse(kPubDev), method: HttpMethod.head),
]),
);
// Run the validation check and get the results
final ValidationResult result = await httpHostValidator.validate();
// Check for a ValidationType.success result
expect(result.type, equals(ValidationType.success));
}
});
testWithoutContext('all http hosts are available - iOS disabled', () async {
// Run the check for all operating systems one by one
for (final String os in osTested) {
final Platform platform = FakePlatform(operatingSystem: os);
final HttpHostValidator httpHostValidator = HttpHostValidator(
platform: platform,
featureFlags: TestFeatureFlags(isIOSEnabled: false),
httpClient: FakeHttpClient.list(<FakeRequest>[
FakeRequest(Uri.parse(kCloudHost), method: HttpMethod.head),
FakeRequest(Uri.parse(kGitHub), method: HttpMethod.head),
FakeRequest(Uri.parse(kMaven), method: HttpMethod.head),
FakeRequest(Uri.parse(kPubDev), method: HttpMethod.head),
]),
);
// Run the validation check and get the results
final ValidationResult result = await httpHostValidator.validate();
// Check for a ValidationType.success result
expect(result.type, equals(ValidationType.success));
}
});
testWithoutContext('all http hosts are available - android, iOS disabled', () async {
// Run the check for all operating systems one by one
for (final String os in osTested) {
final HttpHostValidator httpHostValidator = HttpHostValidator(
platform: FakePlatform(operatingSystem: os),
featureFlags: TestFeatureFlags(isAndroidEnabled: false, isIOSEnabled: false),
httpClient: FakeHttpClient.list(<FakeRequest>[
FakeRequest(Uri.parse(kCloudHost), method: HttpMethod.head),
FakeRequest(Uri.parse(kGitHub), method: HttpMethod.head),
FakeRequest(Uri.parse(kPubDev), method: HttpMethod.head),
]),
);
// Run the validation check and get the results
final ValidationResult result = await httpHostValidator.validate();
// Check for a ValidationType.success result
expect(result.type, equals(ValidationType.success));
}
});
});
});
testWithoutContext('Does not throw on HandshakeException', () async {
const String handshakeMessage = '''
Handshake error in client (OS Error:
BLOCK_TYPE_IS_NOT_01(../../third_party/boringssl/src/crypto/fipsmodule/rsa/padding.c:108)
PADDING_CHECK_FAILED(../../third_party/boringssl/src/crypto/fipsmodule/rsa/rsa_impl.c:676)
public key routines(../../third_party/boringssl/src/crypto/x509/a_verify.c:108)
CERTIFICATE_VERIFY_FAILED: certificate signature failure(../../third_party/boringssl/src/ssl/handshake.cc:393))
''';
final HttpHostValidator httpHostValidator = HttpHostValidator(
platform: FakePlatform(environment: kTestEnvironment),
featureFlags: TestFeatureFlags(isAndroidEnabled: false),
httpClient: FakeHttpClient.list(<FakeRequest>[
FakeRequest(
Uri.parse(kTestEnvPubHost),
method: HttpMethod.head,
responseError: const HandshakeException(handshakeMessage),
),
FakeRequest(Uri.parse(kTestEnvGCloudHost), method: HttpMethod.head),
FakeRequest(Uri.parse(kGitHub), method: HttpMethod.head),
]),
);
// Run the validation check and get the results
final ValidationResult result = await httpHostValidator.validate();
expect(
result.messages.first,
isA<ValidationMessage>().having(
(ValidationMessage msg) => msg.message,
'message',
contains(handshakeMessage),
),
);
});
}
| flutter/packages/flutter_tools/test/commands.shard/hermetic/http_host_validator_test.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/commands.shard/hermetic/http_host_validator_test.dart",
"repo_id": "flutter",
"token_count": 5718
} | 766 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:args/command_runner.dart';
import 'package:flutter_tools/src/android/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/build_info.dart';
import 'package:flutter_tools/src/cache.dart';
import 'package:flutter_tools/src/commands/build_aar.dart';
import 'package:flutter_tools/src/features.dart';
import 'package:flutter_tools/src/globals.dart' as globals;
import 'package:flutter_tools/src/project.dart';
import 'package:flutter_tools/src/reporting/reporting.dart';
import 'package:test/fake.dart';
import '../../src/android_common.dart';
import '../../src/common.dart';
import '../../src/context.dart';
import '../../src/fake_process_manager.dart';
import '../../src/fakes.dart' hide FakeFlutterProjectFactory;
import '../../src/test_flutter_command_runner.dart';
void main() {
Cache.disableLocking();
Future<BuildAarCommand> runCommandIn(String target, { List<String>? arguments }) async {
final BuildAarCommand command = BuildAarCommand(
androidSdk: FakeAndroidSdk(),
fileSystem: globals.fs,
logger: BufferLogger.test(),
verboseHelp: false,
);
final CommandRunner<void> runner = createTestCommandRunner(command);
await runner.run(<String>[
'aar',
'--no-pub',
...?arguments,
target,
]);
return command;
}
group('Usage', () {
late Directory tempDir;
late TestUsage testUsage;
setUp(() {
testUsage = TestUsage();
tempDir = globals.fs.systemTempDirectory.createTempSync('flutter_tools_packages_test.');
});
tearDown(() {
tryToDelete(tempDir);
});
testUsingContext('indicate that project is a module', () async {
final String projectPath = await createProject(tempDir,
arguments: <String>['--no-pub', '--template=module']);
final BuildAarCommand command = await runCommandIn(projectPath);
expect((await command.usageValues).commandBuildAarProjectType, 'module');
}, overrides: <Type, Generator>{
AndroidBuilder: () => FakeAndroidBuilder(),
});
testUsingContext('indicate the target platform', () async {
final String projectPath = await createProject(tempDir,
arguments: <String>['--no-pub', '--template=module']);
final BuildAarCommand command = await runCommandIn(projectPath,
arguments: <String>['--target-platform=android-arm']);
expect((await command.usageValues).commandBuildAarTargetPlatform, 'android-arm');
}, overrides: <Type, Generator>{
AndroidBuilder: () => FakeAndroidBuilder(),
});
testUsingContext('logs success', () async {
final String projectPath = await createProject(tempDir,
arguments: <String>['--no-pub', '--template=module']);
await runCommandIn(projectPath,
arguments: <String>['--target-platform=android-arm']);
expect(testUsage.events, contains(
const TestUsageEvent(
'tool-command-result',
'aar',
label: 'success',
),
));
},
overrides: <Type, Generator>{
AndroidBuilder: () => FakeAndroidBuilder(),
Usage: () => testUsage,
});
});
group('flag parsing', () {
late Directory tempDir;
late FakeAndroidBuilder fakeAndroidBuilder;
setUp(() {
fakeAndroidBuilder = FakeAndroidBuilder();
tempDir = globals.fs.systemTempDirectory.createTempSync('flutter_tools_build_aar_test.');
});
tearDown(() {
tryToDelete(tempDir);
});
testUsingContext('defaults', () async {
final String projectPath = await createProject(tempDir,
arguments: <String>['--no-pub', '--template=module']);
await runCommandIn(projectPath);
expect(fakeAndroidBuilder.buildNumber, '1.0');
expect(fakeAndroidBuilder.androidBuildInfo.length, 3);
final List<BuildMode> buildModes = <BuildMode>[];
for (final AndroidBuildInfo androidBuildInfo in fakeAndroidBuilder.androidBuildInfo) {
final BuildInfo buildInfo = androidBuildInfo.buildInfo;
buildModes.add(buildInfo.mode);
if (buildInfo.mode.isPrecompiled) {
expect(buildInfo.treeShakeIcons, isTrue);
expect(buildInfo.trackWidgetCreation, isTrue);
} else {
expect(buildInfo.treeShakeIcons, isFalse);
expect(buildInfo.trackWidgetCreation, isTrue);
}
expect(buildInfo.flavor, isNull);
expect(buildInfo.splitDebugInfoPath, isNull);
expect(buildInfo.dartObfuscation, isFalse);
expect(androidBuildInfo.targetArchs, <AndroidArch>[AndroidArch.armeabi_v7a, AndroidArch.arm64_v8a, AndroidArch.x86_64]);
}
expect(buildModes.length, 3);
expect(buildModes, containsAll(<BuildMode>[BuildMode.debug, BuildMode.profile, BuildMode.release]));
}, overrides: <Type, Generator>{
AndroidBuilder: () => fakeAndroidBuilder,
});
testUsingContext('parses flags', () async {
final String projectPath = await createProject(tempDir,
arguments: <String>['--no-pub', '--template=module']);
await runCommandIn(
projectPath,
arguments: <String>[
'--no-debug',
'--no-profile',
'--target-platform',
'android-x86',
'--tree-shake-icons',
'--flavor',
'free',
'--build-number',
'200',
'--split-debug-info',
'/project-name/v1.2.3/',
'--obfuscate',
'--dart-define=foo=bar',
],
);
expect(fakeAndroidBuilder.buildNumber, '200');
final AndroidBuildInfo androidBuildInfo = fakeAndroidBuilder.androidBuildInfo.single;
expect(androidBuildInfo.targetArchs, <AndroidArch>[AndroidArch.x86]);
final BuildInfo buildInfo = androidBuildInfo.buildInfo;
expect(buildInfo.mode, BuildMode.release);
expect(buildInfo.treeShakeIcons, isTrue);
expect(buildInfo.flavor, 'free');
expect(buildInfo.splitDebugInfoPath, '/project-name/v1.2.3/');
expect(buildInfo.dartObfuscation, isTrue);
expect(buildInfo.dartDefines.contains('foo=bar'), isTrue);
expect(buildInfo.nullSafetyMode, NullSafetyMode.sound);
}, overrides: <Type, Generator>{
AndroidBuilder: () => fakeAndroidBuilder,
});
});
group('Gradle', () {
late Directory tempDir;
late AndroidSdk mockAndroidSdk;
late String gradlew;
late FakeProcessManager processManager;
late String flutterRoot;
setUp(() {
tempDir = globals.fs.systemTempDirectory.createTempSync('flutter_tools_packages_test.');
mockAndroidSdk = FakeAndroidSdk();
gradlew = globals.fs.path.join(tempDir.path, 'flutter_project', '.android',
globals.platform.isWindows ? 'gradlew.bat' : 'gradlew');
processManager = FakeProcessManager.empty();
flutterRoot = getFlutterRoot();
});
tearDown(() {
tryToDelete(tempDir);
});
group('AndroidSdk', () {
testUsingContext('throws throwsToolExit if AndroidSdk is null', () async {
final String projectPath = await createProject(tempDir,
arguments: <String>['--no-pub', '--template=module']);
await expectLater(() async {
await runBuildAarCommand(
projectPath,
null,
arguments: <String>['--no-pub'],
);
}, throwsToolExit(
message: 'No Android SDK found. Try setting the ANDROID_HOME environment variable',
));
},
overrides: <Type, Generator>{
FlutterProjectFactory: () => FakeFlutterProjectFactory(tempDir),
ProcessManager: () => FakeProcessManager.any(),
});
});
group('throws ToolExit', () {
testUsingContext('main.dart not found', () async {
await expectLater(() async {
await runBuildAarCommand(
'missing_project',
mockAndroidSdk,
arguments: <String>['--no-pub'],
);
}, throwsToolExit(
message: 'main.dart does not exist',
));
});
testUsingContext('flutter project not valid', () async {
await expectLater(() async {
await runCommandIn(
tempDir.path,
arguments: <String>['--no-pub'],
);
}, throwsToolExit(
message: 'is not a valid flutter project',
));
});
});
testUsingContext('support ExtraDartFlagOptions', () async {
final String projectPath = await createProject(tempDir,
arguments: <String>['--no-pub', '--template=module']);
processManager.addCommand(FakeCommand(
command: <String>[
gradlew,
'-I=${globals.fs.path.join(flutterRoot, 'packages', 'flutter_tools', 'gradle','aar_init_script.gradle')}',
'-Pflutter-root=$flutterRoot',
'-Poutput-dir=${globals.fs.path.join(tempDir.path, 'flutter_project', 'build', 'host')}',
'-Pis-plugin=false',
'-PbuildNumber=1.0',
'-q',
'-Ptarget=${globals.fs.path.join('lib', 'main.dart')}',
'-Pdart-obfuscation=false',
'-Pextra-front-end-options=foo,bar',
'-Ptrack-widget-creation=true',
'-Ptree-shake-icons=true',
'-Ptarget-platform=android-arm,android-arm64,android-x64',
'assembleAarRelease',
],
exitCode: 1,
));
await expectLater(() => runBuildAarCommand(projectPath, mockAndroidSdk, arguments: <String>[
'--no-debug',
'--no-profile',
'--extra-front-end-options=foo',
'--extra-front-end-options=bar',
]), throwsToolExit(message: 'Gradle task assembleAarRelease failed with exit code 1'));
expect(processManager, hasNoRemainingExpectations);
},
overrides: <Type, Generator>{
FlutterProjectFactory: () => FakeFlutterProjectFactory(tempDir),
Java: () => null,
ProcessManager: () => processManager,
FeatureFlags: () => TestFeatureFlags(isIOSEnabled: false),
AndroidStudio: () => FakeAndroidStudio(),
});
});
}
Future<BuildAarCommand> runBuildAarCommand(
String target, AndroidSdk? androidSdk, {
List<String>? arguments,
}) async {
final BuildAarCommand command = BuildAarCommand(
androidSdk: androidSdk,
fileSystem: globals.fs,
logger: BufferLogger.test(),
verboseHelp: false,
);
final CommandRunner<void> runner = createTestCommandRunner(command);
await runner.run(<String>[
'aar',
'--no-pub',
...?arguments,
globals.fs.path.join(target, 'lib', 'main.dart'),
]);
return command;
}
class FakeAndroidBuilder extends Fake implements AndroidBuilder {
late FlutterProject project;
late Set<AndroidBuildInfo> androidBuildInfo;
late String target;
String? outputDirectoryPath;
late String buildNumber;
@override
Future<void> buildAar({
required FlutterProject project,
required Set<AndroidBuildInfo> androidBuildInfo,
required String target,
String? outputDirectoryPath,
required String buildNumber,
}) async {
this.project = project;
this.androidBuildInfo = androidBuildInfo;
this.target = target;
this.outputDirectoryPath = outputDirectoryPath;
this.buildNumber = buildNumber;
}
}
class FakeAndroidSdk extends Fake implements AndroidSdk {
}
class FakeAndroidStudio extends Fake implements AndroidStudio {
@override
String get javaPath => 'java';
}
| flutter/packages/flutter_tools/test/commands.shard/permeable/build_aar_test.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/commands.shard/permeable/build_aar_test.dart",
"repo_id": "flutter",
"token_count": 4630
} | 767 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:file/memory.dart';
import 'package:flutter_tools/src/android/android_device_discovery.dart';
import 'package:flutter_tools/src/android/android_sdk.dart';
import 'package:flutter_tools/src/android/android_workflow.dart';
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/base/platform.dart';
import 'package:flutter_tools/src/base/user_messages.dart';
import 'package:flutter_tools/src/device.dart';
import 'package:test/fake.dart';
import '../../src/common.dart';
import '../../src/fake_process_manager.dart';
import '../../src/fakes.dart';
void main() {
late AndroidWorkflow androidWorkflow;
setUp(() {
androidWorkflow = AndroidWorkflow(
androidSdk: FakeAndroidSdk(),
featureFlags: TestFeatureFlags(),
);
});
testWithoutContext('AndroidDevices returns empty device list and diagnostics on null adb', () async {
final AndroidDevices androidDevices = AndroidDevices(
androidSdk: FakeAndroidSdk(null),
logger: BufferLogger.test(),
androidWorkflow: AndroidWorkflow(
androidSdk: FakeAndroidSdk(null),
featureFlags: TestFeatureFlags(),
),
processManager: FakeProcessManager.empty(),
fileSystem: MemoryFileSystem.test(),
platform: FakePlatform(),
userMessages: UserMessages(),
);
expect(await androidDevices.pollingGetDevices(), isEmpty);
expect(await androidDevices.getDiagnostics(), isEmpty);
});
testWithoutContext('AndroidDevices returns empty device list and diagnostics when adb cannot be run', () async {
final FakeProcessManager fakeProcessManager = FakeProcessManager.empty();
fakeProcessManager.excludedExecutables.add('adb');
final AndroidDevices androidDevices = AndroidDevices(
androidSdk: FakeAndroidSdk(),
logger: BufferLogger.test(),
androidWorkflow: AndroidWorkflow(
androidSdk: FakeAndroidSdk(),
featureFlags: TestFeatureFlags(),
),
processManager: fakeProcessManager,
fileSystem: MemoryFileSystem.test(),
platform: FakePlatform(),
userMessages: UserMessages(),
);
expect(await androidDevices.pollingGetDevices(), isEmpty);
expect(await androidDevices.getDiagnostics(), isEmpty);
expect(fakeProcessManager, hasNoRemainingExpectations);
});
testWithoutContext('AndroidDevices returns empty device list and diagnostics on null Android SDK', () async {
final AndroidDevices androidDevices = AndroidDevices(
logger: BufferLogger.test(),
androidWorkflow: AndroidWorkflow(
androidSdk: FakeAndroidSdk(null),
featureFlags: TestFeatureFlags(),
),
processManager: FakeProcessManager.empty(),
fileSystem: MemoryFileSystem.test(),
platform: FakePlatform(),
userMessages: UserMessages(),
);
expect(await androidDevices.pollingGetDevices(), isEmpty);
expect(await androidDevices.getDiagnostics(), isEmpty);
});
testWithoutContext('AndroidDevices throwsToolExit on failing adb', () {
final ProcessManager processManager = FakeProcessManager.list(<FakeCommand>[
const FakeCommand(
command: <String>['adb', 'devices', '-l'],
exitCode: 1,
),
]);
final AndroidDevices androidDevices = AndroidDevices(
androidSdk: FakeAndroidSdk(),
logger: BufferLogger.test(),
androidWorkflow: androidWorkflow,
processManager: processManager,
fileSystem: MemoryFileSystem.test(),
platform: FakePlatform(),
userMessages: UserMessages(),
);
expect(androidDevices.pollingGetDevices(),
throwsToolExit(message: RegExp('Unable to run "adb"')));
});
testWithoutContext('AndroidDevices is disabled if feature is disabled', () {
final AndroidDevices androidDevices = AndroidDevices(
androidSdk: FakeAndroidSdk(),
logger: BufferLogger.test(),
androidWorkflow: AndroidWorkflow(
androidSdk: FakeAndroidSdk(),
featureFlags: TestFeatureFlags(
isAndroidEnabled: false,
),
),
processManager: FakeProcessManager.any(),
fileSystem: MemoryFileSystem.test(),
platform: FakePlatform(),
userMessages: UserMessages(),
);
expect(androidDevices.supportsPlatform, false);
});
testWithoutContext('AndroidDevices can parse output for physical attached devices', () async {
final AndroidDevices androidDevices = AndroidDevices(
userMessages: UserMessages(),
androidWorkflow: androidWorkflow,
androidSdk: FakeAndroidSdk(),
logger: BufferLogger.test(),
processManager: FakeProcessManager.list(<FakeCommand>[
const FakeCommand(
command: <String>['adb', 'devices', '-l'],
stdout: '''
List of devices attached
05a02bac device usb:336592896X product:razor model:Nexus_7 device:flo
''',
),
]),
platform: FakePlatform(),
fileSystem: MemoryFileSystem.test(),
);
final List<Device> devices = await androidDevices.pollingGetDevices();
expect(devices, hasLength(1));
expect(devices.first.name, 'Nexus 7');
expect(devices.first.category, Category.mobile);
expect(devices.first.connectionInterface, DeviceConnectionInterface.attached);
});
testWithoutContext('AndroidDevices can parse output for physical wireless devices', () async {
final AndroidDevices androidDevices = AndroidDevices(
userMessages: UserMessages(),
androidWorkflow: androidWorkflow,
androidSdk: FakeAndroidSdk(),
logger: BufferLogger.test(),
processManager: FakeProcessManager.list(<FakeCommand>[
const FakeCommand(
command: <String>['adb', 'devices', '-l'],
stdout: '''
List of devices attached
05a02bac._adb-tls-connect._tcp. device product:razor model:Nexus_7 device:flo
''',
),
]),
platform: FakePlatform(),
fileSystem: MemoryFileSystem.test(),
);
final List<Device> devices = await androidDevices.pollingGetDevices();
expect(devices, hasLength(1));
expect(devices.first.name, 'Nexus 7');
expect(devices.first.category, Category.mobile);
expect(devices.first.connectionInterface, DeviceConnectionInterface.wireless);
});
testWithoutContext('AndroidDevices can parse output for emulators and short listings', () async {
final AndroidDevices androidDevices = AndroidDevices(
userMessages: UserMessages(),
androidWorkflow: androidWorkflow,
androidSdk: FakeAndroidSdk(),
logger: BufferLogger.test(),
processManager: FakeProcessManager.list(<FakeCommand>[
const FakeCommand(
command: <String>['adb', 'devices', '-l'],
stdout: '''
List of devices attached
localhost:36790 device
0149947A0D01500C device usb:340787200X
emulator-5612 host features:shell_2
''',
),
]),
platform: FakePlatform(),
fileSystem: MemoryFileSystem.test(),
);
final List<Device> devices = await androidDevices.pollingGetDevices();
expect(devices, hasLength(3));
expect(devices[0].name, 'localhost:36790');
expect(devices[1].name, '0149947A0D01500C');
expect(devices[2].name, 'emulator-5612');
});
testWithoutContext('AndroidDevices can parse output from android n', () async {
final AndroidDevices androidDevices = AndroidDevices(
userMessages: UserMessages(),
androidWorkflow: androidWorkflow,
androidSdk: FakeAndroidSdk(),
logger: BufferLogger.test(),
processManager: FakeProcessManager.list(<FakeCommand>[
const FakeCommand(
command: <String>['adb', 'devices', '-l'],
stdout: '''
List of devices attached
ZX1G22JJWR device usb:3-3 product:shamu model:Nexus_6 device:shamu features:cmd,shell_v2
''',
),
]),
platform: FakePlatform(),
fileSystem: MemoryFileSystem.test(),
);
final List<Device> devices = await androidDevices.pollingGetDevices();
expect(devices, hasLength(1));
expect(devices.first.name, 'Nexus 6');
});
testWithoutContext('AndroidDevices provides adb error message as diagnostics', () async {
final AndroidDevices androidDevices = AndroidDevices(
userMessages: UserMessages(),
androidWorkflow: androidWorkflow,
androidSdk: FakeAndroidSdk(),
logger: BufferLogger.test(),
processManager: FakeProcessManager.list(<FakeCommand>[
const FakeCommand(
command: <String>['adb', 'devices', '-l'],
stdout: '''
It appears you do not have 'Android SDK Platform-tools' installed.
Use the 'android' tool to install them:
android update sdk --no-ui --filter 'platform-tools'
''',
),
]),
platform: FakePlatform(),
fileSystem: MemoryFileSystem.test(),
);
final List<String> diagnostics = await androidDevices.getDiagnostics();
expect(diagnostics, hasLength(1));
expect(diagnostics.first, contains('you do not have'));
});
}
class FakeAndroidSdk extends Fake implements AndroidSdk {
FakeAndroidSdk([this.adbPath = 'adb']);
@override
final String? adbPath;
}
| flutter/packages/flutter_tools/test/general.shard/android/android_device_discovery_test.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/general.shard/android/android_device_discovery_test.dart",
"repo_id": "flutter",
"token_count": 3326
} | 768 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:file/memory.dart';
import 'package:flutter_tools/src/android/gradle.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/build_info.dart';
import 'package:flutter_tools/src/project.dart';
import 'package:flutter_tools/src/reporting/reporting.dart';
import 'package:unified_analytics/unified_analytics.dart';
import '../../src/common.dart';
import '../../src/fakes.dart';
void main() {
late FileSystem fileSystem;
late FakeAnalytics fakeAnalytics;
setUp(() {
fileSystem = MemoryFileSystem.test();
fakeAnalytics = getInitializedFakeAnalyticsInstance(
fs: fileSystem,
fakeFlutterVersion: FakeFlutterVersion(),
);
});
testWithoutContext('Finds app bundle when flavor contains multiple dimensions in release mode', () {
final FlutterProject project = generateFakeAppBundle('fooBarRelease', 'app-foo-bar-release.aab', fileSystem);
final File bundle = findBundleFile(
project,
const BuildInfo(BuildMode.release, 'fooBar', treeShakeIcons: false),
BufferLogger.test(),
TestUsage(),
fakeAnalytics,
);
expect(bundle, isNotNull);
expect(bundle.path, '/build/app/outputs/bundle/fooBarRelease/app-foo-bar-release.aab');
});
testWithoutContext('Finds app bundle when flavor contains underscores in release mode', () {
final FlutterProject project = generateFakeAppBundle('foo_barRelease', 'app.aab', fileSystem);
final File bundle = findBundleFile(
project,
const BuildInfo(BuildMode.release, 'foo_bar', treeShakeIcons: false),
BufferLogger.test(),
TestUsage(),
fakeAnalytics,
);
expect(bundle, isNotNull);
expect(bundle.path, '/build/app/outputs/bundle/foo_barRelease/app.aab');
});
testWithoutContext('Finds app bundle when flavor contains underscores and uppercase letters in release mode', () {
final FlutterProject project = generateFakeAppBundle('foo_barRelease', 'app.aab', fileSystem);
final File bundle = findBundleFile(
project,
const BuildInfo(BuildMode.release, 'foo_Bar', treeShakeIcons: false),
BufferLogger.test(),
TestUsage(),
fakeAnalytics,
);
expect(bundle, isNotNull);
expect(bundle.path, '/build/app/outputs/bundle/foo_barRelease/app.aab');
});
testWithoutContext("Finds app bundle when flavor doesn't contain underscores in release mode", () {
final FlutterProject project = generateFakeAppBundle('fooRelease', 'app.aab', fileSystem);
final File bundle = findBundleFile(
project,
const BuildInfo(BuildMode.release, 'foo', treeShakeIcons: false),
BufferLogger.test(),
TestUsage(),
fakeAnalytics,
);
expect(bundle, isNotNull);
expect(bundle.path, '/build/app/outputs/bundle/fooRelease/app.aab');
});
testWithoutContext("Finds app bundle when flavor doesn't contain underscores but contains uppercase letters in release mode", () {
final FlutterProject project = generateFakeAppBundle('fooaRelease', 'app.aab', fileSystem);
final File bundle = findBundleFile(
project,
const BuildInfo(BuildMode.release, 'fooA', treeShakeIcons: false),
BufferLogger.test(),
TestUsage(),
fakeAnalytics,
);
expect(bundle, isNotNull);
expect(bundle.path, '/build/app/outputs/bundle/fooaRelease/app.aab');
});
testWithoutContext('Finds app bundle when no flavor is used in release mode', () {
final FlutterProject project = generateFakeAppBundle('release', 'app.aab', fileSystem);
final File bundle = findBundleFile(
project,
const BuildInfo(BuildMode.release, null, treeShakeIcons: false),
BufferLogger.test(),
TestUsage(),
fakeAnalytics,
);
expect(bundle, isNotNull);
expect(bundle.path, '/build/app/outputs/bundle/release/app.aab');
});
testWithoutContext('Finds app bundle when flavor contains multiple dimensions in debug mode', () {
final FlutterProject project = generateFakeAppBundle('fooBarDebug', 'app-foo-bar-debug.aab', fileSystem);
final File bundle = findBundleFile(
project,
const BuildInfo(BuildMode.debug, 'fooBar', treeShakeIcons: false),
BufferLogger.test(),
TestUsage(),
fakeAnalytics,
);
expect(bundle, isNotNull);
expect(bundle.path, '/build/app/outputs/bundle/fooBarDebug/app-foo-bar-debug.aab');
});
testWithoutContext('Finds app bundle when flavor contains underscores in debug mode', () {
final FlutterProject project = generateFakeAppBundle('foo_barDebug', 'app.aab', fileSystem);
final File bundle = findBundleFile(
project,
const BuildInfo(BuildMode.debug, 'foo_bar', treeShakeIcons: false),
BufferLogger.test(),
TestUsage(),
fakeAnalytics,
);
expect(bundle, isNotNull);
expect(bundle.path, '/build/app/outputs/bundle/foo_barDebug/app.aab');
});
testWithoutContext('Finds app bundle when flavor contains underscores and uppercase letters in debug mode', () {
final FlutterProject project = generateFakeAppBundle('foo_barDebug', 'app.aab', fileSystem);
final File bundle = findBundleFile(
project,
const BuildInfo(BuildMode.debug, 'foo_Bar', treeShakeIcons: false),
BufferLogger.test(),
TestUsage(),
fakeAnalytics,
);
expect(bundle, isNotNull);
expect(bundle.path, '/build/app/outputs/bundle/foo_barDebug/app.aab');
});
testWithoutContext("Finds app bundle when flavor doesn't contain underscores in debug mode", () {
final FlutterProject project = generateFakeAppBundle('fooDebug', 'app.aab', fileSystem);
final File bundle = findBundleFile(
project,
const BuildInfo(BuildMode.debug, 'foo', treeShakeIcons: false),
BufferLogger.test(),
TestUsage(),
fakeAnalytics,
);
expect(bundle, isNotNull);
expect(bundle.path, '/build/app/outputs/bundle/fooDebug/app.aab');
});
testWithoutContext("Finds app bundle when flavor doesn't contain underscores but contains uppercase letters in debug mode", () {
final FlutterProject project = generateFakeAppBundle('fooaDebug', 'app.aab', fileSystem);
final File bundle = findBundleFile(
project,
const BuildInfo(BuildMode.debug, 'fooA', treeShakeIcons: false),
BufferLogger.test(),
TestUsage(),
fakeAnalytics,
);
expect(bundle, isNotNull);
expect(bundle.path, '/build/app/outputs/bundle/fooaDebug/app.aab');
});
testWithoutContext('Finds app bundle when no flavor is used in debug mode', () {
final FlutterProject project = generateFakeAppBundle('debug', 'app.aab', fileSystem);
final File bundle = findBundleFile(
project,
BuildInfo.debug,
BufferLogger.test(),
TestUsage(),
fakeAnalytics,
);
expect(bundle, isNotNull);
expect(bundle.path, '/build/app/outputs/bundle/debug/app.aab');
});
testWithoutContext('Finds app bundle when flavor contains multiple dimensions in profile mode', () {
final FlutterProject project = generateFakeAppBundle('fooBarProfile', 'app-foo-bar-profile.aab', fileSystem);
final File bundle = findBundleFile(
project,
const BuildInfo(BuildMode.profile, 'fooBar', treeShakeIcons: false),
BufferLogger.test(),
TestUsage(),
fakeAnalytics,
);
expect(bundle, isNotNull);
expect(bundle.path, '/build/app/outputs/bundle/fooBarProfile/app-foo-bar-profile.aab');
});
testWithoutContext('Finds app bundle when flavor contains underscores in profile mode', () {
final FlutterProject project = generateFakeAppBundle('foo_barProfile', 'app.aab', fileSystem);
final File bundle = findBundleFile(
project,
const BuildInfo(BuildMode.profile, 'foo_bar', treeShakeIcons: false),
BufferLogger.test(),
TestUsage(),
fakeAnalytics,
);
expect(bundle, isNotNull);
expect(bundle.path, '/build/app/outputs/bundle/foo_barProfile/app.aab');
});
testWithoutContext('Finds app bundle when flavor contains underscores and uppercase letters in profile mode', () {
final FlutterProject project = generateFakeAppBundle('foo_barProfile', 'app.aab', fileSystem);
final File bundle = findBundleFile(
project,
const BuildInfo(BuildMode.profile, 'foo_Bar', treeShakeIcons: false),
BufferLogger.test(),
TestUsage(),
fakeAnalytics,
);
expect(bundle, isNotNull);
expect(bundle.path, '/build/app/outputs/bundle/foo_barProfile/app.aab');
});
testWithoutContext("Finds app bundle when flavor doesn't contain underscores in profile mode", () {
final FlutterProject project = generateFakeAppBundle('fooProfile', 'app.aab', fileSystem);
final File bundle = findBundleFile(
project,
const BuildInfo(BuildMode.profile, 'foo', treeShakeIcons: false),
BufferLogger.test(),
TestUsage(),
fakeAnalytics,
);
expect(bundle, isNotNull);
expect(bundle.path, '/build/app/outputs/bundle/fooProfile/app.aab');
});
testWithoutContext("Finds app bundle when flavor doesn't contain underscores but contains uppercase letters in profile mode", () {
final FlutterProject project = generateFakeAppBundle('fooaProfile', 'app.aab', fileSystem);
final File bundle = findBundleFile(
project,
const BuildInfo(BuildMode.profile, 'fooA', treeShakeIcons: false),
BufferLogger.test(),
TestUsage(),
fakeAnalytics,
);
expect(bundle, isNotNull);
expect(bundle.path, '/build/app/outputs/bundle/fooaProfile/app.aab');
});
testWithoutContext('Finds app bundle when no flavor is used in profile mode', () {
final FlutterProject project = generateFakeAppBundle('profile', 'app.aab', fileSystem);
final File bundle = findBundleFile(
project,
const BuildInfo(BuildMode.profile, null, treeShakeIcons: false),
BufferLogger.test(),
TestUsage(),
fakeAnalytics,
);
expect(bundle, isNotNull);
expect(bundle.path, '/build/app/outputs/bundle/profile/app.aab');
});
testWithoutContext('Finds app bundle in release mode - Gradle 3.5', () {
final FlutterProject project = generateFakeAppBundle('release', 'app-release.aab', fileSystem);
final File bundle = findBundleFile(
project,
const BuildInfo(BuildMode.release, null, treeShakeIcons: false),
BufferLogger.test(),
TestUsage(),
fakeAnalytics,
);
expect(bundle, isNotNull);
expect(bundle.path, '/build/app/outputs/bundle/release/app-release.aab');
});
testWithoutContext('Finds app bundle in profile mode - Gradle 3.5', () {
final FlutterProject project = generateFakeAppBundle('profile', 'app-profile.aab', fileSystem);
final File bundle = findBundleFile(
project,
const BuildInfo(BuildMode.profile, null, treeShakeIcons: false),
BufferLogger.test(),
TestUsage(),
fakeAnalytics,
);
expect(bundle, isNotNull);
expect(bundle.path, '/build/app/outputs/bundle/profile/app-profile.aab');
});
testWithoutContext('Finds app bundle in debug mode - Gradle 3.5', () {
final FlutterProject project = generateFakeAppBundle('debug', 'app-debug.aab', fileSystem);
final File bundle = findBundleFile(
project,
BuildInfo.debug,
BufferLogger.test(),
TestUsage(),
fakeAnalytics,
);
expect(bundle, isNotNull);
expect(bundle.path, '/build/app/outputs/bundle/debug/app-debug.aab');
});
testWithoutContext('Finds app bundle when flavor contains underscores in release mode - Gradle 3.5', () {
final FlutterProject project = generateFakeAppBundle('foo_barRelease', 'app-foo_bar-release.aab', fileSystem);
final File bundle = findBundleFile(
project,
const BuildInfo(BuildMode.release, 'foo_bar', treeShakeIcons: false),
BufferLogger.test(),
TestUsage(),
fakeAnalytics,
);
expect(bundle, isNotNull);
expect(bundle.path, '/build/app/outputs/bundle/foo_barRelease/app-foo_bar-release.aab');
});
testWithoutContext('Finds app bundle when flavor contains underscores and uppercase letters in release mode - Gradle 3.5', () {
final FlutterProject project = generateFakeAppBundle('foo_barRelease', 'app-foo_bar-release.aab', fileSystem);
final File bundle = findBundleFile(
project,
const BuildInfo(BuildMode.release, 'foo_Bar', treeShakeIcons: false),
BufferLogger.test(),
TestUsage(),
fakeAnalytics,
);
expect(bundle, isNotNull);
expect(bundle.path, '/build/app/outputs/bundle/foo_barRelease/app-foo_bar-release.aab');
});
testWithoutContext('Finds app bundle when flavor contains underscores in profile mode - Gradle 3.5', () {
final FlutterProject project = generateFakeAppBundle('foo_barProfile', 'app-foo_bar-profile.aab', fileSystem);
final File bundle = findBundleFile(
project,
const BuildInfo(BuildMode.profile, 'foo_bar', treeShakeIcons: false),
BufferLogger.test(),
TestUsage(),
fakeAnalytics,
);
expect(bundle, isNotNull);
expect(bundle.path, '/build/app/outputs/bundle/foo_barProfile/app-foo_bar-profile.aab');
});
testWithoutContext('Finds app bundle when flavor contains underscores and uppercase letters in debug mode - Gradle 3.5', () {
final FlutterProject project = generateFakeAppBundle('foo_barDebug', 'app-foo_bar-debug.aab', fileSystem);
final File bundle = findBundleFile(
project,
const BuildInfo(BuildMode.debug, 'foo_Bar', treeShakeIcons: false),
BufferLogger.test(),
TestUsage(),
fakeAnalytics,
);
expect(bundle, isNotNull);
expect(bundle.path, '/build/app/outputs/bundle/foo_barDebug/app-foo_bar-debug.aab');
});
testWithoutContext(
'Finds app bundle when flavor contains underscores and uppercase letters in release mode - Gradle 4.1', () {
final FlutterProject project = generateFakeAppBundle('foo_BarRelease', 'app-foo_Bar-release.aab', fileSystem);
final File bundle = findBundleFile(
project,
const BuildInfo(BuildMode.release, 'Foo_Bar', treeShakeIcons: false),
BufferLogger.test(),
TestUsage(),
fakeAnalytics,
);
expect(bundle, isNotNull);
expect(bundle.path, '/build/app/outputs/bundle/foo_BarRelease/app-foo_Bar-release.aab');
});
testWithoutContext(
'Finds app bundle when flavor contains underscores and uppercase letters in debug mode - Gradle 4.1', () {
final FlutterProject project = generateFakeAppBundle('foo_BarDebug', 'app-foo_Bar-debug.aab', fileSystem);
final File bundle = findBundleFile(
project,
const BuildInfo(BuildMode.debug, 'Foo_Bar', treeShakeIcons: false),
BufferLogger.test(),
TestUsage(),
fakeAnalytics,
);
expect(bundle, isNotNull);
expect(bundle.path, '/build/app/outputs/bundle/foo_BarDebug/app-foo_Bar-debug.aab');
});
testWithoutContext('AAB not found', () {
final FlutterProject project = FlutterProject.fromDirectoryTest(fileSystem.currentDirectory);
final TestUsage testUsage = TestUsage();
expect(
() {
findBundleFile(
project,
const BuildInfo(BuildMode.debug, 'foo_bar', treeShakeIcons: false),
BufferLogger.test(),
testUsage,
fakeAnalytics,
);
},
throwsToolExit(
message:
"Gradle build failed to produce an .aab file. It's likely that this file "
"was generated under ${project.android.buildDirectory.path}, but the tool couldn't find it."
)
);
expect(testUsage.events, contains(
TestUsageEvent(
'build',
'gradle',
label: 'gradle-expected-file-not-found',
parameters: CustomDimensions.fromMap(<String, String> {
'cd37': 'androidGradlePluginVersion: 7.6.3, fileExtension: .aab',
}),
),
));
expect(fakeAnalytics.sentEvents, hasLength(1));
expect(
fakeAnalytics.sentEvents,
contains(
Event.flutterBuildInfo(
label: 'gradle-expected-file-not-found',
buildType: 'gradle',
settings: 'androidGradlePluginVersion: 7.6.3, fileExtension: .aab',
),
),
);
});
}
/// Generates a fake app bundle at the location [directoryName]/[fileName].
FlutterProject generateFakeAppBundle(String directoryName, String fileName, FileSystem fileSystem) {
final FlutterProject project = FlutterProject.fromDirectoryTest(fileSystem.currentDirectory);
final Directory bundleDirectory = getBundleDirectory(project);
bundleDirectory
.childDirectory(directoryName)
.createSync(recursive: true);
bundleDirectory
.childDirectory(directoryName)
.childFile(fileName)
.createSync();
return project;
}
| flutter/packages/flutter_tools/test/general.shard/android/gradle_find_bundle_test.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/general.shard/android/gradle_find_bundle_test.dart",
"repo_id": "flutter",
"token_count": 6111
} | 769 |
// 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:archive/archive.dart';
import 'package:file/memory.dart';
import 'package:flutter_tools/src/base/analyze_size.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/reporting/reporting.dart';
import 'package:unified_analytics/unified_analytics.dart';
import '../../src/common.dart';
const String aotSizeOutput = '''
[
{
"l": "dart:_internal",
"c": "SubListIterable",
"n": "[Optimized] skip",
"s": 2400
},
{
"l": "dart:_internal",
"c": "SubListIterable",
"n": "[Optimized] new SubListIterable.",
"s": 3560
},
{
"l": "dart:core",
"c": "RangeError",
"n": "[Optimized] new RangeError.range",
"s": 3920
},
{
"l": "dart:core",
"c": "ArgumentError",
"n": "[Stub] Allocate ArgumentError",
"s": 4650
}
]
''';
void main() {
late MemoryFileSystem fileSystem;
late BufferLogger logger;
setUp(() {
fileSystem = MemoryFileSystem.test();
logger = BufferLogger.test();
});
testWithoutContext('matchesPattern matches only entire strings', () {
expect(matchesPattern('', pattern: ''), isNotNull);
expect(matchesPattern('', pattern: 'foo'), null);
expect(matchesPattern('foo', pattern: ''), null);
expect(matchesPattern('foo', pattern: 'foo'), isNotNull);
expect(matchesPattern('foo', pattern: 'foobar'), null);
expect(matchesPattern('foobar', pattern: 'foo'), null);
expect(matchesPattern('foobar', pattern: RegExp(r'.*b.*')), isNotNull);
expect(matchesPattern('foobar', pattern: RegExp(r'.*b')), null);
});
testWithoutContext('builds APK analysis correctly', () async {
final SizeAnalyzer sizeAnalyzer = SizeAnalyzer(
fileSystem: fileSystem,
logger: logger,
appFilenamePattern: RegExp(r'lib.*app\.so'),
flutterUsage: TestUsage(),
analytics: const NoOpAnalytics(),
);
final Archive archive = Archive()
..addFile(ArchiveFile('AndroidManifest.xml', 100, List<int>.filled(100, 0)))
..addFile(ArchiveFile('META-INF/CERT.RSA', 10, List<int>.filled(10, 0)))
..addFile(ArchiveFile('META-INF/CERT.SF', 10, List<int>.filled(10, 0)))
..addFile(ArchiveFile('lib/arm64-v8a/libxyzzyapp.so', 50, List<int>.filled(50, 0)))
..addFile(ArchiveFile('lib/arm64-v8a/libflutter.so', 50, List<int>.filled(50, 0)));
final File apk = fileSystem.file('test.apk')
..writeAsBytesSync(ZipEncoder().encode(archive)!);
final File aotSizeJson = fileSystem.file('test.json')
..createSync()
..writeAsStringSync(aotSizeOutput);
final File precompilerTrace = fileSystem.file('trace.json')
..writeAsStringSync('{}');
final Map<String, dynamic> result = await sizeAnalyzer.analyzeZipSizeAndAotSnapshot(
zipFile: apk,
aotSnapshot: aotSizeJson,
precompilerTrace: precompilerTrace,
kind: 'apk',
);
expect(result['type'], 'apk');
final List<dynamic> resultChildren = result['children'] as List<dynamic>;
final Map<String, dynamic> androidManifestMap = resultChildren[0] as Map<String, dynamic>;
expect(androidManifestMap['n'], 'AndroidManifest.xml');
expect(androidManifestMap['value'], 6);
final Map<String, Object?> metaInfMap = resultChildren[1] as Map<String, Object?>;
final List<Map<String, Object?>> metaInfMapChildren = metaInfMap['children']! as List<Map<String, Object?>>;
expect(metaInfMap['n'], 'META-INF');
expect(metaInfMap['value'], 10);
final Map<String, dynamic> certRsaMap = metaInfMapChildren[0];
expect(certRsaMap['n'], 'CERT.RSA');
expect(certRsaMap['value'], 5);
final Map<String, dynamic> certSfMap = metaInfMapChildren[1];
expect(certSfMap['n'], 'CERT.SF');
expect(certSfMap['value'], 5);
final Map<String, Object?> libMap = resultChildren[2] as Map<String, Object?>;
final List<Map<String, Object?>> libMapChildren = libMap['children']! as List<Map<String, Object?>>;
expect(libMap['n'], 'lib');
expect(libMap['value'], 12);
final Map<String, Object?> arm64Map = libMapChildren[0];
final List<Map<String, Object?>> arn64MapChildren = arm64Map['children']! as List<Map<String, Object?>>;
expect(arm64Map['n'], 'arm64-v8a');
expect(arm64Map['value'], 12);
final Map<String, Object?> libAppMap = arn64MapChildren[0];
final List<dynamic> libAppMapChildren = libAppMap['children']! as List<dynamic>;
expect(libAppMap['n'], 'libxyzzyapp.so (Dart AOT)');
expect(libAppMap['value'], 6);
expect(libAppMapChildren.length, 3);
final Map<String, Object?> internalMap = libAppMapChildren[0] as Map<String, Object?>;
final List<dynamic> internalMapChildren = internalMap['children']! as List<dynamic>;
final Map<String, Object?> skipMap = internalMapChildren[0] as Map<String, Object?>;
expect(skipMap['n'], 'skip');
expect(skipMap['value'], 2400);
final Map<String, Object?> subListIterableMap = internalMapChildren[1] as Map<String, Object?>;
expect(subListIterableMap['n'], 'new SubListIterable.');
expect(subListIterableMap['value'], 3560);
final Map<String, Object?> coreMap = libAppMapChildren[1] as Map<String, Object?>;
final List<dynamic> coreMapChildren = coreMap['children']! as List<dynamic>;
final Map<String, Object?> rangeErrorMap = coreMapChildren[0] as Map<String, Object?>;
expect(rangeErrorMap['n'], 'new RangeError.range');
expect(rangeErrorMap['value'], 3920);
final Map<String, Object?> stubsMap = libAppMapChildren[2] as Map<String, Object?>;
final List<dynamic> stubsMapChildren = stubsMap['children']! as List<dynamic>;
final Map<String, Object?> allocateMap = stubsMapChildren[0] as Map<String, Object?>;
expect(allocateMap['n'], 'Allocate ArgumentError');
expect(allocateMap['value'], 4650);
final Map<String, Object?> libFlutterMap = arn64MapChildren[1];
expect(libFlutterMap['n'], 'libflutter.so (Flutter Engine)');
expect(libFlutterMap['value'], 6);
expect(result['precompiler-trace'], <String, Object>{});
});
testWithoutContext('outputs summary to command line correctly', () async {
final SizeAnalyzer sizeAnalyzer = SizeAnalyzer(
fileSystem: fileSystem,
logger: logger,
appFilenamePattern: RegExp(r'lib.*app\.so'),
flutterUsage: TestUsage(),
analytics: const NoOpAnalytics(),
);
final Archive archive = Archive()
..addFile(ArchiveFile('AndroidManifest.xml', 100, List<int>.filled(100, 0)))
..addFile(ArchiveFile('META-INF/CERT.RSA', 10, List<int>.filled(10, 0)))
..addFile(ArchiveFile('META-INF/CERT.SF', 10, List<int>.filled(10, 0)))
..addFile(ArchiveFile('lib/arm64-v8a/libxyzzyapp.so', 50, List<int>.filled(50, 0)))
..addFile(ArchiveFile('lib/arm64-v8a/libflutter.so', 50, List<int>.filled(50, 0)));
final File apk = fileSystem.file('test.apk')
..writeAsBytesSync(ZipEncoder().encode(archive)!);
final File aotSizeJson = fileSystem.file('test.json')
..writeAsStringSync(aotSizeOutput);
final File precompilerTrace = fileSystem.file('trace.json')
..writeAsStringSync('{}');
await sizeAnalyzer.analyzeZipSizeAndAotSnapshot(
zipFile: apk,
aotSnapshot: aotSizeJson,
precompilerTrace: precompilerTrace,
kind: 'apk',
);
final List<String> stdout = logger.statusText.split('\n');
expect(
stdout,
containsAll(<String>[
'test.apk (total compressed) 644 B',
'━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━',
' lib 12 B',
' Dart AOT symbols accounted decompressed size 14 KB',
' dart:core/',
' RangeError 4 KB',
]),
);
});
testWithoutContext('can analyze contents of output directory', () async {
final SizeAnalyzer sizeAnalyzer = SizeAnalyzer(
fileSystem: fileSystem,
logger: logger,
appFilenamePattern: RegExp(r'lib.*app\.so'),
flutterUsage: TestUsage(),
analytics: const NoOpAnalytics(),
);
final Directory outputDirectory = fileSystem.directory('example/out/foo.app')
..createSync(recursive: true);
outputDirectory.childFile('a.txt')
..createSync()
..writeAsStringSync('hello');
outputDirectory.childFile('libapp.so')
..createSync()
..writeAsStringSync('goodbye');
final File aotSizeJson = fileSystem.file('test.json')
..writeAsStringSync(aotSizeOutput);
final File precompilerTrace = fileSystem.file('trace.json')
..writeAsStringSync('{}');
final Map<String, Object?> result = await sizeAnalyzer.analyzeAotSnapshot(
outputDirectory: outputDirectory,
aotSnapshot: aotSizeJson,
precompilerTrace: precompilerTrace,
type: 'linux',
);
final List<String> stdout = logger.statusText.split('\n');
expect(
stdout,
containsAll(<String>[
' foo.app 12 B',
' foo.app 12 B',
' Dart AOT symbols accounted decompressed size 14 KB',
' dart:core/',
' RangeError 4 KB',
]),
);
expect(result['type'], 'linux');
expect(result['precompiler-trace'], <String, Object>{});
});
testWithoutContext('handles null AOT snapshot json', () async {
final SizeAnalyzer sizeAnalyzer = SizeAnalyzer(
fileSystem: fileSystem,
logger: logger,
appFilenamePattern: RegExp(r'lib.*app\.so'),
flutterUsage: TestUsage(),
analytics: const NoOpAnalytics(),
);
final Directory outputDirectory = fileSystem.directory('example/out/foo.app')..createSync(recursive: true);
final File invalidAotSizeJson = fileSystem.file('test.json')..writeAsStringSync('null');
final File precompilerTrace = fileSystem.file('trace.json');
await expectLater(
() => sizeAnalyzer.analyzeAotSnapshot(
outputDirectory: outputDirectory,
aotSnapshot: invalidAotSizeJson,
precompilerTrace: precompilerTrace,
type: 'linux',
),
throwsToolExit());
final File apk = fileSystem.file('test.apk')..writeAsBytesSync(ZipEncoder().encode(Archive())!);
await expectLater(
() => sizeAnalyzer.analyzeZipSizeAndAotSnapshot(
zipFile: apk,
aotSnapshot: invalidAotSizeJson,
precompilerTrace: precompilerTrace,
kind: 'apk',
),
throwsToolExit());
});
}
| flutter/packages/flutter_tools/test/general.shard/base/analyze_size_test.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/general.shard/base/analyze_size_test.dart",
"repo_id": "flutter",
"token_count": 4726
} | 770 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.