text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui';
import 'package:fake_async/fake_async.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('Deferred frames will trigger the first frame callback', () {
FakeAsync().run((FakeAsync fakeAsync) {
final WidgetsBinding binding = WidgetsFlutterBinding.ensureInitialized();
binding.deferFirstFrame();
runApp(const Placeholder());
fakeAsync.flushTimers();
// Simulates the engine completing a frame render to trigger the
// appropriate callback setting [WidgetBinding.firstFrameRasterized].
binding.platformDispatcher.onReportTimings!(<FrameTiming>[]);
expect(binding.firstFrameRasterized, isFalse);
binding.allowFirstFrame();
fakeAsync.flushTimers();
// Simulates the engine again.
binding.platformDispatcher.onReportTimings!(<FrameTiming>[]);
expect(binding.firstFrameRasterized, isTrue);
});
});
}
| flutter/packages/flutter/test/widgets/binding_first_frame_rasterized_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/binding_first_frame_rasterized_test.dart",
"repo_id": "flutter",
"token_count": 377
} | 712 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Placeholder intrinsics', (WidgetTester tester) async {
await tester.pumpWidget(const Placeholder());
expect(tester.renderObject<RenderBox>(find.byType(Placeholder)).getMinIntrinsicWidth(double.infinity), 0.0);
expect(tester.renderObject<RenderBox>(find.byType(Placeholder)).getMaxIntrinsicWidth(double.infinity), 0.0);
expect(tester.renderObject<RenderBox>(find.byType(Placeholder)).getMinIntrinsicHeight(double.infinity), 0.0);
expect(tester.renderObject<RenderBox>(find.byType(Placeholder)).getMaxIntrinsicHeight(double.infinity), 0.0);
});
testWidgets('ConstrainedBox intrinsics - minHeight', (WidgetTester tester) async {
await tester.pumpWidget(
ConstrainedBox(
constraints: const BoxConstraints(
minHeight: 20.0,
),
child: const Placeholder(),
),
);
expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMinIntrinsicWidth(double.infinity), 0.0);
expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMaxIntrinsicWidth(double.infinity), 0.0);
expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMinIntrinsicHeight(double.infinity), 20.0);
expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMaxIntrinsicHeight(double.infinity), 20.0);
});
testWidgets('ConstrainedBox intrinsics - minWidth', (WidgetTester tester) async {
await tester.pumpWidget(
ConstrainedBox(
constraints: const BoxConstraints(
minWidth: 20.0,
),
child: const Placeholder(),
),
);
expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMinIntrinsicWidth(double.infinity), 20.0);
expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMaxIntrinsicWidth(double.infinity), 20.0);
expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMinIntrinsicHeight(double.infinity), 0.0);
expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMaxIntrinsicHeight(double.infinity), 0.0);
});
testWidgets('ConstrainedBox intrinsics - maxHeight', (WidgetTester tester) async {
await tester.pumpWidget(
ConstrainedBox(
constraints: const BoxConstraints(
maxHeight: 20.0,
),
child: const Placeholder(),
),
);
expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMinIntrinsicWidth(double.infinity), 0.0);
expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMaxIntrinsicWidth(double.infinity), 0.0);
expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMinIntrinsicHeight(double.infinity), 0.0);
expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMaxIntrinsicHeight(double.infinity), 0.0);
});
testWidgets('ConstrainedBox intrinsics - maxWidth', (WidgetTester tester) async {
await tester.pumpWidget(
ConstrainedBox(
constraints: const BoxConstraints(
maxWidth: 20.0,
),
child: const Placeholder(),
),
);
expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMinIntrinsicWidth(double.infinity), 0.0);
expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMaxIntrinsicWidth(double.infinity), 0.0);
expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMinIntrinsicHeight(double.infinity), 0.0);
expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMaxIntrinsicHeight(double.infinity), 0.0);
});
testWidgets('ConstrainedBox intrinsics - tight', (WidgetTester tester) async {
await tester.pumpWidget(
ConstrainedBox(
constraints: const BoxConstraints.tightFor(width: 10.0, height: 30.0),
child: const Placeholder(),
),
);
expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMinIntrinsicWidth(double.infinity), 10.0);
expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMaxIntrinsicWidth(double.infinity), 10.0);
expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMinIntrinsicHeight(double.infinity), 30.0);
expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMaxIntrinsicHeight(double.infinity), 30.0);
});
testWidgets('ConstrainedBox intrinsics - minHeight - with infinite width', (WidgetTester tester) async {
await tester.pumpWidget(
ConstrainedBox(
constraints: const BoxConstraints(
minWidth: double.infinity,
minHeight: 20.0,
),
child: const Placeholder(),
),
);
expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMinIntrinsicWidth(double.infinity), 0.0);
expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMaxIntrinsicWidth(double.infinity), 0.0);
expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMinIntrinsicHeight(double.infinity), 20.0);
expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMaxIntrinsicHeight(double.infinity), 20.0);
});
testWidgets('ConstrainedBox intrinsics - minWidth - with infinite height', (WidgetTester tester) async {
await tester.pumpWidget(
ConstrainedBox(
constraints: const BoxConstraints(
minWidth: 20.0,
minHeight: double.infinity,
),
child: const Placeholder(),
),
);
expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMinIntrinsicWidth(double.infinity), 20.0);
expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMaxIntrinsicWidth(double.infinity), 20.0);
expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMinIntrinsicHeight(double.infinity), 0.0);
expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMaxIntrinsicHeight(double.infinity), 0.0);
});
testWidgets('ConstrainedBox intrinsics - infinite', (WidgetTester tester) async {
await tester.pumpWidget(
ConstrainedBox(
constraints: const BoxConstraints.tightFor(width: double.infinity, height: double.infinity),
child: const Placeholder(),
),
);
expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMinIntrinsicWidth(double.infinity), 0.0);
expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMaxIntrinsicWidth(double.infinity), 0.0);
expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMinIntrinsicHeight(double.infinity), 0.0);
expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMaxIntrinsicHeight(double.infinity), 0.0);
});
}
| flutter/packages/flutter/test/widgets/constrained_box_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/constrained_box_test.dart",
"repo_id": "flutter",
"token_count": 2609
} | 713 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Directionality', (WidgetTester tester) async {
final List<TextDirection> log = <TextDirection>[];
final Widget inner = Builder(
builder: (BuildContext context) {
log.add(Directionality.of(context));
return const Placeholder();
},
);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: inner,
),
);
expect(log, <TextDirection>[TextDirection.ltr]);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: inner,
),
);
expect(log, <TextDirection>[TextDirection.ltr]);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.rtl,
child: inner,
),
);
expect(log, <TextDirection>[TextDirection.ltr, TextDirection.rtl]);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.rtl,
child: inner,
),
);
expect(log, <TextDirection>[TextDirection.ltr, TextDirection.rtl]);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: inner,
),
);
expect(log, <TextDirection>[TextDirection.ltr, TextDirection.rtl, TextDirection.ltr]);
});
testWidgets('Directionality default', (WidgetTester tester) async {
bool good = false;
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
expect(Directionality.maybeOf(context), isNull);
good = true;
return const Placeholder();
},
));
expect(good, isTrue);
});
testWidgets('Directionality.maybeOf', (WidgetTester tester) async {
final GlobalKey hasDirectionality = GlobalKey();
final GlobalKey noDirectionality = GlobalKey();
await tester.pumpWidget(
Container(
key: noDirectionality,
child: Directionality(
textDirection: TextDirection.rtl,
child: Container(
key: hasDirectionality,
),
),
),
);
expect(Directionality.maybeOf(noDirectionality.currentContext!), isNull);
expect(Directionality.maybeOf(hasDirectionality.currentContext!), TextDirection.rtl);
});
testWidgets('Directionality.of', (WidgetTester tester) async {
final GlobalKey hasDirectionality = GlobalKey();
final GlobalKey noDirectionality = GlobalKey();
await tester.pumpWidget(
Container(
key: noDirectionality,
child: Directionality(
textDirection: TextDirection.rtl,
child: Container(
key: hasDirectionality,
),
),
),
);
expect(() => Directionality.of(noDirectionality.currentContext!), throwsA(isAssertionError.having(
(AssertionError e) => e.message,
'message',
contains('No Directionality widget found.'),
)));
expect(Directionality.of(hasDirectionality.currentContext!), TextDirection.rtl);
});
}
| flutter/packages/flutter/test/widgets/directionality_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/directionality_test.dart",
"repo_id": "flutter",
"token_count": 1311
} | 714 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('ErrorWidget displays actual error when throwing during build', (WidgetTester tester) async {
final Key container = UniqueKey();
const String errorText = 'Oh no, there was a crash!!1';
await tester.pumpWidget(
Container(
key: container,
color: Colors.red,
padding: const EdgeInsets.all(10),
child: Builder(
builder: (BuildContext context) {
throw UnsupportedError(errorText);
},
),
),
);
expect(
tester.takeException(),
isA<UnsupportedError>().having((UnsupportedError error) => error.message, 'message', contains(errorText)),
);
final ErrorWidget errorWidget = tester.widget(find.byType(ErrorWidget));
expect(errorWidget.message, contains(errorText));
// Failure in one widget shouldn't ripple through the entire tree and effect
// ancestors. Those should still be in the tree.
expect(find.byKey(container), findsOneWidget);
});
testWidgets('when constructing an ErrorWidget due to a build failure throws an error, fail gracefully', (WidgetTester tester) async {
final Key container = UniqueKey();
await tester.pumpWidget(
Container(
key: container,
color: Colors.red,
padding: const EdgeInsets.all(10),
// This widget throws during build, which causes the construction of an
// ErrorWidget with the build error. However, during construction of
// that ErrorWidget, another error is thrown.
child: const MyDoubleThrowingWidget(),
),
);
expect(
tester.takeException(),
isA<UnsupportedError>().having((UnsupportedError error) => error.message, 'message', contains(MyThrowingElement.debugFillPropertiesErrorMessage)),
);
final ErrorWidget errorWidget = tester.widget(find.byType(ErrorWidget));
expect(errorWidget.message, contains(MyThrowingElement.debugFillPropertiesErrorMessage));
// Failure in one widget shouldn't ripple through the entire tree and effect
// ancestors. Those should still be in the tree.
expect(find.byKey(container), findsOneWidget);
});
}
// This widget throws during its regular build and then again when the
// ErrorWidget is constructed, which calls MyThrowingElement.debugFillProperties.
class MyDoubleThrowingWidget extends StatelessWidget {
const MyDoubleThrowingWidget({super.key});
@override
StatelessElement createElement() => MyThrowingElement(this);
@override
Widget build(BuildContext context) {
throw UnsupportedError('You cannot build me!');
}
}
class MyThrowingElement extends StatelessElement {
MyThrowingElement(super.widget);
static const String debugFillPropertiesErrorMessage = 'Crash during debugFillProperties';
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
throw UnsupportedError(debugFillPropertiesErrorMessage);
}
}
| flutter/packages/flutter/test/widgets/error_widget_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/error_widget_test.dart",
"repo_id": "flutter",
"token_count": 1028
} | 715 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
// There's also some duplicate GlobalKey tests in the framework_test.dart file.
void main() {
testWidgets('GlobalKey children of one node', (WidgetTester tester) async {
// This is actually a test of the regular duplicate key logic, which
// happens before the duplicate GlobalKey logic.
await tester.pumpWidget(const Stack(children: <Widget>[
DummyWidget(key: GlobalObjectKey(0)),
DummyWidget(key: GlobalObjectKey(0)),
]));
final dynamic error = tester.takeException();
expect(error, isFlutterError);
expect(error.toString(), startsWith('Duplicate keys found.\n'));
expect(error.toString(), contains('Stack'));
expect(error.toString(), contains('[GlobalObjectKey ${describeIdentity(0)}]'));
});
testWidgets('GlobalKey children of two nodes - A', (WidgetTester tester) async {
await tester.pumpWidget(const Stack(
textDirection: TextDirection.ltr,
children: <Widget>[
DummyWidget(child: DummyWidget(key: GlobalObjectKey(0))),
DummyWidget(
child: DummyWidget(key: GlobalObjectKey(0),
),
),
],
));
final dynamic error = tester.takeException();
expect(error, isFlutterError);
expect(error.toString(), startsWith('Multiple widgets used the same GlobalKey.\n'));
expect(error.toString(), contains('different widgets that both had the following description'));
expect(error.toString(), contains('DummyWidget'));
expect(error.toString(), contains('[GlobalObjectKey ${describeIdentity(0)}]'));
expect(error.toString(), endsWith('\nA GlobalKey can only be specified on one widget at a time in the widget tree.'));
});
testWidgets('GlobalKey children of two different nodes - B', (WidgetTester tester) async {
await tester.pumpWidget(const Stack(
textDirection: TextDirection.ltr,
children: <Widget>[
DummyWidget(child: DummyWidget(key: GlobalObjectKey(0))),
DummyWidget(key: Key('x'), child: DummyWidget(key: GlobalObjectKey(0))),
],
));
final dynamic error = tester.takeException();
expect(error, isFlutterError);
expect(error.toString(), startsWith('Multiple widgets used the same GlobalKey.\n'));
expect(error.toString(), isNot(contains('different widgets that both had the following description')));
expect(error.toString(), contains('DummyWidget'));
expect(error.toString(), contains("DummyWidget-[<'x'>]"));
expect(error.toString(), contains('[GlobalObjectKey ${describeIdentity(0)}]'));
expect(error.toString(), endsWith('\nA GlobalKey can only be specified on one widget at a time in the widget tree.'));
});
testWidgets('GlobalKey children of two nodes - C', (WidgetTester tester) async {
late StateSetter nestedSetState;
bool flag = false;
await tester.pumpWidget(Stack(
textDirection: TextDirection.ltr,
children: <Widget>[
const DummyWidget(child: DummyWidget(key: GlobalObjectKey(0))),
DummyWidget(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
nestedSetState = setState;
if (flag) {
return const DummyWidget(key: GlobalObjectKey(0));
}
return const DummyWidget();
},
),
),
],
));
nestedSetState(() { flag = true; });
await tester.pump();
final dynamic error = tester.takeException();
expect(error.toString(), startsWith('Duplicate GlobalKey detected in widget tree.\n'));
expect(error.toString(), contains('The following GlobalKey was specified multiple times'));
// The following line is verifying the grammar is correct in this common case.
// We should probably also verify the three other combinations that can be generated...
expect(error.toString().split('\n').join(' '), contains('This was determined by noticing that after the widget with the above global key was moved out of its previous parent, that previous parent never updated during this frame, meaning that it either did not update at all or updated before the widget was moved, in either case implying that it still thinks that it should have a child with that global key.'));
expect(error.toString(), contains('[GlobalObjectKey ${describeIdentity(0)}]'));
expect(error.toString(), contains('DummyWidget'));
expect(error.toString(), endsWith('\nA GlobalKey can only be specified on one widget at a time in the widget tree.'));
expect(error, isFlutterError);
});
}
class DummyWidget extends StatelessWidget {
const DummyWidget({ super.key, this.child });
final Widget? child;
@override
Widget build(BuildContext context) {
return child ?? LimitedBox(
maxWidth: 0.0,
maxHeight: 0.0,
child: ConstrainedBox(constraints: const BoxConstraints.expand()),
);
}
}
| flutter/packages/flutter/test/widgets/global_keys_duplicated_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/global_keys_duplicated_test.dart",
"repo_id": "flutter",
"token_count": 1743
} | 716 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('AssetImage from package', () {
const AssetImage image = AssetImage(
'assets/image.png',
package: 'test_package',
);
expect(image.keyName, 'packages/test_package/assets/image.png');
});
test('ExactAssetImage from package', () {
const ExactAssetImage image = ExactAssetImage(
'assets/image.png',
scale: 1.5,
package: 'test_package',
);
expect(image.keyName, 'packages/test_package/assets/image.png');
});
test('Image.asset from package', () {
final Image imageWidget = Image.asset(
'assets/image.png',
package: 'test_package',
);
assert(imageWidget.image is AssetImage);
final AssetImage assetImage = imageWidget.image as AssetImage;
expect(assetImage.keyName, 'packages/test_package/assets/image.png');
});
test('Image.asset from package', () {
final Image imageWidget = Image.asset(
'assets/image.png',
scale: 1.5,
package: 'test_package',
);
assert(imageWidget.image is ExactAssetImage);
final ExactAssetImage assetImage = imageWidget.image as ExactAssetImage;
expect(assetImage.keyName, 'packages/test_package/assets/image.png');
});
}
| flutter/packages/flutter/test/widgets/image_package_asset_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/image_package_asset_test.dart",
"repo_id": "flutter",
"token_count": 518
} | 717 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
class TestValueKey<T> extends ValueKey<T> {
const TestValueKey(super.value);
}
@immutable
class NotEquals {
const NotEquals();
@override
bool operator ==(Object other) => false;
@override
int get hashCode => 0;
}
void main() {
testWidgets('Keys', (WidgetTester tester) async {
expect(ValueKey<int>(nonconst(3)) == ValueKey<int>(nonconst(3)), isTrue);
expect(ValueKey<num>(nonconst(3)) == ValueKey<int>(nonconst(3)), isFalse);
expect(ValueKey<int>(nonconst(3)) == ValueKey<int>(nonconst(2)), isFalse);
expect(const ValueKey<double>(double.nan) == const ValueKey<double>(double.nan), isFalse);
expect(Key(nonconst('')) == ValueKey<String>(nonconst('')), isTrue);
expect(ValueKey<String>(nonconst('')) == ValueKey<String>(nonconst('')), isTrue);
expect(TestValueKey<String>(nonconst('')) == ValueKey<String>(nonconst('')), isFalse);
expect(TestValueKey<String>(nonconst('')) == TestValueKey<String>(nonconst('')), isTrue);
expect(ValueKey<String>(nonconst('')) == ValueKey<dynamic>(nonconst('')), isFalse);
expect(TestValueKey<String>(nonconst('')) == TestValueKey<dynamic>(nonconst('')), isFalse);
expect(UniqueKey() == UniqueKey(), isFalse);
final UniqueKey k = UniqueKey();
expect(UniqueKey() == UniqueKey(), isFalse);
expect(k == k, isTrue);
expect(ValueKey<LocalKey>(k) == ValueKey<LocalKey>(k), isTrue);
expect(ValueKey<LocalKey>(k) == ValueKey<UniqueKey>(k), isFalse);
expect(ObjectKey(k) == ObjectKey(k), isTrue);
final NotEquals constNotEquals = nonconst(const NotEquals());
expect(ValueKey<NotEquals>(constNotEquals) == ValueKey<NotEquals>(constNotEquals), isFalse);
expect(ObjectKey(constNotEquals) == ObjectKey(constNotEquals), isTrue);
final Object constObject = nonconst(const Object());
expect(ObjectKey(constObject) == ObjectKey(constObject), isTrue);
expect(ObjectKey(nonconst(Object())) == ObjectKey(nonconst(Object())), isFalse);
expect(const ValueKey<bool>(true), hasOneLineDescription);
expect(UniqueKey(), hasOneLineDescription);
expect(const ObjectKey(true), hasOneLineDescription);
expect(GlobalKey(), hasOneLineDescription);
expect(GlobalKey(debugLabel: 'hello'), hasOneLineDescription);
expect(const GlobalObjectKey(true), hasOneLineDescription);
});
}
| flutter/packages/flutter/test/widgets/key_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/key_test.dart",
"repo_id": "flutter",
"token_count": 864
} | 718 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'semantics_tester.dart';
void main() {
group('Available semantic scroll actions', () {
// Regression tests for https://github.com/flutter/flutter/issues/52032.
const int itemCount = 10;
const double itemHeight = 150.0;
testWidgets('forward vertical', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: ListView.builder(
controller: controller,
itemCount: itemCount,
itemBuilder: (BuildContext context, int index) {
return SizedBox(
height: itemHeight,
child: Text('Tile $index'),
);
},
),
),
);
expect(semantics, includesNodeWith(actions: <SemanticsAction>[SemanticsAction.scrollUp]));
// Jump to the end.
controller.jumpTo(itemCount * itemHeight);
await tester.pumpAndSettle();
expect(semantics, includesNodeWith(actions: <SemanticsAction>[SemanticsAction.scrollDown]));
semantics.dispose();
});
testWidgets('reverse vertical', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: ListView.builder(
reverse: true,
controller: controller,
itemCount: itemCount,
itemBuilder: (BuildContext context, int index) {
return SizedBox(
height: itemHeight,
child: Text('Tile $index'),
);
},
),
),
);
expect(semantics, includesNodeWith(actions: <SemanticsAction>[SemanticsAction.scrollDown]));
// Jump to the end.
controller.jumpTo(itemCount * itemHeight);
await tester.pumpAndSettle();
expect(semantics, includesNodeWith(actions: <SemanticsAction>[SemanticsAction.scrollUp]));
semantics.dispose();
});
testWidgets('forward horizontal', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: ListView.builder(
scrollDirection: Axis.horizontal,
controller: controller,
itemCount: itemCount,
itemBuilder: (BuildContext context, int index) {
return SizedBox(
height: itemHeight,
child: Text('Tile $index'),
);
},
),
),
);
expect(semantics, includesNodeWith(actions: <SemanticsAction>[SemanticsAction.scrollLeft]));
// Jump to the end.
controller.jumpTo(itemCount * itemHeight);
await tester.pumpAndSettle();
expect(semantics, includesNodeWith(actions: <SemanticsAction>[SemanticsAction.scrollRight]));
semantics.dispose();
});
testWidgets('reverse horizontal', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: ListView.builder(
scrollDirection: Axis.horizontal,
reverse: true,
controller: controller,
itemCount: itemCount,
itemBuilder: (BuildContext context, int index) {
return SizedBox(
height: itemHeight,
child: Text('Tile $index'),
);
},
),
),
);
expect(semantics, includesNodeWith(actions: <SemanticsAction>[SemanticsAction.scrollRight]));
// Jump to the end.
controller.jumpTo(itemCount * itemHeight);
await tester.pumpAndSettle();
expect(semantics, includesNodeWith(actions: <SemanticsAction>[SemanticsAction.scrollLeft]));
semantics.dispose();
});
});
}
| flutter/packages/flutter/test/widgets/list_view_semantics_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/list_view_semantics_test.dart",
"repo_id": "flutter",
"token_count": 1965
} | 719 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
class HoverClient extends StatefulWidget {
const HoverClient({
super.key,
this.onHover,
this.child,
this.onEnter,
this.onExit,
});
final ValueChanged<bool>? onHover;
final Widget? child;
final VoidCallback? onEnter;
final VoidCallback? onExit;
@override
HoverClientState createState() => HoverClientState();
}
class HoverClientState extends State<HoverClient> {
void _onExit(PointerExitEvent details) {
widget.onExit?.call();
widget.onHover?.call(false);
}
void _onEnter(PointerEnterEvent details) {
widget.onEnter?.call();
widget.onHover?.call(true);
}
@override
Widget build(BuildContext context) {
return MouseRegion(
onEnter: _onEnter,
onExit: _onExit,
child: widget.child,
);
}
}
class HoverFeedback extends StatefulWidget {
const HoverFeedback({super.key, this.onEnter, this.onExit});
final VoidCallback? onEnter;
final VoidCallback? onExit;
@override
State<HoverFeedback> createState() => _HoverFeedbackState();
}
class _HoverFeedbackState extends State<HoverFeedback> {
bool _hovering = false;
@override
Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.ltr,
child: HoverClient(
onHover: (bool hovering) => setState(() => _hovering = hovering),
onEnter: widget.onEnter,
onExit: widget.onExit,
child: Text(_hovering ? 'HOVERING' : 'not hovering'),
),
);
}
}
void main() {
// Regression test for https://github.com/flutter/flutter/issues/73330
testWidgets('hitTestBehavior test - HitTestBehavior.deferToChild/opaque', (WidgetTester tester) async {
bool onEnter = false;
await tester.pumpWidget(Center(
child: MouseRegion(
hitTestBehavior: HitTestBehavior.deferToChild,
onEnter: (_) => onEnter = true,
),
));
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer(location: Offset.zero);
await tester.pump();
// The child is null, so `onEnter` does not trigger.
expect(onEnter, false);
// Update to the default value `HitTestBehavior.opaque`
await tester.pumpWidget(Center(
child: MouseRegion(
onEnter: (_) => onEnter = true,
),
));
expect(onEnter, true);
});
testWidgets('hitTestBehavior test - HitTestBehavior.deferToChild and non-opaque', (WidgetTester tester) async {
bool onEnterRegion1 = false;
bool onEnterRegion2 = false;
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: Stack(
children: <Widget>[
SizedBox(
width: 50.0,
height: 50.0,
child: MouseRegion(
onEnter: (_) => onEnterRegion1 = true,
),
),
SizedBox(
width: 50.0,
height: 50.0,
child: MouseRegion(
opaque: false,
hitTestBehavior: HitTestBehavior.deferToChild,
onEnter: (_) => onEnterRegion2 = true,
child: Container(
color: const Color.fromARGB(0xff, 0xff, 0x10, 0x19),
width: 50.0,
height: 50.0,
),
),
),
],
),
));
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer(location: Offset.zero);
await tester.pump();
expect(onEnterRegion2, true);
expect(onEnterRegion1, true);
});
testWidgets('hitTestBehavior test - HitTestBehavior.translucent', (WidgetTester tester) async {
bool onEnterRegion1 = false;
bool onEnterRegion2 = false;
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: Stack(
children: <Widget>[
SizedBox(
width: 50.0,
height: 50.0,
child: MouseRegion(
onEnter: (_) => onEnterRegion1 = true,
),
),
SizedBox(
width: 50.0,
height: 50.0,
child: MouseRegion(
hitTestBehavior: HitTestBehavior.translucent,
onEnter: (_) => onEnterRegion2 = true,
),
),
],
),
));
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer(location: Offset.zero);
await tester.pump();
expect(onEnterRegion2, true);
expect(onEnterRegion1, true);
});
testWidgets('onEnter and onExit can be triggered with mouse buttons pressed', (WidgetTester tester) async {
PointerEnterEvent? enter;
PointerExitEvent? exit;
await tester.pumpWidget(Center(
child: MouseRegion(
child: Container(
color: const Color.fromARGB(0xff, 0xff, 0x00, 0x00),
width: 100.0,
height: 100.0,
),
onEnter: (PointerEnterEvent details) => enter = details,
onExit: (PointerExitEvent details) => exit = details,
),
));
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer(location: Offset.zero);
await gesture.down(Offset.zero); // Press the mouse button.
await tester.pump();
enter = null;
exit = null;
// Trigger the enter event.
await gesture.moveTo(const Offset(400.0, 300.0));
expect(enter, isNotNull);
expect(enter!.position, equals(const Offset(400.0, 300.0)));
expect(enter!.localPosition, equals(const Offset(50.0, 50.0)));
expect(exit, isNull);
// Trigger the exit event.
await gesture.moveTo(const Offset(1.0, 1.0));
expect(exit, isNotNull);
expect(exit!.position, equals(const Offset(1.0, 1.0)));
expect(exit!.localPosition, equals(const Offset(-349.0, -249.0)));
});
testWidgets('detects pointer enter', (WidgetTester tester) async {
PointerEnterEvent? enter;
PointerHoverEvent? move;
PointerExitEvent? exit;
await tester.pumpWidget(Center(
child: MouseRegion(
child: Container(
color: const Color.fromARGB(0xff, 0xff, 0x00, 0x00),
width: 100.0,
height: 100.0,
),
onEnter: (PointerEnterEvent details) => enter = details,
onHover: (PointerHoverEvent details) => move = details,
onExit: (PointerExitEvent details) => exit = details,
),
));
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer(location: Offset.zero);
await tester.pump();
move = null;
enter = null;
exit = null;
await gesture.moveTo(const Offset(400.0, 300.0));
expect(move, isNotNull);
expect(move!.position, equals(const Offset(400.0, 300.0)));
expect(move!.localPosition, equals(const Offset(50.0, 50.0)));
expect(enter, isNotNull);
expect(enter!.position, equals(const Offset(400.0, 300.0)));
expect(enter!.localPosition, equals(const Offset(50.0, 50.0)));
expect(exit, isNull);
});
testWidgets('detects pointer exiting', (WidgetTester tester) async {
PointerEnterEvent? enter;
PointerHoverEvent? move;
PointerExitEvent? exit;
await tester.pumpWidget(Center(
child: MouseRegion(
child: Container(
color: const Color.fromARGB(0xff, 0xff, 0x00, 0x00),
width: 100.0,
height: 100.0,
),
onEnter: (PointerEnterEvent details) => enter = details,
onHover: (PointerHoverEvent details) => move = details,
onExit: (PointerExitEvent details) => exit = details,
),
));
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer(location: Offset.zero);
await gesture.moveTo(const Offset(400.0, 300.0));
await tester.pump();
move = null;
enter = null;
exit = null;
await gesture.moveTo(const Offset(1.0, 1.0));
expect(move, isNull);
expect(enter, isNull);
expect(exit, isNotNull);
expect(exit!.position, equals(const Offset(1.0, 1.0)));
expect(exit!.localPosition, equals(const Offset(-349.0, -249.0)));
});
testWidgets('triggers pointer enter when a mouse is connected', (WidgetTester tester) async {
PointerEnterEvent? enter;
PointerHoverEvent? move;
PointerExitEvent? exit;
await tester.pumpWidget(Center(
child: MouseRegion(
child: const SizedBox(
width: 100.0,
height: 100.0,
),
onEnter: (PointerEnterEvent details) => enter = details,
onHover: (PointerHoverEvent details) => move = details,
onExit: (PointerExitEvent details) => exit = details,
),
));
await tester.pump();
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer(location: const Offset(400, 300));
expect(move, isNull);
expect(enter, isNotNull);
expect(enter!.position, equals(const Offset(400.0, 300.0)));
expect(enter!.localPosition, equals(const Offset(50.0, 50.0)));
expect(exit, isNull);
});
testWidgets('triggers pointer exit when a mouse is disconnected', (WidgetTester tester) async {
PointerEnterEvent? enter;
PointerHoverEvent? move;
PointerExitEvent? exit;
await tester.pumpWidget(Center(
child: MouseRegion(
child: const SizedBox(
width: 100.0,
height: 100.0,
),
onEnter: (PointerEnterEvent details) => enter = details,
onHover: (PointerHoverEvent details) => move = details,
onExit: (PointerExitEvent details) => exit = details,
),
));
await tester.pump();
TestGesture? gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer(location: const Offset(400, 300));
addTearDown(() => gesture?.removePointer);
await tester.pump();
move = null;
enter = null;
exit = null;
await gesture.removePointer();
gesture = null;
expect(move, isNull);
expect(enter, isNull);
expect(exit, isNotNull);
expect(exit!.position, equals(const Offset(400.0, 300.0)));
expect(exit!.localPosition, equals(const Offset(50.0, 50.0)));
exit = null;
await tester.pump();
expect(move, isNull);
expect(enter, isNull);
expect(exit, isNull);
});
testWidgets('triggers pointer enter when widget appears', (WidgetTester tester) async {
PointerEnterEvent? enter;
PointerHoverEvent? move;
PointerExitEvent? exit;
await tester.pumpWidget(const Center(
child: SizedBox(
width: 100.0,
height: 100.0,
),
));
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer(location: Offset.zero);
await gesture.moveTo(const Offset(400.0, 300.0));
await tester.pump();
expect(enter, isNull);
expect(move, isNull);
expect(exit, isNull);
await tester.pumpWidget(Center(
child: MouseRegion(
child: const SizedBox(
width: 100.0,
height: 100.0,
),
onEnter: (PointerEnterEvent details) => enter = details,
onHover: (PointerHoverEvent details) => move = details,
onExit: (PointerExitEvent details) => exit = details,
),
));
await tester.pump();
expect(move, isNull);
expect(enter, isNotNull);
expect(enter!.position, equals(const Offset(400.0, 300.0)));
expect(enter!.localPosition, equals(const Offset(50.0, 50.0)));
expect(exit, isNull);
});
testWidgets("doesn't trigger pointer exit when widget disappears", (WidgetTester tester) async {
PointerEnterEvent? enter;
PointerHoverEvent? move;
PointerExitEvent? exit;
await tester.pumpWidget(Center(
child: MouseRegion(
child: const SizedBox(
width: 100.0,
height: 100.0,
),
onEnter: (PointerEnterEvent details) => enter = details,
onHover: (PointerHoverEvent details) => move = details,
onExit: (PointerExitEvent details) => exit = details,
),
));
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer(location: Offset.zero);
await gesture.moveTo(const Offset(400.0, 300.0));
await tester.pump();
move = null;
enter = null;
exit = null;
await tester.pumpWidget(const Center(
child: SizedBox(
width: 100.0,
height: 100.0,
),
));
expect(enter, isNull);
expect(move, isNull);
expect(exit, isNull);
});
testWidgets('triggers pointer enter when widget moves in', (WidgetTester tester) async {
PointerEnterEvent? enter;
PointerHoverEvent? move;
PointerExitEvent? exit;
await tester.pumpWidget(Container(
alignment: Alignment.topLeft,
child: MouseRegion(
child: const SizedBox(
width: 100.0,
height: 100.0,
),
onEnter: (PointerEnterEvent details) => enter = details,
onHover: (PointerHoverEvent details) => move = details,
onExit: (PointerExitEvent details) => exit = details,
),
));
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer(location: const Offset(401.0, 301.0));
await tester.pump();
expect(enter, isNull);
expect(move, isNull);
expect(exit, isNull);
await tester.pumpWidget(Container(
alignment: Alignment.center,
child: MouseRegion(
child: const SizedBox(
width: 100.0,
height: 100.0,
),
onEnter: (PointerEnterEvent details) => enter = details,
onHover: (PointerHoverEvent details) => move = details,
onExit: (PointerExitEvent details) => exit = details,
),
));
await tester.pump();
expect(enter, isNotNull);
expect(enter!.position, equals(const Offset(401.0, 301.0)));
expect(enter!.localPosition, equals(const Offset(51.0, 51.0)));
expect(move, isNull);
expect(exit, isNull);
});
testWidgets('triggers pointer exit when widget moves out', (WidgetTester tester) async {
PointerEnterEvent? enter;
PointerHoverEvent? move;
PointerExitEvent? exit;
await tester.pumpWidget(Container(
alignment: Alignment.center,
child: MouseRegion(
child: const SizedBox(
width: 100.0,
height: 100.0,
),
onEnter: (PointerEnterEvent details) => enter = details,
onHover: (PointerHoverEvent details) => move = details,
onExit: (PointerExitEvent details) => exit = details,
),
));
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer(location: const Offset(400, 300));
await tester.pump();
enter = null;
move = null;
exit = null;
await tester.pumpWidget(Container(
alignment: Alignment.topLeft,
child: MouseRegion(
child: const SizedBox(
width: 100.0,
height: 100.0,
),
onEnter: (PointerEnterEvent details) => enter = details,
onHover: (PointerHoverEvent details) => move = details,
onExit: (PointerExitEvent details) => exit = details,
),
));
await tester.pump();
expect(enter, isNull);
expect(move, isNull);
expect(exit, isNotNull);
expect(exit!.position, equals(const Offset(400, 300)));
expect(exit!.localPosition, equals(const Offset(50, 50)));
});
testWidgets('detects hover from touch devices', (WidgetTester tester) async {
PointerEnterEvent? enter;
PointerHoverEvent? move;
PointerExitEvent? exit;
await tester.pumpWidget(Center(
child: MouseRegion(
child: Container(
color: const Color.fromARGB(0xff, 0xff, 0x00, 0x00),
width: 100.0,
height: 100.0,
),
onEnter: (PointerEnterEvent details) => enter = details,
onHover: (PointerHoverEvent details) => move = details,
onExit: (PointerExitEvent details) => exit = details,
),
));
final TestGesture gesture = await tester.createGesture();
await gesture.addPointer(location: Offset.zero);
await tester.pump();
move = null;
enter = null;
exit = null;
await gesture.moveTo(const Offset(400.0, 300.0));
expect(move, isNotNull);
expect(move!.position, equals(const Offset(400.0, 300.0)));
expect(move!.localPosition, equals(const Offset(50.0, 50.0)));
expect(enter, isNull);
expect(exit, isNull);
});
testWidgets('Hover works with nested listeners', (WidgetTester tester) async {
final UniqueKey key1 = UniqueKey();
final UniqueKey key2 = UniqueKey();
final List<PointerEnterEvent> enter1 = <PointerEnterEvent>[];
final List<PointerHoverEvent> move1 = <PointerHoverEvent>[];
final List<PointerExitEvent> exit1 = <PointerExitEvent>[];
final List<PointerEnterEvent> enter2 = <PointerEnterEvent>[];
final List<PointerHoverEvent> move2 = <PointerHoverEvent>[];
final List<PointerExitEvent> exit2 = <PointerExitEvent>[];
void clearLists() {
enter1.clear();
move1.clear();
exit1.clear();
enter2.clear();
move2.clear();
exit2.clear();
}
await tester.pumpWidget(Container());
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.moveTo(const Offset(400.0, 0.0));
await tester.pump();
await tester.pumpWidget(
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
MouseRegion(
onEnter: (PointerEnterEvent details) => enter1.add(details),
onHover: (PointerHoverEvent details) => move1.add(details),
onExit: (PointerExitEvent details) => exit1.add(details),
key: key1,
child: Container(
width: 200,
height: 200,
padding: const EdgeInsets.all(50.0),
child: MouseRegion(
key: key2,
onEnter: (PointerEnterEvent details) => enter2.add(details),
onHover: (PointerHoverEvent details) => move2.add(details),
onExit: (PointerExitEvent details) => exit2.add(details),
child: Container(),
),
),
),
],
),
);
Offset center = tester.getCenter(find.byKey(key2));
await gesture.moveTo(center);
await tester.pump();
expect(move2, isNotEmpty);
expect(enter2, isNotEmpty);
expect(exit2, isEmpty);
expect(move1, isNotEmpty);
expect(move1.last.position, equals(center));
expect(enter1, isNotEmpty);
expect(enter1.last.position, equals(center));
expect(exit1, isEmpty);
clearLists();
// Now make sure that exiting the child only triggers the child exit, not
// the parent too.
center = center - const Offset(75.0, 0.0);
await gesture.moveTo(center);
await tester.pumpAndSettle();
expect(move2, isEmpty);
expect(enter2, isEmpty);
expect(exit2, isNotEmpty);
expect(move1, isNotEmpty);
expect(move1.last.position, equals(center));
expect(enter1, isEmpty);
expect(exit1, isEmpty);
clearLists();
});
testWidgets('Hover transfers between two listeners', (WidgetTester tester) async {
final UniqueKey key1 = UniqueKey();
final UniqueKey key2 = UniqueKey();
final List<PointerEnterEvent> enter1 = <PointerEnterEvent>[];
final List<PointerHoverEvent> move1 = <PointerHoverEvent>[];
final List<PointerExitEvent> exit1 = <PointerExitEvent>[];
final List<PointerEnterEvent> enter2 = <PointerEnterEvent>[];
final List<PointerHoverEvent> move2 = <PointerHoverEvent>[];
final List<PointerExitEvent> exit2 = <PointerExitEvent>[];
void clearLists() {
enter1.clear();
move1.clear();
exit1.clear();
enter2.clear();
move2.clear();
exit2.clear();
}
await tester.pumpWidget(Container());
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.moveTo(const Offset(400.0, 0.0));
await tester.pump();
await tester.pumpWidget(
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
MouseRegion(
key: key1,
child: const SizedBox(
width: 100.0,
height: 100.0,
),
onEnter: (PointerEnterEvent details) => enter1.add(details),
onHover: (PointerHoverEvent details) => move1.add(details),
onExit: (PointerExitEvent details) => exit1.add(details),
),
MouseRegion(
key: key2,
child: const SizedBox(
width: 100.0,
height: 100.0,
),
onEnter: (PointerEnterEvent details) => enter2.add(details),
onHover: (PointerHoverEvent details) => move2.add(details),
onExit: (PointerExitEvent details) => exit2.add(details),
),
],
),
);
final Offset center1 = tester.getCenter(find.byKey(key1));
final Offset center2 = tester.getCenter(find.byKey(key2));
await gesture.moveTo(center1);
await tester.pump();
expect(move1, isNotEmpty);
expect(move1.last.position, equals(center1));
expect(enter1, isNotEmpty);
expect(enter1.last.position, equals(center1));
expect(exit1, isEmpty);
expect(move2, isEmpty);
expect(enter2, isEmpty);
expect(exit2, isEmpty);
clearLists();
await gesture.moveTo(center2);
await tester.pump();
expect(move1, isEmpty);
expect(enter1, isEmpty);
expect(exit1, isNotEmpty);
expect(exit1.last.position, equals(center2));
expect(move2, isNotEmpty);
expect(move2.last.position, equals(center2));
expect(enter2, isNotEmpty);
expect(enter2.last.position, equals(center2));
expect(exit2, isEmpty);
clearLists();
await gesture.moveTo(const Offset(400.0, 450.0));
await tester.pump();
expect(move1, isEmpty);
expect(enter1, isEmpty);
expect(exit1, isEmpty);
expect(move2, isEmpty);
expect(enter2, isEmpty);
expect(exit2, isNotEmpty);
expect(exit2.last.position, equals(const Offset(400.0, 450.0)));
clearLists();
await tester.pumpWidget(Container());
expect(move1, isEmpty);
expect(enter1, isEmpty);
expect(exit1, isEmpty);
expect(move2, isEmpty);
expect(enter2, isEmpty);
expect(exit2, isEmpty);
});
testWidgets('applies mouse cursor', (WidgetTester tester) async {
await tester.pumpWidget(const _Scaffold(
topLeft: MouseRegion(
cursor: SystemMouseCursors.text,
child: SizedBox(width: 10, height: 10),
),
));
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer(location: const Offset(100, 100));
await tester.pump();
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic);
await gesture.moveTo(const Offset(5, 5));
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text);
await gesture.moveTo(const Offset(100, 100));
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic);
});
testWidgets('MouseRegion uses updated callbacks', (WidgetTester tester) async {
final List<String> logs = <String>[];
Widget hoverableContainer({
PointerEnterEventListener? onEnter,
PointerHoverEventListener? onHover,
PointerExitEventListener? onExit,
}) {
return Container(
alignment: Alignment.topLeft,
child: MouseRegion(
onEnter: onEnter,
onHover: onHover,
onExit: onExit,
child: Container(
color: const Color.fromARGB(0xff, 0xff, 0x00, 0x00),
width: 100.0,
height: 100.0,
),
),
);
}
await tester.pumpWidget(hoverableContainer(
onEnter: (PointerEnterEvent details) {
logs.add('enter1');
},
onHover: (PointerHoverEvent details) {
logs.add('hover1');
},
onExit: (PointerExitEvent details) { logs.add('exit1'); },
));
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer(location: const Offset(150.0, 150.0));
// Start outside, move inside, then move outside
await gesture.moveTo(const Offset(150.0, 150.0));
await tester.pump();
expect(logs, isEmpty);
logs.clear();
await gesture.moveTo(const Offset(50.0, 50.0));
await tester.pump();
await gesture.moveTo(const Offset(150.0, 150.0));
await tester.pump();
expect(logs, <String>['enter1', 'hover1', 'exit1']);
logs.clear();
// Same tests but with updated callbacks
await tester.pumpWidget(hoverableContainer(
onEnter: (PointerEnterEvent details) => logs.add('enter2'),
onHover: (PointerHoverEvent details) => logs.add('hover2'),
onExit: (PointerExitEvent details) => logs.add('exit2'),
));
await gesture.moveTo(const Offset(150.0, 150.0));
await tester.pump();
await gesture.moveTo(const Offset(50.0, 50.0));
await tester.pump();
await gesture.moveTo(const Offset(150.0, 150.0));
await tester.pump();
expect(logs, <String>['enter2', 'hover2', 'exit2']);
});
testWidgets('needsCompositing set when parent class needsCompositing is set', (WidgetTester tester) async {
await tester.pumpWidget(
MouseRegion(
onEnter: (PointerEnterEvent _) {},
child: const RepaintBoundary(child: Placeholder()),
),
);
RenderMouseRegion listener = tester.renderObject(find.byType(MouseRegion).first);
expect(listener.needsCompositing, isTrue);
await tester.pumpWidget(
MouseRegion(
onEnter: (PointerEnterEvent _) {},
child: const Placeholder(),
),
);
listener = tester.renderObject(find.byType(MouseRegion).first);
expect(listener.needsCompositing, isFalse);
});
testWidgets('works with transform', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/31986.
final Key key = UniqueKey();
const double scaleFactor = 2.0;
const double localWidth = 150.0;
const double localHeight = 100.0;
final List<PointerEvent> events = <PointerEvent>[];
await tester.pumpWidget(
MaterialApp(
home: Center(
child: Transform.scale(
scale: scaleFactor,
child: MouseRegion(
onEnter: (PointerEnterEvent event) {
events.add(event);
},
onHover: (PointerHoverEvent event) {
events.add(event);
},
onExit: (PointerExitEvent event) {
events.add(event);
},
child: Container(
key: key,
color: Colors.blue,
height: localHeight,
width: localWidth,
child: const Text('Hi'),
),
),
),
),
),
);
final Offset topLeft = tester.getTopLeft(find.byKey(key));
final Offset topRight = tester.getTopRight(find.byKey(key));
final Offset bottomLeft = tester.getBottomLeft(find.byKey(key));
expect(topRight.dx - topLeft.dx, scaleFactor * localWidth);
expect(bottomLeft.dy - topLeft.dy, scaleFactor * localHeight);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(topLeft - const Offset(1, 1));
await tester.pump();
expect(events, isEmpty);
await gesture.moveTo(topLeft + const Offset(1, 1));
await tester.pump();
expect(events, hasLength(2));
expect(events.first, isA<PointerEnterEvent>());
expect(events.last, isA<PointerHoverEvent>());
events.clear();
await gesture.moveTo(bottomLeft + const Offset(1, -1));
await tester.pump();
expect(events.single, isA<PointerHoverEvent>());
expect(events.single.delta, const Offset(0.0, scaleFactor * localHeight - 2));
events.clear();
await gesture.moveTo(bottomLeft + const Offset(1, 1));
await tester.pump();
expect(events.single, isA<PointerExitEvent>());
events.clear();
});
testWidgets('needsCompositing is always false', (WidgetTester tester) async {
// Pretend that we have a mouse connected.
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await tester.pumpWidget(
Transform.scale(
scale: 2.0,
child: const MouseRegion(opaque: false),
),
);
final RenderMouseRegion mouseRegion = tester.renderObject(find.byType(MouseRegion));
expect(mouseRegion.needsCompositing, isFalse);
// No TransformLayer for `Transform.scale` is added because composting is
// not required and therefore the transform is executed on the canvas
// directly. (One TransformLayer is always present for the root
// transform.)
expect(tester.layers.whereType<TransformLayer>(), hasLength(1));
// Test that needsCompositing stays false with callback change
await tester.pumpWidget(
Transform.scale(
scale: 2.0,
child: MouseRegion(
opaque: false,
onHover: (PointerHoverEvent _) {},
),
),
);
expect(mouseRegion.needsCompositing, isFalse);
// If compositing was required, a dedicated TransformLayer for
// `Transform.scale` would be added.
expect(tester.layers.whereType<TransformLayer>(), hasLength(1));
});
testWidgets("Callbacks aren't called during build", (WidgetTester tester) async {
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer(location: Offset.zero);
int numEntrances = 0;
int numExits = 0;
await tester.pumpWidget(
Center(
child: HoverFeedback(
onEnter: () { numEntrances += 1; },
onExit: () { numExits += 1; },
),
),
);
await gesture.moveTo(tester.getCenter(find.byType(Text)));
await tester.pumpAndSettle();
expect(numEntrances, equals(1));
expect(numExits, equals(0));
expect(find.text('HOVERING'), findsOneWidget);
await tester.pumpWidget(
Container(),
);
await tester.pump();
expect(numEntrances, equals(1));
expect(numExits, equals(0));
await tester.pumpWidget(
Center(
child: HoverFeedback(
onEnter: () { numEntrances += 1; },
onExit: () { numExits += 1; },
),
),
);
await tester.pump();
expect(numEntrances, equals(2));
expect(numExits, equals(0));
});
testWidgets("MouseRegion activate/deactivate don't duplicate annotations", (WidgetTester tester) async {
final GlobalKey feedbackKey = GlobalKey();
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
int numEntrances = 0;
int numExits = 0;
await tester.pumpWidget(
Center(
child: HoverFeedback(
key: feedbackKey,
onEnter: () { numEntrances += 1; },
onExit: () { numExits += 1; },
),
),
);
await gesture.moveTo(tester.getCenter(find.byType(Text)));
await tester.pumpAndSettle();
expect(numEntrances, equals(1));
expect(numExits, equals(0));
expect(find.text('HOVERING'), findsOneWidget);
await tester.pumpWidget(
Center(
child: HoverFeedback(
key: feedbackKey,
onEnter: () { numEntrances += 1; },
onExit: () { numExits += 1; },
),
),
);
await tester.pump();
expect(numEntrances, equals(1));
expect(numExits, equals(0));
await tester.pumpWidget(
Container(),
);
await tester.pump();
expect(numEntrances, equals(1));
expect(numExits, equals(0));
});
testWidgets('Exit event when unplugging mouse should have a position', (WidgetTester tester) async {
final List<PointerEnterEvent> enter = <PointerEnterEvent>[];
final List<PointerHoverEvent> hover = <PointerHoverEvent>[];
final List<PointerExitEvent> exit = <PointerExitEvent>[];
await tester.pumpWidget(
Center(
child: MouseRegion(
onEnter: (PointerEnterEvent e) => enter.add(e),
onHover: (PointerHoverEvent e) => hover.add(e),
onExit: (PointerExitEvent e) => exit.add(e),
child: const SizedBox(
height: 100.0,
width: 100.0,
),
),
),
);
// Plug-in a mouse and move it to the center of the container.
TestGesture? gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer(location: Offset.zero);
addTearDown(() => gesture?.removePointer());
await tester.pumpAndSettle();
await gesture.moveTo(tester.getCenter(find.byType(SizedBox)));
expect(enter.length, 1);
expect(enter.single.position, const Offset(400.0, 300.0));
expect(hover.length, 1);
expect(hover.single.position, const Offset(400.0, 300.0));
expect(exit.length, 0);
enter.clear();
hover.clear();
exit.clear();
// Unplug the mouse.
await gesture.removePointer();
gesture = null;
await tester.pumpAndSettle();
expect(enter.length, 0);
expect(hover.length, 0);
expect(exit.length, 1);
expect(exit.single.position, const Offset(400.0, 300.0));
expect(exit.single.delta, Offset.zero);
});
testWidgets('detects pointer enter with closure arguments', (WidgetTester tester) async {
await tester.pumpWidget(const _HoverClientWithClosures());
expect(find.text('not hovering'), findsOneWidget);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
// Move to a position out of MouseRegion
await gesture.moveTo(tester.getBottomRight(find.byType(MouseRegion)) + const Offset(10, -10));
await tester.pumpAndSettle();
expect(find.text('not hovering'), findsOneWidget);
// Move into MouseRegion
await gesture.moveBy(const Offset(-20, 0));
await tester.pumpAndSettle();
expect(find.text('HOVERING'), findsOneWidget);
});
testWidgets('MouseRegion paints child once and only once when MouseRegion is inactive', (WidgetTester tester) async {
int paintCount = 0;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: MouseRegion(
onEnter: (PointerEnterEvent e) {},
child: CustomPaint(
painter: _DelegatedPainter(onPaint: () { paintCount += 1; }),
child: const Text('123'),
),
),
),
);
expect(paintCount, 1);
});
testWidgets('MouseRegion paints child once and only once when MouseRegion is active', (WidgetTester tester) async {
int paintCount = 0;
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: MouseRegion(
onEnter: (PointerEnterEvent e) {},
child: CustomPaint(
painter: _DelegatedPainter(onPaint: () { paintCount += 1; }),
child: const Text('123'),
),
),
),
);
expect(paintCount, 1);
});
testWidgets('A MouseRegion mounted under the pointer should take effect in the next postframe', (WidgetTester tester) async {
bool hovered = false;
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer(location: const Offset(5, 5));
await tester.pumpWidget(
StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
return _ColumnContainer(
children: <Widget>[
Text(hovered ? 'hover outer' : 'unhover outer'),
],
);
}),
);
expect(find.text('unhover outer'), findsOneWidget);
await tester.pumpWidget(
StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
return _ColumnContainer(
children: <Widget>[
HoverClient(
onHover: (bool value) { setState(() { hovered = value; }); },
child: Text(hovered ? 'hover inner' : 'unhover inner'),
),
Text(hovered ? 'hover outer' : 'unhover outer'),
],
);
}),
);
expect(find.text('unhover outer'), findsOneWidget);
expect(find.text('unhover inner'), findsOneWidget);
await tester.pump();
expect(find.text('hover outer'), findsOneWidget);
expect(find.text('hover inner'), findsOneWidget);
expect(tester.binding.hasScheduledFrame, isFalse);
});
testWidgets('A MouseRegion unmounted under the pointer should not trigger state change', (WidgetTester tester) async {
bool hovered = true;
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer(location: const Offset(5, 5));
await tester.pumpWidget(
StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
return _ColumnContainer(
children: <Widget>[
HoverClient(
onHover: (bool value) { setState(() { hovered = value; }); },
child: Text(hovered ? 'hover inner' : 'unhover inner'),
),
Text(hovered ? 'hover outer' : 'unhover outer'),
],
);
}),
);
expect(find.text('hover outer'), findsOneWidget);
expect(find.text('hover inner'), findsOneWidget);
expect(tester.binding.hasScheduledFrame, isTrue);
await tester.pump();
expect(find.text('hover outer'), findsOneWidget);
expect(find.text('hover inner'), findsOneWidget);
expect(tester.binding.hasScheduledFrame, isFalse);
await tester.pumpWidget(
StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
return _ColumnContainer(
children: <Widget> [
Text(hovered ? 'hover outer' : 'unhover outer'),
],
);
}),
);
expect(find.text('hover outer'), findsOneWidget);
expect(tester.binding.hasScheduledFrame, isFalse);
});
testWidgets('A MouseRegion moved into the mouse should take effect in the next postframe', (WidgetTester tester) async {
bool hovered = false;
final List<bool> logHovered = <bool>[];
bool moved = false;
late StateSetter mySetState;
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer(location: const Offset(5, 5));
await tester.pumpWidget(
StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
mySetState = setState;
return _ColumnContainer(
children: <Widget>[
Container(
height: 100,
width: 10,
alignment: moved ? Alignment.topLeft : Alignment.bottomLeft,
child: SizedBox(
height: 10,
width: 10,
child: HoverClient(
onHover: (bool value) {
setState(() { hovered = value; });
logHovered.add(value);
},
child: Text(hovered ? 'hover inner' : 'unhover inner'),
),
),
),
Text(hovered ? 'hover outer' : 'unhover outer'),
],
);
}),
);
expect(find.text('unhover inner'), findsOneWidget);
expect(find.text('unhover outer'), findsOneWidget);
expect(logHovered, isEmpty);
expect(tester.binding.hasScheduledFrame, isFalse);
mySetState(() { moved = true; });
// The first frame is for the widget movement to take effect.
await tester.pump();
expect(find.text('unhover inner'), findsOneWidget);
expect(find.text('unhover outer'), findsOneWidget);
expect(logHovered, <bool>[true]);
logHovered.clear();
// The second frame is for the mouse hover to take effect.
await tester.pump();
expect(find.text('hover inner'), findsOneWidget);
expect(find.text('hover outer'), findsOneWidget);
expect(logHovered, isEmpty);
expect(tester.binding.hasScheduledFrame, isFalse);
});
group('MouseRegion respects opacity:', () {
// A widget that contains 3 MouseRegions:
// y
// —————————————————————— 0
// | ——————————— A | 20
// | | B | |
// | | ——————————— | 50
// | | | C | |
// | ——————| | | 100
// | | | |
// | ——————————— | 130
// —————————————————————— 150
// x 0 20 50 100 130 150
Widget tripleRegions({bool? opaqueC, required void Function(String) addLog}) {
// Same as MouseRegion, but when opaque is null, use the default value.
Widget mouseRegionWithOptionalOpaque({
void Function(PointerEnterEvent e)? onEnter,
void Function(PointerHoverEvent e)? onHover,
void Function(PointerExitEvent e)? onExit,
Widget? child,
bool? opaque,
}) {
if (opaque == null) {
return MouseRegion(onEnter: onEnter, onHover: onHover, onExit: onExit, child: child);
}
return MouseRegion(onEnter: onEnter, onHover: onHover, onExit: onExit, opaque: opaque, child: child);
}
return Directionality(
textDirection: TextDirection.ltr,
child: Align(
alignment: Alignment.topLeft,
child: MouseRegion(
onEnter: (PointerEnterEvent e) { addLog('enterA'); },
onHover: (PointerHoverEvent e) { addLog('hoverA'); },
onExit: (PointerExitEvent e) { addLog('exitA'); },
child: SizedBox(
width: 150,
height: 150,
child: Stack(
children: <Widget>[
Positioned(
left: 20,
top: 20,
width: 80,
height: 80,
child: MouseRegion(
onEnter: (PointerEnterEvent e) { addLog('enterB'); },
onHover: (PointerHoverEvent e) { addLog('hoverB'); },
onExit: (PointerExitEvent e) { addLog('exitB'); },
),
),
Positioned(
left: 50,
top: 50,
width: 80,
height: 80,
child: mouseRegionWithOptionalOpaque(
opaque: opaqueC,
onEnter: (PointerEnterEvent e) { addLog('enterC'); },
onHover: (PointerHoverEvent e) { addLog('hoverC'); },
onExit: (PointerExitEvent e) { addLog('exitC'); },
),
),
],
),
),
),
),
);
}
testWidgets('a transparent one should allow MouseRegions behind it to receive pointers', (WidgetTester tester) async {
final List<String> logs = <String>[];
await tester.pumpWidget(tripleRegions(
opaqueC: false,
addLog: (String log) => logs.add(log),
));
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await tester.pumpAndSettle();
// Move to the overlapping area.
await gesture.moveTo(const Offset(75, 75));
await tester.pumpAndSettle();
expect(logs, <String>['enterA', 'enterB', 'enterC', 'hoverC', 'hoverB', 'hoverA']);
logs.clear();
// Move to the B only area.
await gesture.moveTo(const Offset(25, 75));
await tester.pumpAndSettle();
expect(logs, <String>['exitC', 'hoverB', 'hoverA']);
logs.clear();
// Move back to the overlapping area.
await gesture.moveTo(const Offset(75, 75));
await tester.pumpAndSettle();
expect(logs, <String>['enterC', 'hoverC', 'hoverB', 'hoverA']);
logs.clear();
// Move to the C only area.
await gesture.moveTo(const Offset(125, 75));
await tester.pumpAndSettle();
expect(logs, <String>['exitB', 'hoverC', 'hoverA']);
logs.clear();
// Move back to the overlapping area.
await gesture.moveTo(const Offset(75, 75));
await tester.pumpAndSettle();
expect(logs, <String>['enterB', 'hoverC', 'hoverB', 'hoverA']);
logs.clear();
// Move out.
await gesture.moveTo(const Offset(160, 160));
await tester.pumpAndSettle();
expect(logs, <String>['exitC', 'exitB', 'exitA']);
});
testWidgets('an opaque one should prevent MouseRegions behind it receiving pointers', (WidgetTester tester) async {
final List<String> logs = <String>[];
await tester.pumpWidget(tripleRegions(
opaqueC: true,
addLog: (String log) => logs.add(log),
));
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await tester.pumpAndSettle();
// Move to the overlapping area.
await gesture.moveTo(const Offset(75, 75));
await tester.pumpAndSettle();
expect(logs, <String>['enterA', 'enterC', 'hoverC', 'hoverA']);
logs.clear();
// Move to the B only area.
await gesture.moveTo(const Offset(25, 75));
await tester.pumpAndSettle();
expect(logs, <String>['exitC', 'enterB', 'hoverB', 'hoverA']);
logs.clear();
// Move back to the overlapping area.
await gesture.moveTo(const Offset(75, 75));
await tester.pumpAndSettle();
expect(logs, <String>['exitB', 'enterC', 'hoverC', 'hoverA']);
logs.clear();
// Move to the C only area.
await gesture.moveTo(const Offset(125, 75));
await tester.pumpAndSettle();
expect(logs, <String>['hoverC', 'hoverA']);
logs.clear();
// Move back to the overlapping area.
await gesture.moveTo(const Offset(75, 75));
await tester.pumpAndSettle();
expect(logs, <String>['hoverC', 'hoverA']);
logs.clear();
// Move out.
await gesture.moveTo(const Offset(160, 160));
await tester.pumpAndSettle();
expect(logs, <String>['exitC', 'exitA']);
});
testWidgets('opaque should default to true', (WidgetTester tester) async {
final List<String> logs = <String>[];
await tester.pumpWidget(tripleRegions(
addLog: (String log) => logs.add(log),
));
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await tester.pumpAndSettle();
// Move to the overlapping area.
await gesture.moveTo(const Offset(75, 75));
await tester.pumpAndSettle();
expect(logs, <String>['enterA', 'enterC', 'hoverC', 'hoverA']);
logs.clear();
// Move out.
await gesture.moveTo(const Offset(160, 160));
await tester.pumpAndSettle();
expect(logs, <String>['exitC', 'exitA']);
});
});
testWidgets('an empty opaque MouseRegion is effective', (WidgetTester tester) async {
bool bottomRegionIsHovered = false;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Stack(
children: <Widget>[
Align(
alignment: Alignment.topLeft,
child: MouseRegion(
onEnter: (_) { bottomRegionIsHovered = true; },
onHover: (_) { bottomRegionIsHovered = true; },
onExit: (_) { bottomRegionIsHovered = true; },
child: const SizedBox(
width: 10,
height: 10,
),
),
),
const MouseRegion(),
],
),
),
);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer(location: const Offset(20, 20));
await gesture.moveTo(const Offset(5, 5));
await tester.pump();
await gesture.moveTo(const Offset(20, 20));
await tester.pump();
expect(bottomRegionIsHovered, isFalse);
});
testWidgets("Changing MouseRegion's callbacks is effective and doesn't repaint", (WidgetTester tester) async {
final List<String> logs = <String>[];
const Key key = ValueKey<int>(1);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer(location: const Offset(20, 20));
await tester.pumpWidget(_Scaffold(
topLeft: SizedBox(
height: 10,
width: 10,
child: MouseRegion(
onEnter: (_) { logs.add('enter1'); },
onHover: (_) { logs.add('hover1'); },
onExit: (_) { logs.add('exit1'); },
child: CustomPaint(
painter: _DelegatedPainter(onPaint: () { logs.add('paint'); }, key: key),
),
),
),
));
expect(logs, <String>['paint']);
logs.clear();
await gesture.moveTo(const Offset(5, 5));
expect(logs, <String>['enter1', 'hover1']);
logs.clear();
await tester.pumpWidget(_Scaffold(
topLeft: SizedBox(
height: 10,
width: 10,
child: MouseRegion(
onEnter: (_) { logs.add('enter2'); },
onHover: (_) { logs.add('hover2'); },
onExit: (_) { logs.add('exit2'); },
child: CustomPaint(
painter: _DelegatedPainter(onPaint: () { logs.add('paint'); }, key: key),
),
),
),
));
expect(logs, isEmpty);
await gesture.moveTo(const Offset(6, 6));
expect(logs, <String>['hover2']);
logs.clear();
// Compare: It repaints if the MouseRegion is deactivated.
await tester.pumpWidget(_Scaffold(
topLeft: SizedBox(
height: 10,
width: 10,
child: MouseRegion(
opaque: false,
child: CustomPaint(
painter: _DelegatedPainter(onPaint: () { logs.add('paint'); }, key: key),
),
),
),
));
expect(logs, <String>['paint']);
});
testWidgets('Changing MouseRegion.opaque is effective and repaints', (WidgetTester tester) async {
final List<String> logs = <String>[];
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer(location: const Offset(5, 5));
void handleHover(PointerHoverEvent _) {}
void handlePaintChild() { logs.add('paint'); }
await tester.pumpWidget(_Scaffold(
topLeft: SizedBox(
height: 10,
width: 10,
child: MouseRegion(
onHover: handleHover,
child: CustomPaint(painter: _DelegatedPainter(onPaint: handlePaintChild)),
),
),
background: MouseRegion(onEnter: (_) { logs.add('hover-enter'); }),
));
expect(logs, <String>['paint']);
logs.clear();
expect(logs, isEmpty);
logs.clear();
await tester.pumpWidget(_Scaffold(
topLeft: SizedBox(
height: 10,
width: 10,
child: MouseRegion(
opaque: false,
// Dummy callback so that MouseRegion stays affective after opaque
// turns false.
onHover: handleHover,
child: CustomPaint(painter: _DelegatedPainter(onPaint: handlePaintChild)),
),
),
background: MouseRegion(onEnter: (_) { logs.add('hover-enter'); }),
));
expect(logs, <String>['paint', 'hover-enter']);
});
testWidgets('Changing MouseRegion.cursor is effective and repaints', (WidgetTester tester) async {
final List<String> logPaints = <String>[];
final List<String> logEnters = <String>[];
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer(location: const Offset(100, 100));
void onPaintChild() { logPaints.add('paint'); }
await tester.pumpWidget(_Scaffold(
topLeft: SizedBox(
height: 10,
width: 10,
child: MouseRegion(
cursor: SystemMouseCursors.forbidden,
onEnter: (_) { logEnters.add('enter'); },
child: CustomPaint(painter: _DelegatedPainter(onPaint: onPaintChild)),
),
),
));
await gesture.moveTo(const Offset(5, 5));
expect(logPaints, <String>['paint']);
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.forbidden);
expect(logEnters, <String>['enter']);
logPaints.clear();
logEnters.clear();
await tester.pumpWidget(_Scaffold(
topLeft: SizedBox(
height: 10,
width: 10,
child: MouseRegion(
cursor: SystemMouseCursors.text,
onEnter: (_) { logEnters.add('enter'); },
child: CustomPaint(painter: _DelegatedPainter(onPaint: onPaintChild)),
),
),
));
expect(logPaints, <String>['paint']);
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text);
expect(logEnters, isEmpty);
logPaints.clear();
logEnters.clear();
});
testWidgets('Changing whether MouseRegion.cursor is null is effective and repaints', (WidgetTester tester) async {
final List<String> logEnters = <String>[];
final List<String> logPaints = <String>[];
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer(location: const Offset(100, 100));
void onPaintChild() { logPaints.add('paint'); }
await tester.pumpWidget(_Scaffold(
topLeft: SizedBox(
height: 10,
width: 10,
child: MouseRegion(
cursor: SystemMouseCursors.forbidden,
child: MouseRegion(
cursor: SystemMouseCursors.text,
onEnter: (_) { logEnters.add('enter'); },
child: CustomPaint(painter: _DelegatedPainter(onPaint: onPaintChild)),
),
),
),
));
await gesture.moveTo(const Offset(5, 5));
expect(logPaints, <String>['paint']);
expect(logEnters, <String>['enter']);
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text);
logPaints.clear();
logEnters.clear();
await tester.pumpWidget(_Scaffold(
topLeft: SizedBox(
height: 10,
width: 10,
child: MouseRegion(
cursor: SystemMouseCursors.forbidden,
child: MouseRegion(
onEnter: (_) { logEnters.add('enter'); },
child: CustomPaint(painter: _DelegatedPainter(onPaint: onPaintChild)),
),
),
),
));
expect(logPaints, <String>['paint']);
expect(logEnters, isEmpty);
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.forbidden);
logPaints.clear();
logEnters.clear();
await tester.pumpWidget(_Scaffold(
topLeft: SizedBox(
height: 10,
width: 10,
child: MouseRegion(
cursor: SystemMouseCursors.forbidden,
child: MouseRegion(
cursor: SystemMouseCursors.text,
child: CustomPaint(painter: _DelegatedPainter(onPaint: onPaintChild)),
),
),
),
));
expect(logPaints, <String>['paint']);
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text);
expect(logEnters, isEmpty);
logPaints.clear();
logEnters.clear();
});
testWidgets('Does not trigger side effects during a reparent', (WidgetTester tester) async {
final List<String> logEnters = <String>[];
final List<String> logExits = <String>[];
final List<String> logCursors = <String>[];
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer(location: const Offset(100, 100));
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.mouseCursor, (_) async {
logCursors.add('cursor');
return null;
});
final GlobalKey key = GlobalKey();
// Pump a row of 2 SizedBox's, each taking 50px of width.
await tester.pumpWidget(_Scaffold(
topLeft: SizedBox(
width: 100,
height: 50,
child: Row(
children: <Widget>[
SizedBox(
width: 50,
height: 50,
child: MouseRegion(
key: key,
onEnter: (_) { logEnters.add('enter'); },
onExit: (_) { logEnters.add('enter'); },
cursor: SystemMouseCursors.click,
),
),
const SizedBox(
width: 50,
height: 50,
),
],
),
),
));
// Move to the mouse region inside the first box.
await gesture.moveTo(const Offset(40, 5));
expect(logEnters, <String>['enter']);
expect(logExits, isEmpty);
expect(logCursors, isNotEmpty);
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.click);
logEnters.clear();
logExits.clear();
logCursors.clear();
// Move MouseRegion to the second box while resizing them so that the
// mouse is still on the MouseRegion
await tester.pumpWidget(_Scaffold(
topLeft: SizedBox(
width: 100,
height: 50,
child: Row(
children: <Widget>[
const SizedBox(
width: 30,
height: 50,
),
SizedBox(
width: 70,
height: 50,
child: MouseRegion(
key: key,
onEnter: (_) { logEnters.add('enter'); },
onExit: (_) { logEnters.add('enter'); },
cursor: SystemMouseCursors.click,
),
),
],
),
),
));
expect(logEnters, isEmpty);
expect(logExits, isEmpty);
expect(logCursors, isEmpty);
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.click);
});
testWidgets("RenderMouseRegion's debugFillProperties when default", (WidgetTester tester) async {
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
final RenderMouseRegion renderMouseRegion = RenderMouseRegion();
addTearDown(renderMouseRegion.dispose);
renderMouseRegion.debugFillProperties(builder);
final List<String> description = builder.properties.where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)).map((DiagnosticsNode node) => node.toString()).toList();
expect(description, <String>[
'parentData: MISSING',
'constraints: MISSING',
'size: MISSING',
'behavior: opaque',
'listeners: <none>',
]);
});
testWidgets("RenderMouseRegion's debugFillProperties when full", (WidgetTester tester) async {
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
final RenderErrorBox renderErrorBox = RenderErrorBox();
addTearDown(renderErrorBox.dispose);
final RenderMouseRegion renderMouseRegion = RenderMouseRegion(
onEnter: (PointerEnterEvent event) {},
onExit: (PointerExitEvent event) {},
onHover: (PointerHoverEvent event) {},
cursor: SystemMouseCursors.click,
validForMouseTracker: false,
child: renderErrorBox,
);
addTearDown(renderMouseRegion.dispose);
renderMouseRegion.debugFillProperties(builder);
final List<String> description = builder.properties.where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)).map((DiagnosticsNode node) => node.toString()).toList();
expect(description, <String>[
'parentData: MISSING',
'constraints: MISSING',
'size: MISSING',
'behavior: opaque',
'listeners: enter, hover, exit',
'cursor: SystemMouseCursor(click)',
'invalid for MouseTracker',
]);
});
testWidgets('No new frames are scheduled when mouse moves without triggering callbacks', (WidgetTester tester) async {
await tester.pumpWidget(Center(
child: MouseRegion(
child: const SizedBox(
width: 100.0,
height: 100.0,
),
onEnter: (PointerEnterEvent details) {},
onHover: (PointerHoverEvent details) {},
onExit: (PointerExitEvent details) {},
),
));
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer(location: const Offset(400.0, 300.0));
await tester.pumpAndSettle();
await gesture.moveBy(const Offset(10.0, 10.0));
expect(tester.binding.hasScheduledFrame, isFalse);
});
// Regression test for https://github.com/flutter/flutter/issues/67044
testWidgets('Handle mouse events should ignore the detached MouseTrackerAnnotation', (WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(
home: Center(
child: Draggable<int>(
feedback: Container(width: 20, height: 20, color: Colors.blue),
childWhenDragging: Container(width: 20, height: 20, color: Colors.yellow),
child: ElevatedButton(child: const Text('Drag me'), onPressed: (){}),
),
),
));
// Long press the button with mouse.
final Offset textFieldPos = tester.getCenter(find.byType(Text));
final TestGesture gesture = await tester.startGesture(
textFieldPos,
kind: PointerDeviceKind.mouse,
);
await tester.pump(const Duration(seconds: 2));
await tester.pumpAndSettle();
// Drag the Draggable Widget will replace the child with [childWhenDragging].
await gesture.moveBy(const Offset(10.0, 10.0));
await tester.pump(); // Trigger detach the button.
// Continue drag mouse should not trigger any assert.
await gesture.moveBy(const Offset(10.0, 10.0));
expect(tester.takeException(), isNull);
});
}
// Render widget `topLeft` at the top-left corner, stacking on top of the widget
// `background`.
class _Scaffold extends StatelessWidget {
const _Scaffold({this.topLeft, this.background});
final Widget? topLeft;
final Widget? background;
@override
Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.ltr,
child: Stack(
children: <Widget>[
if (background != null) background!,
Align(
alignment: Alignment.topLeft,
child: topLeft,
),
],
),
);
}
}
class _DelegatedPainter extends CustomPainter {
_DelegatedPainter({this.key, required this.onPaint});
final Key? key;
final VoidCallback onPaint;
@override
void paint(Canvas canvas, Size size) {
onPaint();
}
@override
bool shouldRepaint(CustomPainter oldDelegate) =>
!(oldDelegate is _DelegatedPainter && key == oldDelegate.key);
}
class _HoverClientWithClosures extends StatefulWidget {
const _HoverClientWithClosures();
@override
_HoverClientWithClosuresState createState() => _HoverClientWithClosuresState();
}
class _HoverClientWithClosuresState extends State<_HoverClientWithClosures> {
bool _hovering = false;
@override
Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.ltr,
child: MouseRegion(
onEnter: (PointerEnterEvent _) {
setState(() {
_hovering = true;
});
},
onExit: (PointerExitEvent _) {
setState(() {
_hovering = false;
});
},
child: Text(_hovering ? 'HOVERING' : 'not hovering'),
),
);
}
}
// A column that aligns to the top left.
class _ColumnContainer extends StatelessWidget {
const _ColumnContainer({
required this.children,
});
final List<Widget> children;
@override
Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.ltr,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: children,
),
);
}
}
| flutter/packages/flutter/test/widgets/mouse_region_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/mouse_region_test.dart",
"repo_id": "flutter",
"token_count": 27350
} | 720 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('RenderOpacity avoids repainting and does not drop layer at fully opaque', (WidgetTester tester) async {
RenderTestObject.paintCount = 0;
await tester.pumpWidget(
const ColoredBox(
color: Colors.red,
child: Opacity(
opacity: 0.0,
child: TestWidget(),
),
)
);
expect(RenderTestObject.paintCount, 0);
await tester.pumpWidget(
const ColoredBox(
color: Colors.red,
child: Opacity(
opacity: 0.1,
child: TestWidget(),
),
)
);
expect(RenderTestObject.paintCount, 1);
await tester.pumpWidget(
const ColoredBox(
color: Colors.red,
child: Opacity(
opacity: 1,
child: TestWidget(),
),
)
);
expect(RenderTestObject.paintCount, 1);
});
testWidgets('RenderOpacity allows opacity layer to be dropped at 0 opacity', (WidgetTester tester) async {
RenderTestObject.paintCount = 0;
await tester.pumpWidget(
const ColoredBox(
color: Colors.red,
child: Opacity(
opacity: 0.5,
child: TestWidget(),
),
)
);
expect(RenderTestObject.paintCount, 1);
await tester.pumpWidget(
const ColoredBox(
color: Colors.red,
child: Opacity(
opacity: 0.0,
child: TestWidget(),
),
)
);
expect(RenderTestObject.paintCount, 1);
expect(tester.layers, isNot(contains(isA<OpacityLayer>())));
});
}
class TestWidget extends SingleChildRenderObjectWidget {
const TestWidget({super.key, super.child});
@override
RenderObject createRenderObject(BuildContext context) {
return RenderTestObject();
}
}
class RenderTestObject extends RenderProxyBox {
static int paintCount = 0;
@override
void paint(PaintingContext context, Offset offset) {
paintCount += 1;
super.paint(context, offset);
}
}
| flutter/packages/flutter/test/widgets/opacity_repaint_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/opacity_repaint_test.dart",
"repo_id": "flutter",
"token_count": 931
} | 721 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file is run as part of a reduced test set in CI on Mac and Windows
// machines.
@Tags(<String>['reduced-test-set'])
library;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('PhysicalModel updates clipBehavior in updateRenderObject', (WidgetTester tester) async {
await tester.pumpWidget(
const MaterialApp(home: PhysicalModel(color: Colors.red)),
);
final RenderPhysicalModel renderPhysicalModel = tester.allRenderObjects.whereType<RenderPhysicalModel>().first;
expect(renderPhysicalModel.clipBehavior, equals(Clip.none));
await tester.pumpWidget(
const MaterialApp(home: PhysicalModel(clipBehavior: Clip.antiAlias, color: Colors.red)),
);
expect(renderPhysicalModel.clipBehavior, equals(Clip.antiAlias));
});
testWidgets('PhysicalShape updates clipBehavior in updateRenderObject', (WidgetTester tester) async {
await tester.pumpWidget(
const MaterialApp(home: PhysicalShape(color: Colors.red, clipper: ShapeBorderClipper(shape: CircleBorder()))),
);
final RenderPhysicalShape renderPhysicalShape = tester.allRenderObjects.whereType<RenderPhysicalShape>().first;
expect(renderPhysicalShape.clipBehavior, equals(Clip.none));
await tester.pumpWidget(
const MaterialApp(home: PhysicalShape(clipBehavior: Clip.antiAlias, color: Colors.red, clipper: ShapeBorderClipper(shape: CircleBorder()))),
);
expect(renderPhysicalShape.clipBehavior, equals(Clip.antiAlias));
});
testWidgets('PhysicalModel - clips when overflows and elevation is 0', (WidgetTester tester) async {
const Key key = Key('test');
await tester.pumpWidget(
Theme(
data: ThemeData(useMaterial3: false),
child: const MediaQuery(
key: key,
data: MediaQueryData(),
child: Directionality(
textDirection: TextDirection.ltr,
child: Padding(
padding: EdgeInsets.all(50),
child: Row(
children: <Widget>[
Material(child: Text('A long long long long long long long string')),
Material(child: Text('A long long long long long long long string')),
Material(child: Text('A long long long long long long long string')),
Material(child: Text('A long long long long long long long string')),
],
),
),
),
),
),
);
final dynamic exception = tester.takeException();
expect(exception, isFlutterError);
// ignore: avoid_dynamic_calls
expect(exception.diagnostics.first.level, DiagnosticLevel.summary);
// ignore: avoid_dynamic_calls
expect(exception.diagnostics.first.toString(), startsWith('A RenderFlex overflowed by '));
await expectLater(
find.byKey(key),
matchesGoldenFile('physical_model_overflow.png'),
);
});
}
| flutter/packages/flutter/test/widgets/physical_model_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/physical_model_test.dart",
"repo_id": "flutter",
"token_count": 1157
} | 722 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart';
void main() {
testWidgets('value is not accessible when not registered', (WidgetTester tester) async {
final RestorableNum<num> numValue = RestorableNum<num>(0);
addTearDown(numValue.dispose);
expect(() => numValue.value, throwsAssertionError);
final RestorableDouble doubleValue = RestorableDouble(1.0);
addTearDown(doubleValue.dispose);
expect(() => doubleValue.value, throwsAssertionError);
final RestorableInt intValue = RestorableInt(1);
addTearDown(intValue.dispose);
expect(() => intValue.value, throwsAssertionError);
final RestorableString stringValue = RestorableString('hello');
addTearDown(stringValue.dispose);
expect(() => stringValue.value, throwsAssertionError);
final RestorableBool boolValue = RestorableBool(true);
addTearDown(boolValue.dispose);
expect(() => boolValue.value, throwsAssertionError);
final RestorableNumN<num?> nullableNumValue = RestorableNumN<num?>(0);
addTearDown(nullableNumValue.dispose);
expect(() => nullableNumValue.value, throwsAssertionError);
final RestorableDoubleN nullableDoubleValue = RestorableDoubleN(1.0);
addTearDown(nullableDoubleValue.dispose);
expect(() => nullableDoubleValue.value, throwsAssertionError);
final RestorableIntN nullableIntValue = RestorableIntN(1);
addTearDown(nullableIntValue.dispose);
expect(() => nullableIntValue.value, throwsAssertionError);
final RestorableStringN nullableStringValue = RestorableStringN('hello');
addTearDown(nullableStringValue.dispose);
expect(() => nullableStringValue.value, throwsAssertionError);
final RestorableBoolN nullableBoolValue = RestorableBoolN(true);
addTearDown(nullableBoolValue.dispose);
expect(() => nullableBoolValue.value, throwsAssertionError);
final RestorableTextEditingController controllerValue = RestorableTextEditingController();
addTearDown(controllerValue.dispose);
expect(() => controllerValue.value, throwsAssertionError);
final RestorableDateTime dateTimeValue = RestorableDateTime(DateTime(2020, 4, 3));
addTearDown(dateTimeValue.dispose);
expect(() => dateTimeValue.value, throwsAssertionError);
final RestorableDateTimeN nullableDateTimeValue = RestorableDateTimeN(DateTime(2020, 4, 3));
addTearDown(nullableDateTimeValue.dispose);
expect(() => nullableDateTimeValue.value, throwsAssertionError);
final RestorableEnumN<TestEnum> nullableEnumValue = RestorableEnumN<TestEnum>(TestEnum.one, values: TestEnum.values);
addTearDown(nullableEnumValue.dispose);
expect(() => nullableEnumValue.value, throwsAssertionError);
final RestorableEnum<TestEnum> enumValue = RestorableEnum<TestEnum>(TestEnum.one, values: TestEnum.values);
addTearDown(enumValue.dispose);
expect(() => enumValue.value, throwsAssertionError);
final _TestRestorableValue objectValue = _TestRestorableValue();
addTearDown(objectValue.dispose);
expect(() => objectValue.value, throwsAssertionError);
});
testWidgets('$RestorableProperty dispatches creation in constructor', (WidgetTester widgetTester) async {
await expectLater(
await memoryEvents(() => RestorableDateTimeN(null).dispose(), RestorableDateTimeN),
areCreateAndDispose,
);
});
testWidgets('work when not in restoration scope', (WidgetTester tester) async {
await tester.pumpWidget(const _RestorableWidget());
expect(find.text('hello world'), findsOneWidget);
final _RestorableWidgetState state = tester.state(find.byType(_RestorableWidget));
// Initialized to default values.
expect(state.numValue.value, 99);
expect(state.doubleValue.value, 123.2);
expect(state.intValue.value, 42);
expect(state.stringValue.value, 'hello world');
expect(state.boolValue.value, false);
expect(state.dateTimeValue.value, DateTime(2021, 3, 16));
expect(state.enumValue.value, TestEnum.one);
expect(state.nullableNumValue.value, null);
expect(state.nullableDoubleValue.value, null);
expect(state.nullableIntValue.value, null);
expect(state.nullableStringValue.value, null);
expect(state.nullableBoolValue.value, null);
expect(state.nullableDateTimeValue.value, null);
expect(state.nullableEnumValue.value, null);
expect(state.controllerValue.value.text, 'FooBar');
expect(state.objectValue.value, 55);
// Modify values.
state.setProperties(() {
state.numValue.value = 42.2;
state.doubleValue.value = 441.3;
state.intValue.value = 10;
state.stringValue.value = 'guten tag';
state.boolValue.value = true;
state.dateTimeValue.value = DateTime(2020, 7, 4);
state.enumValue.value = TestEnum.two;
state.nullableNumValue.value = 5.0;
state.nullableDoubleValue.value = 2.0;
state.nullableIntValue.value = 1;
state.nullableStringValue.value = 'hullo';
state.nullableBoolValue.value = false;
state.nullableDateTimeValue.value = DateTime(2020, 4, 4);
state.nullableEnumValue.value = TestEnum.three;
state.controllerValue.value.text = 'blabla';
state.objectValue.value = 53;
});
await tester.pump();
expect(state.numValue.value, 42.2);
expect(state.doubleValue.value, 441.3);
expect(state.intValue.value, 10);
expect(state.stringValue.value, 'guten tag');
expect(state.boolValue.value, true);
expect(state.dateTimeValue.value, DateTime(2020, 7, 4));
expect(state.enumValue.value, TestEnum.two);
expect(state.nullableNumValue.value, 5.0);
expect(state.nullableDoubleValue.value, 2.0);
expect(state.nullableIntValue.value, 1);
expect(state.nullableStringValue.value, 'hullo');
expect(state.nullableBoolValue.value, false);
expect(state.nullableDateTimeValue.value, DateTime(2020, 4, 4));
expect(state.nullableEnumValue.value, TestEnum.three);
expect(state.controllerValue.value.text, 'blabla');
expect(state.objectValue.value, 53);
expect(find.text('guten tag'), findsOneWidget);
});
testWidgets('restart and restore', (WidgetTester tester) async {
await tester.pumpWidget(const RootRestorationScope(
restorationId: 'root-child',
child: _RestorableWidget(),
));
expect(find.text('hello world'), findsOneWidget);
_RestorableWidgetState state = tester.state(find.byType(_RestorableWidget));
// Initialized to default values.
expect(state.numValue.value, 99);
expect(state.doubleValue.value, 123.2);
expect(state.intValue.value, 42);
expect(state.stringValue.value, 'hello world');
expect(state.boolValue.value, false);
expect(state.dateTimeValue.value, DateTime(2021, 3, 16));
expect(state.enumValue.value, TestEnum.one);
expect(state.nullableNumValue.value, null);
expect(state.nullableDoubleValue.value, null);
expect(state.nullableIntValue.value, null);
expect(state.nullableStringValue.value, null);
expect(state.nullableBoolValue.value, null);
expect(state.nullableDateTimeValue.value, null);
expect(state.nullableEnumValue.value, null);
expect(state.controllerValue.value.text, 'FooBar');
expect(state.objectValue.value, 55);
// Modify values.
state.setProperties(() {
state.numValue.value = 42.2;
state.doubleValue.value = 441.3;
state.intValue.value = 10;
state.stringValue.value = 'guten tag';
state.boolValue.value = true;
state.dateTimeValue.value = DateTime(2020, 7, 4);
state.enumValue.value = TestEnum.two;
state.nullableNumValue.value = 5.0;
state.nullableDoubleValue.value = 2.0;
state.nullableIntValue.value = 1;
state.nullableStringValue.value = 'hullo';
state.nullableBoolValue.value = false;
state.nullableDateTimeValue.value = DateTime(2020, 4, 4);
state.nullableEnumValue.value = TestEnum.three;
state.controllerValue.value.text = 'blabla';
state.objectValue.value = 53;
});
await tester.pump();
expect(state.numValue.value, 42.2);
expect(state.doubleValue.value, 441.3);
expect(state.intValue.value, 10);
expect(state.stringValue.value, 'guten tag');
expect(state.boolValue.value, true);
expect(state.dateTimeValue.value, DateTime(2020, 7, 4));
expect(state.enumValue.value, TestEnum.two);
expect(state.nullableNumValue.value, 5.0);
expect(state.nullableDoubleValue.value, 2.0);
expect(state.nullableIntValue.value, 1);
expect(state.nullableStringValue.value, 'hullo');
expect(state.nullableBoolValue.value, false);
expect(state.nullableDateTimeValue.value, DateTime(2020, 4, 4));
expect(state.nullableEnumValue.value, TestEnum.three);
expect(state.controllerValue.value.text, 'blabla');
expect(state.objectValue.value, 53);
expect(find.text('guten tag'), findsOneWidget);
// Restores to previous values.
await tester.restartAndRestore();
final _RestorableWidgetState oldState = state;
state = tester.state(find.byType(_RestorableWidget));
expect(state, isNot(same(oldState)));
expect(state.numValue.value, 42.2);
expect(state.doubleValue.value, 441.3);
expect(state.intValue.value, 10);
expect(state.stringValue.value, 'guten tag');
expect(state.boolValue.value, true);
expect(state.dateTimeValue.value, DateTime(2020, 7, 4));
expect(state.enumValue.value, TestEnum.two);
expect(state.nullableNumValue.value, 5.0);
expect(state.nullableDoubleValue.value, 2.0);
expect(state.nullableIntValue.value, 1);
expect(state.nullableStringValue.value, 'hullo');
expect(state.nullableBoolValue.value, false);
expect(state.nullableDateTimeValue.value, DateTime(2020, 4, 4));
expect(state.nullableEnumValue.value, TestEnum.three);
expect(state.controllerValue.value.text, 'blabla');
expect(state.objectValue.value, 53);
expect(find.text('guten tag'), findsOneWidget);
});
testWidgets('restore to older state', (WidgetTester tester) async {
await tester.pumpWidget(const RootRestorationScope(
restorationId: 'root-child',
child: _RestorableWidget(),
));
expect(find.text('hello world'), findsOneWidget);
final _RestorableWidgetState state = tester.state(find.byType(_RestorableWidget));
// Modify values.
state.setProperties(() {
state.numValue.value = 42.2;
state.doubleValue.value = 441.3;
state.intValue.value = 10;
state.stringValue.value = 'guten tag';
state.boolValue.value = true;
state.dateTimeValue.value = DateTime(2020, 7, 4);
state.enumValue.value = TestEnum.two;
state.nullableNumValue.value = 5.0;
state.nullableDoubleValue.value = 2.0;
state.nullableIntValue.value = 1;
state.nullableStringValue.value = 'hullo';
state.nullableBoolValue.value = false;
state.nullableDateTimeValue.value = DateTime(2020, 4, 4);
state.nullableEnumValue.value = TestEnum.three;
state.controllerValue.value.text = 'blabla';
state.objectValue.value = 53;
});
await tester.pump();
expect(find.text('guten tag'), findsOneWidget);
final TestRestorationData restorationData = await tester.getRestorationData();
// Modify values.
state.setProperties(() {
state.numValue.value = 20;
state.doubleValue.value = 20.0;
state.intValue.value = 20;
state.stringValue.value = 'ciao';
state.boolValue.value = false;
state.dateTimeValue.value = DateTime(2020, 3, 2);
state.enumValue.value = TestEnum.four;
state.nullableNumValue.value = 20.0;
state.nullableDoubleValue.value = 20.0;
state.nullableIntValue.value = 20;
state.nullableStringValue.value = 'ni hao';
state.nullableBoolValue.value = null;
state.nullableDateTimeValue.value = DateTime(2020, 5, 5);
state.nullableEnumValue.value = TestEnum.two;
state.controllerValue.value.text = 'blub';
state.objectValue.value = 20;
});
await tester.pump();
expect(find.text('ciao'), findsOneWidget);
final TextEditingController controller = state.controllerValue.value;
// Restore to previous.
await tester.restoreFrom(restorationData);
expect(state.numValue.value, 42.2);
expect(state.doubleValue.value, 441.3);
expect(state.intValue.value, 10);
expect(state.stringValue.value, 'guten tag');
expect(state.boolValue.value, true);
expect(state.dateTimeValue.value, DateTime(2020, 7, 4));
expect(state.enumValue.value, TestEnum.two);
expect(state.nullableNumValue.value, 5.0);
expect(state.nullableDoubleValue.value, 2.0);
expect(state.nullableIntValue.value, 1);
expect(state.nullableStringValue.value, 'hullo');
expect(state.nullableBoolValue.value, false);
expect(state.nullableDateTimeValue.value, DateTime(2020, 4, 4));
expect(state.nullableEnumValue.value, TestEnum.three);
expect(state.controllerValue.value.text, 'blabla');
expect(state.objectValue.value, 53);
expect(find.text('guten tag'), findsOneWidget);
expect(state.controllerValue.value, isNot(same(controller)));
// Restore to empty data will re-initialize to default values.
await tester.restoreFrom(TestRestorationData.empty);
expect(state.numValue.value, 99);
expect(state.doubleValue.value, 123.2);
expect(state.intValue.value, 42);
expect(state.stringValue.value, 'hello world');
expect(state.boolValue.value, false);
expect(state.dateTimeValue.value, DateTime(2021, 3, 16));
expect(state.enumValue.value, TestEnum.one);
expect(state.nullableNumValue.value, null);
expect(state.nullableDoubleValue.value, null);
expect(state.nullableIntValue.value, null);
expect(state.nullableStringValue.value, null);
expect(state.nullableBoolValue.value, null);
expect(state.nullableDateTimeValue.value, null);
expect(state.nullableEnumValue.value, null);
expect(state.controllerValue.value.text, 'FooBar');
expect(state.objectValue.value, 55);
expect(find.text('hello world'), findsOneWidget);
});
testWidgets('call notifiers when value changes', (WidgetTester tester) async {
await tester.pumpWidget(const RootRestorationScope(
restorationId: 'root-child',
child: _RestorableWidget(),
));
expect(find.text('hello world'), findsOneWidget);
final _RestorableWidgetState state = tester.state(find.byType(_RestorableWidget));
final List<String> notifyLog = <String>[];
state.numValue.addListener(() {
notifyLog.add('num');
});
state.doubleValue.addListener(() {
notifyLog.add('double');
});
state.intValue.addListener(() {
notifyLog.add('int');
});
state.stringValue.addListener(() {
notifyLog.add('string');
});
state.boolValue.addListener(() {
notifyLog.add('bool');
});
state.dateTimeValue.addListener(() {
notifyLog.add('date-time');
});
state.enumValue.addListener(() {
notifyLog.add('enum');
});
state.nullableNumValue.addListener(() {
notifyLog.add('nullable-num');
});
state.nullableDoubleValue.addListener(() {
notifyLog.add('nullable-double');
});
state.nullableIntValue.addListener(() {
notifyLog.add('nullable-int');
});
state.nullableStringValue.addListener(() {
notifyLog.add('nullable-string');
});
state.nullableBoolValue.addListener(() {
notifyLog.add('nullable-bool');
});
state.nullableDateTimeValue.addListener(() {
notifyLog.add('nullable-date-time');
});
state.nullableEnumValue.addListener(() {
notifyLog.add('nullable-enum');
});
state.controllerValue.addListener(() {
notifyLog.add('controller');
});
state.objectValue.addListener(() {
notifyLog.add('object');
});
state.setProperties(() {
state.numValue.value = 42.2;
});
expect(notifyLog.single, 'num');
notifyLog.clear();
state.setProperties(() {
state.doubleValue.value = 42.2;
});
expect(notifyLog.single, 'double');
notifyLog.clear();
state.setProperties(() {
state.intValue.value = 45;
});
expect(notifyLog.single, 'int');
notifyLog.clear();
state.setProperties(() {
state.stringValue.value = 'bar';
});
expect(notifyLog.single, 'string');
notifyLog.clear();
state.setProperties(() {
state.boolValue.value = true;
});
expect(notifyLog.single, 'bool');
notifyLog.clear();
state.setProperties(() {
state.dateTimeValue.value = DateTime(2020, 7, 4);
});
expect(notifyLog.single, 'date-time');
notifyLog.clear();
state.setProperties(() {
state.enumValue.value = TestEnum.two;
});
expect(notifyLog.single, 'enum');
notifyLog.clear();
state.setProperties(() {
state.nullableNumValue.value = 42.2;
});
expect(notifyLog.single, 'nullable-num');
notifyLog.clear();
state.setProperties(() {
state.nullableDoubleValue.value = 42.2;
});
expect(notifyLog.single, 'nullable-double');
notifyLog.clear();
state.setProperties(() {
state.nullableIntValue.value = 45;
});
expect(notifyLog.single, 'nullable-int');
notifyLog.clear();
state.setProperties(() {
state.nullableStringValue.value = 'bar';
});
expect(notifyLog.single, 'nullable-string');
notifyLog.clear();
state.setProperties(() {
state.nullableBoolValue.value = true;
});
expect(notifyLog.single, 'nullable-bool');
notifyLog.clear();
state.setProperties(() {
state.nullableDateTimeValue.value = DateTime(2020, 4, 4);
});
expect(notifyLog.single, 'nullable-date-time');
notifyLog.clear();
state.setProperties(() {
state.nullableEnumValue.value = TestEnum.three;
});
expect(notifyLog.single, 'nullable-enum');
notifyLog.clear();
state.setProperties(() {
state.controllerValue.value.text = 'foo';
});
expect(notifyLog.single, 'controller');
notifyLog.clear();
state.setProperties(() {
state.objectValue.value = 42;
});
expect(notifyLog.single, 'object');
notifyLog.clear();
await tester.pump();
expect(find.text('bar'), findsOneWidget);
// Does not notify when set to same value.
state.setProperties(() {
state.numValue.value = 42.2;
state.doubleValue.value = 42.2;
state.intValue.value = 45;
state.stringValue.value = 'bar';
state.boolValue.value = true;
state.dateTimeValue.value = DateTime(2020, 7, 4);
state.enumValue.value = TestEnum.two;
state.nullableNumValue.value = 42.2;
state.nullableDoubleValue.value = 42.2;
state.nullableIntValue.value = 45;
state.nullableStringValue.value = 'bar';
state.nullableBoolValue.value = true;
state.nullableDateTimeValue.value = DateTime(2020, 4, 4);
state.nullableEnumValue.value = TestEnum.three;
state.controllerValue.value.text = 'foo';
state.objectValue.value = 42;
});
expect(notifyLog, isEmpty);
});
testWidgets('RestorableValue calls didUpdateValue', (WidgetTester tester) async {
await tester.pumpWidget(const RootRestorationScope(
restorationId: 'root-child',
child: _RestorableWidget(),
));
expect(find.text('hello world'), findsOneWidget);
final _RestorableWidgetState state = tester.state(find.byType(_RestorableWidget));
expect(state.objectValue.didUpdateValueCallCount, 0);
state.setProperties(() {
state.objectValue.value = 44;
});
expect(state.objectValue.didUpdateValueCallCount, 1);
await tester.pump();
state.setProperties(() {
state.objectValue.value = 44;
});
expect(state.objectValue.didUpdateValueCallCount, 1);
});
testWidgets('RestorableEnum and RestorableEnumN assert if default value is not in enum', (WidgetTester tester) async {
expect(() => RestorableEnum<TestEnum>(
TestEnum.four,
values: TestEnum.values.toSet().difference(<TestEnum>{TestEnum.four})), throwsAssertionError);
expect(() => RestorableEnumN<TestEnum>(
TestEnum.four,
values: TestEnum.values.toSet().difference(<TestEnum>{TestEnum.four})), throwsAssertionError);
});
testWidgets('RestorableEnum and RestorableEnumN assert if unknown values are set', (WidgetTester tester) async {
final RestorableEnum<TestEnum> enumMissingValue = RestorableEnum<TestEnum>(
TestEnum.one,
values: TestEnum.values.toSet().difference(<TestEnum>{TestEnum.four}),
);
addTearDown(enumMissingValue.dispose);
expect(() => enumMissingValue.value = TestEnum.four, throwsAssertionError);
final RestorableEnumN<TestEnum> nullableEnumMissingValue = RestorableEnumN<TestEnum>(
null,
values: TestEnum.values.toSet().difference(<TestEnum>{TestEnum.four}),
);
addTearDown(nullableEnumMissingValue.dispose);
expect(() => nullableEnumMissingValue.value = TestEnum.four, throwsAssertionError);
});
testWidgets('RestorableEnum and RestorableEnumN assert if unknown values are restored', (WidgetTester tester) async {
final RestorableEnum<TestEnum> enumMissingValue = RestorableEnum<TestEnum>(
TestEnum.one,
values: TestEnum.values.toSet().difference(<TestEnum>{TestEnum.four}),
);
addTearDown(enumMissingValue.dispose);
expect(() => enumMissingValue.fromPrimitives('four'), throwsAssertionError);
final RestorableEnumN<TestEnum> nullableEnumMissingValue = RestorableEnumN<TestEnum>(
null,
values: TestEnum.values.toSet().difference(<TestEnum>{TestEnum.four}),
);
addTearDown(nullableEnumMissingValue.dispose);
expect(() => nullableEnumMissingValue.fromPrimitives('four'), throwsAssertionError);
});
testWidgets('RestorableN types are properly defined', (WidgetTester tester) async {
await tester.pumpWidget(const RootRestorationScope(
restorationId: 'root-child',
child: _RestorableWidget(),
));
expect(find.text('hello world'), findsOneWidget);
final _RestorableWidgetState state = tester.state(find.byType(_RestorableWidget));
state.setProperties(() {
state.nullableIntValue.value = 24;
state.nullableDoubleValue.value = 1.5;
});
// The following types of asserts do not work. They pass even when the
// type of `value` is a `num` and not an `int` because `num` is a
// superclass of `int`. This test is intended to prevent a regression
// where RestorableIntN's value is of type `num?`, but it is passed into
// a function which requires an `int?` value. This resulted in Dart
// compile-time errors.
//
// expect(state.nullableIntValue.value, isA<int>());
// expect(state.nullableIntValue.value.runtimeType, int);
// A function that takes a nullable int value.
void takesInt(int? value) {}
// The following would result in a Dart compile-time error if `value` is
// a `num?` instead of an `int?`.
takesInt(state.nullableIntValue.value);
// A function that takes a nullable double value.
void takesDouble(double? value) {}
// The following would result in a Dart compile-time error if `value` is
// a `num?` instead of a `double?`.
takesDouble(state.nullableDoubleValue.value);
});
}
class _TestRestorableValue extends RestorableValue<Object?> {
@override
Object createDefaultValue() {
return 55;
}
int didUpdateValueCallCount = 0;
@override
void didUpdateValue(Object? oldValue) {
didUpdateValueCallCount++;
notifyListeners();
}
@override
Object? fromPrimitives(Object? data) {
return data;
}
@override
Object? toPrimitives() {
return value;
}
}
class _RestorableWidget extends StatefulWidget {
const _RestorableWidget();
@override
State<_RestorableWidget> createState() => _RestorableWidgetState();
}
class _RestorableWidgetState extends State<_RestorableWidget> with RestorationMixin {
final RestorableNum<num> numValue = RestorableNum<num>(99);
final RestorableDouble doubleValue = RestorableDouble(123.2);
final RestorableInt intValue = RestorableInt(42);
final RestorableString stringValue = RestorableString('hello world');
final RestorableBool boolValue = RestorableBool(false);
final RestorableDateTime dateTimeValue = RestorableDateTime(DateTime(2021, 3, 16));
final RestorableEnum<TestEnum> enumValue = RestorableEnum<TestEnum>(TestEnum.one, values: TestEnum.values);
final RestorableNumN<num?> nullableNumValue = RestorableNumN<num?>(null);
final RestorableDoubleN nullableDoubleValue = RestorableDoubleN(null);
final RestorableIntN nullableIntValue = RestorableIntN(null);
final RestorableStringN nullableStringValue = RestorableStringN(null);
final RestorableBoolN nullableBoolValue = RestorableBoolN(null);
final RestorableDateTimeN nullableDateTimeValue = RestorableDateTimeN(null);
final RestorableEnumN<TestEnum> nullableEnumValue = RestorableEnumN<TestEnum>(null, values: TestEnum.values);
final RestorableTextEditingController controllerValue = RestorableTextEditingController(text: 'FooBar');
final _TestRestorableValue objectValue = _TestRestorableValue();
@override
void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
registerForRestoration(numValue, 'num');
registerForRestoration(doubleValue, 'double');
registerForRestoration(intValue, 'int');
registerForRestoration(stringValue, 'string');
registerForRestoration(boolValue, 'bool');
registerForRestoration(dateTimeValue, 'dateTime');
registerForRestoration(enumValue, 'enum');
registerForRestoration(nullableNumValue, 'nullableNum');
registerForRestoration(nullableDoubleValue, 'nullableDouble');
registerForRestoration(nullableIntValue, 'nullableInt');
registerForRestoration(nullableStringValue, 'nullableString');
registerForRestoration(nullableBoolValue, 'nullableBool');
registerForRestoration(nullableDateTimeValue, 'nullableDateTime');
registerForRestoration(nullableEnumValue, 'nullableEnum');
registerForRestoration(controllerValue, 'controller');
registerForRestoration(objectValue, 'object');
}
@override
void dispose() {
numValue.dispose();
doubleValue.dispose();
intValue.dispose();
stringValue.dispose();
boolValue.dispose();
dateTimeValue.dispose();
enumValue.dispose();
nullableNumValue.dispose();
nullableDoubleValue.dispose();
nullableIntValue.dispose();
nullableStringValue.dispose();
nullableBoolValue.dispose();
nullableDateTimeValue.dispose();
nullableEnumValue.dispose();
controllerValue.dispose();
objectValue.dispose();
super.dispose();
}
void setProperties(VoidCallback callback) {
setState(callback);
}
@override
Widget build(BuildContext context) {
return Text(stringValue.value, textDirection: TextDirection.ltr);
}
@override
String get restorationId => 'widget';
}
enum TestEnum {
one,
two,
three,
four,
}
| flutter/packages/flutter/test/widgets/restorable_property_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/restorable_property_test.dart",
"repo_id": "flutter",
"token_count": 9944
} | 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/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('SafeArea', () {
testWidgets('SafeArea - basic', (WidgetTester tester) async {
await tester.pumpWidget(
const MediaQuery(
data: MediaQueryData(padding: EdgeInsets.all(20.0)),
child: SafeArea(
left: false,
child: Placeholder(),
),
),
);
expect(tester.getTopLeft(find.byType(Placeholder)), const Offset(0.0, 20.0));
expect(tester.getBottomRight(find.byType(Placeholder)), const Offset(780.0, 580.0));
});
testWidgets('SafeArea - with minimums', (WidgetTester tester) async {
await tester.pumpWidget(
const MediaQuery(
data: MediaQueryData(padding: EdgeInsets.all(20.0)),
child: SafeArea(
top: false,
minimum: EdgeInsets.fromLTRB(0.0, 10.0, 20.0, 30.0),
child: Placeholder(),
),
),
);
expect(tester.getTopLeft(find.byType(Placeholder)), const Offset(20.0, 10.0));
expect(tester.getBottomRight(find.byType(Placeholder)), const Offset(780.0, 570.0));
});
testWidgets('SafeArea - nested', (WidgetTester tester) async {
await tester.pumpWidget(
const MediaQuery(
data: MediaQueryData(padding: EdgeInsets.all(20.0)),
child: SafeArea(
top: false,
child: SafeArea(
right: false,
child: Placeholder(),
),
),
),
);
expect(tester.getTopLeft(find.byType(Placeholder)), const Offset(20.0, 20.0));
expect(tester.getBottomRight(find.byType(Placeholder)), const Offset(780.0, 580.0));
});
testWidgets('SafeArea - changing', (WidgetTester tester) async {
const Widget child = SafeArea(
bottom: false,
child: SafeArea(
left: false,
bottom: false,
child: Placeholder(),
),
);
await tester.pumpWidget(
const MediaQuery(
data: MediaQueryData(padding: EdgeInsets.all(20.0)),
child: child,
),
);
expect(tester.getTopLeft(find.byType(Placeholder)), const Offset(20.0, 20.0));
expect(tester.getBottomRight(find.byType(Placeholder)), const Offset(780.0, 600.0));
await tester.pumpWidget(
const MediaQuery(
data: MediaQueryData(padding: EdgeInsets.only(
left: 100.0,
top: 30.0,
bottom: 40.0,
)),
child: child,
),
);
expect(tester.getTopLeft(find.byType(Placeholder)), const Offset(100.0, 30.0));
expect(tester.getBottomRight(find.byType(Placeholder)), const Offset(800.0, 600.0));
});
testWidgets('SafeArea - properties', (WidgetTester tester) async {
final SafeArea child = SafeArea(
right: false,
bottom: false,
child: Container(),
);
final DiagnosticPropertiesBuilder properties = DiagnosticPropertiesBuilder();
child.debugFillProperties(properties);
expect(properties.properties.any((DiagnosticsNode n) => n is FlagProperty && n.toString() == 'avoid left padding'), true);
expect(properties.properties.any((DiagnosticsNode n) => n is FlagProperty && n.toString() == 'avoid right padding'), false);
expect(properties.properties.any((DiagnosticsNode n) => n is FlagProperty && n.toString() == 'avoid top padding'), true);
expect(properties.properties.any((DiagnosticsNode n) => n is FlagProperty && n.toString() == 'avoid bottom padding'), false);
});
group('SafeArea maintains bottom viewPadding when specified for consumed bottom padding', () {
Widget boilerplate(Widget child) {
return Localizations(
locale: const Locale('en', 'us'),
delegates: const <LocalizationsDelegate<dynamic>>[
DefaultWidgetsLocalizations.delegate,
DefaultMaterialLocalizations.delegate,
],
child: Directionality(textDirection: TextDirection.ltr, child: child),
);
}
testWidgets('SafeArea alone.', (WidgetTester tester) async {
final Widget child = boilerplate(const SafeArea(
maintainBottomViewPadding: true,
child: Column(
children: <Widget>[
Expanded(child: Placeholder()),
],
),
));
await tester.pumpWidget(
MediaQuery(
data: const MediaQueryData(
padding: EdgeInsets.symmetric(vertical: 20.0),
viewPadding: EdgeInsets.only(bottom: 20.0),
),
child: child,
),
);
final Offset initialPoint = tester.getCenter(find.byType(Placeholder));
// Consume bottom padding - as if by the keyboard opening
await tester.pumpWidget(
MediaQuery(
data: const MediaQueryData(
padding: EdgeInsets.only(top: 20.0),
viewPadding: EdgeInsets.only(bottom: 20.0),
viewInsets: EdgeInsets.only(bottom: 300.0),
),
child: child,
),
);
final Offset finalPoint = tester.getCenter(find.byType(Placeholder));
expect(initialPoint, finalPoint);
});
testWidgets('SafeArea alone - partial ViewInsets consume Padding', (WidgetTester tester) async {
final Widget child = boilerplate(const SafeArea(
maintainBottomViewPadding: true,
child: Column(
children: <Widget>[
Expanded(child: Placeholder()),
],
),
));
await tester.pumpWidget(
MediaQuery(
data: const MediaQueryData(
viewPadding: EdgeInsets.only(bottom: 20.0),
),
child: child,
),
);
final Offset initialPoint = tester.getCenter(find.byType(Placeholder));
// Consume bottom padding - as if by the keyboard opening
await tester.pumpWidget(
MediaQuery(
data: const MediaQueryData(
viewPadding: EdgeInsets.only(bottom: 20.0),
viewInsets: EdgeInsets.only(bottom: 10.0),
),
child: child,
),
);
final Offset finalPoint = tester.getCenter(find.byType(Placeholder));
expect(initialPoint, finalPoint);
});
testWidgets('SafeArea with nested Scaffold', (WidgetTester tester) async {
final Widget child = boilerplate(const SafeArea(
maintainBottomViewPadding: true,
child: Scaffold(
resizeToAvoidBottomInset: false,
body: Column(
children: <Widget>[
Expanded(child: Placeholder()),
],
),
),
));
await tester.pumpWidget(
MediaQuery(
data: const MediaQueryData(
padding: EdgeInsets.symmetric(vertical: 20.0),
viewPadding: EdgeInsets.only(bottom: 20.0),
),
child: child,
),
);
final Offset initialPoint = tester.getCenter(find.byType(Placeholder));
// Consume bottom padding - as if by the keyboard opening
await tester.pumpWidget(
MediaQuery(
data: const MediaQueryData(
padding: EdgeInsets.only(top: 20.0),
viewPadding: EdgeInsets.only(bottom: 20.0),
viewInsets: EdgeInsets.only(bottom: 300.0),
),
child: child,
),
);
final Offset finalPoint = tester.getCenter(find.byType(Placeholder));
expect(initialPoint, finalPoint);
});
testWidgets('SafeArea with nested Scaffold - partial ViewInsets consume Padding', (WidgetTester tester) async {
final Widget child = boilerplate(const SafeArea(
maintainBottomViewPadding: true,
child: Scaffold(
resizeToAvoidBottomInset: false,
body: Column(
children: <Widget>[
Expanded(child: Placeholder()),
],
),
),
));
await tester.pumpWidget(
MediaQuery(
data: const MediaQueryData(
viewPadding: EdgeInsets.only(bottom: 20.0),
),
child: child,
),
);
final Offset initialPoint = tester.getCenter(find.byType(Placeholder));
// Consume bottom padding - as if by the keyboard opening
await tester.pumpWidget(
MediaQuery(
data: const MediaQueryData(
viewPadding: EdgeInsets.only(bottom: 20.0),
viewInsets: EdgeInsets.only(bottom: 10.0),
),
child: child,
),
);
final Offset finalPoint = tester.getCenter(find.byType(Placeholder));
expect(initialPoint, finalPoint);
});
});
});
group('SliverSafeArea', () {
Widget buildWidget(EdgeInsets mediaPadding, Widget sliver) {
late final ViewportOffset offset;
addTearDown(() => offset.dispose());
return MediaQuery(
data: MediaQueryData(padding: mediaPadding),
child: Directionality(
textDirection: TextDirection.ltr,
child: Viewport(
offset: offset = ViewportOffset.fixed(0.0),
slivers: <Widget>[
const SliverToBoxAdapter(child: SizedBox(width: 800.0, height: 100.0, child: Text('before'))),
sliver,
const SliverToBoxAdapter(child: SizedBox(width: 800.0, height: 100.0, child: Text('after'))),
],
),
),
);
}
void verify(WidgetTester tester, List<Rect> expectedRects) {
final List<Rect> testAnswers = tester.renderObjectList<RenderBox>(find.byType(SizedBox)).map<Rect>(
(RenderBox target) {
final Offset topLeft = target.localToGlobal(Offset.zero);
final Offset bottomRight = target.localToGlobal(target.size.bottomRight(Offset.zero));
return Rect.fromPoints(topLeft, bottomRight);
},
).toList();
expect(testAnswers, equals(expectedRects));
}
testWidgets('SliverSafeArea - basic', (WidgetTester tester) async {
await tester.pumpWidget(
buildWidget(
const EdgeInsets.all(20.0),
const SliverSafeArea(
left: false,
sliver: SliverToBoxAdapter(child: SizedBox(width: 800.0, height: 100.0, child: Text('padded'))),
),
),
);
verify(tester, <Rect>[
const Rect.fromLTWH(0.0, 0.0, 800.0, 100.0),
const Rect.fromLTWH(0.0, 120.0, 780.0, 100.0),
const Rect.fromLTWH(0.0, 240.0, 800.0, 100.0),
]);
});
testWidgets('SliverSafeArea - basic', (WidgetTester tester) async {
await tester.pumpWidget(
buildWidget(
const EdgeInsets.all(20.0),
const SliverSafeArea(
top: false,
minimum: EdgeInsets.fromLTRB(0.0, 10.0, 20.0, 30.0),
sliver: SliverToBoxAdapter(child: SizedBox(width: 800.0, height: 100.0, child: Text('padded'))),
),
),
);
verify(tester, <Rect>[
const Rect.fromLTWH(0.0, 0.0, 800.0, 100.0),
const Rect.fromLTWH(20.0, 110.0, 760.0, 100.0),
const Rect.fromLTWH(0.0, 240.0, 800.0, 100.0),
]);
});
testWidgets('SliverSafeArea - nested', (WidgetTester tester) async {
await tester.pumpWidget(
buildWidget(
const EdgeInsets.all(20.0),
const SliverSafeArea(
top: false,
sliver: SliverSafeArea(
right: false,
sliver: SliverToBoxAdapter(child: SizedBox(width: 800.0, height: 100.0, child: Text('padded'))),
),
),
),
);
verify(tester, <Rect>[
const Rect.fromLTWH(0.0, 0.0, 800.0, 100.0),
const Rect.fromLTWH(20.0, 120.0, 760.0, 100.0),
const Rect.fromLTWH(0.0, 240.0, 800.0, 100.0),
]);
});
testWidgets('SliverSafeArea - changing', (WidgetTester tester) async {
const Widget sliver = SliverSafeArea(
bottom: false,
sliver: SliverSafeArea(
left: false,
bottom: false,
sliver: SliverToBoxAdapter(child: SizedBox(width: 800.0, height: 100.0, child: Text('padded'))),
),
);
await tester.pumpWidget(
buildWidget(
const EdgeInsets.all(20.0),
sliver,
),
);
verify(tester, <Rect>[
const Rect.fromLTWH(0.0, 0.0, 800.0, 100.0),
const Rect.fromLTWH(20.0, 120.0, 760.0, 100.0),
const Rect.fromLTWH(0.0, 220.0, 800.0, 100.0),
]);
await tester.pumpWidget(
buildWidget(
const EdgeInsets.only(
left: 100.0,
top: 30.0,
bottom: 40.0,
),
sliver,
),
);
verify(tester, <Rect>[
const Rect.fromLTWH(0.0, 0.0, 800.0, 100.0),
const Rect.fromLTWH(100.0, 130.0, 700.0, 100.0),
const Rect.fromLTWH(0.0, 230.0, 800.0, 100.0),
]);
});
});
testWidgets('SliverSafeArea - properties', (WidgetTester tester) async {
const SliverSafeArea child = SliverSafeArea(
right: false,
bottom: false,
sliver: SliverToBoxAdapter(child: SizedBox(width: 800.0, height: 100.0, child: Text('padded'))),
);
final DiagnosticPropertiesBuilder properties = DiagnosticPropertiesBuilder();
child.debugFillProperties(properties);
expect(properties.properties.any((DiagnosticsNode n) => n is FlagProperty && n.toString() == 'avoid left padding'), true);
expect(properties.properties.any((DiagnosticsNode n) => n is FlagProperty && n.toString() == 'avoid right padding'), false);
expect(properties.properties.any((DiagnosticsNode n) => n is FlagProperty && n.toString() == 'avoid top padding'), true);
expect(properties.properties.any((DiagnosticsNode n) => n is FlagProperty && n.toString() == 'avoid bottom padding'), false);
});
}
| flutter/packages/flutter/test/widgets/safe_area_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/safe_area_test.dart",
"repo_id": "flutter",
"token_count": 6659
} | 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:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
final LogicalKeyboardKey modifierKey = defaultTargetPlatform == TargetPlatform.macOS
? LogicalKeyboardKey.metaLeft
: LogicalKeyboardKey.controlLeft;
void main() {
group('ScrollableDetails', (){
test('copyWith / == / hashCode', () {
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
final ScrollableDetails details = ScrollableDetails(
direction: AxisDirection.down,
controller: controller,
physics: const AlwaysScrollableScrollPhysics(),
decorationClipBehavior: Clip.hardEdge,
);
ScrollableDetails copiedDetails = details.copyWith();
expect(details, copiedDetails);
expect(details.hashCode, copiedDetails.hashCode);
copiedDetails = details.copyWith(
direction: AxisDirection.left,
physics: const ClampingScrollPhysics(),
decorationClipBehavior: Clip.none,
);
expect(
copiedDetails,
ScrollableDetails(
direction: AxisDirection.left,
controller: controller,
physics: const ClampingScrollPhysics(),
decorationClipBehavior: Clip.none,
),
);
});
test('toString', (){
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
const ScrollableDetails bareDetails = ScrollableDetails(
direction: AxisDirection.right,
);
expect(
bareDetails.toString(),
equalsIgnoringHashCodes(
'ScrollableDetails#00000(axisDirection: AxisDirection.right)'
),
);
final ScrollableDetails fullDetails = ScrollableDetails(
direction: AxisDirection.down,
controller: controller,
physics: const AlwaysScrollableScrollPhysics(),
decorationClipBehavior: Clip.hardEdge,
);
expect(
fullDetails.toString(),
equalsIgnoringHashCodes(
'ScrollableDetails#00000('
'axisDirection: AxisDirection.down, '
'scroll controller: ScrollController#00000(no clients), '
'scroll physics: AlwaysScrollableScrollPhysics, '
'decorationClipBehavior: Clip.hardEdge)'
),
);
});
test('deprecated clipBehavior is backwards compatible', (){
const ScrollableDetails deprecatedClip = ScrollableDetails(
direction: AxisDirection.right,
clipBehavior: Clip.hardEdge,
);
expect(deprecatedClip.clipBehavior, Clip.hardEdge);
expect(deprecatedClip.decorationClipBehavior, Clip.hardEdge);
const ScrollableDetails newClip = ScrollableDetails(
direction: AxisDirection.right,
decorationClipBehavior: Clip.hardEdge,
);
expect(newClip.clipBehavior, Clip.hardEdge);
expect(newClip.decorationClipBehavior, Clip.hardEdge);
});
});
testWidgets("Keyboard scrolling doesn't happen if scroll physics are set to NeverScrollableScrollPhysics", (WidgetTester tester) async {
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(platform: TargetPlatform.fuchsia),
home: CustomScrollView(
controller: controller,
physics: const NeverScrollableScrollPhysics(),
slivers: List<Widget>.generate(
20,
(int index) {
return SliverToBoxAdapter(
child: Focus(
autofocus: index == 0,
child: SizedBox(
key: ValueKey<String>('Box $index'),
height: 50.0,
),
),
);
},
),
),
),
);
await tester.pumpAndSettle();
expect(controller.position.pixels, equals(0.0));
expect(
tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)),
equals(const Rect.fromLTRB(0.0, 0.0, 800.0, 50.0)),
);
await tester.sendKeyDownEvent(modifierKey);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
await tester.sendKeyUpEvent(modifierKey);
await tester.pumpAndSettle();
expect(controller.position.pixels, equals(0.0));
expect(
tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)),
equals(const Rect.fromLTRB(0.0, 0.0, 800.0, 50.0)),
);
await tester.sendKeyDownEvent(modifierKey);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
await tester.sendKeyUpEvent(modifierKey);
await tester.pumpAndSettle();
expect(controller.position.pixels, equals(0.0));
expect(
tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)),
equals(const Rect.fromLTRB(0.0, 0.0, 800.0, 50.0)),
);
await tester.sendKeyEvent(LogicalKeyboardKey.pageDown);
await tester.pumpAndSettle();
expect(controller.position.pixels, equals(0.0));
expect(
tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)),
equals(const Rect.fromLTRB(0.0, 0.0, 800.0, 50.0)),
);
await tester.sendKeyEvent(LogicalKeyboardKey.pageUp);
await tester.pumpAndSettle();
expect(controller.position.pixels, equals(0.0));
expect(
tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)),
equals(const Rect.fromLTRB(0.0, 0.0, 800.0, 50.0)),
);
}, variant: KeySimulatorTransitModeVariant.all());
testWidgets('Vertical scrollables are scrolled when activated via keyboard.', (WidgetTester tester) async {
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(platform: TargetPlatform.fuchsia),
home: CustomScrollView(
controller: controller,
slivers: List<Widget>.generate(
20,
(int index) {
return SliverToBoxAdapter(
child: Focus(
autofocus: index == 0,
child: SizedBox(
key: ValueKey<String>('Box $index'),
height: 50.0,
),
),
);
},
),
),
),
);
await tester.pumpAndSettle();
expect(controller.position.pixels, equals(0.0));
expect(
tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)),
equals(const Rect.fromLTRB(0.0, 0.0, 800.0, 50.0)),
);
// We exclude the modifier keys here for web testing since default web shortcuts
// do not use a modifier key with arrow keys for ScrollActions.
if (!kIsWeb) {
await tester.sendKeyDownEvent(modifierKey);
}
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
if (!kIsWeb) {
await tester.sendKeyUpEvent(modifierKey);
}
await tester.pumpAndSettle();
expect(
tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)),
equals(const Rect.fromLTRB(0.0, -50.0, 800.0, 0.0)),
);
if (!kIsWeb) {
await tester.sendKeyDownEvent(modifierKey);
}
await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
if (!kIsWeb) {
await tester.sendKeyUpEvent(modifierKey);
}
await tester.pumpAndSettle();
expect(
tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)),
equals(const Rect.fromLTRB(0.0, 0.0, 800.0, 50.0)),
);
await tester.sendKeyEvent(LogicalKeyboardKey.pageDown);
await tester.pumpAndSettle();
expect(
tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)),
equals(const Rect.fromLTRB(0.0, -400.0, 800.0, -350.0)),
);
await tester.sendKeyEvent(LogicalKeyboardKey.pageUp);
await tester.pumpAndSettle();
expect(
tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)),
equals(const Rect.fromLTRB(0.0, 0.0, 800.0, 50.0)),
);
}, variant: KeySimulatorTransitModeVariant.all());
testWidgets('Horizontal scrollables are scrolled when activated via keyboard.', (WidgetTester tester) async {
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(platform: TargetPlatform.fuchsia),
home: CustomScrollView(
controller: controller,
scrollDirection: Axis.horizontal,
slivers: List<Widget>.generate(
20,
(int index) {
return SliverToBoxAdapter(
child: Focus(
autofocus: index == 0,
child: SizedBox(
key: ValueKey<String>('Box $index'),
width: 50.0,
),
),
);
},
),
),
),
);
await tester.pumpAndSettle();
expect(controller.position.pixels, equals(0.0));
expect(
tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)),
equals(const Rect.fromLTRB(0.0, 0.0, 50.0, 600.0)),
);
// We exclude the modifier keys here for web testing since default web shortcuts
// do not use a modifier key with arrow keys for ScrollActions.
if (!kIsWeb) {
await tester.sendKeyDownEvent(modifierKey);
}
await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
if (!kIsWeb) {
await tester.sendKeyUpEvent(modifierKey);
}
await tester.pumpAndSettle();
expect(
tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)),
equals(const Rect.fromLTRB(-50.0, 0.0, 0.0, 600.0)),
);
if (!kIsWeb) {
await tester.sendKeyDownEvent(modifierKey);
}
await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
if (!kIsWeb) {
await tester.sendKeyUpEvent(modifierKey);
}
await tester.pumpAndSettle();
expect(
tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)),
equals(const Rect.fromLTRB(0.0, 0.0, 50.0, 600.0)),
);
}, variant: KeySimulatorTransitModeVariant.all());
testWidgets('Horizontal scrollables are scrolled the correct direction in RTL locales.', (WidgetTester tester) async {
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(platform: TargetPlatform.fuchsia),
home: Directionality(
textDirection: TextDirection.rtl,
child: CustomScrollView(
controller: controller,
scrollDirection: Axis.horizontal,
slivers: List<Widget>.generate(
20,
(int index) {
return SliverToBoxAdapter(
child: Focus(
autofocus: index == 0,
child: SizedBox(
key: ValueKey<String>('Box $index'),
width: 50.0,
),
),
);
},
),
),
),
),
);
await tester.pumpAndSettle();
expect(controller.position.pixels, equals(0.0));
expect(
tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)),
equals(const Rect.fromLTRB(750.0, 0.0, 800.0, 600.0)),
);
// We exclude the modifier keys here for web testing since default web shortcuts
// do not use a modifier key with arrow keys for ScrollActions.
if (!kIsWeb) {
await tester.sendKeyDownEvent(modifierKey);
}
await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
if (!kIsWeb) {
await tester.sendKeyUpEvent(modifierKey);
}
await tester.pumpAndSettle();
expect(
tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)),
equals(const Rect.fromLTRB(800.0, 0.0, 850.0, 600.0)),
);
if (!kIsWeb) {
await tester.sendKeyDownEvent(modifierKey);
}
await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
if (!kIsWeb) {
await tester.sendKeyUpEvent(modifierKey);
}
await tester.pumpAndSettle();
expect(
tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)),
equals(const Rect.fromLTRB(750.0, 0.0, 800.0, 600.0)),
);
}, variant: KeySimulatorTransitModeVariant.all());
testWidgets('Reversed vertical scrollables are scrolled when activated via keyboard.', (WidgetTester tester) async {
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
final FocusNode focusNode = FocusNode(debugLabel: 'SizedBox');
addTearDown(focusNode.dispose);
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(platform: TargetPlatform.fuchsia),
home: CustomScrollView(
controller: controller,
reverse: true,
slivers: List<Widget>.generate(
20,
(int index) {
return SliverToBoxAdapter(
child: Focus(
focusNode: focusNode,
child: SizedBox(
key: ValueKey<String>('Box $index'),
height: 50.0,
),
),
);
},
),
),
),
);
focusNode.requestFocus();
await tester.pumpAndSettle();
expect(controller.position.pixels, equals(0.0));
expect(
tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)),
equals(const Rect.fromLTRB(0.0, 550.0, 800.0, 600.0)),
);
// We exclude the modifier keys here for web testing since default web shortcuts
// do not use a modifier key with arrow keys for ScrollActions.
if (!kIsWeb) {
await tester.sendKeyDownEvent(modifierKey);
}
await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
if (!kIsWeb) {
await tester.sendKeyUpEvent(modifierKey);
}
await tester.pumpAndSettle();
expect(
tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)),
equals(const Rect.fromLTRB(0.0, 600.0, 800.0, 650.0)),
);
if (!kIsWeb) {
await tester.sendKeyDownEvent(modifierKey);
}
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
if (!kIsWeb) {
await tester.sendKeyUpEvent(modifierKey);
}
await tester.pumpAndSettle();
expect(
tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)),
equals(const Rect.fromLTRB(0.0, 550.0, 800.0, 600.0)),
);
await tester.sendKeyEvent(LogicalKeyboardKey.pageUp);
await tester.pumpAndSettle();
expect(
tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)),
equals(const Rect.fromLTRB(0.0, 950.0, 800.0, 1000.0)),
);
await tester.sendKeyEvent(LogicalKeyboardKey.pageDown);
await tester.pumpAndSettle();
expect(
tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)),
equals(const Rect.fromLTRB(0.0, 550.0, 800.0, 600.0)),
);
}, variant: KeySimulatorTransitModeVariant.all());
testWidgets('Reversed horizontal scrollables are scrolled when activated via keyboard.', (WidgetTester tester) async {
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
final FocusNode focusNode = FocusNode(debugLabel: 'SizedBox');
addTearDown(focusNode.dispose);
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(platform: TargetPlatform.fuchsia),
home: CustomScrollView(
controller: controller,
scrollDirection: Axis.horizontal,
reverse: true,
slivers: List<Widget>.generate(
20,
(int index) {
return SliverToBoxAdapter(
child: Focus(
focusNode: focusNode,
child: SizedBox(
key: ValueKey<String>('Box $index'),
width: 50.0,
),
),
);
},
),
),
),
);
focusNode.requestFocus();
await tester.pumpAndSettle();
expect(controller.position.pixels, equals(0.0));
expect(
tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)),
equals(const Rect.fromLTRB(750.0, 0.0, 800.0, 600.00)),
);
// We exclude the modifier keys here for web testing since default web shortcuts
// do not use a modifier key with arrow keys for ScrollActions.
if (!kIsWeb) {
await tester.sendKeyDownEvent(modifierKey);
}
await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
if (!kIsWeb) {
await tester.sendKeyUpEvent(modifierKey);
}
await tester.pumpAndSettle();
expect(
tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)),
equals(const Rect.fromLTRB(800.0, 0.0, 850.0, 600.0)),
);
if (!kIsWeb) {
await tester.sendKeyDownEvent(modifierKey);
}
await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
if (!kIsWeb) {
await tester.sendKeyUpEvent(modifierKey);
}
await tester.pumpAndSettle();
}, variant: KeySimulatorTransitModeVariant.all());
testWidgets('Custom scrollables with a center sliver are scrolled when activated via keyboard.', (WidgetTester tester) async {
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
final List<String> items = List<String>.generate(20, (int index) => 'Item $index');
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(platform: TargetPlatform.fuchsia),
home: CustomScrollView(
controller: controller,
center: const ValueKey<String>('Center'),
slivers: items.map<Widget>(
(String item) {
return SliverToBoxAdapter(
key: item == 'Item 10' ? const ValueKey<String>('Center') : null,
child: Focus(
autofocus: item == 'Item 10',
child: Container(
key: ValueKey<String>(item),
alignment: Alignment.center,
height: 100,
child: Text(item),
),
),
);
},
).toList(),
),
),
);
await tester.pumpAndSettle();
expect(controller.position.pixels, equals(0.0));
expect(
tester.getRect(find.byKey(const ValueKey<String>('Item 10'), skipOffstage: false)),
equals(const Rect.fromLTRB(0.0, 0.0, 800.0, 100.0)),
);
for (int i = 0; i < 10; ++i) {
// We exclude the modifier keys here for web testing since default web shortcuts
// do not use a modifier key with arrow keys for ScrollActions.
if (!kIsWeb) {
await tester.sendKeyDownEvent(modifierKey);
}
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
if (!kIsWeb) {
await tester.sendKeyUpEvent(modifierKey);
}
await tester.pumpAndSettle();
}
// Starts at #10 already, so doesn't work out to 500.0 because it hits bottom.
expect(controller.position.pixels, equals(400.0));
expect(
tester.getRect(find.byKey(const ValueKey<String>('Item 10'), skipOffstage: false)),
equals(const Rect.fromLTRB(0.0, -400.0, 800.0, -300.0)),
);
for (int i = 0; i < 10; ++i) {
if (!kIsWeb) {
await tester.sendKeyDownEvent(modifierKey);
}
await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
if (!kIsWeb) {
await tester.sendKeyUpEvent(modifierKey);
}
await tester.pumpAndSettle();
}
// Goes up two past "center" where it started, so negative.
expect(controller.position.pixels, equals(-100.0));
expect(
tester.getRect(find.byKey(const ValueKey<String>('Item 10'), skipOffstage: false)),
equals(const Rect.fromLTRB(0.0, 100.0, 800.0, 200.0)),
);
}, variant: KeySimulatorTransitModeVariant.all());
testWidgets('Can scroll using intents only', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: ListView(
children: const <Widget>[
SizedBox(height: 600.0, child: Text('The cow as white as milk')),
SizedBox(height: 600.0, child: Text('The cape as red as blood')),
SizedBox(height: 600.0, child: Text('The hair as yellow as corn')),
],
),
),
);
expect(find.text('The cow as white as milk'), findsOneWidget);
expect(find.text('The cape as red as blood'), findsNothing);
expect(find.text('The hair as yellow as corn'), findsNothing);
Actions.invoke(tester.element(find.byType(SliverList)), const ScrollIntent(direction: AxisDirection.down, type: ScrollIncrementType.page));
await tester.pump(); // start scroll
await tester.pump(const Duration(milliseconds: 1000)); // end scroll
expect(find.text('The cow as white as milk'), findsOneWidget);
expect(find.text('The cape as red as blood'), findsOneWidget);
expect(find.text('The hair as yellow as corn'), findsNothing);
Actions.invoke(tester.element(find.byType(SliverList)), const ScrollIntent(direction: AxisDirection.down, type: ScrollIncrementType.page));
await tester.pump(); // start scroll
await tester.pump(const Duration(milliseconds: 1000)); // end scroll
expect(find.text('The cow as white as milk'), findsNothing);
expect(find.text('The cape as red as blood'), findsOneWidget);
expect(find.text('The hair as yellow as corn'), findsOneWidget);
});
}
| flutter/packages/flutter/test/widgets/scrollable_helpers_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/scrollable_helpers_test.dart",
"repo_id": "flutter",
"token_count": 9513
} | 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 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'semantics_tester.dart';
void main() {
testWidgets('Semantics 1', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
// smoketest
await tester.pumpWidget(
Semantics(
container: true,
child: Semantics(
label: 'test1',
textDirection: TextDirection.ltr,
selected: true,
child: Container(),
),
),
);
expect(semantics, hasSemantics(TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
id: 1,
label: 'test1',
rect: TestSemantics.fullScreen,
flags: SemanticsFlag.isSelected.index,
),
],
)));
// control for forking
await tester.pumpWidget(
Semantics(
container: true,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
SizedBox(
height: 10.0,
child: Semantics(
label: 'child1',
textDirection: TextDirection.ltr,
selected: true,
),
),
SizedBox(
height: 10.0,
child: ExcludeSemantics(
child: Semantics(
label: 'child1',
textDirection: TextDirection.ltr,
selected: true,
),
),
),
],
),
),
);
expect(semantics, hasSemantics(TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
id: 1,
label: 'child1',
rect: TestSemantics.fullScreen,
flags: SemanticsFlag.isSelected.index,
),
],
)));
// forking semantics
await tester.pumpWidget(
Semantics(
container: true,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
SizedBox(
height: 10.0,
child: Semantics(
label: 'child1',
textDirection: TextDirection.ltr,
selected: true,
),
),
SizedBox(
height: 10.0,
child: ExcludeSemantics(
excluding: false,
child: Semantics(
label: 'child2',
textDirection: TextDirection.ltr,
selected: true,
),
),
),
],
),
),
);
expect(semantics, hasSemantics(TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
id: 1,
rect: TestSemantics.fullScreen,
children: <TestSemantics>[
TestSemantics(
id: 2,
label: 'child1',
rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 10.0),
flags: SemanticsFlag.isSelected.index,
),
TestSemantics(
id: 3,
label: 'child2',
rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 10.0),
flags: SemanticsFlag.isSelected.index,
),
],
),
],
), ignoreTransform: true));
// toggle a branch off
await tester.pumpWidget(
Semantics(
container: true,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
SizedBox(
height: 10.0,
child: Semantics(
label: 'child1',
textDirection: TextDirection.ltr,
selected: true,
),
),
SizedBox(
height: 10.0,
child: ExcludeSemantics(
child: Semantics(
label: 'child2',
textDirection: TextDirection.ltr,
selected: true,
),
),
),
],
),
),
);
expect(semantics, hasSemantics(TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
id: 1,
label: 'child1',
rect: TestSemantics.fullScreen,
flags: SemanticsFlag.isSelected.index,
),
],
)));
// toggle a branch back on
await tester.pumpWidget(
Semantics(
container: true,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
SizedBox(
height: 10.0,
child: Semantics(
label: 'child1',
textDirection: TextDirection.ltr,
selected: true,
),
),
SizedBox(
height: 10.0,
child: ExcludeSemantics(
excluding: false,
child: Semantics(
label: 'child2',
textDirection: TextDirection.ltr,
selected: true,
),
),
),
],
),
),
);
expect(semantics, hasSemantics(TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
id: 1,
rect: TestSemantics.fullScreen,
children: <TestSemantics>[
TestSemantics(
id: 4,
label: 'child1',
rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 10.0),
flags: SemanticsFlag.isSelected.index,
),
TestSemantics(
id: 3,
label: 'child2',
rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 10.0),
flags: SemanticsFlag.isSelected.index,
),
],
),
],
), ignoreTransform: true));
semantics.dispose();
});
}
| flutter/packages/flutter/test/widgets/semantics_1_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/semantics_1_test.dart",
"repo_id": "flutter",
"token_count": 3464
} | 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/foundation.dart';
import 'package:flutter/physics.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
export 'dart:ui' show SemanticsAction, SemanticsFlag;
export 'package:flutter/rendering.dart' show SemanticsData;
const String _matcherHelp = 'Try dumping the semantics with debugDumpSemanticsTree(DebugSemanticsDumpOrder.inverseHitTest) from the package:flutter/rendering.dart library to see what the semantics tree looks like.';
/// Test semantics data that is compared against real semantics tree.
///
/// Useful with [hasSemantics] and [SemanticsTester] to test the contents of the
/// semantics tree.
class TestSemantics {
/// Creates an object with some test semantics data.
///
/// The [id] field is required. The root node has an id of zero. Other nodes
/// are given a unique id when they are created, in a predictable fashion, and
/// so these values can be hard-coded.
///
/// The [rect] field is required and has no default. Convenient values are
/// available:
///
/// * [TestSemantics.rootRect]: 2400x1600, the test screen's size in physical
/// pixels, useful for the node with id zero.
///
/// * [TestSemantics.fullScreen] 800x600, the test screen's size in logical
/// pixels, useful for other full-screen widgets.
TestSemantics({
this.id,
this.flags = 0,
this.actions = 0,
this.label = '',
this.value = '',
this.tooltip = '',
this.increasedValue = '',
this.decreasedValue = '',
this.hint = '',
this.textDirection,
this.rect,
this.transform,
this.elevation,
this.thickness,
this.textSelection,
this.children = const <TestSemantics>[],
this.scrollIndex,
this.scrollChildren,
Iterable<SemanticsTag>? tags,
}) : assert(flags is int || flags is List<SemanticsFlag>),
assert(actions is int || actions is List<SemanticsAction>),
tags = tags?.toSet() ?? <SemanticsTag>{};
/// Creates an object with some test semantics data, with the [id] and [rect]
/// set to the appropriate values for the root node.
TestSemantics.root({
this.flags = 0,
this.actions = 0,
this.label = '',
this.value = '',
this.increasedValue = '',
this.decreasedValue = '',
this.hint = '',
this.tooltip = '',
this.textDirection,
this.transform,
this.textSelection,
this.children = const <TestSemantics>[],
this.scrollIndex,
this.scrollChildren,
Iterable<SemanticsTag>? tags,
}) : id = 0,
assert(flags is int || flags is List<SemanticsFlag>),
assert(actions is int || actions is List<SemanticsAction>),
rect = TestSemantics.rootRect,
elevation = 0.0,
thickness = 0.0,
tags = tags?.toSet() ?? <SemanticsTag>{};
/// Creates an object with some test semantics data, with the [id] and [rect]
/// set to the appropriate values for direct children of the root node.
///
/// The [transform] is set to a 3.0 scale (to account for the
/// [dart:ui.FlutterView.devicePixelRatio] being 3.0 on the test
/// pseudo-device).
///
/// The [rect] field is required and has no default. The
/// [TestSemantics.fullScreen] property may be useful as a value; it describes
/// an 800x600 rectangle, which is the test screen's size in logical pixels.
TestSemantics.rootChild({
this.id,
this.flags = 0,
this.actions = 0,
this.label = '',
this.hint = '',
this.value = '',
this.tooltip = '',
this.increasedValue = '',
this.decreasedValue = '',
this.textDirection,
this.rect,
Matrix4? transform,
this.elevation,
this.thickness,
this.textSelection,
this.children = const <TestSemantics>[],
this.scrollIndex,
this.scrollChildren,
Iterable<SemanticsTag>? tags,
}) : assert(flags is int || flags is List<SemanticsFlag>),
assert(actions is int || actions is List<SemanticsAction>),
transform = _applyRootChildScale(transform),
tags = tags?.toSet() ?? <SemanticsTag>{};
/// The unique identifier for this node.
///
/// The root node has an id of zero. Other nodes are given a unique id when
/// they are created.
final int? id;
/// The [SemanticsFlag]s set on this node.
///
/// There are two ways to specify this property: as an `int` that encodes the
/// flags as a bit field, or as a `List<SemanticsFlag>` that are _on_.
///
/// Using `List<SemanticsFlag>` is recommended due to better readability.
final dynamic flags;
/// The [SemanticsAction]s set on this node.
///
/// There are two ways to specify this property: as an `int` that encodes the
/// actions as a bit field, or as a `List<SemanticsAction>`.
///
/// Using `List<SemanticsAction>` is recommended due to better readability.
///
/// The tester does not check the function corresponding to the action, but
/// only its existence.
final dynamic actions;
/// A textual description of this node.
final String label;
/// A textual description for the value of this node.
final String value;
/// What [value] will become after [SemanticsAction.increase] has been
/// performed.
final String increasedValue;
/// What [value] will become after [SemanticsAction.decrease] has been
/// performed.
final String decreasedValue;
/// A brief textual description of the result of the action that can be
/// performed on this node.
final String hint;
/// A textual tooltip of this node.
final String tooltip;
/// The reading direction of the [label].
///
/// Even if this is not set, the [hasSemantics] matcher will verify that if a
/// label is present on the [SemanticsNode], a [SemanticsNode.textDirection]
/// is also set.
final TextDirection? textDirection;
/// The bounding box for this node in its coordinate system.
///
/// Convenient values are available:
///
/// * [TestSemantics.rootRect]: 2400x1600, the test screen's size in physical
/// pixels, useful for the node with id zero.
///
/// * [TestSemantics.fullScreen] 800x600, the test screen's size in logical
/// pixels, useful for other full-screen widgets.
final Rect? rect;
/// The test screen's size in physical pixels, typically used as the [rect]
/// for the node with id zero.
///
/// See also:
///
/// * [TestSemantics.root], which uses this value to describe the root
/// node.
static const Rect rootRect = Rect.fromLTWH(0.0, 0.0, 2400.0, 1800.0);
/// The test screen's size in logical pixels, useful for the [rect] of
/// full-screen widgets other than the root node.
static const Rect fullScreen = Rect.fromLTWH(0.0, 0.0, 800.0, 600.0);
/// The transform from this node's coordinate system to its parent's coordinate system.
///
/// By default, the transform is null, which represents the identity
/// transformation (i.e., that this node has the same coordinate system as its
/// parent).
final Matrix4? transform;
/// The elevation of this node relative to the parent node.
///
/// See also:
///
/// * [SemanticsConfiguration.elevation] for a detailed discussion regarding
/// elevation and semantics.
final double? elevation;
/// The extend that this node occupies in z-direction starting at [elevation].
///
/// See also:
///
/// * [SemanticsConfiguration.thickness] for a more detailed definition.
final double? thickness;
/// The index of the first visible semantic node within a scrollable.
final int? scrollIndex;
/// The total number of semantic nodes within a scrollable.
final int? scrollChildren;
final TextSelection? textSelection;
static Matrix4 _applyRootChildScale(Matrix4? transform) {
final Matrix4 result = Matrix4.diagonal3Values(3.0, 3.0, 1.0);
if (transform != null) {
result.multiply(transform);
}
return result;
}
/// The children of this node.
final List<TestSemantics> children;
/// The tags of this node.
final Set<SemanticsTag> tags;
bool _matches(
SemanticsNode? node,
Map<dynamic, dynamic> matchState, {
bool ignoreRect = false,
bool ignoreTransform = false,
bool ignoreId = false,
DebugSemanticsDumpOrder childOrder = DebugSemanticsDumpOrder.inverseHitTest,
}) {
bool fail(String message) {
matchState[TestSemantics] = message;
return false;
}
if (node == null) {
return fail('could not find node with id $id.');
}
if (!ignoreId && id != node.id) {
return fail('expected node id $id but found id ${node.id}.');
}
final SemanticsData nodeData = node.getSemanticsData();
final int flagsBitmask = flags is int
? flags as int
: (flags as List<SemanticsFlag>).fold<int>(0, (int bitmask, SemanticsFlag flag) => bitmask | flag.index);
if (flagsBitmask != nodeData.flags) {
return fail('expected node id $id to have flags $flags but found flags ${nodeData.flags}.');
}
final int actionsBitmask = actions is int
? actions as int
: (actions as List<SemanticsAction>).fold<int>(0, (int bitmask, SemanticsAction action) => bitmask | action.index);
if (actionsBitmask != nodeData.actions) {
return fail('expected node id $id to have actions $actions but found actions ${nodeData.actions}.');
}
if (label != nodeData.label) {
return fail('expected node id $id to have label "$label" but found label "${nodeData.label}".');
}
if (value != nodeData.value) {
return fail('expected node id $id to have value "$value" but found value "${nodeData.value}".');
}
if (increasedValue != nodeData.increasedValue) {
return fail('expected node id $id to have increasedValue "$increasedValue" but found value "${nodeData.increasedValue}".');
}
if (decreasedValue != nodeData.decreasedValue) {
return fail('expected node id $id to have decreasedValue "$decreasedValue" but found value "${nodeData.decreasedValue}".');
}
if (hint != nodeData.hint) {
return fail('expected node id $id to have hint "$hint" but found hint "${nodeData.hint}".');
}
if (tooltip != nodeData.tooltip) {
return fail('expected node id $id to have tooltip "$tooltip" but found hint "${nodeData.tooltip}".');
}
if (textDirection != null && textDirection != nodeData.textDirection) {
return fail('expected node id $id to have textDirection "$textDirection" but found "${nodeData.textDirection}".');
}
if ((nodeData.label != '' || nodeData.value != '' || nodeData.hint != '' || node.increasedValue != '' || node.decreasedValue != '') && nodeData.textDirection == null) {
return fail('expected node id $id, which has a label, value, or hint, to have a textDirection, but it did not.');
}
if (!ignoreRect && rect != nodeData.rect) {
return fail('expected node id $id to have rect $rect but found rect ${nodeData.rect}.');
}
if (!ignoreTransform && transform != nodeData.transform) {
return fail('expected node id $id to have transform $transform but found transform:\n${nodeData.transform}.');
}
if (elevation != null && elevation != nodeData.elevation) {
return fail('expected node id $id to have elevation $elevation but found elevation:\n${nodeData.elevation}.');
}
if (thickness != null && thickness != nodeData.thickness) {
return fail('expected node id $id to have thickness $thickness but found thickness:\n${nodeData.thickness}.');
}
if (textSelection?.baseOffset != nodeData.textSelection?.baseOffset || textSelection?.extentOffset != nodeData.textSelection?.extentOffset) {
return fail('expected node id $id to have textSelection [${textSelection?.baseOffset}, ${textSelection?.end}] but found: [${nodeData.textSelection?.baseOffset}, ${nodeData.textSelection?.extentOffset}].');
}
if (scrollIndex != null && scrollIndex != nodeData.scrollIndex) {
return fail('expected node id $id to have scrollIndex $scrollIndex but found scrollIndex ${nodeData.scrollIndex}.');
}
if (scrollChildren != null && scrollChildren != nodeData.scrollChildCount) {
return fail('expected node id $id to have scrollIndex $scrollChildren but found scrollIndex ${nodeData.scrollChildCount}.');
}
final int childrenCount = node.mergeAllDescendantsIntoThisNode ? 0 : node.childrenCount;
if (children.length != childrenCount) {
return fail('expected node id $id to have ${children.length} child${ children.length == 1 ? "" : "ren" } but found $childrenCount.');
}
if (children.isEmpty) {
return true;
}
bool result = true;
final Iterator<TestSemantics> it = children.iterator;
for (final SemanticsNode child in node.debugListChildrenInOrder(childOrder)) {
it.moveNext();
final bool childMatches = it.current._matches(
child,
matchState,
ignoreRect: ignoreRect,
ignoreTransform: ignoreTransform,
ignoreId: ignoreId,
childOrder: childOrder,
);
if (!childMatches) {
result = false;
return false;
}
}
if (it.moveNext()) {
return false;
}
return result;
}
@override
String toString([ int indentAmount = 0 ]) {
final String indent = ' ' * indentAmount;
final StringBuffer buf = StringBuffer();
buf.writeln('$indent${objectRuntimeType(this, 'TestSemantics')}(');
if (id != null) {
buf.writeln('$indent id: $id,');
}
if (flags is int && flags != 0 || flags is List<SemanticsFlag> && (flags as List<SemanticsFlag>).isNotEmpty) {
buf.writeln('$indent flags: ${SemanticsTester._flagsToSemanticsFlagExpression(flags)},');
}
if (actions is int && actions != 0 || actions is List<SemanticsAction> && (actions as List<SemanticsAction>).isNotEmpty) {
buf.writeln('$indent actions: ${SemanticsTester._actionsToSemanticsActionExpression(actions)},');
}
if (label != '') {
buf.writeln("$indent label: '$label',");
}
if (value != '') {
buf.writeln("$indent value: '$value',");
}
if (increasedValue != '') {
buf.writeln("$indent increasedValue: '$increasedValue',");
}
if (decreasedValue != '') {
buf.writeln("$indent decreasedValue: '$decreasedValue',");
}
if (hint != '') {
buf.writeln("$indent hint: '$hint',");
}
if (tooltip != '') {
buf.writeln("$indent tooltip: '$tooltip',");
}
if (textDirection != null) {
buf.writeln('$indent textDirection: $textDirection,');
}
if (textSelection?.isValid ?? false) {
buf.writeln('$indent textSelection:\n[${textSelection!.start}, ${textSelection!.end}],');
}
if (scrollIndex != null) {
buf.writeln('$indent scrollIndex: $scrollIndex,');
}
if (rect != null) {
buf.writeln('$indent rect: $rect,');
}
if (transform != null) {
buf.writeln('$indent transform:\n${transform.toString().trim().split('\n').map<String>((String line) => '$indent $line').join('\n')},');
}
if (elevation != null) {
buf.writeln('$indent elevation: $elevation,');
}
if (thickness != null) {
buf.writeln('$indent thickness: $thickness,');
}
buf.writeln('$indent children: <TestSemantics>[');
for (final TestSemantics child in children) {
buf.writeln('${child.toString(indentAmount + 2)},');
}
buf.writeln('$indent ],');
buf.write('$indent)');
return buf.toString();
}
}
/// Ensures that the given widget tester has a semantics tree to test.
///
/// Useful with [hasSemantics] to test the contents of the semantics tree.
class SemanticsTester {
/// Creates a semantics tester for the given widget tester.
///
/// You should call [dispose] at the end of a test that creates a semantics
/// tester.
SemanticsTester(this.tester) {
_semanticsHandle = tester.ensureSemantics();
// This _extra_ clean-up is needed for the case when a test fails and
// therefore fails to call dispose() explicitly. The test is still required
// to call dispose() explicitly, because the semanticsOwner check is
// performed irrespective of whether the owner was created via
// SemanticsTester or directly. When the test succeeds, this tear-down
// becomes a no-op.
addTearDown(dispose);
}
/// The widget tester that this object is testing the semantics of.
final WidgetTester tester;
SemanticsHandle? _semanticsHandle;
/// Release resources held by this semantics tester.
///
/// Call this function at the end of any test that uses a semantics tester. It
/// is OK to call this function multiple times. If the resources have already
/// been released, the subsequent calls have no effect.
@mustCallSuper
void dispose() {
_semanticsHandle?.dispose();
_semanticsHandle = null;
}
@override
String toString() => 'SemanticsTester for ${tester.binding.pipelineOwner.semanticsOwner?.rootSemanticsNode}';
bool _stringAttributesEqual(List<StringAttribute> first, List<StringAttribute> second) {
if (first.length != second.length) {
return false;
}
for (int i = 0; i < first.length; i++) {
if (first[i] is SpellOutStringAttribute &&
(second[i] is! SpellOutStringAttribute ||
second[i].range != first[i].range)) {
return false;
}
if (first[i] is LocaleStringAttribute &&
(second[i] is! LocaleStringAttribute ||
second[i].range != first[i].range ||
(second[i] as LocaleStringAttribute).locale != (second[i] as LocaleStringAttribute).locale)) {
return false;
}
}
return true;
}
/// Returns all semantics nodes in the current semantics tree whose properties
/// match the non-null arguments.
///
/// If multiple arguments are non-null, each of the returned nodes must match
/// on all of them.
///
/// If `ancestor` is not null, only the descendants of it are returned.
Iterable<SemanticsNode> nodesWith({
AttributedString? attributedLabel,
AttributedString? attributedValue,
AttributedString? attributedHint,
String? label,
String? value,
String? hint,
TextDirection? textDirection,
List<SemanticsAction>? actions,
List<SemanticsFlag>? flags,
Set<SemanticsTag>? tags,
double? scrollPosition,
double? scrollExtentMax,
double? scrollExtentMin,
int? currentValueLength,
int? maxValueLength,
SemanticsNode? ancestor,
}) {
bool checkNode(SemanticsNode node) {
if (label != null && node.label != label) {
return false;
}
if (attributedLabel != null &&
(attributedLabel.string != node.attributedLabel.string ||
!_stringAttributesEqual(attributedLabel.attributes, node.attributedLabel.attributes))) {
return false;
}
if (value != null && node.value != value) {
return false;
}
if (attributedValue != null &&
(attributedValue.string != node.attributedValue.string ||
!_stringAttributesEqual(attributedValue.attributes, node.attributedValue.attributes))) {
return false;
}
if (hint != null && node.hint != hint) {
return false;
}
if (attributedHint != null &&
(attributedHint.string != node.attributedHint.string ||
!_stringAttributesEqual(attributedHint.attributes, node.attributedHint.attributes))) {
return false;
}
if (textDirection != null && node.textDirection != textDirection) {
return false;
}
if (actions != null) {
final int expectedActions = actions.fold<int>(0, (int value, SemanticsAction action) => value | action.index);
final int actualActions = node.getSemanticsData().actions;
if (expectedActions != actualActions) {
return false;
}
}
if (flags != null) {
final int expectedFlags = flags.fold<int>(0, (int value, SemanticsFlag flag) => value | flag.index);
final int actualFlags = node.getSemanticsData().flags;
if (expectedFlags != actualFlags) {
return false;
}
}
if (tags != null) {
final Set<SemanticsTag>? actualTags = node.getSemanticsData().tags;
if (!setEquals<SemanticsTag>(actualTags, tags)) {
return false;
}
}
if (scrollPosition != null && !nearEqual(node.scrollPosition, scrollPosition, 0.1)) {
return false;
}
if (scrollExtentMax != null && !nearEqual(node.scrollExtentMax, scrollExtentMax, 0.1)) {
return false;
}
if (scrollExtentMin != null && !nearEqual(node.scrollExtentMin, scrollExtentMin, 0.1)) {
return false;
}
if (currentValueLength != null && node.currentValueLength != currentValueLength) {
return false;
}
if (maxValueLength != null && node.maxValueLength != maxValueLength) {
return false;
}
return true;
}
final List<SemanticsNode> result = <SemanticsNode>[];
bool visit(SemanticsNode node) {
if (checkNode(node)) {
result.add(node);
}
node.visitChildren(visit);
return true;
}
if (ancestor != null) {
visit(ancestor);
} else {
visit(tester.binding.pipelineOwner.semanticsOwner!.rootSemanticsNode!);
}
return result;
}
/// Generates an expression that creates a [TestSemantics] reflecting the
/// current tree of [SemanticsNode]s.
///
/// Use this method to generate code for unit tests. It works similar to
/// screenshot testing. The very first time you add semantics to a widget you
/// verify manually that the widget behaves correctly. You then use this
/// method to generate test code for this widget.
///
/// Example:
///
/// ```dart
/// testWidgets('generate code for MyWidget', (WidgetTester tester) async {
/// var semantics = SemanticsTester(tester);
/// await tester.pumpWidget(MyWidget());
/// print(semantics.generateTestSemanticsExpressionForCurrentSemanticsTree());
/// semantics.dispose();
/// });
/// ```
///
/// You can now copy the code printed to the console into a unit test:
///
/// ```dart
/// testWidgets('generate code for MyWidget', (WidgetTester tester) async {
/// var semantics = SemanticsTester(tester);
/// await tester.pumpWidget(MyWidget());
/// expect(semantics, hasSemantics(
/// // Generated code:
/// TestSemantics(
/// ... properties and child nodes ...
/// ),
/// ignoreRect: true,
/// ignoreTransform: true,
/// ignoreId: true,
/// ));
/// semantics.dispose();
/// });
/// ```
///
/// At this point the unit test should automatically pass because it was
/// generated from the actual [SemanticsNode]s. Next time the semantics tree
/// changes, the test code may either be updated manually, or regenerated and
/// replaced using this method again.
///
/// Avoid submitting huge piles of generated test code. This will make test
/// code hard to review and it will make it tempting to regenerate test code
/// every time and ignore potential regressions. Make sure you do not
/// over-test. Prefer breaking your widgets into smaller widgets and test them
/// individually.
String generateTestSemanticsExpressionForCurrentSemanticsTree(DebugSemanticsDumpOrder childOrder) {
final SemanticsNode? node = tester.binding.pipelineOwner.semanticsOwner?.rootSemanticsNode;
return _generateSemanticsTestForNode(node, 0, childOrder);
}
static String _flagsToSemanticsFlagExpression(dynamic flags) {
Iterable<SemanticsFlag> list;
if (flags is int) {
list = SemanticsFlag.values
.where((SemanticsFlag flag) => (flag.index & flags) != 0);
} else {
list = flags as List<SemanticsFlag>;
}
return '<SemanticsFlag>[${list.join(', ')}]';
}
static String _tagsToSemanticsTagExpression(Set<SemanticsTag> tags) {
return '<SemanticsTag>[${tags.map<String>((SemanticsTag tag) => "const SemanticsTag('${tag.name}')").join(', ')}]';
}
static String _actionsToSemanticsActionExpression(dynamic actions) {
Iterable<SemanticsAction> list;
if (actions is int) {
list = SemanticsAction.values
.where((SemanticsAction action) => (action.index & actions) != 0);
} else {
list = actions as List<SemanticsAction>;
}
return '<SemanticsAction>[${list.join(', ')}]';
}
/// Recursively generates [TestSemantics] code for [node] and its children,
/// indenting the expression by `indentAmount`.
static String _generateSemanticsTestForNode(SemanticsNode? node, int indentAmount, DebugSemanticsDumpOrder childOrder) {
if (node == null) {
return 'null';
}
final String indent = ' ' * indentAmount;
final StringBuffer buf = StringBuffer();
final SemanticsData nodeData = node.getSemanticsData();
final bool isRoot = node.id == 0;
buf.writeln('TestSemantics${isRoot ? '.root': ''}(');
if (!isRoot) {
buf.writeln(' id: ${node.id},');
}
if (nodeData.tags != null) {
buf.writeln(' tags: ${_tagsToSemanticsTagExpression(nodeData.tags!)},');
}
if (nodeData.flags != 0) {
buf.writeln(' flags: ${_flagsToSemanticsFlagExpression(nodeData.flags)},');
}
if (nodeData.actions != 0) {
buf.writeln(' actions: ${_actionsToSemanticsActionExpression(nodeData.actions)},');
}
if (node.label.isNotEmpty) {
// Escape newlines and text directionality control characters.
final String escapedLabel = node.label.replaceAll('\n', r'\n').replaceAll('\u202a', r'\u202a').replaceAll('\u202c', r'\u202c');
buf.writeln(" label: '$escapedLabel',");
}
if (node.value.isNotEmpty) {
buf.writeln(" value: '${node.value}',");
}
if (node.increasedValue.isNotEmpty) {
buf.writeln(" increasedValue: '${node.increasedValue}',");
}
if (node.decreasedValue.isNotEmpty) {
buf.writeln(" decreasedValue: '${node.decreasedValue}',");
}
if (node.hint.isNotEmpty) {
buf.writeln(" hint: '${node.hint}',");
}
if (node.textDirection != null) {
buf.writeln(' textDirection: ${node.textDirection},');
}
if (node.hasChildren) {
buf.writeln(' children: <TestSemantics>[');
for (final SemanticsNode child in node.debugListChildrenInOrder(childOrder)) {
buf
..write(_generateSemanticsTestForNode(child, 2, childOrder))
..writeln(',');
}
buf.writeln(' ],');
}
buf.write(')');
return buf.toString().split('\n').map<String>((String l) => '$indent$l').join('\n');
}
}
class _HasSemantics extends Matcher {
const _HasSemantics(
this._semantics, {
required this.ignoreRect,
required this.ignoreTransform,
required this.ignoreId,
required this.childOrder,
});
final TestSemantics _semantics;
final bool ignoreRect;
final bool ignoreTransform;
final bool ignoreId;
final DebugSemanticsDumpOrder childOrder;
@override
bool matches(covariant SemanticsTester item, Map<dynamic, dynamic> matchState) {
final bool doesMatch = _semantics._matches(
item.tester.binding.pipelineOwner.semanticsOwner?.rootSemanticsNode,
matchState,
ignoreTransform: ignoreTransform,
ignoreRect: ignoreRect,
ignoreId: ignoreId,
childOrder: childOrder,
);
if (!doesMatch) {
matchState['would-match'] = item.generateTestSemanticsExpressionForCurrentSemanticsTree(childOrder);
}
if (item.tester.binding.pipelineOwner.semanticsOwner == null) {
matchState['additional-notes'] = '(Check that the SemanticsTester has not been disposed early.)';
}
return doesMatch;
}
@override
Description describe(Description description) {
return description.add('semantics node matching:\n$_semantics');
}
String _indent(String? text) {
return text.toString().trimRight().split('\n').map<String>((String line) => ' $line').join('\n');
}
@override
Description describeMismatch(dynamic item, Description mismatchDescription, Map<dynamic, dynamic> matchState, bool verbose) {
Description result = mismatchDescription
.add('${matchState[TestSemantics]}\n')
.add('Current SemanticsNode tree:\n')
.add(_indent(RendererBinding.instance.renderView.debugSemantics?.toStringDeep(childOrder: childOrder)))
.add('\n')
.add('The semantics tree would have matched the following configuration:\n')
.add(_indent(matchState['would-match'] as String));
if (matchState.containsKey('additional-notes')) {
result = result
.add('\n')
.add(matchState['additional-notes'] as String);
}
return result;
}
}
/// Asserts that a [SemanticsTester] has a semantics tree that exactly matches the given semantics.
Matcher hasSemantics(
TestSemantics semantics, {
bool ignoreRect = false,
bool ignoreTransform = false,
bool ignoreId = false,
DebugSemanticsDumpOrder childOrder = DebugSemanticsDumpOrder.traversalOrder,
}) {
return _HasSemantics(
semantics,
ignoreRect: ignoreRect,
ignoreTransform: ignoreTransform,
ignoreId: ignoreId,
childOrder: childOrder,
);
}
class _IncludesNodeWith extends Matcher {
const _IncludesNodeWith({
this.attributedLabel,
this.attributedValue,
this.attributedHint,
this.label,
this.value,
this.hint,
this.textDirection,
this.actions,
this.flags,
this.tags,
this.scrollPosition,
this.scrollExtentMax,
this.scrollExtentMin,
this.maxValueLength,
this.currentValueLength,
}) : assert(
label != null ||
value != null ||
actions != null ||
flags != null ||
tags != null ||
scrollPosition != null ||
scrollExtentMax != null ||
scrollExtentMin != null ||
maxValueLength != null ||
currentValueLength != null,
);
final AttributedString? attributedLabel;
final AttributedString? attributedValue;
final AttributedString? attributedHint;
final String? label;
final String? value;
final String? hint;
final TextDirection? textDirection;
final List<SemanticsAction>? actions;
final List<SemanticsFlag>? flags;
final Set<SemanticsTag>? tags;
final double? scrollPosition;
final double? scrollExtentMax;
final double? scrollExtentMin;
final int? currentValueLength;
final int? maxValueLength;
@override
bool matches(covariant SemanticsTester item, Map<dynamic, dynamic> matchState) {
return item.nodesWith(
attributedLabel: attributedLabel,
attributedValue: attributedValue,
attributedHint: attributedHint,
label: label,
value: value,
hint: hint,
textDirection: textDirection,
actions: actions,
flags: flags,
tags: tags,
scrollPosition: scrollPosition,
scrollExtentMax: scrollExtentMax,
scrollExtentMin: scrollExtentMin,
currentValueLength: currentValueLength,
maxValueLength: maxValueLength,
).isNotEmpty;
}
@override
Description describe(Description description) {
return description.add('includes node with $_configAsString');
}
@override
Description describeMismatch(dynamic item, Description mismatchDescription, Map<dynamic, dynamic> matchState, bool verbose) {
return mismatchDescription.add('could not find node with $_configAsString.\n$_matcherHelp');
}
String get _configAsString {
final List<String> strings = <String>[
if (label != null) 'label "$label"',
if (value != null) 'value "$value"',
if (hint != null) 'hint "$hint"',
if (textDirection != null) ' (${textDirection!.name})',
if (actions != null) 'actions "${actions!.join(', ')}"',
if (flags != null) 'flags "${flags!.join(', ')}"',
if (tags != null) 'tags "${tags!.join(', ')}"',
if (scrollPosition != null) 'scrollPosition "$scrollPosition"',
if (scrollExtentMax != null) 'scrollExtentMax "$scrollExtentMax"',
if (scrollExtentMin != null) 'scrollExtentMin "$scrollExtentMin"',
if (currentValueLength != null) 'currentValueLength "$currentValueLength"',
if (maxValueLength != null) 'maxValueLength "$maxValueLength"',
];
return strings.join(', ');
}
}
/// Asserts that a node in the semantics tree of [SemanticsTester] has `label`,
/// `textDirection`, and `actions`.
///
/// If null is provided for an argument, it will match against any value.
Matcher includesNodeWith({
String? label,
AttributedString? attributedLabel,
String? value,
AttributedString? attributedValue,
String? hint,
AttributedString? attributedHint,
TextDirection? textDirection,
List<SemanticsAction>? actions,
List<SemanticsFlag>? flags,
Set<SemanticsTag>? tags,
double? scrollPosition,
double? scrollExtentMax,
double? scrollExtentMin,
int? maxValueLength,
int? currentValueLength,
}) {
return _IncludesNodeWith(
label: label,
attributedLabel: attributedLabel,
value: value,
attributedValue: attributedValue,
hint: hint,
attributedHint: attributedHint,
textDirection: textDirection,
actions: actions,
flags: flags,
tags: tags,
scrollPosition: scrollPosition,
scrollExtentMax: scrollExtentMax,
scrollExtentMin: scrollExtentMin,
maxValueLength: maxValueLength,
currentValueLength: currentValueLength,
);
}
| flutter/packages/flutter/test/widgets/semantics_tester.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/semantics_tester.dart",
"repo_id": "flutter",
"token_count": 11739
} | 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/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'semantics_tester.dart';
void main() {
testWidgets('Simple tree is simple', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(
const Center(
child: Text('Hello!', textDirection: TextDirection.ltr),
),
);
expect(semantics, hasSemantics(TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
id: 1,
label: 'Hello!',
textDirection: TextDirection.ltr,
rect: const Rect.fromLTRB(0.0, 0.0, 84.0, 14.0),
transform: Matrix4.translationValues(358.0, 293.0, 0.0),
),
],
)));
semantics.dispose();
});
testWidgets('Simple tree is simple - material', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
// Not using Text widget because of https://github.com/flutter/flutter/issues/12357.
await tester.pumpWidget(MaterialApp(
home: Center(
child: Semantics(
label: 'Hello!',
child: const SizedBox(
width: 10.0,
height: 10.0,
),
),
),
));
expect(semantics, hasSemantics(TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
id: 1,
rect: const Rect.fromLTWH(0.0, 0.0, 800.0, 600.0),
children: <TestSemantics>[
TestSemantics(
id: 2,
rect: const Rect.fromLTWH(0.0, 0.0, 800.0, 600.0),
children: <TestSemantics>[
TestSemantics(
id: 3,
rect: const Rect.fromLTWH(0.0, 0.0, 800.0, 600.0),
flags: <SemanticsFlag>[SemanticsFlag.scopesRoute],
children: <TestSemantics>[
TestSemantics(
id: 4,
label: 'Hello!',
textDirection: TextDirection.ltr,
rect: const Rect.fromLTRB(0.0, 0.0, 10.0, 10.0),
transform: Matrix4.translationValues(395.0, 295.0, 0.0),
),
],
),
],
),
],
),
],
)));
semantics.dispose();
});
}
| flutter/packages/flutter/test/widgets/simple_semantics_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/simple_semantics_test.dart",
"repo_id": "flutter",
"token_count": 1292
} | 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/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'semantics_tester.dart';
void main() {
testWidgets('Sliver appBars - floating and pinned - correct elevation', (WidgetTester tester) async {
await tester.pumpWidget(Localizations(
locale: const Locale('en', 'us'),
delegates: const <LocalizationsDelegate<dynamic>>[
DefaultWidgetsLocalizations.delegate,
DefaultMaterialLocalizations.delegate,
],
child: Directionality(
textDirection: TextDirection.ltr,
child: MediaQuery(
data: const MediaQueryData(),
child: CustomScrollView(
slivers: <Widget>[
const SliverAppBar(
bottom: PreferredSize(
preferredSize: Size.fromHeight(28),
child: Text('Bottom'),
),
backgroundColor: Colors.green,
floating: true,
primary: false,
automaticallyImplyLeading: false,
),
SliverToBoxAdapter(child: Container(color: Colors.yellow, height: 50.0)),
SliverToBoxAdapter(child: Container(color: Colors.red, height: 50.0)),
],
),
),
),
),
);
final RenderPhysicalModel renderObject = tester.renderObject<RenderPhysicalModel>(find.byType(PhysicalModel));
expect(renderObject, isNotNull);
expect(renderObject.elevation, 0.0);
});
testWidgets('Sliver appbars - floating and pinned - correct semantics', (WidgetTester tester) async {
await tester.pumpWidget(
Localizations(
locale: const Locale('en', 'us'),
delegates: const <LocalizationsDelegate<dynamic>>[
DefaultWidgetsLocalizations.delegate,
DefaultMaterialLocalizations.delegate,
],
child: Directionality(
textDirection: TextDirection.ltr,
child: MediaQuery(
data: const MediaQueryData(),
child: CustomScrollView(
slivers: <Widget>[
const SliverAppBar(
title: Text('Hello'),
pinned: true,
floating: true,
expandedHeight: 200.0,
),
SliverFixedExtentList(
itemExtent: 100.0,
delegate: SliverChildBuilderDelegate(
(BuildContext _, int index) {
return Container(
height: 100.0,
color: index.isEven ? Colors.red : Colors.yellow,
child: Text('Tile $index'),
);
},
),
),
],
),
),
),
),
);
final SemanticsTester semantics = SemanticsTester(tester);
TestSemantics expectedSemantics = TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
textDirection: TextDirection.ltr,
children: <TestSemantics>[
TestSemantics(
children: <TestSemantics>[
TestSemantics(
thickness: 0,
children: <TestSemantics>[
TestSemantics(
label: 'Hello',
elevation: 0,
flags: <SemanticsFlag>[SemanticsFlag.isHeader, SemanticsFlag.namesRoute],
textDirection: TextDirection.ltr,
),
],
),
TestSemantics(
actions: <SemanticsAction>[SemanticsAction.scrollUp],
flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling],
scrollIndex: 0,
children: <TestSemantics>[
TestSemantics(
label: 'Tile 0',
textDirection: TextDirection.ltr,
),
TestSemantics(
label: 'Tile 1',
textDirection: TextDirection.ltr,
),
TestSemantics(
label: 'Tile 2',
textDirection: TextDirection.ltr,
),
TestSemantics(
label: 'Tile 3',
textDirection: TextDirection.ltr,
),
TestSemantics(
label: 'Tile 4',
textDirection: TextDirection.ltr,
flags: <SemanticsFlag>[SemanticsFlag.isHidden],
),
TestSemantics(
label: 'Tile 5',
textDirection: TextDirection.ltr,
flags: <SemanticsFlag>[SemanticsFlag.isHidden],
),
TestSemantics(
label: 'Tile 6',
textDirection: TextDirection.ltr,
flags: <SemanticsFlag>[SemanticsFlag.isHidden],
),
],
),
],
),
],
),
],
);
expect(semantics, hasSemantics(expectedSemantics, ignoreTransform: true, ignoreId: true, ignoreRect: true));
await tester.fling(find.text('Tile 2'), const Offset(0, -600), 2000);
await tester.pumpAndSettle();
expectedSemantics = TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
textDirection: TextDirection.ltr,
children: <TestSemantics>[
TestSemantics(
children: <TestSemantics>[
TestSemantics(
children: <TestSemantics>[
TestSemantics(
label: 'Hello',
flags: <SemanticsFlag>[SemanticsFlag.isHeader, SemanticsFlag.namesRoute],
textDirection: TextDirection.ltr,
),
],
),
TestSemantics(
actions: <SemanticsAction>[SemanticsAction.scrollUp, SemanticsAction.scrollDown],
flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling],
scrollIndex: 11,
children: <TestSemantics>[
TestSemantics(
label: 'Tile 7',
textDirection: TextDirection.ltr,
flags: <SemanticsFlag>[SemanticsFlag.isHidden],
),
TestSemantics(
label: 'Tile 8',
textDirection: TextDirection.ltr,
flags: <SemanticsFlag>[SemanticsFlag.isHidden],
),
TestSemantics(
label: 'Tile 9',
textDirection: TextDirection.ltr,
flags: <SemanticsFlag>[SemanticsFlag.isHidden],
),
TestSemantics(
label: 'Tile 10',
textDirection: TextDirection.ltr,
flags: <SemanticsFlag>[SemanticsFlag.isHidden],
),
TestSemantics(
label: 'Tile 11',
textDirection: TextDirection.ltr,
),
TestSemantics(
label: 'Tile 12',
textDirection: TextDirection.ltr,
),
TestSemantics(
label: 'Tile 13',
textDirection: TextDirection.ltr,
),
TestSemantics(
label: 'Tile 14',
textDirection: TextDirection.ltr,
),
TestSemantics(
label: 'Tile 15',
textDirection: TextDirection.ltr,
),
TestSemantics(
label: 'Tile 16',
textDirection: TextDirection.ltr,
),
TestSemantics(
label: 'Tile 17',
textDirection: TextDirection.ltr,
flags: <SemanticsFlag>[SemanticsFlag.isHidden],
),
TestSemantics(
label: 'Tile 18',
textDirection: TextDirection.ltr,
flags: <SemanticsFlag>[SemanticsFlag.isHidden],
),
],
),
],
),
],
),
],
);
expect(semantics, hasSemantics(expectedSemantics, ignoreTransform: true, ignoreId: true, ignoreRect: true));
semantics.dispose();
});
testWidgets('Sliver appbars - floating and pinned - second app bar stacks below', (WidgetTester tester) async {
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: CustomScrollView(
controller: controller,
slivers: <Widget>[
const SliverAppBar(floating: true, pinned: true, expandedHeight: 200.0, title: Text('A')),
const SliverAppBar(primary: false, pinned: true, title: Text('B')),
SliverList(
delegate: SliverChildListDelegate(
const <Widget>[
Text('C'),
Text('D'),
SizedBox(height: 500.0),
Text('E'),
SizedBox(height: 500.0),
],
),
),
],
),
),
);
const Offset textPositionInAppBar = Offset(16.0, 18.0);
expect(tester.getTopLeft(find.text('A')), textPositionInAppBar);
// top app bar is 200.0 high at this point
expect(tester.getTopLeft(find.text('B')), const Offset(0.0, 200.0) + textPositionInAppBar);
// second app bar is 56.0 high
expect(tester.getTopLeft(find.text('C')), const Offset(0.0, 200.0 + 56.0)); // height of both appbars
final Size cSize = tester.getSize(find.text('C'));
controller.jumpTo(200.0 - 56.0);
await tester.pump();
expect(tester.getTopLeft(find.text('A')), textPositionInAppBar);
// top app bar is now only 56.0 high, same as second
expect(tester.getTopLeft(find.text('B')), const Offset(0.0, 56.0) + textPositionInAppBar);
expect(tester.getTopLeft(find.text('C')), const Offset(0.0, 56.0 * 2.0)); // height of both collapsed appbars
expect(find.text('E'), findsNothing);
controller.jumpTo(600.0);
await tester.pump();
expect(tester.getTopLeft(find.text('A')), textPositionInAppBar); // app bar is pinned at top
expect(tester.getTopLeft(find.text('B')), const Offset(0.0, 56.0) + textPositionInAppBar); // second one too
expect(find.text('C'), findsNothing); // contents are scrolled off though
expect(find.text('D'), findsNothing);
// we have scrolled 600.0 pixels
// initial position of E was 200 + 56 + cSize.height + cSize.height + 500
// we've scrolled that up by 600.0, meaning it's at that minus 600 now:
expect(tester.getTopLeft(find.text('E')), Offset(0.0, 200.0 + 56.0 + cSize.height * 2.0 + 500.0 - 600.0));
});
testWidgets('Does not crash when there is less than minExtent remainingPaintExtent', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/21887.
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
const double availableHeight = 50.0;
await tester.pumpWidget(
MaterialApp(
home: Center(
child: Container(
height: availableHeight,
color: Colors.green,
child: CustomScrollView(
controller: controller,
slivers: <Widget>[
const SliverAppBar(
pinned: true,
floating: true,
expandedHeight: 120.0,
),
SliverList(
delegate: SliverChildListDelegate(List<Widget>.generate(20, (int i) {
return SizedBox(
height: 100.0,
child: Text('Tile $i'),
);
})),
),
],
),
),
),
),
);
final RenderSliverFloatingPinnedPersistentHeader render = tester.renderObject(find.byType(SliverAppBar));
expect(render.minExtent, greaterThan(availableHeight)); // Precondition
expect(render.geometry!.scrollExtent, 120.0);
expect(render.geometry!.paintExtent, availableHeight);
expect(render.geometry!.layoutExtent, availableHeight);
controller.jumpTo(200.0);
await tester.pumpAndSettle();
expect(render.geometry!.scrollExtent, 120.0);
expect(render.geometry!.paintExtent, availableHeight);
expect(render.geometry!.layoutExtent, 0.0);
});
testWidgets('Pinned and floating SliverAppBar sticks to top the content is scroll down', (WidgetTester tester) async {
const Key anchor = Key('drag');
await tester.pumpWidget(
MaterialApp(
home: Center(
child: Container(
height: 300,
color: Colors.green,
child: CustomScrollView(
physics: const BouncingScrollPhysics(),
slivers: <Widget>[
const SliverAppBar(
pinned: true,
floating: true,
expandedHeight: 100.0,
),
SliverToBoxAdapter(child: Container(key: anchor, color: Colors.red, height: 100)),
SliverToBoxAdapter(child: Container(height: 600, color: Colors.green)),
],
),
),
),
),
);
final RenderSliverFloatingPinnedPersistentHeader render = tester.renderObject(find.byType(SliverAppBar));
const double scrollDistance = 40;
final TestGesture gesture = await tester.press(find.byKey(anchor));
await gesture.moveBy(const Offset(0, scrollDistance));
await tester.pump();
expect(render.geometry!.paintOrigin, -scrollDistance);
});
testWidgets('Floating SliverAppBar sticks to top the content is scroll down', (WidgetTester tester) async {
const Key anchor = Key('drag');
await tester.pumpWidget(
MaterialApp(
home: Center(
child: Container(
height: 300,
color: Colors.green,
child: CustomScrollView(
physics: const BouncingScrollPhysics(),
slivers: <Widget>[
const SliverAppBar(
floating: true,
expandedHeight: 100.0,
),
SliverToBoxAdapter(child: Container(key: anchor, color: Colors.red, height: 100)),
SliverToBoxAdapter(child: Container(height: 600, color: Colors.green)),
],
),
),
),
),
);
final RenderSliverFloatingPersistentHeader render = tester.renderObject(find.byType(SliverAppBar));
const double scrollDistance = 40;
final TestGesture gesture = await tester.press(find.byKey(anchor));
await gesture.moveBy(const Offset(0, scrollDistance));
await tester.pump();
expect(render.geometry!.paintOrigin, -scrollDistance);
});
testWidgets('Pinned SliverAppBar sticks to top the content is scroll down', (WidgetTester tester) async {
const Key anchor = Key('drag');
await tester.pumpWidget(
MaterialApp(
home: Center(
child: Container(
height: 300,
color: Colors.green,
child: CustomScrollView(
physics: const BouncingScrollPhysics(),
slivers: <Widget>[
const SliverAppBar(
pinned: true,
expandedHeight: 100.0,
),
SliverToBoxAdapter(child: Container(key: anchor, color: Colors.red, height: 100)),
SliverToBoxAdapter(child: Container(height: 600, color: Colors.green)),
],
),
),
),
),
);
final RenderSliverPinnedPersistentHeader render = tester.renderObject(find.byType(SliverAppBar));
const double scrollDistance = 40;
final TestGesture gesture = await tester.press(find.byKey(anchor));
await gesture.moveBy(const Offset(0, scrollDistance));
await tester.pump();
expect(render.geometry!.paintOrigin, -scrollDistance);
});
}
| flutter/packages/flutter/test/widgets/slivers_appbar_floating_pinned_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/slivers_appbar_floating_pinned_test.dart",
"repo_id": "flutter",
"token_count": 8699
} | 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/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import '../rendering/rendering_tester.dart' show TestCallbackPainter;
class TestPaintingContext implements PaintingContext {
final List<Invocation> invocations = <Invocation>[];
@override
void noSuchMethod(Invocation invocation) {
invocations.add(invocation);
}
}
void main() {
testWidgets('Can construct an empty Stack', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Stack(),
),
);
});
testWidgets('Can construct an empty Centered Stack', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Center(child: Stack()),
),
);
});
testWidgets('Can change position data', (WidgetTester tester) async {
const Key key = Key('container');
await tester.pumpWidget(
const Stack(
alignment: Alignment.topLeft,
children: <Widget>[
Positioned(
left: 10.0,
child: SizedBox(
key: key,
width: 10.0,
height: 10.0,
),
),
],
),
);
Element container;
StackParentData parentData;
container = tester.element(find.byKey(key));
parentData = container.renderObject!.parentData! as StackParentData;
expect(parentData.top, isNull);
expect(parentData.right, isNull);
expect(parentData.bottom, isNull);
expect(parentData.left, equals(10.0));
expect(parentData.width, isNull);
expect(parentData.height, isNull);
await tester.pumpWidget(
const Stack(
alignment: Alignment.topLeft,
children: <Widget>[
Positioned(
right: 10.0,
child: SizedBox(
key: key,
width: 10.0,
height: 10.0,
),
),
],
),
);
container = tester.element(find.byKey(key));
parentData = container.renderObject!.parentData! as StackParentData;
expect(parentData.top, isNull);
expect(parentData.right, equals(10.0));
expect(parentData.bottom, isNull);
expect(parentData.left, isNull);
expect(parentData.width, isNull);
expect(parentData.height, isNull);
});
testWidgets('Can remove parent data', (WidgetTester tester) async {
const Key key = Key('container');
const SizedBox sizedBox = SizedBox(key: key, width: 10.0, height: 10.0);
await tester.pumpWidget(
const Stack(
textDirection: TextDirection.ltr,
children: <Widget>[ Positioned(left: 10.0, child: sizedBox) ],
),
);
Element containerElement = tester.element(find.byKey(key));
StackParentData parentData;
parentData = containerElement.renderObject!.parentData! as StackParentData;
expect(parentData.top, isNull);
expect(parentData.right, isNull);
expect(parentData.bottom, isNull);
expect(parentData.left, equals(10.0));
expect(parentData.width, isNull);
expect(parentData.height, isNull);
await tester.pumpWidget(
const Stack(
textDirection: TextDirection.ltr,
children: <Widget>[ sizedBox ],
),
);
containerElement = tester.element(find.byKey(key));
parentData = containerElement.renderObject!.parentData! as StackParentData;
expect(parentData.top, isNull);
expect(parentData.right, isNull);
expect(parentData.bottom, isNull);
expect(parentData.left, isNull);
expect(parentData.width, isNull);
expect(parentData.height, isNull);
});
testWidgets('Can align non-positioned children (LTR)', (WidgetTester tester) async {
const Key child0Key = Key('child0');
const Key child1Key = Key('child1');
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: Stack(
alignment: Alignment.center,
children: <Widget>[
SizedBox(key: child0Key, width: 20.0, height: 20.0),
SizedBox(key: child1Key, width: 10.0, height: 10.0),
],
),
),
),
);
final Element child0 = tester.element(find.byKey(child0Key));
final StackParentData child0RenderObjectParentData = child0.renderObject!.parentData! as StackParentData;
expect(child0RenderObjectParentData.offset, equals(Offset.zero));
final Element child1 = tester.element(find.byKey(child1Key));
final StackParentData child1RenderObjectParentData = child1.renderObject!.parentData! as StackParentData;
expect(child1RenderObjectParentData.offset, equals(const Offset(5.0, 5.0)));
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: Stack(
alignment: AlignmentDirectional.bottomEnd,
children: <Widget>[
SizedBox(key: child0Key, width: 20.0, height: 20.0),
SizedBox(key: child1Key, width: 10.0, height: 10.0),
],
),
),
),
);
expect(child0RenderObjectParentData.offset, equals(Offset.zero));
expect(child1RenderObjectParentData.offset, equals(const Offset(10.0, 10.0)));
});
testWidgets('Can align non-positioned children (RTL)', (WidgetTester tester) async {
const Key child0Key = Key('child0');
const Key child1Key = Key('child1');
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.rtl,
child: Center(
child: Stack(
alignment: Alignment.center,
children: <Widget>[
SizedBox(key: child0Key, width: 20.0, height: 20.0),
SizedBox(key: child1Key, width: 10.0, height: 10.0),
],
),
),
),
);
final Element child0 = tester.element(find.byKey(child0Key));
final StackParentData child0RenderObjectParentData = child0.renderObject!.parentData! as StackParentData;
expect(child0RenderObjectParentData.offset, equals(Offset.zero));
final Element child1 = tester.element(find.byKey(child1Key));
final StackParentData child1RenderObjectParentData = child1.renderObject!.parentData! as StackParentData;
expect(child1RenderObjectParentData.offset, equals(const Offset(5.0, 5.0)));
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.rtl,
child: Center(
child: Stack(
alignment: AlignmentDirectional.bottomEnd,
children: <Widget>[
SizedBox(key: child0Key, width: 20.0, height: 20.0),
SizedBox(key: child1Key, width: 10.0, height: 10.0),
],
),
),
),
);
expect(child0RenderObjectParentData.offset, equals(Offset.zero));
expect(child1RenderObjectParentData.offset, equals(const Offset(0.0, 10.0)));
});
testWidgets('Can construct an empty IndexedStack', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: IndexedStack(),
),
);
});
testWidgets('Can construct an empty Centered IndexedStack', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Center(child: IndexedStack()),
),
);
});
testWidgets('Can construct an IndexedStack', (WidgetTester tester) async {
const int itemCount = 3;
late List<int> itemsPainted;
Widget buildFrame(int index) {
itemsPainted = <int>[];
final List<Widget> items = List<Widget>.generate(itemCount, (int i) {
return CustomPaint(
painter: TestCallbackPainter(
onPaint: () { itemsPainted.add(i); },
),
child: Text('$i', textDirection: TextDirection.ltr),
);
});
return Center(
child: IndexedStack(
alignment: Alignment.topLeft,
index: index,
children: items,
),
);
}
void expectFindsChild(int n) {
for (int i = 0; i < 3; i++) {
expect(find.text('$i', skipOffstage: false), findsOneWidget);
if (i == n) {
expect(find.text('$i'), findsOneWidget);
} else {
expect(find.text('$i'), findsNothing);
}
}
}
await tester.pumpWidget(buildFrame(0));
expectFindsChild(0);
expect(itemsPainted, equals(<int>[0]));
await tester.pumpWidget(buildFrame(1));
expectFindsChild(1);
expect(itemsPainted, equals(<int>[1]));
await tester.pumpWidget(buildFrame(2));
expectFindsChild(2);
expect(itemsPainted, equals(<int>[2]));
});
testWidgets('Can hit test an IndexedStack', (WidgetTester tester) async {
const Key key = Key('indexedStack');
const int itemCount = 3;
late List<int> itemsTapped;
Widget buildFrame(int index) {
itemsTapped = <int>[];
final List<Widget> items = List<Widget>.generate(itemCount, (int i) {
return GestureDetector(child: Text('$i', textDirection: TextDirection.ltr), onTap: () { itemsTapped.add(i); });
});
return Center(
child: IndexedStack(
alignment: Alignment.topLeft,
key: key,
index: index,
children: items,
),
);
}
await tester.pumpWidget(buildFrame(0));
expect(itemsTapped, isEmpty);
await tester.tap(find.byKey(key));
expect(itemsTapped, <int>[0]);
await tester.pumpWidget(buildFrame(2));
expect(itemsTapped, isEmpty);
await tester.tap(find.byKey(key));
expect(itemsTapped, <int>[2]);
});
testWidgets('IndexedStack sets non-selected indexes to visible=false', (WidgetTester tester) async {
Widget buildStack({required int itemCount, required int? selectedIndex}) {
final List<Widget> children = List<Widget>.generate(itemCount, (int i) {
return _ShowVisibility(index: i);
});
return Directionality(
textDirection: TextDirection.ltr,
child: IndexedStack(
index: selectedIndex,
children: children,
),
);
}
await tester.pumpWidget(buildStack(itemCount: 3, selectedIndex: null));
expect(find.text('index 0 is visible ? false', skipOffstage: false), findsOneWidget);
expect(find.text('index 1 is visible ? false', skipOffstage: false), findsOneWidget);
expect(find.text('index 2 is visible ? false', skipOffstage: false), findsOneWidget);
await tester.pumpWidget(buildStack(itemCount: 3, selectedIndex: 0));
expect(find.text('index 0 is visible ? true', skipOffstage: false), findsOneWidget);
expect(find.text('index 1 is visible ? false', skipOffstage: false), findsOneWidget);
expect(find.text('index 2 is visible ? false', skipOffstage: false), findsOneWidget);
await tester.pumpWidget(buildStack(itemCount: 3, selectedIndex: 1));
expect(find.text('index 0 is visible ? false', skipOffstage: false), findsOneWidget);
expect(find.text('index 1 is visible ? true', skipOffstage: false), findsOneWidget);
expect(find.text('index 2 is visible ? false', skipOffstage: false), findsOneWidget);
await tester.pumpWidget(buildStack(itemCount: 3, selectedIndex: 2));
expect(find.text('index 0 is visible ? false', skipOffstage: false), findsOneWidget);
expect(find.text('index 1 is visible ? false', skipOffstage: false), findsOneWidget);
expect(find.text('index 2 is visible ? true', skipOffstage: false), findsOneWidget);
});
testWidgets('Can set width and height', (WidgetTester tester) async {
const Key key = Key('container');
const BoxDecoration kBoxDecoration = BoxDecoration(
color: Color(0xFF00FF00),
);
await tester.pumpWidget(
const Stack(
textDirection: TextDirection.ltr,
children: <Widget>[
Positioned(
left: 10.0,
width: 11.0,
height: 12.0,
child: DecoratedBox(key: key, decoration: kBoxDecoration),
),
],
),
);
Element box;
RenderBox renderBox;
StackParentData parentData;
box = tester.element(find.byKey(key));
renderBox = box.renderObject! as RenderBox;
parentData = renderBox.parentData! as StackParentData;
expect(parentData.top, isNull);
expect(parentData.right, isNull);
expect(parentData.bottom, isNull);
expect(parentData.left, equals(10.0));
expect(parentData.width, equals(11.0));
expect(parentData.height, equals(12.0));
expect(parentData.offset.dx, equals(10.0));
expect(parentData.offset.dy, equals(0.0));
expect(renderBox.size.width, equals(11.0));
expect(renderBox.size.height, equals(12.0));
await tester.pumpWidget(
const Stack(
textDirection: TextDirection.ltr,
children: <Widget>[
Positioned(
right: 10.0,
width: 11.0,
height: 12.0,
child: DecoratedBox(key: key, decoration: kBoxDecoration),
),
],
),
);
box = tester.element(find.byKey(key));
renderBox = box.renderObject! as RenderBox;
parentData = renderBox.parentData! as StackParentData;
expect(parentData.top, isNull);
expect(parentData.right, equals(10.0));
expect(parentData.bottom, isNull);
expect(parentData.left, isNull);
expect(parentData.width, equals(11.0));
expect(parentData.height, equals(12.0));
expect(parentData.offset.dx, equals(779.0));
expect(parentData.offset.dy, equals(0.0));
expect(renderBox.size.width, equals(11.0));
expect(renderBox.size.height, equals(12.0));
});
testWidgets('Can set and update clipBehavior', (WidgetTester tester) async {
await tester.pumpWidget(const Stack(textDirection: TextDirection.ltr));
final RenderStack renderObject = tester.allRenderObjects.whereType<RenderStack>().first;
expect(renderObject.clipBehavior, equals(Clip.hardEdge));
await tester.pumpWidget(const Stack(textDirection: TextDirection.ltr));
expect(renderObject.clipBehavior, equals(Clip.hardEdge));
});
testWidgets('Clip.none is respected by describeApproximateClip', (WidgetTester tester) async {
await tester.pumpWidget(const Stack(
textDirection: TextDirection.ltr,
children: <Widget>[Positioned(left: 1000, right: 2000, child: SizedBox(width: 2000, height: 2000))],
));
final RenderStack renderObject = tester.allRenderObjects.whereType<RenderStack>().first;
expect(renderObject.clipBehavior, equals(Clip.hardEdge));
bool visited = false;
renderObject.visitChildren((RenderObject child) {
visited = true;
expect(renderObject.describeApproximatePaintClip(child), const Rect.fromLTRB(0.0, 0.0, 800.0, 600.0));
});
expect(visited, true);
visited = false;
renderObject.clipBehavior = Clip.none;
renderObject.visitChildren((RenderObject child) {
visited = true;
expect(renderObject.describeApproximatePaintClip(child), null);
});
expect(visited, true);
});
testWidgets('IndexedStack with null index', (WidgetTester tester) async {
bool? tapped;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: IndexedStack(
index: null,
children: <Widget>[
GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () { tapped = true; },
child: const SizedBox(
width: 200.0,
height: 200.0,
),
),
],
),
),
),
);
await tester.tap(find.byType(IndexedStack), warnIfMissed: false);
final RenderBox box = tester.renderObject(find.byType(IndexedStack));
expect(box.size, equals(const Size(200.0, 200.0)));
expect(tapped, isNull);
});
testWidgets('IndexedStack reports hidden children as offstage', (WidgetTester tester) async {
final List<Widget> children = <Widget>[
for (int i = 0; i < 5; i++) Text('child $i'),
];
Future<void> pumpIndexedStack(int? activeIndex) async{
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: IndexedStack(
index: activeIndex,
children: children,
),
)
);
}
final Finder finder = find.byType(Text);
final Finder finderIncludingOffstage = find.byType(Text, skipOffstage: false);
await pumpIndexedStack(null);
expect(finder, findsNothing); // IndexedStack with null index shows nothing
expect(finderIncludingOffstage, findsNWidgets(5));
for (int i = 0; i < 5; i++) {
await pumpIndexedStack(i);
expect(finder, findsOneWidget);
expect(finderIncludingOffstage, findsNWidgets(5));
expect(find.text('child $i'), findsOneWidget);
}
});
testWidgets('Stack clip test', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: Stack(
children: <Widget>[
SizedBox(
width: 100.0,
height: 100.0,
),
Positioned(
top: 0.0,
left: 0.0,
child: SizedBox(
width: 200.0,
height: 200.0,
),
),
],
),
),
),
);
RenderBox box = tester.renderObject(find.byType(Stack));
TestPaintingContext context = TestPaintingContext();
box.paint(context, Offset.zero);
expect(context.invocations.first.memberName, equals(#pushClipRect));
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: Stack(
clipBehavior: Clip.none,
children: <Widget>[
SizedBox(
width: 100.0,
height: 100.0,
),
Positioned(
top: 0.0,
left: 0.0,
child: SizedBox(
width: 200.0,
height: 200.0,
),
),
],
),
),
),
);
box = tester.renderObject(find.byType(Stack));
context = TestPaintingContext();
box.paint(context, Offset.zero);
expect(context.invocations.first.memberName, equals(#paintChild));
});
testWidgets('Stack sizing: default', (WidgetTester tester) async {
final List<String> logs = <String>[];
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(
minWidth: 2.0,
maxWidth: 3.0,
minHeight: 5.0,
maxHeight: 7.0,
),
child: Stack(
children: <Widget>[
LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
logs.add(constraints.toString());
return const Placeholder();
},
),
],
),
),
),
),
);
expect(logs, <String>['BoxConstraints(0.0<=w<=3.0, 0.0<=h<=7.0)']);
});
testWidgets('Stack sizing: explicit', (WidgetTester tester) async {
final List<String> logs = <String>[];
Widget buildStack(StackFit sizing) {
return Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(
minWidth: 2.0,
maxWidth: 3.0,
minHeight: 5.0,
maxHeight: 7.0,
),
child: Stack(
fit: sizing,
children: <Widget>[
LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
logs.add(constraints.toString());
return const Placeholder();
},
),
],
),
),
),
);
}
await tester.pumpWidget(buildStack(StackFit.loose));
logs.add('=1=');
await tester.pumpWidget(buildStack(StackFit.expand));
logs.add('=2=');
await tester.pumpWidget(buildStack(StackFit.passthrough));
expect(logs, <String>[
'BoxConstraints(0.0<=w<=3.0, 0.0<=h<=7.0)',
'=1=',
'BoxConstraints(w=3.0, h=7.0)',
'=2=',
'BoxConstraints(2.0<=w<=3.0, 5.0<=h<=7.0)',
]);
});
testWidgets('Positioned.directional control test', (WidgetTester tester) async {
final Key key = UniqueKey();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Stack(
children: <Widget>[
Positioned.directional(
textDirection: TextDirection.rtl,
start: 50.0,
child: SizedBox(key: key, width: 75.0, height: 175.0),
),
],
),
),
);
expect(tester.getTopLeft(find.byKey(key)), const Offset(675.0, 0.0));
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Stack(
children: <Widget>[
Positioned.directional(
textDirection: TextDirection.ltr,
start: 50.0,
child: SizedBox(key: key, width: 75.0, height: 175.0),
),
],
),
),
);
expect(tester.getTopLeft(find.byKey(key)), const Offset(50.0, 0.0));
});
testWidgets('PositionedDirectional control test', (WidgetTester tester) async {
final Key key = UniqueKey();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.rtl,
child: Stack(
children: <Widget>[
PositionedDirectional(
start: 50.0,
child: SizedBox(key: key, width: 75.0, height: 175.0),
),
],
),
),
);
expect(tester.getTopLeft(find.byKey(key)), const Offset(675.0, 0.0));
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Stack(
children: <Widget>[
PositionedDirectional(
start: 50.0,
child: SizedBox(key: key, width: 75.0, height: 175.0),
),
],
),
),
);
expect(tester.getTopLeft(find.byKey(key)), const Offset(50.0, 0.0));
});
testWidgets('Can change the text direction of a Stack', (WidgetTester tester) async {
await tester.pumpWidget(
const Stack(
alignment: Alignment.center,
),
);
await tester.pumpWidget(
const Stack(
textDirection: TextDirection.rtl,
),
);
await tester.pumpWidget(
const Stack(
alignment: Alignment.center,
),
);
});
testWidgets('Alignment with partially-positioned children', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.rtl,
child: Stack(
alignment: Alignment.center,
children: <Widget>[
SizedBox(width: 100.0, height: 100.0),
Positioned(left: 0.0, child: SizedBox(width: 100.0, height: 100.0)),
Positioned(right: 0.0, child: SizedBox(width: 100.0, height: 100.0)),
Positioned(top: 0.0, child: SizedBox(width: 100.0, height: 100.0)),
Positioned(bottom: 0.0, child: SizedBox(width: 100.0, height: 100.0)),
PositionedDirectional(start: 0.0, child: SizedBox(width: 100.0, height: 100.0)),
PositionedDirectional(end: 0.0, child: SizedBox(width: 100.0, height: 100.0)),
PositionedDirectional(top: 0.0, child: SizedBox(width: 100.0, height: 100.0)),
PositionedDirectional(bottom: 0.0, child: SizedBox(width: 100.0, height: 100.0)),
],
),
),
);
expect(tester.getRect(find.byType(SizedBox).at(0)), const Rect.fromLTWH(350.0, 250.0, 100.0, 100.0));
expect(tester.getRect(find.byType(SizedBox).at(1)), const Rect.fromLTWH(0.0, 250.0, 100.0, 100.0));
expect(tester.getRect(find.byType(SizedBox).at(2)), const Rect.fromLTWH(700.0, 250.0, 100.0, 100.0));
expect(tester.getRect(find.byType(SizedBox).at(3)), const Rect.fromLTWH(350.0, 0.0, 100.0, 100.0));
expect(tester.getRect(find.byType(SizedBox).at(4)), const Rect.fromLTWH(350.0, 500.0, 100.0, 100.0));
expect(tester.getRect(find.byType(SizedBox).at(5)), const Rect.fromLTWH(700.0, 250.0, 100.0, 100.0));
expect(tester.getRect(find.byType(SizedBox).at(6)), const Rect.fromLTWH(0.0, 250.0, 100.0, 100.0));
expect(tester.getRect(find.byType(SizedBox).at(7)), const Rect.fromLTWH(350.0, 0.0, 100.0, 100.0));
expect(tester.getRect(find.byType(SizedBox).at(8)), const Rect.fromLTWH(350.0, 500.0, 100.0, 100.0));
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Stack(
alignment: Alignment.center,
children: <Widget>[
SizedBox(width: 100.0, height: 100.0),
Positioned(left: 0.0, child: SizedBox(width: 100.0, height: 100.0)),
Positioned(right: 0.0, child: SizedBox(width: 100.0, height: 100.0)),
Positioned(top: 0.0, child: SizedBox(width: 100.0, height: 100.0)),
Positioned(bottom: 0.0, child: SizedBox(width: 100.0, height: 100.0)),
PositionedDirectional(start: 0.0, child: SizedBox(width: 100.0, height: 100.0)),
PositionedDirectional(end: 0.0, child: SizedBox(width: 100.0, height: 100.0)),
PositionedDirectional(top: 0.0, child: SizedBox(width: 100.0, height: 100.0)),
PositionedDirectional(bottom: 0.0, child: SizedBox(width: 100.0, height: 100.0)),
],
),
),
);
expect(tester.getRect(find.byType(SizedBox).at(0)), const Rect.fromLTWH(350.0, 250.0, 100.0, 100.0));
expect(tester.getRect(find.byType(SizedBox).at(1)), const Rect.fromLTWH(0.0, 250.0, 100.0, 100.0));
expect(tester.getRect(find.byType(SizedBox).at(2)), const Rect.fromLTWH(700.0, 250.0, 100.0, 100.0));
expect(tester.getRect(find.byType(SizedBox).at(3)), const Rect.fromLTWH(350.0, 0.0, 100.0, 100.0));
expect(tester.getRect(find.byType(SizedBox).at(4)), const Rect.fromLTWH(350.0, 500.0, 100.0, 100.0));
expect(tester.getRect(find.byType(SizedBox).at(5)), const Rect.fromLTWH(0.0, 250.0, 100.0, 100.0));
expect(tester.getRect(find.byType(SizedBox).at(6)), const Rect.fromLTWH(700.0, 250.0, 100.0, 100.0));
expect(tester.getRect(find.byType(SizedBox).at(7)), const Rect.fromLTWH(350.0, 0.0, 100.0, 100.0));
expect(tester.getRect(find.byType(SizedBox).at(8)), const Rect.fromLTWH(350.0, 500.0, 100.0, 100.0));
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Stack(
alignment: Alignment.bottomRight,
children: <Widget>[
SizedBox(width: 100.0, height: 100.0),
Positioned(left: 0.0, child: SizedBox(width: 100.0, height: 100.0)),
Positioned(right: 0.0, child: SizedBox(width: 100.0, height: 100.0)),
Positioned(top: 0.0, child: SizedBox(width: 100.0, height: 100.0)),
Positioned(bottom: 0.0, child: SizedBox(width: 100.0, height: 100.0)),
PositionedDirectional(start: 0.0, child: SizedBox(width: 100.0, height: 100.0)),
PositionedDirectional(end: 0.0, child: SizedBox(width: 100.0, height: 100.0)),
PositionedDirectional(top: 0.0, child: SizedBox(width: 100.0, height: 100.0)),
PositionedDirectional(bottom: 0.0, child: SizedBox(width: 100.0, height: 100.0)),
],
),
),
);
expect(tester.getRect(find.byType(SizedBox).at(0)), const Rect.fromLTWH(700.0, 500.0, 100.0, 100.0));
expect(tester.getRect(find.byType(SizedBox).at(1)), const Rect.fromLTWH(0.0, 500.0, 100.0, 100.0));
expect(tester.getRect(find.byType(SizedBox).at(2)), const Rect.fromLTWH(700.0, 500.0, 100.0, 100.0));
expect(tester.getRect(find.byType(SizedBox).at(3)), const Rect.fromLTWH(700.0, 0.0, 100.0, 100.0));
expect(tester.getRect(find.byType(SizedBox).at(4)), const Rect.fromLTWH(700.0, 500.0, 100.0, 100.0));
expect(tester.getRect(find.byType(SizedBox).at(5)), const Rect.fromLTWH(0.0, 500.0, 100.0, 100.0));
expect(tester.getRect(find.byType(SizedBox).at(6)), const Rect.fromLTWH(700.0, 500.0, 100.0, 100.0));
expect(tester.getRect(find.byType(SizedBox).at(7)), const Rect.fromLTWH(700.0, 0.0, 100.0, 100.0));
expect(tester.getRect(find.byType(SizedBox).at(8)), const Rect.fromLTWH(700.0, 500.0, 100.0, 100.0));
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Stack(
alignment: Alignment.topLeft,
children: <Widget>[
SizedBox(width: 100.0, height: 100.0),
Positioned(left: 0.0, child: SizedBox(width: 100.0, height: 100.0)),
Positioned(right: 0.0, child: SizedBox(width: 100.0, height: 100.0)),
Positioned(top: 0.0, child: SizedBox(width: 100.0, height: 100.0)),
Positioned(bottom: 0.0, child: SizedBox(width: 100.0, height: 100.0)),
PositionedDirectional(start: 0.0, child: SizedBox(width: 100.0, height: 100.0)),
PositionedDirectional(end: 0.0, child: SizedBox(width: 100.0, height: 100.0)),
PositionedDirectional(top: 0.0, child: SizedBox(width: 100.0, height: 100.0)),
PositionedDirectional(bottom: 0.0, child: SizedBox(width: 100.0, height: 100.0)),
],
),
),
);
expect(tester.getRect(find.byType(SizedBox).at(0)), const Rect.fromLTWH(0.0, 0.0, 100.0, 100.0));
expect(tester.getRect(find.byType(SizedBox).at(1)), const Rect.fromLTWH(0.0, 0.0, 100.0, 100.0));
expect(tester.getRect(find.byType(SizedBox).at(2)), const Rect.fromLTWH(700.0, 0.0, 100.0, 100.0));
expect(tester.getRect(find.byType(SizedBox).at(3)), const Rect.fromLTWH(0.0, 0.0, 100.0, 100.0));
expect(tester.getRect(find.byType(SizedBox).at(4)), const Rect.fromLTWH(0.0, 500.0, 100.0, 100.0));
expect(tester.getRect(find.byType(SizedBox).at(5)), const Rect.fromLTWH(0.0, 0.0, 100.0, 100.0));
expect(tester.getRect(find.byType(SizedBox).at(6)), const Rect.fromLTWH(700.0, 0.0, 100.0, 100.0));
expect(tester.getRect(find.byType(SizedBox).at(7)), const Rect.fromLTWH(0.0, 0.0, 100.0, 100.0));
expect(tester.getRect(find.byType(SizedBox).at(8)), const Rect.fromLTWH(0.0, 500.0, 100.0, 100.0));
});
testWidgets('Stack error messages', (WidgetTester tester) async {
await tester.pumpWidget(
const Stack(),
);
final String exception = tester.takeException().toString();
expect(
exception, startsWith(
'No Directionality widget found.\n'
"Stack widgets require a Directionality widget ancestor to resolve the 'alignment' argument.\n"
"The default value for 'alignment' is AlignmentDirectional.topStart, which requires a text direction.\n"
'The specific widget that could not find a Directionality ancestor was:\n'
' Stack\n'
'The ownership chain for the affected widget is: "Stack ← ', // Omitted full ownership chain because it is not relevant for the test.
));
expect(
exception, endsWith(
'← [root]"\n' // End of ownership chain.
'Typically, the Directionality widget is introduced by the MaterialApp or WidgetsApp widget at the '
'top of your application widget tree. It determines the ambient reading direction and is used, for '
'example, to determine how to lay out text, how to interpret "start" and "end" values, and to resolve '
'EdgeInsetsDirectional, AlignmentDirectional, and other *Directional objects.\n'
'Instead of providing a Directionality widget, another solution would be passing a non-directional '
"'alignment', or an explicit 'textDirection', to the Stack.",
));
});
testWidgets('Can update clipBehavior of IndexedStack',
(WidgetTester tester) async {
await tester.pumpWidget(const IndexedStack(textDirection: TextDirection.ltr));
final RenderIndexedStack renderObject =
tester.renderObject<RenderIndexedStack>(find.byType(IndexedStack));
expect(renderObject.clipBehavior, equals(Clip.hardEdge));
// Update clipBehavior to Clip.antiAlias
await tester.pumpWidget(const IndexedStack(
textDirection: TextDirection.ltr,
clipBehavior: Clip.antiAlias,
));
final RenderIndexedStack renderIndexedObject =
tester.renderObject<RenderIndexedStack>(find.byType(IndexedStack));
expect(renderIndexedObject.clipBehavior, equals(Clip.antiAlias));
});
testWidgets('IndexedStack sizing: explicit', (WidgetTester tester) async {
final List<String> logs = <String>[];
Widget buildIndexedStack(StackFit sizing) {
return Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(
minWidth: 2.0,
maxWidth: 3.0,
minHeight: 5.0,
maxHeight: 7.0,
),
child: IndexedStack(
sizing: sizing,
children: <Widget>[
LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
logs.add(constraints.toString());
return const Placeholder();
},
),
],
),
),
),
);
}
await tester.pumpWidget(buildIndexedStack(StackFit.loose));
logs.add('=1=');
await tester.pumpWidget(buildIndexedStack(StackFit.expand));
logs.add('=2=');
await tester.pumpWidget(buildIndexedStack(StackFit.passthrough));
expect(logs, <String>[
'BoxConstraints(0.0<=w<=3.0, 0.0<=h<=7.0)',
'=1=',
'BoxConstraints(w=3.0, h=7.0)',
'=2=',
'BoxConstraints(2.0<=w<=3.0, 5.0<=h<=7.0)',
]);
});
}
class _ShowVisibility extends StatelessWidget {
const _ShowVisibility({required this.index});
final int index;
@override
Widget build(BuildContext context) {
return Text('index $index is visible ? ${Visibility.of(context)}');
}
}
| flutter/packages/flutter/test/widgets/stack_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/stack_test.dart",
"repo_id": "flutter",
"token_count": 15535
} | 730 |
// 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/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'semantics_tester.dart';
void main() {
testWidgets('SemanticsNode ids are stable', (WidgetTester tester) async {
// Regression test for b/151732341.
final SemanticsTester semantics = SemanticsTester(tester);
final TapGestureRecognizer recognizer1 = TapGestureRecognizer();
addTearDown(recognizer1.dispose);
final TapGestureRecognizer recognizer2 = TapGestureRecognizer();
addTearDown(recognizer2.dispose);
final TapGestureRecognizer recognizer3 = TapGestureRecognizer();
addTearDown(recognizer3.dispose);
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: Text.rich(
TextSpan(
text: 'Hallo ',
recognizer: recognizer1..onTap = () {},
children: <TextSpan>[
TextSpan(
text: 'Welt ',
recognizer: recognizer2..onTap = () {},
),
TextSpan(
text: '!!!',
recognizer: recognizer3..onTap = () {},
),
],
),
),
));
expect(find.text('Hallo Welt !!!'), findsOneWidget);
final SemanticsNode node = tester.getSemantics(find.text('Hallo Welt !!!'));
final Map<String, int> labelToNodeId = <String, int>{};
node.visitChildren((SemanticsNode node) {
labelToNodeId[node.label] = node.id;
return true;
});
expect(node.id, 1);
expect(labelToNodeId['Hallo '], 2);
expect(labelToNodeId['Welt '], 3);
expect(labelToNodeId['!!!'], 4);
expect(labelToNodeId.length, 3);
// Rebuild semantics.
tester.renderObject(find.text('Hallo Welt !!!')).markNeedsSemanticsUpdate();
await tester.pump();
final SemanticsNode nodeAfterRebuild = tester.getSemantics(find.text('Hallo Welt !!!'));
final Map<String, int> labelToNodeIdAfterRebuild = <String, int>{};
nodeAfterRebuild.visitChildren((SemanticsNode node) {
labelToNodeIdAfterRebuild[node.label] = node.id;
return true;
});
// Node IDs are stable.
expect(nodeAfterRebuild.id, node.id);
expect(labelToNodeIdAfterRebuild['Hallo '], labelToNodeId['Hallo ']);
expect(labelToNodeIdAfterRebuild['Welt '], labelToNodeId['Welt ']);
expect(labelToNodeIdAfterRebuild['!!!'], labelToNodeId['!!!']);
expect(labelToNodeIdAfterRebuild.length, 3);
final TapGestureRecognizer recognizer4 = TapGestureRecognizer();
addTearDown(recognizer4.dispose);
final TapGestureRecognizer recognizer5 = TapGestureRecognizer();
addTearDown(recognizer5.dispose);
// Remove one node.
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: Text.rich(
TextSpan(
text: 'Hallo ',
recognizer: recognizer4..onTap = () {},
children: <TextSpan>[
TextSpan(
text: 'Welt ',
recognizer: recognizer5..onTap = () {},
),
],
),
),
));
final SemanticsNode nodeAfterRemoval = tester.getSemantics(find.text('Hallo Welt '));
final Map<String, int> labelToNodeIdAfterRemoval = <String, int>{};
nodeAfterRemoval.visitChildren((SemanticsNode node) {
labelToNodeIdAfterRemoval[node.label] = node.id;
return true;
});
// Node IDs are stable.
expect(nodeAfterRemoval.id, node.id);
expect(labelToNodeIdAfterRemoval['Hallo '], labelToNodeId['Hallo ']);
expect(labelToNodeIdAfterRemoval['Welt '], labelToNodeId['Welt ']);
expect(labelToNodeIdAfterRemoval.length, 2);
final TapGestureRecognizer recognizer6 = TapGestureRecognizer();
addTearDown(recognizer6.dispose);
final TapGestureRecognizer recognizer7 = TapGestureRecognizer();
addTearDown(recognizer7.dispose);
final TapGestureRecognizer recognizer8 = TapGestureRecognizer();
addTearDown(recognizer8.dispose);
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: Text.rich(
TextSpan(
text: 'Hallo ',
recognizer: recognizer6..onTap = () {},
children: <TextSpan>[
TextSpan(
text: 'Welt ',
recognizer: recognizer7..onTap = () {},
),
TextSpan(
text: '!!!',
recognizer: recognizer8..onTap = () {},
),
],
),
),
));
expect(find.text('Hallo Welt !!!'), findsOneWidget);
final SemanticsNode nodeAfterAddition = tester.getSemantics(find.text('Hallo Welt !!!'));
final Map<String, int> labelToNodeIdAfterAddition = <String, int>{};
nodeAfterAddition.visitChildren((SemanticsNode node) {
labelToNodeIdAfterAddition[node.label] = node.id;
return true;
});
// New node gets a new ID.
expect(nodeAfterAddition.id, node.id);
expect(labelToNodeIdAfterAddition['Hallo '], labelToNodeId['Hallo ']);
expect(labelToNodeIdAfterAddition['Welt '], labelToNodeId['Welt ']);
expect(labelToNodeIdAfterAddition['!!!'], isNot(labelToNodeId['!!!']));
expect(labelToNodeIdAfterAddition['!!!'], isNotNull);
expect(labelToNodeIdAfterAddition.length, 3);
semantics.dispose();
});
}
| flutter/packages/flutter/test/widgets/text_semantics_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/text_semantics_test.dart",
"repo_id": "flutter",
"token_count": 2318
} | 731 |
// 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 TestUniqueWidget extends UniqueWidget<TestUniqueWidgetState> {
const TestUniqueWidget({ required super.key });
@override
TestUniqueWidgetState createState() => TestUniqueWidgetState();
}
class TestUniqueWidgetState extends State<TestUniqueWidget> {
@override
Widget build(BuildContext context) => Container();
}
void main() {
testWidgets('Unique widget control test', (WidgetTester tester) async {
final TestUniqueWidget widget = TestUniqueWidget(key: GlobalKey<TestUniqueWidgetState>());
await tester.pumpWidget(widget);
final TestUniqueWidgetState state = widget.currentState!;
expect(state, isNotNull);
await tester.pumpWidget(Container(child: widget));
expect(widget.currentState, equals(state));
});
}
| flutter/packages/flutter/test/widgets/unique_widget_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/unique_widget_test.dart",
"repo_id": "flutter",
"token_count": 292
} | 732 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
void main() {
// Changes made in https://github.com/flutter/flutter/pull/48547
var textTheme = TextTheme(
display4: displayStyle4,
display3: displayStyle3,
display2: displayStyle2,
display1: displayStyle1,
headline: headlineStyle,
title: titleStyle,
subhead: subheadStyle,
body2: body2Style,
body1: body1Style,
caption: captionStyle,
button: buttonStyle,
subtitle: subtitleStyle,
overline: overlineStyle,
);
var errorTextTheme = TextTheme(error: '');
// Changes made in https://github.com/flutter/flutter/pull/48547
var copiedTextTheme = TextTheme.copyWith(
display4: displayStyle4,
display3: displayStyle3,
display2: displayStyle2,
display1: displayStyle1,
headline: headlineStyle,
title: titleStyle,
subhead: subheadStyle,
body2: body2Style,
body1: body1Style,
caption: captionStyle,
button: buttonStyle,
subtitle: subtitleStyle,
overline: overlineStyle,
);
var errorCopiedTextTheme = TextTheme.copyWith(error: '');
// Changes made in https://github.com/flutter/flutter/pull/48547
var style;
style = textTheme.display4;
style = textTheme.display3;
style = textTheme.display2;
style = textTheme.display1;
style = textTheme.headline;
style = textTheme.title;
style = textTheme.subhead;
style = textTheme.body2;
style = textTheme.body1;
style = textTheme.caption;
style = textTheme.button;
style = textTheme.subtitle;
style = textTheme.overline;
// Changes made in https://github.com/flutter/flutter/pull/109817
var anotherTextTheme = TextTheme(
headline1: headline1Style,
headline2: headline2Style,
headline3: headline3Style,
headline4: headline4Style,
headline5: headline5Style,
headline6: headline6Style,
subtitle1: subtitle1Style,
subtitle2: subtitle2Style,
bodyText1: bodyText1Style,
bodyText2: bodyText2Style,
caption: captionStyle,
button: buttonStyle,
overline: overlineStyle,
);
var anotherErrorTextTheme = TextTheme(error: '');
// Changes made in https://github.com/flutter/flutter/pull/109817
var anotherCopiedTextTheme = TextTheme.copyWith(
headline1: headline1Style,
headline2: headline2Style,
headline3: headline3Style,
headline4: headline4Style,
headline5: headline5Style,
headline6: headline6Style,
subtitle1: subtitle1Style,
subtitle2: subtitle2Style,
bodyText1: bodyText1Style,
bodyText2: bodyText2Style,
caption: captionStyle,
button: buttonStyle,
overline: overlineStyle,
);
var anotherErrorCopiedTextTheme = TextTheme.copyWith(error: '');
// Changes made in https://github.com/flutter/flutter/pull/109817
var style;
style = textTheme.headline1;
style = textTheme.headline2;
style = textTheme.headline3;
style = textTheme.headline4;
style = textTheme.headline5;
style = textTheme.headline6;
style = textTheme.subtitle1;
style = textTheme.subtitle2;
style = textTheme.bodyText1;
style = textTheme.bodyText2;
style = textTheme.caption;
style = textTheme.button;
style = textTheme.overline;
}
| flutter/packages/flutter/test_fixes/material/text_theme.dart/0 | {
"file_path": "flutter/packages/flutter/test_fixes/material/text_theme.dart",
"repo_id": "flutter",
"token_count": 1154
} | 733 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:convert';
import 'dart:io';
import 'package:path/path.dart' as path;
import 'package:process_runner/process_runner.dart';
// This program enables testing of private interfaces in the flutter package.
//
// See README.md for more information.
final Directory flutterRoot =
Directory(path.fromUri(Platform.script)).absolute.parent.parent.parent.parent.parent;
final Directory flutterPackageDir = Directory(path.join(flutterRoot.path, 'packages', 'flutter'));
final Directory testPrivateDir = Directory(path.join(flutterPackageDir.path, 'test_private'));
final Directory privateTestsDir = Directory(path.join(testPrivateDir.path, 'test'));
void _usage() {
print('Usage: test_private.dart [--help] [--temp-dir=<temp_dir>]');
print('''
--help Print a usage message.
--temp-dir A location where temporary files may be written. Defaults to a
directory in the system temp folder. If a temp_dir is not
specified, then the default temp_dir will be created, used, and
removed automatically.
''');
}
Future<void> main(List<String> args) async {
// TODO(gspencergoog): Convert to using the args package once it has been
// converted to be non-nullable by default.
if (args.isNotEmpty && args[0] == '--help') {
_usage();
exit(0);
}
void errorExit(String message, {int exitCode = -1}) {
stderr.write('Error: $message\n\n');
_usage();
exit(exitCode);
}
if (args.length > 2) {
errorExit('Too many arguments.');
}
String? tempDirArg;
if (args.isNotEmpty) {
if (args[0].startsWith('--temp-dir')) {
if (args[0].startsWith('--temp-dir=')) {
tempDirArg = args[0].replaceFirst('--temp-dir=', '');
} else {
if (args.length < 2) {
errorExit('Not enough arguments to --temp-dir');
}
tempDirArg = args[1];
}
} else {
errorExit('Invalid arguments ${args.join(' ')}.');
}
}
Directory tempDir;
bool removeTempDir = false;
if (tempDirArg == null || tempDirArg.isEmpty) {
tempDir = Directory.systemTemp.createTempSync('flutter_package.');
removeTempDir = true;
} else {
tempDir = Directory(tempDirArg);
if (!tempDir.existsSync()) {
errorExit("Temporary directory $tempDirArg doesn't exist.");
}
}
bool success = true;
try {
await for (final TestCase testCase in getTestCases(tempDir)) {
stderr.writeln('Analyzing test case $testCase');
if (!testCase.setUp()) {
stderr.writeln('Unable to set up $testCase');
success = false;
break;
}
if (!await testCase.runAnalyzer()) {
stderr.writeln('Test case $testCase failed analysis.');
success = false;
break;
} else {
stderr.writeln('Test case $testCase passed analysis.');
}
stderr.writeln('Running test case $testCase');
if (!await testCase.runTests()) {
stderr.writeln('Test case $testCase failed.');
success = false;
break;
} else {
stderr.writeln('Test case $testCase succeeded.');
}
}
} finally {
if (removeTempDir) {
tempDir.deleteSync(recursive: true);
}
}
exit(success ? 0 : 1);
}
File makeAbsolute(File file, {Directory? workingDirectory}) {
workingDirectory ??= Directory.current;
return File(path.join(workingDirectory.absolute.path, file.path));
}
/// A test case representing a private test file that should be run.
///
/// It is loaded from a JSON manifest file that contains a list of dependencies
/// to copy, a list of test files themselves, and a pubspec file.
///
/// The dependencies are copied into the test area with the same relative path.
///
/// The test files are copied to the root of the test area.
///
/// The pubspec file is copied to the root of the test area too, but renamed to
/// "pubspec.yaml".
class TestCase {
TestCase.fromManifest(this.manifest, this.tmpdir) {
_json = jsonDecode(manifest.readAsStringSync()) as Map<String, dynamic>;
tmpdir.createSync(recursive: true);
assert(tmpdir.existsSync());
}
final File manifest;
final Directory tmpdir;
Map<String, dynamic> _json = <String, dynamic>{};
Iterable<File> _getList(String name) sync* {
for (final dynamic entry in _json[name] as List<dynamic>) {
final String name = entry as String;
yield File(path.joinAll(name.split('/')));
}
}
Iterable<File> get dependencies => _getList('deps');
Iterable<File> get testDependencies => _getList('test_deps');
Iterable<File> get tests => _getList('tests');
File get pubspec => File(_json['pubspec'] as String);
bool setUp() {
// Copy the manifest tests and deps to the same relative path under the
// tmpdir.
for (final File file in dependencies) {
try {
final Directory destDir = Directory(path.join(tmpdir.absolute.path, file.parent.path));
destDir.createSync(recursive: true);
final File absFile = makeAbsolute(file, workingDirectory: flutterPackageDir);
final String destination = path.join(tmpdir.absolute.path, file.path);
absFile.copySync(destination);
} on FileSystemException catch (e) {
stderr.writeln('Problem copying manifest dep file ${file.path} to ${tmpdir.path}: $e');
return false;
}
}
for (final File file in testDependencies) {
try {
final Directory destDir = Directory(path.join(tmpdir.absolute.path, 'lib', file.parent.path));
destDir.createSync(recursive: true);
final File absFile = makeAbsolute(file, workingDirectory: flutterPackageDir);
final String destination = path.join(tmpdir.absolute.path, 'lib', file.path);
absFile.copySync(destination);
} on FileSystemException catch (e) {
stderr.writeln('Problem copying manifest test_dep file ${file.path} to ${tmpdir.path}: $e');
return false;
}
}
// Copy the test files into the tmpdir's lib directory.
for (final File file in tests) {
String destination = tmpdir.path;
try {
final File absFile = makeAbsolute(file, workingDirectory: privateTestsDir);
// Copy the file, but without the ".tmpl" extension.
destination = path.join(tmpdir.absolute.path, 'lib', path.basenameWithoutExtension(file.path));
absFile.copySync(destination);
} on FileSystemException catch (e) {
stderr.writeln('Problem copying test ${file.path} to $destination: $e');
return false;
}
}
// Copy the pubspec to the right place.
makeAbsolute(pubspec, workingDirectory: privateTestsDir)
.copySync(path.join(tmpdir.absolute.path, 'pubspec.yaml'));
// Use Flutter's analysis_options.yaml file from packages/flutter.
File(path.join(tmpdir.absolute.path, 'analysis_options.yaml'))
.writeAsStringSync(
'include: ${path.toUri(path.join(flutterRoot.path, 'packages', 'flutter', 'analysis_options.yaml'))}\n'
'linter:\n'
' rules:\n'
// The code does wonky things with the part-of directive that cause false positives.
' unreachable_from_main: false'
);
return true;
}
Future<bool> runAnalyzer() async {
final String flutter = path.join(flutterRoot.path, 'bin', 'flutter');
final ProcessRunner runner = ProcessRunner(
defaultWorkingDirectory: tmpdir.absolute,
printOutputDefault: true,
);
final ProcessRunnerResult result = await runner.runProcess(
<String>[flutter, 'analyze', '--current-package', '--pub', '--congratulate', '.'],
failOk: true,
);
if (result.exitCode != 0) {
return false;
}
return true;
}
Future<bool> runTests() async {
final ProcessRunner runner = ProcessRunner(
defaultWorkingDirectory: tmpdir.absolute,
printOutputDefault: true,
);
final String flutter = path.join(flutterRoot.path, 'bin', 'flutter');
for (final File test in tests) {
final String testPath = path.join(path.dirname(test.path), 'lib', path.basenameWithoutExtension(test.path));
final ProcessRunnerResult result = await runner.runProcess(
<String>[flutter, 'test', testPath],
failOk: true,
);
if (result.exitCode != 0) {
return false;
}
}
return true;
}
@override
String toString() {
return path.basenameWithoutExtension(manifest.path);
}
}
Stream<TestCase> getTestCases(Directory tmpdir) async* {
final Directory testDir = Directory(path.join(testPrivateDir.path, 'test'));
await for (final FileSystemEntity entity in testDir.list(recursive: true)) {
if (path.split(entity.path).where((String element) => element.startsWith('.')).isNotEmpty) {
// Skip hidden files, directories, and the files inside them, like
// .dart_tool, which contains a (non-hidden) .json file.
continue;
}
if (entity is File && path.basename(entity.path).endsWith('_test.json')) {
print('Found manifest ${entity.path}');
final Directory testTmpDir =
Directory(path.join(tmpdir.absolute.path, path.basenameWithoutExtension(entity.path)));
yield TestCase.fromManifest(entity, testTmpDir);
}
}
}
| flutter/packages/flutter/test_private/bin/test_private.dart/0 | {
"file_path": "flutter/packages/flutter/test_private/bin/test_private.dart",
"repo_id": "flutter",
"token_count": 3463
} | 734 |
// 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';
/// An object sent from the Flutter Driver to a Flutter application to instruct
/// the application to perform a task.
abstract class Command {
/// Abstract const constructor. This constructor enables subclasses to provide
/// const constructors so that they can be used in const expressions.
const Command({ this.timeout });
/// Deserializes this command from the value generated by [serialize].
Command.deserialize(Map<String, String> json)
: timeout = _parseTimeout(json);
static Duration? _parseTimeout(Map<String, String> json) {
final String? timeout = json['timeout'];
if (timeout == null) {
return null;
}
return Duration(milliseconds: int.parse(timeout));
}
/// The maximum amount of time to wait for the command to complete.
///
/// Defaults to no timeout, because it is common for operations to take oddly
/// long in test environments (e.g. because the test host is overloaded), and
/// having timeouts essentially means having race conditions.
final Duration? timeout;
/// Identifies the type of the command object and of the handler.
String get kind;
/// Whether this command requires the widget tree to be initialized before
/// the command may be run.
///
/// This defaults to true to force the application under test to call [runApp]
/// before attempting to remotely drive the application. Subclasses may
/// override this to return false if they allow invocation before the
/// application has started.
///
/// See also:
///
/// * [WidgetsBinding.isRootWidgetAttached], which indicates whether the
/// widget tree has been initialized.
bool get requiresRootWidgetAttached => true;
/// Serializes this command to parameter name/value pairs.
@mustCallSuper
Map<String, String> serialize() {
final Map<String, String> result = <String, String>{
'command': kind,
};
if (timeout != null) {
result['timeout'] = '${timeout!.inMilliseconds}';
}
return result;
}
}
/// An object sent from a Flutter application back to the Flutter Driver in
/// response to a command.
abstract class Result {
/// A const constructor to allow subclasses to be const.
const Result();
/// An empty responds that does not include any result data.
///
/// Consider using this object as a result for [Command]s that do not return
/// any data.
static const Result empty = _EmptyResult();
/// Serializes this message to a JSON map.
Map<String, dynamic> toJson();
}
class _EmptyResult extends Result {
const _EmptyResult();
@override
Map<String, dynamic> toJson() => <String, dynamic>{};
}
| flutter/packages/flutter_driver/lib/src/common/message.dart/0 | {
"file_path": "flutter/packages/flutter_driver/lib/src/common/message.dart",
"repo_id": "flutter",
"token_count": 773
} | 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 'timeline.dart';
/// Event name for refresh rate related timeline events.
const String kUIThreadVsyncProcessEvent = 'VsyncProcessCallback';
/// A summary of [TimelineEvents]s corresponding to `kUIThreadVsyncProcessEvent` events.
///
/// `RefreshRate` is the time between the start of a vsync pulse and the target time of that vsync.
class RefreshRateSummary {
/// Creates a [RefreshRateSummary] given the timeline events.
RefreshRateSummary({required List<TimelineEvent> vsyncEvents}) {
final List<double> refreshRates = _computeRefreshRates(vsyncEvents);
_numberOfTotalFrames = refreshRates.length;
for (final double refreshRate in refreshRates) {
if ((refreshRate - 30).abs() < _kErrorMargin) {
_numberOf30HzFrames++;
continue;
}
if ((refreshRate - 60).abs() < _kErrorMargin) {
_numberOf60HzFrames++;
continue;
}
if ((refreshRate - 80).abs() < _kErrorMargin) {
_numberOf80HzFrames++;
continue;
}
if ((refreshRate - 90).abs() < _kErrorMargin) {
_numberOf90HzFrames++;
continue;
}
if ((refreshRate - 120).abs() < _kErrorMargin) {
_numberOf120HzFrames++;
continue;
}
_framesWithIllegalRefreshRate.add(refreshRate);
}
assert(_numberOfTotalFrames ==
_numberOf30HzFrames +
_numberOf60HzFrames +
_numberOf80HzFrames +
_numberOf90HzFrames +
_numberOf120HzFrames +
_framesWithIllegalRefreshRate.length);
}
// The error margin to determine the frame refresh rate.
// For example, when we calculated a frame that has a refresh rate of 65, we consider the frame to be a 60Hz frame.
// Can be adjusted if necessary.
static const double _kErrorMargin = 6.0;
/// The percentage of 30hz frames.
///
/// For example, if this value is 20, it means there are 20 percent of total
/// frames are 30hz. 0 means no frames are 30hz, 100 means all frames are 30hz.
double get percentageOf30HzFrames => _numberOfTotalFrames > 0
? _numberOf30HzFrames / _numberOfTotalFrames * 100
: 0;
/// The percentage of 60hz frames.
///
/// For example, if this value is 20, it means there are 20 percent of total
/// frames are 60hz. 0 means no frames are 60hz, 100 means all frames are 60hz.
double get percentageOf60HzFrames => _numberOfTotalFrames > 0
? _numberOf60HzFrames / _numberOfTotalFrames * 100
: 0;
/// The percentage of 80hz frames.
///
/// For example, if this value is 20, it means there are 20 percent of total
/// frames are 80hz. 0 means no frames are 80hz, 100 means all frames are 80hz.
double get percentageOf80HzFrames => _numberOfTotalFrames > 0
? _numberOf80HzFrames / _numberOfTotalFrames * 100
: 0;
/// The percentage of 90hz frames.
///
/// For example, if this value is 20, it means there are 20 percent of total
/// frames are 90hz. 0 means no frames are 90hz, 100 means all frames are 90hz.
double get percentageOf90HzFrames => _numberOfTotalFrames > 0
? _numberOf90HzFrames / _numberOfTotalFrames * 100
: 0;
/// The percentage of 120hz frames.
///
/// For example, if this value is 20, it means there are 20 percent of total
/// frames are 120hz. 0 means no frames are 120hz, 100 means all frames are 120hz.
double get percentageOf120HzFrames => _numberOfTotalFrames > 0
? _numberOf120HzFrames / _numberOfTotalFrames * 100
: 0;
/// A list of all the frames with Illegal refresh rate.
///
/// A refresh rate is consider illegal if it does not belong to anyone of the refresh rate this class is
/// explicitly tracking.
List<double> get framesWithIllegalRefreshRate =>
_framesWithIllegalRefreshRate;
int _numberOf30HzFrames = 0;
int _numberOf60HzFrames = 0;
int _numberOf80HzFrames = 0;
int _numberOf90HzFrames = 0;
int _numberOf120HzFrames = 0;
int _numberOfTotalFrames = 0;
final List<double> _framesWithIllegalRefreshRate = <double>[];
static List<double> _computeRefreshRates(List<TimelineEvent> vsyncEvents) {
final List<double> result = <double>[];
for (int i = 0; i < vsyncEvents.length; i++) {
final TimelineEvent event = vsyncEvents[i];
if (event.phase != 'B') {
continue;
}
assert(event.name == kUIThreadVsyncProcessEvent);
assert(event.arguments != null);
final Map<String, dynamic> arguments = event.arguments!;
const double nanosecondsPerSecond = 1e+9;
final int startTimeInNanoseconds = int.parse(arguments['StartTime'] as String);
final int targetTimeInNanoseconds = int.parse(arguments['TargetTime'] as String);
final int frameDurationInNanoseconds = targetTimeInNanoseconds - startTimeInNanoseconds;
final double refreshRate = nanosecondsPerSecond /
frameDurationInNanoseconds;
result.add(refreshRate);
}
return result;
}
}
| flutter/packages/flutter_driver/lib/src/driver/refresh_rate_summarizer.dart/0 | {
"file_path": "flutter/packages/flutter_driver/lib/src/driver/refresh_rate_summarizer.dart",
"repo_id": "flutter",
"token_count": 1772
} | 736 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_driver/flutter_driver.dart';
import '../../common.dart';
void main() {
final FakeDeserialize fakeDeserialize = FakeDeserialize();
test('Ancestor finder serialize', () {
const SerializableFinder of = ByType('Text');
final SerializableFinder matching = ByValueKey('hello');
final Ancestor a = Ancestor(
of: of,
matching: matching,
matchRoot: true,
firstMatchOnly: true,
);
expect(a.serialize(), <String, String>{
'finderType': 'Ancestor',
'of': '{"finderType":"ByType","type":"Text"}',
'matching': '{"finderType":"ByValueKey","keyValueString":"hello","keyValueType":"String"}',
'matchRoot': 'true',
'firstMatchOnly': 'true',
});
});
test('Ancestor finder deserialize', () {
final Map<String, String> serialized = <String, String>{
'finderType': 'Ancestor',
'of': '{"finderType":"ByType","type":"Text"}',
'matching': '{"finderType":"ByValueKey","keyValueString":"hello","keyValueType":"String"}',
'matchRoot': 'true',
'firstMatchOnly': 'true',
};
final Ancestor a = Ancestor.deserialize(serialized, fakeDeserialize);
expect(a.of, isA<ByType>());
expect(a.matching, isA<ByValueKey>());
expect(a.matchRoot, isTrue);
expect(a.firstMatchOnly, isTrue);
});
test('Descendant finder serialize', () {
const SerializableFinder of = ByType('Text');
final SerializableFinder matching = ByValueKey('hello');
final Descendant a = Descendant(
of: of,
matching: matching,
matchRoot: true,
firstMatchOnly: true,
);
expect(a.serialize(), <String, String>{
'finderType': 'Descendant',
'of': '{"finderType":"ByType","type":"Text"}',
'matching': '{"finderType":"ByValueKey","keyValueString":"hello","keyValueType":"String"}',
'matchRoot': 'true',
'firstMatchOnly': 'true',
});
});
test('Descendant finder deserialize', () {
final Map<String, String> serialized = <String, String>{
'finderType': 'Descendant',
'of': '{"finderType":"ByType","type":"Text"}',
'matching': '{"finderType":"ByValueKey","keyValueString":"hello","keyValueType":"String"}',
'matchRoot': 'true',
'firstMatchOnly': 'true',
};
final Descendant a = Descendant.deserialize(serialized, fakeDeserialize);
expect(a.of, isA<ByType>());
expect(a.matching, isA<ByValueKey>());
expect(a.matchRoot, isTrue);
expect(a.firstMatchOnly, isTrue);
});
}
class FakeDeserialize extends Fake with DeserializeFinderFactory { }
| flutter/packages/flutter_driver/test/src/real_tests/find_test.dart/0 | {
"file_path": "flutter/packages/flutter_driver/test/src/real_tests/find_test.dart",
"repo_id": "flutter",
"token_count": 1026
} | 737 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:intl/intl.dart' as intl;
import 'l10n/generated_cupertino_localizations.dart';
import 'utils/date_localizations.dart' as util;
import 'widgets_localizations.dart';
// Examples can assume:
// import 'package:flutter_localizations/flutter_localizations.dart';
// import 'package:flutter/cupertino.dart';
/// Implementation of localized strings for Cupertino widgets using the `intl`
/// package for date and time formatting.
///
/// Further localization of strings beyond date time formatting are provided
/// by language specific subclasses of [GlobalCupertinoLocalizations].
///
/// ## Supported languages
///
/// This class supports locales with the following [Locale.languageCode]s:
///
/// {@macro flutter.localizations.cupertino.languages}
///
/// This list is available programmatically via [kCupertinoSupportedLanguages].
///
/// ## Sample code
///
/// To include the localizations provided by this class in a [CupertinoApp],
/// add [GlobalCupertinoLocalizations.delegates] to
/// [CupertinoApp.localizationsDelegates], and specify the locales your
/// app supports with [CupertinoApp.supportedLocales]:
///
/// ```dart
/// const CupertinoApp(
/// localizationsDelegates: GlobalCupertinoLocalizations.delegates,
/// supportedLocales: <Locale>[
/// Locale('en', 'US'), // American English
/// Locale('he', 'IL'), // Israeli Hebrew
/// // ...
/// ],
/// // ...
/// )
/// ```
///
/// See also:
///
/// * [DefaultCupertinoLocalizations], which provides US English localizations
/// for Cupertino widgets.
abstract class GlobalCupertinoLocalizations implements CupertinoLocalizations {
/// Initializes an object that defines the Cupertino widgets' localized
/// strings for the given `localeName`.
///
/// The remaining '*Format' arguments uses the intl package to provide
/// [DateFormat] configurations for the `localeName`.
const GlobalCupertinoLocalizations({
required String localeName,
required intl.DateFormat fullYearFormat,
required intl.DateFormat dayFormat,
required intl.DateFormat mediumDateFormat,
required intl.DateFormat singleDigitHourFormat,
required intl.DateFormat singleDigitMinuteFormat,
required intl.DateFormat doubleDigitMinuteFormat,
required intl.DateFormat singleDigitSecondFormat,
required intl.NumberFormat decimalFormat,
}) : _localeName = localeName,
_fullYearFormat = fullYearFormat,
_dayFormat = dayFormat,
_mediumDateFormat = mediumDateFormat,
_singleDigitHourFormat = singleDigitHourFormat,
_singleDigitMinuteFormat = singleDigitMinuteFormat,
_doubleDigitMinuteFormat = doubleDigitMinuteFormat,
_singleDigitSecondFormat = singleDigitSecondFormat,
_decimalFormat =decimalFormat;
final String _localeName;
final intl.DateFormat _fullYearFormat;
final intl.DateFormat _dayFormat;
final intl.DateFormat _mediumDateFormat;
final intl.DateFormat _singleDigitHourFormat;
final intl.DateFormat _singleDigitMinuteFormat;
final intl.DateFormat _doubleDigitMinuteFormat;
final intl.DateFormat _singleDigitSecondFormat;
final intl.NumberFormat _decimalFormat;
@override
String datePickerYear(int yearIndex) {
return _fullYearFormat.format(DateTime.utc(yearIndex));
}
@override
String datePickerMonth(int monthIndex) {
// It doesn't actually have anything to do with _fullYearFormat. It's just
// taking advantage of the fact that _fullYearFormat loaded the needed
// locale's symbols.
return _fullYearFormat.dateSymbols.MONTHS[monthIndex - 1];
}
@override
String datePickerStandaloneMonth(int monthIndex) {
// It doesn't actually have anything to do with _fullYearFormat. It's just
// taking advantage of the fact that _fullYearFormat loaded the needed
// locale's symbols.
//
// Because this will be used without specifying any day of month,
// in most cases it should be capitalized (according to rules in specific language).
return intl.toBeginningOfSentenceCase(_fullYearFormat.dateSymbols.STANDALONEMONTHS[monthIndex - 1]) ??
_fullYearFormat.dateSymbols.STANDALONEMONTHS[monthIndex - 1];
}
@override
String datePickerDayOfMonth(int dayIndex, [int? weekDay]) {
if (weekDay != null) {
return ' ${DefaultCupertinoLocalizations.shortWeekdays[weekDay - DateTime.monday]} $dayIndex ';
}
// Year and month doesn't matter since we just want to day formatted.
return _dayFormat.format(DateTime.utc(0, 0, dayIndex));
}
@override
String datePickerMediumDate(DateTime date) {
return _mediumDateFormat.format(date);
}
@override
String datePickerHour(int hour) {
return _singleDigitHourFormat.format(DateTime.utc(0, 0, 0, hour));
}
@override
String datePickerMinute(int minute) {
return _doubleDigitMinuteFormat.format(DateTime.utc(0, 0, 0, 0, minute));
}
/// Subclasses should provide the optional zero pluralization of [datePickerHourSemanticsLabel] based on the ARB file.
@protected
String? get datePickerHourSemanticsLabelZero => null;
/// Subclasses should provide the optional one pluralization of [datePickerHourSemanticsLabel] based on the ARB file.
@protected
String? get datePickerHourSemanticsLabelOne => null;
/// Subclasses should provide the optional two pluralization of [datePickerHourSemanticsLabel] based on the ARB file.
@protected
String? get datePickerHourSemanticsLabelTwo => null;
/// Subclasses should provide the optional few pluralization of [datePickerHourSemanticsLabel] based on the ARB file.
@protected
String? get datePickerHourSemanticsLabelFew => null;
/// Subclasses should provide the optional many pluralization of [datePickerHourSemanticsLabel] based on the ARB file.
@protected
String? get datePickerHourSemanticsLabelMany => null;
/// Subclasses should provide the required other pluralization of [datePickerHourSemanticsLabel] based on the ARB file.
@protected
String? get datePickerHourSemanticsLabelOther;
@override
String? datePickerHourSemanticsLabel(int hour) {
return intl.Intl.pluralLogic(
hour,
zero: datePickerHourSemanticsLabelZero,
one: datePickerHourSemanticsLabelOne,
two: datePickerHourSemanticsLabelTwo,
few: datePickerHourSemanticsLabelFew,
many: datePickerHourSemanticsLabelMany,
other: datePickerHourSemanticsLabelOther,
locale: _localeName,
)?.replaceFirst(r'$hour', _decimalFormat.format(hour));
}
/// Subclasses should provide the optional zero pluralization of [datePickerMinuteSemanticsLabel] based on the ARB file.
@protected
String? get datePickerMinuteSemanticsLabelZero => null;
/// Subclasses should provide the optional one pluralization of [datePickerMinuteSemanticsLabel] based on the ARB file.
@protected
String? get datePickerMinuteSemanticsLabelOne => null;
/// Subclasses should provide the optional two pluralization of [datePickerMinuteSemanticsLabel] based on the ARB file.
@protected
String? get datePickerMinuteSemanticsLabelTwo => null;
/// Subclasses should provide the optional few pluralization of [datePickerMinuteSemanticsLabel] based on the ARB file.
@protected
String? get datePickerMinuteSemanticsLabelFew => null;
/// Subclasses should provide the optional many pluralization of [datePickerMinuteSemanticsLabel] based on the ARB file.
@protected
String? get datePickerMinuteSemanticsLabelMany => null;
/// Subclasses should provide the required other pluralization of [datePickerMinuteSemanticsLabel] based on the ARB file.
@protected
String? get datePickerMinuteSemanticsLabelOther;
@override
String? datePickerMinuteSemanticsLabel(int minute) {
return intl.Intl.pluralLogic(
minute,
zero: datePickerMinuteSemanticsLabelZero,
one: datePickerMinuteSemanticsLabelOne,
two: datePickerMinuteSemanticsLabelTwo,
few: datePickerMinuteSemanticsLabelFew,
many: datePickerMinuteSemanticsLabelMany,
other: datePickerMinuteSemanticsLabelOther,
locale: _localeName,
)?.replaceFirst(r'$minute', _decimalFormat.format(minute));
}
/// A string describing the [DatePickerDateOrder] enum value.
///
/// Subclasses should provide this string value based on the ARB file for
/// the locale.
///
/// See also:
///
/// * [datePickerDateOrder], which provides the [DatePickerDateOrder]
/// enum value for [CupertinoLocalizations] based on this string value
@protected
String get datePickerDateOrderString;
@override
DatePickerDateOrder get datePickerDateOrder {
switch (datePickerDateOrderString) {
case 'dmy':
return DatePickerDateOrder.dmy;
case 'mdy':
return DatePickerDateOrder.mdy;
case 'ymd':
return DatePickerDateOrder.ymd;
case 'ydm':
return DatePickerDateOrder.ydm;
default:
assert(
false,
'Failed to load DatePickerDateOrder $datePickerDateOrderString for '
"locale $_localeName.\nNon conforming string for $_localeName's "
'.arb file',
);
return DatePickerDateOrder.mdy;
}
}
/// A string describing the [DatePickerDateTimeOrder] enum value.
///
/// Subclasses should provide this string value based on the ARB file for
/// the locale.
///
/// See also:
///
/// * [datePickerDateTimeOrder], which provides the [DatePickerDateTimeOrder]
/// enum value for [CupertinoLocalizations] based on this string value.
@protected
String get datePickerDateTimeOrderString;
@override
DatePickerDateTimeOrder get datePickerDateTimeOrder {
switch (datePickerDateTimeOrderString) {
case 'date_time_dayPeriod':
return DatePickerDateTimeOrder.date_time_dayPeriod;
case 'date_dayPeriod_time':
return DatePickerDateTimeOrder.date_dayPeriod_time;
case 'time_dayPeriod_date':
return DatePickerDateTimeOrder.time_dayPeriod_date;
case 'dayPeriod_time_date':
return DatePickerDateTimeOrder.dayPeriod_time_date;
default:
assert(
false,
'Failed to load DatePickerDateTimeOrder $datePickerDateTimeOrderString '
"for locale $_localeName.\nNon conforming string for $_localeName's "
'.arb file',
);
return DatePickerDateTimeOrder.date_time_dayPeriod;
}
}
/// The raw version of [tabSemanticsLabel], with `$tabIndex` and `$tabCount` verbatim
/// in the string.
@protected
String get tabSemanticsLabelRaw;
@override
String tabSemanticsLabel({ required int tabIndex, required int tabCount }) {
assert(tabIndex >= 1);
assert(tabCount >= 1);
final String template = tabSemanticsLabelRaw;
return template
.replaceFirst(r'$tabIndex', _decimalFormat.format(tabIndex))
.replaceFirst(r'$tabCount', _decimalFormat.format(tabCount));
}
@override
String timerPickerHour(int hour) {
return _singleDigitHourFormat.format(DateTime.utc(0, 0, 0, hour));
}
@override
String timerPickerMinute(int minute) {
return _singleDigitMinuteFormat.format(DateTime.utc(0, 0, 0, 0, minute));
}
@override
String timerPickerSecond(int second) {
return _singleDigitSecondFormat.format(DateTime.utc(0, 0, 0, 0, 0, second));
}
/// Subclasses should provide the optional zero pluralization of [timerPickerHourLabel] based on the ARB file.
@protected
String? get timerPickerHourLabelZero => null;
/// Subclasses should provide the optional one pluralization of [timerPickerHourLabel] based on the ARB file.
@protected
String? get timerPickerHourLabelOne => null;
/// Subclasses should provide the optional two pluralization of [timerPickerHourLabel] based on the ARB file.
@protected
String? get timerPickerHourLabelTwo => null;
/// Subclasses should provide the optional few pluralization of [timerPickerHourLabel] based on the ARB file.
@protected
String? get timerPickerHourLabelFew => null;
/// Subclasses should provide the optional many pluralization of [timerPickerHourLabel] based on the ARB file.
@protected
String? get timerPickerHourLabelMany => null;
/// Subclasses should provide the required other pluralization of [timerPickerHourLabel] based on the ARB file.
@protected
String? get timerPickerHourLabelOther;
@override
String? timerPickerHourLabel(int hour) {
return intl.Intl.pluralLogic(
hour,
zero: timerPickerHourLabelZero,
one: timerPickerHourLabelOne,
two: timerPickerHourLabelTwo,
few: timerPickerHourLabelFew,
many: timerPickerHourLabelMany,
other: timerPickerHourLabelOther,
locale: _localeName,
)?.replaceFirst(r'$hour', _decimalFormat.format(hour));
}
@override
List<String> get timerPickerHourLabels => <String>[
if (timerPickerHourLabelZero != null) timerPickerHourLabelZero!,
if (timerPickerHourLabelOne != null) timerPickerHourLabelOne!,
if (timerPickerHourLabelTwo != null) timerPickerHourLabelTwo!,
if (timerPickerHourLabelFew != null) timerPickerHourLabelFew!,
if (timerPickerHourLabelMany != null) timerPickerHourLabelMany!,
if (timerPickerHourLabelOther != null) timerPickerHourLabelOther!,
];
/// Subclasses should provide the optional zero pluralization of [timerPickerMinuteLabel] based on the ARB file.
@protected
String? get timerPickerMinuteLabelZero => null;
/// Subclasses should provide the optional one pluralization of [timerPickerMinuteLabel] based on the ARB file.
@protected
String? get timerPickerMinuteLabelOne => null;
/// Subclasses should provide the optional two pluralization of [timerPickerMinuteLabel] based on the ARB file.
@protected
String? get timerPickerMinuteLabelTwo => null;
/// Subclasses should provide the optional few pluralization of [timerPickerMinuteLabel] based on the ARB file.
@protected
String? get timerPickerMinuteLabelFew => null;
/// Subclasses should provide the optional many pluralization of [timerPickerMinuteLabel] based on the ARB file.
@protected
String? get timerPickerMinuteLabelMany => null;
/// Subclasses should provide the required other pluralization of [timerPickerMinuteLabel] based on the ARB file.
@protected
String? get timerPickerMinuteLabelOther;
@override
String? timerPickerMinuteLabel(int minute) {
return intl.Intl.pluralLogic(
minute,
zero: timerPickerMinuteLabelZero,
one: timerPickerMinuteLabelOne,
two: timerPickerMinuteLabelTwo,
few: timerPickerMinuteLabelFew,
many: timerPickerMinuteLabelMany,
other: timerPickerMinuteLabelOther,
locale: _localeName,
)?.replaceFirst(r'$minute', _decimalFormat.format(minute));
}
@override
List<String> get timerPickerMinuteLabels => <String>[
if (timerPickerMinuteLabelZero != null) timerPickerMinuteLabelZero!,
if (timerPickerMinuteLabelOne != null) timerPickerMinuteLabelOne!,
if (timerPickerMinuteLabelTwo != null) timerPickerMinuteLabelTwo!,
if (timerPickerMinuteLabelFew != null) timerPickerMinuteLabelFew!,
if (timerPickerMinuteLabelMany != null) timerPickerMinuteLabelMany!,
if (timerPickerMinuteLabelOther != null) timerPickerMinuteLabelOther!,
];
/// Subclasses should provide the optional zero pluralization of [timerPickerSecondLabel] based on the ARB file.
@protected
String? get timerPickerSecondLabelZero => null;
/// Subclasses should provide the optional one pluralization of [timerPickerSecondLabel] based on the ARB file.
@protected
String? get timerPickerSecondLabelOne => null;
/// Subclasses should provide the optional two pluralization of [timerPickerSecondLabel] based on the ARB file.
@protected
String? get timerPickerSecondLabelTwo => null;
/// Subclasses should provide the optional few pluralization of [timerPickerSecondLabel] based on the ARB file.
@protected
String? get timerPickerSecondLabelFew => null;
/// Subclasses should provide the optional many pluralization of [timerPickerSecondLabel] based on the ARB file.
@protected
String? get timerPickerSecondLabelMany => null;
/// Subclasses should provide the required other pluralization of [timerPickerSecondLabel] based on the ARB file.
@protected
String? get timerPickerSecondLabelOther;
@override
String? timerPickerSecondLabel(int second) {
return intl.Intl.pluralLogic(
second,
zero: timerPickerSecondLabelZero,
one: timerPickerSecondLabelOne,
two: timerPickerSecondLabelTwo,
few: timerPickerSecondLabelFew,
many: timerPickerSecondLabelMany,
other: timerPickerSecondLabelOther,
locale: _localeName,
)?.replaceFirst(r'$second', _decimalFormat.format(second));
}
@override
List<String> get timerPickerSecondLabels => <String>[
if (timerPickerSecondLabelZero != null) timerPickerSecondLabelZero!,
if (timerPickerSecondLabelOne != null) timerPickerSecondLabelOne!,
if (timerPickerSecondLabelTwo != null) timerPickerSecondLabelTwo!,
if (timerPickerSecondLabelFew != null) timerPickerSecondLabelFew!,
if (timerPickerSecondLabelMany != null) timerPickerSecondLabelMany!,
if (timerPickerSecondLabelOther != null) timerPickerSecondLabelOther!,
];
/// A [LocalizationsDelegate] for [CupertinoLocalizations].
///
/// Most internationalized apps will use [GlobalCupertinoLocalizations.delegates]
/// as the value of [CupertinoApp.localizationsDelegates] to include
/// the localizations for both the cupertino and widget libraries.
static const LocalizationsDelegate<CupertinoLocalizations> delegate = _GlobalCupertinoLocalizationsDelegate();
/// A value for [CupertinoApp.localizationsDelegates] that's typically used by
/// internationalized apps.
///
/// ## Sample code
///
/// To include the localizations provided by this class and by
/// [GlobalWidgetsLocalizations] in a [CupertinoApp],
/// use [GlobalCupertinoLocalizations.delegates] as the value of
/// [CupertinoApp.localizationsDelegates], and specify the locales your
/// app supports with [CupertinoApp.supportedLocales]:
///
/// ```dart
/// const CupertinoApp(
/// localizationsDelegates: GlobalCupertinoLocalizations.delegates,
/// supportedLocales: <Locale>[
/// Locale('en', 'US'), // English
/// Locale('he', 'IL'), // Hebrew
/// ],
/// // ...
/// )
/// ```
static const List<LocalizationsDelegate<dynamic>> delegates = <LocalizationsDelegate<dynamic>>[
GlobalCupertinoLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
];
}
class _GlobalCupertinoLocalizationsDelegate extends LocalizationsDelegate<CupertinoLocalizations> {
const _GlobalCupertinoLocalizationsDelegate();
@override
bool isSupported(Locale locale) => kCupertinoSupportedLanguages.contains(locale.languageCode);
static final Map<Locale, Future<CupertinoLocalizations>> _loadedTranslations = <Locale, Future<CupertinoLocalizations>>{};
@override
Future<CupertinoLocalizations> load(Locale locale) {
assert(isSupported(locale));
return _loadedTranslations.putIfAbsent(locale, () {
util.loadDateIntlDataIfNotLoaded();
final String localeName = intl.Intl.canonicalizedLocale(locale.toString());
assert(
locale.toString() == localeName,
'Flutter does not support the non-standard locale form $locale (which '
'might be $localeName',
);
late intl.DateFormat fullYearFormat;
late intl.DateFormat dayFormat;
late intl.DateFormat mediumDateFormat;
// We don't want any additional decoration here. The am/pm is handled in
// the date picker. We just want an hour number localized.
late intl.DateFormat singleDigitHourFormat;
late intl.DateFormat singleDigitMinuteFormat;
late intl.DateFormat doubleDigitMinuteFormat;
late intl.DateFormat singleDigitSecondFormat;
late intl.NumberFormat decimalFormat;
void loadFormats(String? locale) {
fullYearFormat = intl.DateFormat.y(locale);
dayFormat = intl.DateFormat.d(locale);
mediumDateFormat = intl.DateFormat.MMMEd(locale);
// TODO(xster): fix when https://github.com/dart-lang/intl/issues/207 is resolved.
singleDigitHourFormat = intl.DateFormat('HH', locale);
singleDigitMinuteFormat = intl.DateFormat.m(locale);
doubleDigitMinuteFormat = intl.DateFormat('mm', locale);
singleDigitSecondFormat = intl.DateFormat.s(locale);
decimalFormat = intl.NumberFormat.decimalPattern(locale);
}
if (intl.DateFormat.localeExists(localeName)) {
loadFormats(localeName);
} else if (intl.DateFormat.localeExists(locale.languageCode)) {
loadFormats(locale.languageCode);
} else {
loadFormats(null);
}
return SynchronousFuture<CupertinoLocalizations>(getCupertinoTranslation(
locale,
fullYearFormat,
dayFormat,
mediumDateFormat,
singleDigitHourFormat,
singleDigitMinuteFormat,
doubleDigitMinuteFormat,
singleDigitSecondFormat,
decimalFormat,
)!);
});
}
@override
bool shouldReload(_GlobalCupertinoLocalizationsDelegate old) => false;
@override
String toString() => 'GlobalCupertinoLocalizations.delegate(${kCupertinoSupportedLanguages.length} locales)';
}
| flutter/packages/flutter_localizations/lib/src/cupertino_localizations.dart/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/cupertino_localizations.dart",
"repo_id": "flutter",
"token_count": 7047
} | 738 |
{
"searchTextFieldPlaceholderLabel": "Suche",
"datePickerHourSemanticsLabelOne": "$hour Uhr",
"datePickerHourSemanticsLabelOther": "$hour Uhr",
"datePickerMinuteSemanticsLabelOne": "1 Minute",
"datePickerMinuteSemanticsLabelOther": "$minute Minuten",
"datePickerDateOrder": "dmy",
"datePickerDateTimeOrder": "date_time_dayPeriod",
"anteMeridiemAbbreviation": "AM",
"postMeridiemAbbreviation": "PM",
"todayLabel": "Heute",
"alertDialogLabel": "Benachrichtigung",
"tabSemanticsLabel": "Tab $tabIndex von $tabCount",
"timerPickerHourLabelOne": "Stunde",
"timerPickerHourLabelOther": "Stunden",
"timerPickerMinuteLabelOne": "Min.",
"timerPickerMinuteLabelOther": "Min.",
"timerPickerSecondLabelOne": "s",
"timerPickerSecondLabelOther": "s",
"cutButtonLabel": "Ausschneiden",
"copyButtonLabel": "Kopieren",
"pasteButtonLabel": "Einsetzen",
"clearButtonLabel": "Clear",
"selectAllButtonLabel": "Alles auswählen",
"modalBarrierDismissLabel": "Schliessen"
}
| flutter/packages/flutter_localizations/lib/src/l10n/cupertino_de_CH.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_de_CH.arb",
"repo_id": "flutter",
"token_count": 366
} | 739 |
{
"datePickerHourSemanticsLabelOne": "Kell $hour",
"datePickerHourSemanticsLabelOther": "Kell $hour",
"datePickerMinuteSemanticsLabelOne": "1 minut",
"datePickerMinuteSemanticsLabelOther": "$minute minutit",
"datePickerDateOrder": "dmy",
"datePickerDateTimeOrder": "date_time_dayPeriod",
"anteMeridiemAbbreviation": "AM",
"postMeridiemAbbreviation": "PM",
"todayLabel": "Täna",
"alertDialogLabel": "Märguanne",
"timerPickerHourLabelOne": "tund",
"timerPickerHourLabelOther": "tundi",
"timerPickerMinuteLabelOne": "min",
"timerPickerMinuteLabelOther": "min",
"timerPickerSecondLabelOne": "s",
"timerPickerSecondLabelOther": "s",
"cutButtonLabel": "Lõika",
"copyButtonLabel": "Kopeeri",
"pasteButtonLabel": "Kleebi",
"selectAllButtonLabel": "Vali kõik",
"tabSemanticsLabel": "$tabIndex. vaheleht $tabCount-st",
"modalBarrierDismissLabel": "Loobu",
"searchTextFieldPlaceholderLabel": "Otsige",
"noSpellCheckReplacementsLabel": "Asendusi ei leitud",
"menuDismissLabel": "Sulge menüü",
"lookUpButtonLabel": "Look Up",
"searchWebButtonLabel": "Otsi veebist",
"shareButtonLabel": "Jaga …",
"clearButtonLabel": "Clear"
}
| flutter/packages/flutter_localizations/lib/src/l10n/cupertino_et.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_et.arb",
"repo_id": "flutter",
"token_count": 440
} | 740 |
{
"datePickerHourSemanticsLabelOne": "klukkan $hour",
"datePickerHourSemanticsLabelOther": "klukkan $hour",
"datePickerMinuteSemanticsLabelOne": "1 mínúta",
"datePickerMinuteSemanticsLabelOther": "$minute mínútur",
"datePickerDateOrder": "dmy",
"datePickerDateTimeOrder": "date_time_dayPeriod",
"anteMeridiemAbbreviation": "f.h.",
"postMeridiemAbbreviation": "e.h.",
"todayLabel": "Í dag",
"alertDialogLabel": "Tilkynning",
"timerPickerHourLabelOne": "klukkustund",
"timerPickerHourLabelOther": "klukkustundir",
"timerPickerMinuteLabelOne": "mín.",
"timerPickerMinuteLabelOther": "mín.",
"timerPickerSecondLabelOne": "sek.",
"timerPickerSecondLabelOther": "sek.",
"cutButtonLabel": "Klippa",
"copyButtonLabel": "Afrita",
"pasteButtonLabel": "Líma",
"selectAllButtonLabel": "Velja allt",
"tabSemanticsLabel": "Flipi $tabIndex af $tabCount",
"modalBarrierDismissLabel": "Hunsa",
"searchTextFieldPlaceholderLabel": "Leit",
"noSpellCheckReplacementsLabel": "Engir staðgenglar fundust",
"menuDismissLabel": "Loka valmynd",
"lookUpButtonLabel": "Look Up",
"searchWebButtonLabel": "Leita á vefnum",
"shareButtonLabel": "Deila...",
"clearButtonLabel": "Clear"
}
| flutter/packages/flutter_localizations/lib/src/l10n/cupertino_is.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_is.arb",
"repo_id": "flutter",
"token_count": 454
} | 741 |
{
"datePickerHourSemanticsLabelOne": "Pukul $hour",
"datePickerHourSemanticsLabelOther": "Pukul $hour",
"datePickerMinuteSemanticsLabelOne": "1 minit",
"datePickerMinuteSemanticsLabelOther": "$minute minit",
"datePickerDateOrder": "dmy",
"datePickerDateTimeOrder": "date_time_dayPeriod",
"anteMeridiemAbbreviation": "PG",
"postMeridiemAbbreviation": "P/M",
"todayLabel": "Hari ini",
"alertDialogLabel": "Makluman",
"timerPickerHourLabelOne": "jam",
"timerPickerHourLabelOther": "jam",
"timerPickerMinuteLabelOne": "minit",
"timerPickerMinuteLabelOther": "minit",
"timerPickerSecondLabelOne": "saat",
"timerPickerSecondLabelOther": "saat",
"cutButtonLabel": "Potong",
"copyButtonLabel": "Salin",
"pasteButtonLabel": "Tampal",
"selectAllButtonLabel": "Pilih Semua",
"tabSemanticsLabel": "Tab $tabIndex daripada $tabCount",
"modalBarrierDismissLabel": "Tolak",
"searchTextFieldPlaceholderLabel": "Cari",
"noSpellCheckReplacementsLabel": "Tiada Penggantian Ditemukan",
"menuDismissLabel": "Ketepikan menu",
"lookUpButtonLabel": "Lihat ke Atas",
"searchWebButtonLabel": "Buat carian pada Web",
"shareButtonLabel": "Kongsi...",
"clearButtonLabel": "Clear"
}
| flutter/packages/flutter_localizations/lib/src/l10n/cupertino_ms.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_ms.arb",
"repo_id": "flutter",
"token_count": 444
} | 742 |
{
"datePickerHourSemanticsLabelOne": "$hour fiks",
"datePickerHourSemanticsLabelOther": "$hour fiks",
"datePickerMinuteSemanticsLabelOne": "1 minutë",
"datePickerMinuteSemanticsLabelOther": "$minute minuta",
"datePickerDateOrder": "dmy",
"datePickerDateTimeOrder": "date_time_dayPeriod",
"anteMeridiemAbbreviation": "paradite",
"postMeridiemAbbreviation": "pasdite",
"todayLabel": "Sot",
"alertDialogLabel": "Sinjalizim",
"timerPickerHourLabelOne": "orë",
"timerPickerHourLabelOther": "orë",
"timerPickerMinuteLabelOne": "min.",
"timerPickerMinuteLabelOther": "min.",
"timerPickerSecondLabelOne": "sek.",
"timerPickerSecondLabelOther": "sek.",
"cutButtonLabel": "Prit",
"copyButtonLabel": "Kopjo",
"pasteButtonLabel": "Ngjit",
"selectAllButtonLabel": "Zgjidhi të gjitha",
"tabSemanticsLabel": "Skeda $tabIndex nga $tabCount",
"modalBarrierDismissLabel": "Hiq",
"searchTextFieldPlaceholderLabel": "Kërko",
"noSpellCheckReplacementsLabel": "Nuk u gjetën zëvendësime",
"menuDismissLabel": "Hiqe menynë",
"lookUpButtonLabel": "Kërko",
"searchWebButtonLabel": "Kërko në ueb",
"shareButtonLabel": "Ndaj...",
"clearButtonLabel": "Clear"
}
| flutter/packages/flutter_localizations/lib/src/l10n/cupertino_sq.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_sq.arb",
"repo_id": "flutter",
"token_count": 454
} | 743 |
{
"lookUpButtonLabel": "查詢",
"searchWebButtonLabel": "搜尋",
"shareButtonLabel": "分享…",
"noSpellCheckReplacementsLabel": "找不到替代文字",
"menuDismissLabel": "關閉選單",
"searchTextFieldPlaceholderLabel": "搜尋",
"tabSemanticsLabel": "第 $tabIndex 個分頁標籤,共 $tabCount 個",
"datePickerHourSemanticsLabelOne": "$hour 點",
"datePickerHourSemanticsLabelOther": "$hour 點",
"datePickerMinuteSemanticsLabelOne": "1 分",
"datePickerMinuteSemanticsLabelOther": "$minute 分",
"datePickerDateOrder": "ymd",
"datePickerDateTimeOrder": "date_time_dayPeriod",
"anteMeridiemAbbreviation": "上午",
"postMeridiemAbbreviation": "下午",
"todayLabel": "今天",
"alertDialogLabel": "快訊",
"timerPickerHourLabelOne": "小時",
"timerPickerHourLabelOther": "小時",
"timerPickerMinuteLabelOne": "分",
"timerPickerMinuteLabelOther": "分",
"timerPickerSecondLabelOne": "秒",
"timerPickerSecondLabelOther": "秒",
"cutButtonLabel": "剪下",
"copyButtonLabel": "複製",
"pasteButtonLabel": "貼上",
"selectAllButtonLabel": "全選",
"modalBarrierDismissLabel": "關閉"
}
| flutter/packages/flutter_localizations/lib/src/l10n/cupertino_zh_TW.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_zh_TW.arb",
"repo_id": "flutter",
"token_count": 480
} | 744 |
{
"licensesPackageDetailTextFew": "$licenseCount licence",
"licensesPackageDetailTextMany": "$licenseCount licence",
"remainingTextFieldCharacterCountFew": "Zbývají $remainingCount znaky",
"remainingTextFieldCharacterCountMany": "Zbývá $remainingCount znaku",
"scriptCategory": "English-like",
"timeOfDayFormat": "HH:mm",
"selectedRowCountTitleFew": "Jsou vybrány $selectedRowCount položky",
"selectedRowCountTitleMany": "Je vybráno $selectedRowCount položky",
"openAppDrawerTooltip": "Otevřít navigační nabídku",
"backButtonTooltip": "Zpět",
"closeButtonTooltip": "Zavřít",
"deleteButtonTooltip": "Smazat",
"nextMonthTooltip": "Další měsíc",
"previousMonthTooltip": "Předchozí měsíc",
"nextPageTooltip": "Další stránka",
"firstPageTooltip": "První stránka",
"lastPageTooltip": "Poslední stránka",
"previousPageTooltip": "Předchozí stránka",
"showMenuTooltip": "Zobrazit nabídku",
"aboutListTileTitle": "O aplikaci $applicationName",
"licensesPageTitle": "Licence",
"pageRowsInfoTitle": "$firstRow–$lastRow z $rowCount",
"pageRowsInfoTitleApproximate": "$firstRow–$lastRow z asi $rowCount",
"rowsPerPageTitle": "Počet řádků na stránku:",
"tabLabel": "Karta $tabIndex z $tabCount",
"selectedRowCountTitleOne": "Je vybrána 1 položka",
"selectedRowCountTitleOther": "Je vybráno $selectedRowCount položek",
"cancelButtonLabel": "Zrušit",
"closeButtonLabel": "Zavřít",
"continueButtonLabel": "Pokračovat",
"copyButtonLabel": "Kopírovat",
"cutButtonLabel": "Vyjmout",
"scanTextButtonLabel": "Naskenovat text",
"okButtonLabel": "OK",
"pasteButtonLabel": "Vložit",
"selectAllButtonLabel": "Vybrat vše",
"viewLicensesButtonLabel": "Zobrazit licence",
"anteMeridiemAbbreviation": "AM",
"postMeridiemAbbreviation": "PM",
"timePickerHourModeAnnouncement": "Vyberte hodiny",
"timePickerMinuteModeAnnouncement": "Vyberte minuty",
"modalBarrierDismissLabel": "Zavřít",
"signedInLabel": "Uživatel přihlášen",
"hideAccountsLabel": "Skrýt účty",
"showAccountsLabel": "Zobrazit účty",
"drawerLabel": "Navigační nabídka",
"popupMenuLabel": "Vyskakovací nabídka",
"dialogLabel": "Dialogové okno",
"alertDialogLabel": "Upozornění",
"searchFieldLabel": "Hledat",
"reorderItemToStart": "Přesunout na začátek",
"reorderItemToEnd": "Přesunout na konec",
"reorderItemUp": "Přesunout nahoru",
"reorderItemDown": "Přesunout dolů",
"reorderItemLeft": "Přesunout doleva",
"reorderItemRight": "Přesunout doprava",
"expandedIconTapHint": "Sbalit",
"collapsedIconTapHint": "Rozbalit",
"remainingTextFieldCharacterCountOne": "Zbývá 1 znak",
"remainingTextFieldCharacterCountOther": "Zbývá $remainingCount znaků",
"refreshIndicatorSemanticLabel": "Obnovit",
"moreButtonTooltip": "Více",
"dateSeparator": ".",
"dateHelpText": "mm.dd.rrrr",
"selectYearSemanticsLabel": "Vyberte rok",
"unspecifiedDate": "Datum",
"unspecifiedDateRange": "Období",
"dateInputLabel": "Zadejte datum",
"dateRangeStartLabel": "Datum zahájení",
"dateRangeEndLabel": "Datum ukončení",
"dateRangeStartDateSemanticLabel": "Datum zahájení $fullDate",
"dateRangeEndDateSemanticLabel": "Datum ukončení $fullDate",
"invalidDateFormatLabel": "Neplatný formát.",
"invalidDateRangeLabel": "Neplatný rozsah.",
"dateOutOfRangeLabel": "Mimo rozsah.",
"saveButtonLabel": "Uložit",
"datePickerHelpText": "Vyberte datum",
"dateRangePickerHelpText": "Vyberte rozsah",
"calendarModeButtonLabel": "Přepnout na kalendář",
"inputDateModeButtonLabel": "Přepnout na zadávání",
"timePickerDialHelpText": "Vyberte čas",
"timePickerInputHelpText": "Zadejte čas",
"timePickerHourLabel": "Hodina",
"timePickerMinuteLabel": "Minuta",
"invalidTimeLabel": "Zadejte platný čas",
"dialModeButtonLabel": "Přepnout na režim výběru času",
"inputTimeModeButtonLabel": "Přepnout na režim zadávání textu",
"licensesPackageDetailTextZero": "No licenses",
"licensesPackageDetailTextOne": "1 licence",
"licensesPackageDetailTextOther": "$licenseCount licencí",
"keyboardKeyAlt": "Alt",
"keyboardKeyAltGraph": "AltGr",
"keyboardKeyBackspace": "Backspace",
"keyboardKeyCapsLock": "Caps Lock",
"keyboardKeyChannelDown": "O kanál dolů",
"keyboardKeyChannelUp": "O kanál nahoru",
"keyboardKeyControl": "Ctrl",
"keyboardKeyDelete": "Del",
"keyboardKeyEject": "Odpojit",
"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": "Vypínač",
"keyboardKeyPowerOff": "Vypnout",
"keyboardKeyPrintScreen": "Print Screen",
"keyboardKeyScrollLock": "Scroll Lock",
"keyboardKeySelect": "Vybrat",
"keyboardKeySpace": "Mezera",
"keyboardKeyMetaMacOs": "Command",
"keyboardKeyMetaWindows": "Win",
"menuBarMenuLabel": "Nabídka na liště s nabídkou",
"currentDateLabel": "Dnes",
"scrimLabel": "Scrim",
"bottomSheetLabel": "Spodní tabulka",
"scrimOnTapHint": "Zavřít $modalRouteContentName",
"keyboardKeyShift": "Shift",
"expansionTileExpandedHint": "dvojitým klepnutím sbalíte",
"expansionTileCollapsedHint": "dvojitým klepnutím rozbalíte",
"expansionTileExpandedTapHint": "Sbalit",
"expansionTileCollapsedTapHint": "Rozbalte pro další podrobnosti",
"expandedHint": "Sbaleno",
"collapsedHint": "Rozbaleno",
"menuDismissLabel": "Zavřít nabídku",
"lookUpButtonLabel": "Vyhledat",
"searchWebButtonLabel": "Vyhledávat na webu",
"shareButtonLabel": "Sdílet…",
"clearButtonTooltip": "Clear text",
"selectedDateLabel": "Selected"
}
| flutter/packages/flutter_localizations/lib/src/l10n/material_cs.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_cs.arb",
"repo_id": "flutter",
"token_count": 2655
} | 745 |
{
"licensesPackageDetailTextFew": "$licenseCount licence",
"remainingTextFieldCharacterCountFew": "Preostala su $remainingCount znaka",
"scriptCategory": "English-like",
"timeOfDayFormat": "HH:mm",
"selectedRowCountTitleFew": "Odabrane su $selectedRowCount stavke",
"openAppDrawerTooltip": "Otvaranje izbornika za navigaciju",
"backButtonTooltip": "Natrag",
"closeButtonTooltip": "Zatvaranje",
"deleteButtonTooltip": "Brisanje",
"nextMonthTooltip": "Sljedeći mjesec",
"previousMonthTooltip": "Prethodni mjesec",
"nextPageTooltip": "Sljedeća stranica",
"previousPageTooltip": "Prethodna stranica",
"firstPageTooltip": "Prva stranica",
"lastPageTooltip": "Posljednja stranica",
"showMenuTooltip": "Prikaz izbornika",
"aboutListTileTitle": "O aplikaciji $applicationName",
"licensesPageTitle": "Licence",
"pageRowsInfoTitle": "$firstRow – $lastRow od $rowCount",
"pageRowsInfoTitleApproximate": "$firstRow – $lastRow od otprilike $rowCount",
"rowsPerPageTitle": "Redaka po stranici:",
"tabLabel": "Kartica $tabIndex od $tabCount",
"selectedRowCountTitleOne": "Odabrana je jedna stavka",
"selectedRowCountTitleOther": "Odabrano je $selectedRowCount stavki",
"cancelButtonLabel": "Odustani",
"closeButtonLabel": "Zatvori",
"continueButtonLabel": "Nastavi",
"copyButtonLabel": "Kopiraj",
"cutButtonLabel": "Izreži",
"scanTextButtonLabel": "Skeniranje teksta",
"okButtonLabel": "U REDU",
"pasteButtonLabel": "Zalijepi",
"selectAllButtonLabel": "Odaberi sve",
"viewLicensesButtonLabel": "Prikaži licence",
"anteMeridiemAbbreviation": "prijepodne",
"postMeridiemAbbreviation": "popodne",
"timePickerHourModeAnnouncement": "Odaberite sate",
"timePickerMinuteModeAnnouncement": "Odaberite minute",
"modalBarrierDismissLabel": "Odbaci",
"signedInLabel": "Prijavljeni korisnik",
"hideAccountsLabel": "Sakrijte račune",
"showAccountsLabel": "Prikažite račune",
"drawerLabel": "Navigacijski izbornik",
"popupMenuLabel": "Skočni izbornik",
"dialogLabel": "Dijalog",
"alertDialogLabel": "Upozorenje",
"searchFieldLabel": "Pretražite",
"reorderItemToStart": "Premjesti na početak",
"reorderItemToEnd": "Premjesti na kraj",
"reorderItemUp": "Pomakni prema gore",
"reorderItemDown": "Pomakni prema dolje",
"reorderItemLeft": "Pomakni ulijevo",
"reorderItemRight": "Pomakni udesno",
"expandedIconTapHint": "Sažmi",
"collapsedIconTapHint": "Proširi",
"remainingTextFieldCharacterCountOne": "Preostao je 1 znak",
"remainingTextFieldCharacterCountOther": "Preostalo je $remainingCount znakova",
"refreshIndicatorSemanticLabel": "Osvježi",
"moreButtonTooltip": "Više",
"dateSeparator": ".",
"dateHelpText": "dd. mm. gggg.",
"selectYearSemanticsLabel": "Odaberite godinu",
"unspecifiedDate": "Datum",
"unspecifiedDateRange": "Datumski raspon",
"dateInputLabel": "Unesite datum",
"dateRangeStartLabel": "Datum početka",
"dateRangeEndLabel": "Datum završetka",
"dateRangeStartDateSemanticLabel": "Datum početka $fullDate",
"dateRangeEndDateSemanticLabel": "Datum završetka $fullDate",
"invalidDateFormatLabel": "Format nije važeći.",
"invalidDateRangeLabel": "Raspon nije važeći.",
"dateOutOfRangeLabel": "Izvan raspona.",
"saveButtonLabel": "Spremi",
"datePickerHelpText": "Odaberi datum",
"dateRangePickerHelpText": "Odaberi raspon",
"calendarModeButtonLabel": "Prijeđite na kalendar",
"inputDateModeButtonLabel": "Prijeđite na unos",
"timePickerDialHelpText": "Odaberi vrijeme",
"timePickerInputHelpText": "Unesi vrijeme",
"timePickerHourLabel": "Sat",
"timePickerMinuteLabel": "Minuta",
"invalidTimeLabel": "Unesite važeće vrijeme",
"dialModeButtonLabel": "Prijelaz na način alata za odabir biranja",
"inputTimeModeButtonLabel": "Prijelaz na način unosa teksta",
"licensesPackageDetailTextZero": "No licenses",
"licensesPackageDetailTextOne": "1 licenca",
"licensesPackageDetailTextOther": "$licenseCount licenci",
"keyboardKeyAlt": "Alt",
"keyboardKeyAltGraph": "AltGr",
"keyboardKeyBackspace": "Backspace",
"keyboardKeyCapsLock": "Caps Lock",
"keyboardKeyChannelDown": "Kanal prema dolje",
"keyboardKeyChannelUp": "Kanal prema gore",
"keyboardKeyControl": "Ctrl",
"keyboardKeyDelete": "Del",
"keyboardKeyEject": "Izbaci",
"keyboardKeyEnd": "Kraj",
"keyboardKeyEscape": "Esc",
"keyboardKeyFn": "Fn",
"keyboardKeyHome": "Home",
"keyboardKeyInsert": "Umetni",
"keyboardKeyMeta": "Meta",
"keyboardKeyNumLock": "Num Lock",
"keyboardKeyNumpad1": "Broj 1",
"keyboardKeyNumpad2": "Broj 2",
"keyboardKeyNumpad3": "Broj 3",
"keyboardKeyNumpad4": "Broj 4",
"keyboardKeyNumpad5": "Broj 5",
"keyboardKeyNumpad6": "Broj 6",
"keyboardKeyNumpad7": "Broj 7",
"keyboardKeyNumpad8": "Broj 8",
"keyboardKeyNumpad9": "Broj 9",
"keyboardKeyNumpad0": "Broj 0",
"keyboardKeyNumpadAdd": "Broj +",
"keyboardKeyNumpadComma": "Broj ,",
"keyboardKeyNumpadDecimal": "Broj .",
"keyboardKeyNumpadDivide": "Broj /",
"keyboardKeyNumpadEnter": "Broj Enter",
"keyboardKeyNumpadEqual": "Broj =",
"keyboardKeyNumpadMultiply": "Broj *",
"keyboardKeyNumpadParenLeft": "Broj (",
"keyboardKeyNumpadParenRight": "Broj )",
"keyboardKeyNumpadSubtract": "Broj -",
"keyboardKeyPageDown": "PgDown",
"keyboardKeyPageUp": "PgUp",
"keyboardKeyPower": "Napajanje",
"keyboardKeyPowerOff": "Isključivanje",
"keyboardKeyPrintScreen": "Print Screen",
"keyboardKeyScrollLock": "Scroll Lock",
"keyboardKeySelect": "Odaberi",
"keyboardKeySpace": "Razmaknica",
"keyboardKeyMetaMacOs": "Naredba",
"keyboardKeyMetaWindows": "Win",
"menuBarMenuLabel": "Izbornik trake izbornika",
"currentDateLabel": "Danas",
"scrimLabel": "Rubno",
"bottomSheetLabel": "Donja tablica",
"scrimOnTapHint": "Zatvori $modalRouteContentName",
"keyboardKeyShift": "Shift",
"expansionTileExpandedHint": "dvaput dodirnite za sažimanje",
"expansionTileCollapsedHint": "dvaput dodirnite za proširivanje",
"expansionTileExpandedTapHint": "Sažmi",
"expansionTileCollapsedTapHint": "Proširite da biste saznali više",
"expandedHint": "Sažeto",
"collapsedHint": "Prošireno",
"menuDismissLabel": "Odbacivanje izbornika",
"lookUpButtonLabel": "Pogled prema gore",
"searchWebButtonLabel": "Pretraži web",
"shareButtonLabel": "Dijeli...",
"clearButtonTooltip": "Clear text",
"selectedDateLabel": "Selected"
}
| flutter/packages/flutter_localizations/lib/src/l10n/material_hr.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_hr.arb",
"repo_id": "flutter",
"token_count": 2521
} | 746 |
{
"scriptCategory": "English-like",
"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": "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_mk.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_mk.arb",
"repo_id": "flutter",
"token_count": 3299
} | 747 |
{
"licensesPackageDetailTextFew": "$licenseCount licențe",
"remainingTextFieldCharacterCountFew": "$remainingCount caractere rămase",
"selectedRowCountTitleFew": "$selectedRowCount articole selectate",
"scriptCategory": "English-like",
"timeOfDayFormat": "HH:mm",
"openAppDrawerTooltip": "Deschideți meniul de navigare",
"backButtonTooltip": "Înapoi",
"closeButtonTooltip": "Închideți",
"deleteButtonTooltip": "Ștergeți",
"nextMonthTooltip": "Luna viitoare",
"previousMonthTooltip": "Luna trecută",
"nextPageTooltip": "Pagina următoare",
"previousPageTooltip": "Pagina anterioară",
"firstPageTooltip": "Prima pagină",
"lastPageTooltip": "Ultima pagină",
"showMenuTooltip": "Afișați meniul",
"aboutListTileTitle": "Despre $applicationName",
"licensesPageTitle": "Licențe",
"pageRowsInfoTitle": "$firstRow–$lastRow din $rowCount",
"pageRowsInfoTitleApproximate": "$firstRow–$lastRow din aproximativ $rowCount",
"rowsPerPageTitle": "Rânduri pe pagină:",
"tabLabel": "Fila $tabIndex din $tabCount",
"selectedRowCountTitleZero": "Nu există elemente selectate",
"selectedRowCountTitleOne": "Un articol selectat",
"selectedRowCountTitleOther": "$selectedRowCount de articole selectate",
"cancelButtonLabel": "Anulați",
"closeButtonLabel": "Închideți",
"continueButtonLabel": "Continuați",
"copyButtonLabel": "Copiați",
"cutButtonLabel": "Decupați",
"scanTextButtonLabel": "Scanați textul",
"okButtonLabel": "OK",
"pasteButtonLabel": "Inserați",
"selectAllButtonLabel": "Selectați tot",
"viewLicensesButtonLabel": "Vedeți licențele",
"anteMeridiemAbbreviation": "a.m.",
"postMeridiemAbbreviation": "p.m.",
"timePickerHourModeAnnouncement": "Selectați orele",
"timePickerMinuteModeAnnouncement": "Selectați minutele",
"signedInLabel": "V-ați conectat",
"hideAccountsLabel": "Ascundeți conturile",
"showAccountsLabel": "Afișați conturile",
"modalBarrierDismissLabel": "Închideți",
"drawerLabel": "Meniu de navigare",
"popupMenuLabel": "Meniu pop-up",
"dialogLabel": "Casetă de dialog",
"alertDialogLabel": "Alertă",
"searchFieldLabel": "Căutați",
"reorderItemToStart": "Mutați la început",
"reorderItemToEnd": "Mutați la sfârșit",
"reorderItemUp": "Mutați în sus",
"reorderItemDown": "Mutați în jos",
"reorderItemLeft": "Mutați la stânga",
"reorderItemRight": "Mutați la dreapta",
"expandedIconTapHint": "Restrângeți",
"collapsedIconTapHint": "Extindeți",
"remainingTextFieldCharacterCountOne": "un caracter rămas",
"remainingTextFieldCharacterCountOther": "$remainingCount de caractere rămase",
"refreshIndicatorSemanticLabel": "Actualizați",
"moreButtonTooltip": "Mai multe",
"dateSeparator": ".",
"dateHelpText": "zz.ll.aaaa",
"selectYearSemanticsLabel": "Selectați anul",
"unspecifiedDate": "Data",
"unspecifiedDateRange": "Interval de date",
"dateInputLabel": "Introduceți data",
"dateRangeStartLabel": "Data de începere",
"dateRangeEndLabel": "Data de încheiere",
"dateRangeStartDateSemanticLabel": "Data de începere: $fullDate",
"dateRangeEndDateSemanticLabel": "Data de încheiere: $fullDate",
"invalidDateFormatLabel": "Format nevalid.",
"invalidDateRangeLabel": "Interval nevalid.",
"dateOutOfRangeLabel": "Fără acoperire.",
"saveButtonLabel": "Salvați",
"datePickerHelpText": "Selectați data",
"dateRangePickerHelpText": "Selectați intervalul",
"calendarModeButtonLabel": "Comutați la calendar",
"inputDateModeButtonLabel": "Comutați la introducerea textului",
"timePickerDialHelpText": "Selectați ora",
"timePickerInputHelpText": "Introduceți ora",
"timePickerHourLabel": "Oră",
"timePickerMinuteLabel": "Minut",
"invalidTimeLabel": "Introduceți o oră validă",
"dialModeButtonLabel": "Comutați la modul selector cadran",
"inputTimeModeButtonLabel": "Comutați la modul de introducere a textului",
"licensesPackageDetailTextZero": "No licenses",
"licensesPackageDetailTextOne": "O licență",
"licensesPackageDetailTextOther": "$licenseCount de licențe",
"keyboardKeyAlt": "Alt",
"keyboardKeyAltGraph": "AltGr",
"keyboardKeyBackspace": "Backspace",
"keyboardKeyCapsLock": "Caps Lock",
"keyboardKeyChannelDown": "Înapoi",
"keyboardKeyChannelUp": "Înainte",
"keyboardKeyControl": "Ctrl",
"keyboardKeyDelete": "Del",
"keyboardKeyEject": "Eject",
"keyboardKeyEnd": "End",
"keyboardKeyEscape": "Esc",
"keyboardKeyFn": "Fn",
"keyboardKeyHome": "Home",
"keyboardKeyInsert": "Insert",
"keyboardKeyMeta": "Meta",
"keyboardKeyNumLock": "Num Lock",
"keyboardKeyNumpad1": "1 de pe tastatura numerică",
"keyboardKeyNumpad2": "2 de pe tastatura numerică",
"keyboardKeyNumpad3": "3 de pe tastatura numerică",
"keyboardKeyNumpad4": "4 de pe tastatura numerică",
"keyboardKeyNumpad5": "5 de pe tastatura numerică",
"keyboardKeyNumpad6": "6 de pe tastatura numerică",
"keyboardKeyNumpad7": "7 de pe tastatura numerică",
"keyboardKeyNumpad8": "8 de pe tastatura numerică",
"keyboardKeyNumpad9": "9 de pe tastatura numerică",
"keyboardKeyNumpad0": "0 de pe tastatura numerică",
"keyboardKeyNumpadAdd": "+ de pe tastatura numerică",
"keyboardKeyNumpadComma": ", de pe tastatura numerică",
"keyboardKeyNumpadDecimal": ". de pe tastatura numerică",
"keyboardKeyNumpadDivide": "/ de pe tastatura numerică",
"keyboardKeyNumpadEnter": "Enter de pe tastatura numerică",
"keyboardKeyNumpadEqual": "= de pe tastatura numerică",
"keyboardKeyNumpadMultiply": "* de pe tastatura numerică",
"keyboardKeyNumpadParenLeft": "( de pe tastatura numerică",
"keyboardKeyNumpadParenRight": ") de pe tastatura numerică",
"keyboardKeyNumpadSubtract": "- de pe tastatura numerică",
"keyboardKeyPageDown": "PgDown",
"keyboardKeyPageUp": "PgUp",
"keyboardKeyPower": "Power",
"keyboardKeyPowerOff": "Power Off",
"keyboardKeyPrintScreen": "Print Screen",
"keyboardKeyScrollLock": "Scroll Lock",
"keyboardKeySelect": "Select",
"keyboardKeySpace": "Spațiu",
"keyboardKeyMetaMacOs": "Command",
"keyboardKeyMetaWindows": "Win",
"menuBarMenuLabel": "Bară de meniu",
"currentDateLabel": "Azi",
"scrimLabel": "Material",
"bottomSheetLabel": "Foaie din partea de jos",
"scrimOnTapHint": "Închideți $modalRouteContentName",
"keyboardKeyShift": "Shift",
"expansionTileExpandedHint": "atingeți de două ori pentru a restrânge",
"expansionTileCollapsedHint": "atingeți de două ori pentru a extinde",
"expansionTileExpandedTapHint": "Restrângeți",
"expansionTileCollapsedTapHint": "Extindeți pentru mai multe detalii",
"expandedHint": "Restrâns",
"collapsedHint": "Extins",
"menuDismissLabel": "Respingeți meniul",
"lookUpButtonLabel": "Privire în sus",
"searchWebButtonLabel": "Căutați pe web",
"shareButtonLabel": "Trimiteți…",
"clearButtonTooltip": "Clear text",
"selectedDateLabel": "Selected"
}
| flutter/packages/flutter_localizations/lib/src/l10n/material_ro.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_ro.arb",
"repo_id": "flutter",
"token_count": 2673
} | 748 |
{
"scriptCategory": "tall",
"timeOfDayFormat": "h:mm a",
"selectedRowCountTitleOne": "1 آئٹم منتخب کیا گیا",
"openAppDrawerTooltip": "نیویگیشن مینیو کھولیں",
"backButtonTooltip": "پیچھے",
"closeButtonTooltip": "بند کریں",
"deleteButtonTooltip": "حذف کریں",
"nextMonthTooltip": "اگلا مہینہ",
"previousMonthTooltip": "پچھلا مہینہ",
"nextPageTooltip": "اگلا صفحہ",
"previousPageTooltip": "گزشتہ صفحہ",
"firstPageTooltip": "پہلا صفحہ",
"lastPageTooltip": "آخری صفحہ",
"showMenuTooltip": "مینیو دکھائیں",
"aboutListTileTitle": "$applicationName کے بارے میں",
"licensesPageTitle": "لائسنسز",
"pageRowsInfoTitle": "$firstRow–$lastRow از $rowCount",
"pageRowsInfoTitleApproximate": "$firstRow–$lastRow $rowCount میں سے تقریباً",
"rowsPerPageTitle": "قطاریں فی صفحہ:",
"tabLabel": "$tabCount میں سے $tabIndex ٹیب",
"selectedRowCountTitleOther": "$selectedRowCount آئٹمز منتخب کیے گئے",
"cancelButtonLabel": "منسوخ کریں",
"closeButtonLabel": "بند کریں",
"continueButtonLabel": "جاری رکھیں",
"copyButtonLabel": "کاپی کریں",
"cutButtonLabel": "کٹ کریں",
"scanTextButtonLabel": "ٹیکسٹ اسکین کریں",
"okButtonLabel": "ٹھیک ہے",
"pasteButtonLabel": "پیسٹ کریں",
"selectAllButtonLabel": "سبھی کو منتخب کریں",
"viewLicensesButtonLabel": "لائسنسز دیکھیں",
"anteMeridiemAbbreviation": "AM",
"postMeridiemAbbreviation": "PM",
"timePickerHourModeAnnouncement": "گھنٹے منتخب کریں",
"timePickerMinuteModeAnnouncement": "منٹ منتخب کریں",
"signedInLabel": "سائن ان کردہ ہے",
"hideAccountsLabel": "اکاؤنٹس چھپائیں",
"showAccountsLabel": "اکاؤنٹس دکھائیں",
"modalBarrierDismissLabel": "برخاست کریں",
"drawerLabel": "نیویگیشن مینیو",
"popupMenuLabel": "پاپ اپ مینیو",
"dialogLabel": "ڈائلاگ",
"alertDialogLabel": "الرٹ",
"searchFieldLabel": "تلاش",
"reorderItemToStart": "شروع میں منتقل کریں",
"reorderItemToEnd": "آخر میں منتقل کریں",
"reorderItemUp": "اوپر منتقل کریں",
"reorderItemDown": "نیچے منتقل کریں",
"reorderItemLeft": "بائیں منتقل کریں",
"reorderItemRight": "دائیں منتقل کریں",
"expandedIconTapHint": "سکیڑیں",
"collapsedIconTapHint": "پھیلائیں",
"remainingTextFieldCharacterCountOne": "1 حرف باقی ہے",
"remainingTextFieldCharacterCountOther": "$remainingCount حروف باقی ہیں",
"refreshIndicatorSemanticLabel": "ریفریش کریں",
"moreButtonTooltip": "مزید",
"dateSeparator": "/",
"dateHelpText": "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_ur.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_ur.arb",
"repo_id": "flutter",
"token_count": 3388
} | 749 |
{
"reorderItemToStart": "Mou al principi",
"reorderItemToEnd": "Mou al final",
"reorderItemUp": "Mou amunt",
"reorderItemDown": "Mou avall",
"reorderItemLeft": "Mou cap a l'esquerra",
"reorderItemRight": "Mou cap a la dreta"
}
| flutter/packages/flutter_localizations/lib/src/l10n/widgets_ca.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_ca.arb",
"repo_id": "flutter",
"token_count": 100
} | 750 |
{
"reorderItemToStart": "शुरुआत पर ले जाएं",
"reorderItemToEnd": "आखिर में ले जाएं",
"reorderItemUp": "ऊपर ले जाएं",
"reorderItemDown": "नीचे ले जाएं",
"reorderItemLeft": "बाएं ले जाएं",
"reorderItemRight": "दाएं ले जाएं"
}
| flutter/packages/flutter_localizations/lib/src/l10n/widgets_hi.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_hi.arb",
"repo_id": "flutter",
"token_count": 190
} | 751 |
{
"reorderItemToStart": "Pārvietot uz sākumu",
"reorderItemToEnd": "Pārvietot uz beigām",
"reorderItemUp": "Pārvietot uz augšu",
"reorderItemDown": "Pārvietot uz leju",
"reorderItemLeft": "Pārvietot pa kreisi",
"reorderItemRight": "Pārvietot pa labi"
}
| flutter/packages/flutter_localizations/lib/src/l10n/widgets_lv.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_lv.arb",
"repo_id": "flutter",
"token_count": 131
} | 752 |
{
"reorderItemToStart": "Mover para o início",
"reorderItemToEnd": "Mover para o fim",
"reorderItemUp": "Mover para cima",
"reorderItemDown": "Mover para baixo",
"reorderItemLeft": "Mover para a esquerda",
"reorderItemRight": "Mover para a direita"
}
| flutter/packages/flutter_localizations/lib/src/l10n/widgets_pt_PT.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_pt_PT.arb",
"repo_id": "flutter",
"token_count": 104
} | 753 |
{
"reorderItemToStart": "Перемістити на початок",
"reorderItemToEnd": "Перемістити в кінець",
"reorderItemUp": "Перемістити вгору",
"reorderItemDown": "Перемістити вниз",
"reorderItemLeft": "Перемістити ліворуч",
"reorderItemRight": "Перемістити праворуч"
}
| flutter/packages/flutter_localizations/lib/src/l10n/widgets_uk.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_uk.arb",
"repo_id": "flutter",
"token_count": 200
} | 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:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:intl/intl.dart';
void main() {
group(GlobalMaterialLocalizations, () {
test('uses exact locale when exists', () async {
final GlobalMaterialLocalizations localizations =
await GlobalMaterialLocalizations.delegate.load(const Locale('pt', 'PT')) as GlobalMaterialLocalizations;
expect(localizations.formatDecimal(10000), '10\u00A0000');
});
test('falls back to language code when exact locale is missing', () async {
final GlobalMaterialLocalizations localizations =
await GlobalMaterialLocalizations.delegate.load(const Locale('pt', 'XX')) as GlobalMaterialLocalizations;
expect(localizations.formatDecimal(10000), '10.000');
});
test('fails when neither language code nor exact locale are available', () async {
await expectLater(() async {
await GlobalMaterialLocalizations.delegate.load(const Locale('xx', 'XX'));
}, throwsAssertionError);
});
group('formatHour', () {
Future<String> formatHour(WidgetTester tester, Locale locale, TimeOfDay timeOfDay) async {
final Completer<String> completer = Completer<String>();
await tester.pumpWidget(MaterialApp(
supportedLocales: <Locale>[locale],
locale: locale,
localizationsDelegates: GlobalMaterialLocalizations.delegates,
home: Builder(builder: (BuildContext context) {
completer.complete(MaterialLocalizations.of(context).formatHour(timeOfDay));
return Container();
}),
));
return completer.future;
}
testWidgets('formats h', (WidgetTester tester) async {
expect(await formatHour(tester, const Locale('en', 'US'), const TimeOfDay(hour: 10, minute: 0)), '10');
expect(await formatHour(tester, const Locale('en', 'US'), const TimeOfDay(hour: 20, minute: 0)), '8');
});
testWidgets('formats HH', (WidgetTester tester) async {
expect(await formatHour(tester, const Locale('de'), const TimeOfDay(hour: 9, minute: 0)), '09');
expect(await formatHour(tester, const Locale('de'), const TimeOfDay(hour: 20, minute: 0)), '20');
expect(await formatHour(tester, const Locale('en', 'GB'), const TimeOfDay(hour: 9, minute: 0)), '09');
expect(await formatHour(tester, const Locale('en', 'GB'), const TimeOfDay(hour: 20, minute: 0)), '20');
});
testWidgets('formats H', (WidgetTester tester) async {
expect(await formatHour(tester, const Locale('es'), const TimeOfDay(hour: 9, minute: 0)), '9');
expect(await formatHour(tester, const Locale('es'), const TimeOfDay(hour: 20, minute: 0)), '20');
expect(await formatHour(tester, const Locale('fa'), const TimeOfDay(hour: 9, minute: 0)), '۹');
expect(await formatHour(tester, const Locale('fa'), const TimeOfDay(hour: 20, minute: 0)), '۲۰');
});
});
group('formatMinute', () {
test('formats English', () async {
final GlobalMaterialLocalizations localizations =
await GlobalMaterialLocalizations.delegate.load(const Locale('en', 'US')) as GlobalMaterialLocalizations;
expect(localizations.formatMinute(const TimeOfDay(hour: 1, minute: 32)), '32');
});
});
group('formatTimeOfDay', () {
Future<String> formatTimeOfDay(WidgetTester tester, Locale locale, TimeOfDay timeOfDay) async {
final Completer<String> completer = Completer<String>();
await tester.pumpWidget(MaterialApp(
supportedLocales: <Locale>[locale],
locale: locale,
localizationsDelegates: GlobalMaterialLocalizations.delegates,
home: Builder(builder: (BuildContext context) {
completer.complete(MaterialLocalizations.of(context).formatTimeOfDay(timeOfDay));
return Container();
}),
));
return completer.future;
}
testWidgets('formats ${TimeOfDayFormat.h_colon_mm_space_a}', (WidgetTester tester) async {
expect(await formatTimeOfDay(tester, const Locale('en'), const TimeOfDay(hour: 9, minute: 32)), '9:32 AM');
expect(await formatTimeOfDay(tester, const Locale('en'), const TimeOfDay(hour: 20, minute: 32)), '8:32 PM');
});
testWidgets('formats ${TimeOfDayFormat.HH_colon_mm}', (WidgetTester tester) async {
expect(await formatTimeOfDay(tester, const Locale('de'), const TimeOfDay(hour: 9, minute: 32)), '09:32');
expect(await formatTimeOfDay(tester, const Locale('en', 'ZA'), const TimeOfDay(hour: 9, minute: 32)), '09:32');
});
testWidgets('formats ${TimeOfDayFormat.H_colon_mm}', (WidgetTester tester) async {
expect(await formatTimeOfDay(tester, const Locale('es'), const TimeOfDay(hour: 9, minute: 32)), '9:32');
expect(await formatTimeOfDay(tester, const Locale('es'), const TimeOfDay(hour: 20, minute: 32)), '20:32');
expect(await formatTimeOfDay(tester, const Locale('ja'), const TimeOfDay(hour: 9, minute: 32)), '9:32');
expect(await formatTimeOfDay(tester, const Locale('ja'), const TimeOfDay(hour: 20, minute: 32)), '20:32');
});
testWidgets('formats ${TimeOfDayFormat.HH_dot_mm}', (WidgetTester tester) async {
expect(await formatTimeOfDay(tester, const Locale('fi'), const TimeOfDay(hour: 20, minute: 32)), '20.32');
expect(await formatTimeOfDay(tester, const Locale('fi'), const TimeOfDay(hour: 9, minute: 32)), '09.32');
expect(await formatTimeOfDay(tester, const Locale('da'), const TimeOfDay(hour: 9, minute: 32)), '09.32');
});
testWidgets('formats ${TimeOfDayFormat.frenchCanadian}', (WidgetTester tester) async {
expect(await formatTimeOfDay(tester, const Locale('fr', 'CA'), const TimeOfDay(hour: 9, minute: 32)), '09 h 32');
});
testWidgets('formats ${TimeOfDayFormat.a_space_h_colon_mm}', (WidgetTester tester) async {
expect(await formatTimeOfDay(tester, const Locale('zh'), const TimeOfDay(hour: 9, minute: 32)), '上午 9:32');
expect(await formatTimeOfDay(tester, const Locale('ta'), const TimeOfDay(hour: 9, minute: 32)), '9:32 AM');
});
});
group('date formatters', () {
Future<Map<DateType, String>> formatDate(WidgetTester tester, Locale locale, DateTime dateTime) async {
final Completer<Map<DateType, String>> completer = Completer<Map<DateType, String>>();
await tester.pumpWidget(MaterialApp(
supportedLocales: <Locale>[locale],
locale: locale,
localizationsDelegates: GlobalMaterialLocalizations.delegates,
home: Builder(builder: (BuildContext context) {
final MaterialLocalizations localizations = MaterialLocalizations.of(context);
completer.complete(<DateType, String>{
DateType.year: localizations.formatYear(dateTime),
DateType.medium: localizations.formatMediumDate(dateTime),
DateType.full: localizations.formatFullDate(dateTime),
DateType.monthYear: localizations.formatMonthYear(dateTime),
});
return Container();
}),
));
return completer.future;
}
testWidgets('formats dates in English', (WidgetTester tester) async {
final Map<DateType, String> formatted = await formatDate(tester, const Locale('en'), DateTime(2018, 8));
expect(formatted[DateType.year], '2018');
expect(formatted[DateType.medium], 'Wed, Aug 1');
expect(formatted[DateType.full], 'Wednesday, August 1, 2018');
expect(formatted[DateType.monthYear], 'August 2018');
});
testWidgets('formats dates in German', (WidgetTester tester) async {
final Map<DateType, String> formatted = await formatDate(tester, const Locale('de'), DateTime(2018, 8));
expect(formatted[DateType.year], '2018');
expect(formatted[DateType.medium], 'Mi., 1. Aug.');
expect(formatted[DateType.full], 'Mittwoch, 1. August 2018');
expect(formatted[DateType.monthYear], 'August 2018');
});
testWidgets('formats dates in Serbian', (WidgetTester tester) async {
final Map<DateType, String> formatted = await formatDate(tester, const Locale('sr'), DateTime(2018, 8));
expect(formatted[DateType.year], '2018.');
expect(formatted[DateType.medium], 'сре 1. авг');
expect(formatted[DateType.full], 'среда, 1. август 2018.');
expect(formatted[DateType.monthYear], 'август 2018.');
});
testWidgets('formats dates in Serbian (Latin)', (WidgetTester tester) async {
final Map<DateType, String> formatted = await formatDate(tester,
const Locale.fromSubtags(languageCode:'sr', scriptCode: 'Latn'), DateTime(2018, 8));
expect(formatted[DateType.year], '2018.');
expect(formatted[DateType.medium], 'sre 1. avg');
expect(formatted[DateType.full], 'sreda, 1. avgust 2018.');
expect(formatted[DateType.monthYear], 'avgust 2018.');
});
});
});
// Regression test for https://github.com/flutter/flutter/issues/67644.
testWidgets('en_US is initialized correctly by Flutter when DateFormat is used', (WidgetTester tester) async {
late DateFormat dateFormat;
await tester.pumpWidget(MaterialApp(
locale: const Locale('en', 'US'),
localizationsDelegates: GlobalMaterialLocalizations.delegates,
home: Builder(builder: (BuildContext context) {
dateFormat = DateFormat('EEE, d MMM yyyy HH:mm:ss', 'en_US');
return Container();
}),
));
expect(dateFormat.locale, 'en_US');
});
testWidgets('cy is initialized correctly by Flutter when DateFormat is used', (WidgetTester tester) async {
late DateFormat dateFormat;
await tester.pumpWidget(MaterialApp(
locale: const Locale('cy'),
localizationsDelegates: GlobalMaterialLocalizations.delegates,
home: Builder(builder: (BuildContext context) {
dateFormat = DateFormat.yMMMd('cy');
return Container();
}),
));
expect(dateFormat.locale, 'cy');
expect(dateFormat.format(DateTime(2023, 4, 10, 2, 32)), equals('10 Ebr 2023'));
});
}
enum DateType { year, medium, full, monthYear }
| flutter/packages/flutter_localizations/test/material/date_time_test.dart/0 | {
"file_path": "flutter/packages/flutter_localizations/test/material/date_time_test.dart",
"repo_id": "flutter",
"token_count": 4040
} | 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.
# For details regarding the *Flutter Fix* feature, see
# https://flutter.dev/docs/development/tools/flutter-fix
# Please add new fixes to the top of the file, separated by one blank line
# from other fixes. In a comment, include a link to the PR where the change
# requiring the fix was made.
# Every fix must be tested. See the
# flutter/packages/flutter_test/test_fixes/README.md file for instructions
# on testing these data driven fixes.
# For documentation about this file format, see
# https://dart.dev/go/data-driven-fixes.
# * Fixes in this file are for the flutter_test/controller.dart file. *
version: 1
transforms:
# Changes made in TBD
- title: "Migrate to startNode and endNode."
date: 2024-02-13
element:
uris: [ 'flutter_test.dart' ]
method: simulatedAccessibilityTraversal
inClass: SemanticsController
oneOf:
- if: "start != '' && end != ''"
changes:
- kind: 'addParameter'
index: 2
name: 'startNode'
style: optional_named
argumentValue:
expression: '{% start %}'
requiredIf: "start != '' && end != ''"
- kind: 'addParameter'
index: 3
name: 'endNode'
style: optional_named
argumentValue:
expression: '{% end %}'
requiredIf: "start != '' && end != ''"
- kind: 'removeParameter'
name: 'start'
- kind: 'removeParameter'
name: 'end'
- if: "start != '' && end == ''"
changes:
- kind: 'addParameter'
index: 2
name: 'startNode'
style: optional_named
argumentValue:
expression: '{% start %}'
requiredIf: "start != '' && end == ''"
- kind: 'removeParameter'
name: 'start'
- if: "start == '' && end != ''"
changes:
- kind: 'addParameter'
index: 2
name: 'endNode'
style: optional_named
argumentValue:
expression: '{% end %}'
requiredIf: "start == '' && end != ''"
- kind: 'removeParameter'
name: 'end'
variables:
start:
kind: 'fragment'
value: 'arguments[start]'
end:
kind: 'fragment'
value: 'arguments[end]'
| flutter/packages/flutter_test/lib/fix_data/fix_flutter_test/fix_semantics_controller.yaml/0 | {
"file_path": "flutter/packages/flutter_test/lib/fix_data/fix_flutter_test/fix_semantics_controller.yaml",
"repo_id": "flutter",
"token_count": 1144
} | 756 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui';
import 'package:flutter/material.dart' show Tooltip;
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'binding.dart';
import 'tree_traversal.dart';
/// Signature for [CommonFinders.byWidgetPredicate].
typedef WidgetPredicate = bool Function(Widget widget);
/// Signature for [CommonFinders.byElementPredicate].
typedef ElementPredicate = bool Function(Element element);
/// Signature for [CommonSemanticsFinders.byPredicate].
typedef SemanticsNodePredicate = bool Function(SemanticsNode node);
/// Signature for [FinderBase.describeMatch].
typedef DescribeMatchCallback = String Function(Plurality plurality);
/// The `CandidateType` of finders that search for and filter substrings,
/// within static text rendered by [RenderParagraph]s.
final class TextRangeContext {
const TextRangeContext._(this.view, this.renderObject, this.textRange);
/// The [View] containing the static text.
///
/// This is used for hit-testing.
final View view;
/// The RenderObject that contains the static text.
final RenderParagraph renderObject;
/// The [TextRange] of the substring within [renderObject]'s text.
final TextRange textRange;
@override
String toString() => 'TextRangeContext($view, $renderObject, $textRange)';
}
/// Some frequently used [Finder]s and [SemanticsFinder]s.
const CommonFinders find = CommonFinders._();
// Examples can assume:
// typedef Button = Placeholder;
// late WidgetTester tester;
// late String filePath;
// late Key backKey;
/// Provides lightweight syntax for getting frequently used [Finder]s and
/// [SemanticsFinder]s through [semantics].
///
/// This class is instantiated once, as [find].
class CommonFinders {
const CommonFinders._();
/// Some frequently used semantics finders.
CommonSemanticsFinders get semantics => const CommonSemanticsFinders._();
/// Some frequently used text range finders.
CommonTextRangeFinders get textRange => const CommonTextRangeFinders._();
/// Finds [Text], [EditableText], and optionally [RichText] widgets
/// containing string equal to the `text` argument.
///
/// If `findRichText` is false, all standalone [RichText] widgets are
/// ignored and `text` is matched with [Text.data] or [Text.textSpan].
/// If `findRichText` is true, [RichText] widgets (and therefore also
/// [Text] and [Text.rich] widgets) are matched by comparing the
/// [InlineSpan.toPlainText] with the given `text`.
///
/// For [EditableText] widgets, the `text` is always compared to the current
/// value of the [EditableText.controller].
///
/// If the `skipOffstage` argument is true (the default), then this skips
/// nodes that are [Offstage] or that are from inactive [Route]s.
///
/// ## Sample code
///
/// ```dart
/// expect(find.text('Back'), findsOneWidget);
/// ```
///
/// This will match [Text], [Text.rich], and [EditableText] widgets that
/// contain the "Back" string.
///
/// ```dart
/// expect(find.text('Close', findRichText: true), findsOneWidget);
/// ```
///
/// This will match [Text], [Text.rich], [EditableText], as well as standalone
/// [RichText] widgets that contain the "Close" string.
Finder text(
String text, {
bool findRichText = false,
bool skipOffstage = true,
}) {
return _TextWidgetFinder(
text,
findRichText: findRichText,
skipOffstage: skipOffstage,
);
}
/// Finds [Text] and [EditableText], and optionally [RichText] widgets
/// which contain the given `pattern` argument.
///
/// If `findRichText` is false, all standalone [RichText] widgets are
/// ignored and `pattern` is matched with [Text.data] or [Text.textSpan].
/// If `findRichText` is true, [RichText] widgets (and therefore also
/// [Text] and [Text.rich] widgets) are matched by comparing the
/// [InlineSpan.toPlainText] with the given `pattern`.
///
/// For [EditableText] widgets, the `pattern` is always compared to the current
/// value of the [EditableText.controller].
///
/// If the `skipOffstage` argument is true (the default), then this skips
/// nodes that are [Offstage] or that are from inactive [Route]s.
///
/// ## Sample code
///
/// ```dart
/// expect(find.textContaining('Back'), findsOneWidget);
/// expect(find.textContaining(RegExp(r'(\w+)')), findsOneWidget);
/// ```
///
/// This will match [Text], [Text.rich], and [EditableText] widgets that
/// contain the given pattern : 'Back' or RegExp(r'(\w+)').
///
/// ```dart
/// expect(find.textContaining('Close', findRichText: true), findsOneWidget);
/// expect(find.textContaining(RegExp(r'(\w+)'), findRichText: true), findsOneWidget);
/// ```
///
/// This will match [Text], [Text.rich], [EditableText], as well as standalone
/// [RichText] widgets that contain the given pattern : 'Close' or RegExp(r'(\w+)').
Finder textContaining(
Pattern pattern, {
bool findRichText = false,
bool skipOffstage = true,
}) {
return _TextContainingWidgetFinder(
pattern,
findRichText: findRichText,
skipOffstage: skipOffstage
);
}
/// Looks for widgets that contain a [Text] descendant with `text`
/// in it.
///
/// ## Sample code
///
/// ```dart
/// // Suppose there is a button with text 'Update' in it:
/// const Button(
/// child: Text('Update')
/// );
///
/// // It can be found and tapped like this:
/// tester.tap(find.widgetWithText(Button, 'Update'));
/// ```
///
/// If the `skipOffstage` argument is true (the default), then this skips
/// nodes that are [Offstage] or that are from inactive [Route]s.
Finder widgetWithText(Type widgetType, String text, { bool skipOffstage = true }) {
return find.ancestor(
of: find.text(text, skipOffstage: skipOffstage),
matching: find.byType(widgetType, skipOffstage: skipOffstage),
);
}
/// Finds [Image] and [FadeInImage] widgets containing `image` equal to the
/// `image` argument.
///
/// ## Sample code
///
/// ```dart
/// expect(find.image(FileImage(File(filePath))), findsOneWidget);
/// ```
///
/// If the `skipOffstage` argument is true (the default), then this skips
/// nodes that are [Offstage] or that are from inactive [Route]s.
Finder image(ImageProvider image, { bool skipOffstage = true }) => _ImageWidgetFinder(image, skipOffstage: skipOffstage);
/// Finds widgets by searching for one with the given `key`.
///
/// ## Sample code
///
/// ```dart
/// expect(find.byKey(backKey), findsOneWidget);
/// ```
///
/// If the `skipOffstage` argument is true (the default), then this skips
/// nodes that are [Offstage] or that are from inactive [Route]s.
Finder byKey(Key key, { bool skipOffstage = true }) => _KeyWidgetFinder(key, skipOffstage: skipOffstage);
/// Finds widgets by searching for widgets implementing a particular type.
///
/// This matcher accepts subtypes. For example a
/// `bySubtype<StatefulWidget>()` will find any stateful widget.
///
/// ## Sample code
///
/// ```dart
/// expect(find.bySubtype<IconButton>(), findsOneWidget);
/// ```
///
/// If the `skipOffstage` argument is true (the default), then this skips
/// nodes that are [Offstage] or that are from inactive [Route]s.
///
/// See also:
/// * [byType], which does not do subtype tests.
Finder bySubtype<T extends Widget>({ bool skipOffstage = true }) => _SubtypeWidgetFinder<T>(skipOffstage: skipOffstage);
/// Finds widgets by searching for widgets with a particular type.
///
/// This does not do subclass tests, so for example
/// `byType(StatefulWidget)` will never find anything since [StatefulWidget]
/// is an abstract class.
///
/// The `type` argument must be a subclass of [Widget].
///
/// ## Sample code
///
/// ```dart
/// expect(find.byType(IconButton), findsOneWidget);
/// ```
///
/// If the `skipOffstage` argument is true (the default), then this skips
/// nodes that are [Offstage] or that are from inactive [Route]s.
///
/// See also:
/// * [bySubtype], which allows subtype tests.
Finder byType(Type type, { bool skipOffstage = true }) => _TypeWidgetFinder(type, skipOffstage: skipOffstage);
/// Finds [Icon] widgets containing icon data equal to the `icon`
/// argument.
///
/// ## Sample code
///
/// ```dart
/// expect(find.byIcon(Icons.inbox), findsOneWidget);
/// ```
///
/// If the `skipOffstage` argument is true (the default), then this skips
/// nodes that are [Offstage] or that are from inactive [Route]s.
Finder byIcon(IconData icon, { bool skipOffstage = true }) => _IconWidgetFinder(icon, skipOffstage: skipOffstage);
/// Looks for widgets that contain an [Icon] descendant displaying [IconData]
/// `icon` in it.
///
/// ## Sample code
///
/// ```dart
/// // Suppose there is a button with icon 'arrow_forward' in it:
/// const Button(
/// child: Icon(Icons.arrow_forward)
/// );
///
/// // It can be found and tapped like this:
/// tester.tap(find.widgetWithIcon(Button, Icons.arrow_forward));
/// ```
///
/// If the `skipOffstage` argument is true (the default), then this skips
/// nodes that are [Offstage] or that are from inactive [Route]s.
Finder widgetWithIcon(Type widgetType, IconData icon, { bool skipOffstage = true }) {
return find.ancestor(
of: find.byIcon(icon),
matching: find.byType(widgetType),
);
}
/// Looks for widgets that contain an [Image] descendant displaying
/// [ImageProvider] `image` in it.
///
/// ## Sample code
///
/// ```dart
/// // Suppose there is a button with an image in it:
/// Button(
/// child: Image.file(File(filePath))
/// );
///
/// // It can be found and tapped like this:
/// tester.tap(find.widgetWithImage(Button, FileImage(File(filePath))));
/// ```
///
/// If the `skipOffstage` argument is true (the default), then this skips
/// nodes that are [Offstage] or that are from inactive [Route]s.
Finder widgetWithImage(Type widgetType, ImageProvider image, { bool skipOffstage = true }) {
return find.ancestor(
of: find.image(image),
matching: find.byType(widgetType),
);
}
/// Finds widgets by searching for elements with a particular type.
///
/// This does not do subclass tests, so for example
/// `byElementType(VirtualViewportElement)` will never find anything
/// since [RenderObjectElement] is an abstract class.
///
/// The `type` argument must be a subclass of [Element].
///
/// ## Sample code
///
/// ```dart
/// expect(find.byElementType(SingleChildRenderObjectElement), findsOneWidget);
/// ```
///
/// If the `skipOffstage` argument is true (the default), then this skips
/// nodes that are [Offstage] or that are from inactive [Route]s.
Finder byElementType(Type type, { bool skipOffstage = true }) => _ElementTypeWidgetFinder(type, skipOffstage: skipOffstage);
/// Finds widgets whose current widget is the instance given by the `widget`
/// argument.
///
/// ## Sample code
///
/// ```dart
/// // Suppose there is a button created like this:
/// Widget myButton = const Button(
/// child: Text('Update')
/// );
///
/// // It can be found and tapped like this:
/// tester.tap(find.byWidget(myButton));
/// ```
///
/// If the `skipOffstage` argument is true (the default), then this skips
/// nodes that are [Offstage] or that are from inactive [Route]s.
Finder byWidget(Widget widget, { bool skipOffstage = true }) => _ExactWidgetFinder(widget, skipOffstage: skipOffstage);
/// Finds widgets using a widget `predicate`.
///
/// ## Sample code
///
/// ```dart
/// expect(find.byWidgetPredicate(
/// (Widget widget) => widget is Tooltip && widget.message == 'Back',
/// description: 'with tooltip "Back"',
/// ), findsOneWidget);
/// ```
///
/// If `description` is provided, then this uses it as the description of the
/// [Finder] and appears, for example, in the error message when the finder
/// fails to locate the desired widget. Otherwise, the description prints the
/// signature of the predicate function.
///
/// If the `skipOffstage` argument is true (the default), then this skips
/// nodes that are [Offstage] or that are from inactive [Route]s.
Finder byWidgetPredicate(WidgetPredicate predicate, { String? description, bool skipOffstage = true }) {
return _WidgetPredicateWidgetFinder(predicate, description: description, skipOffstage: skipOffstage);
}
/// Finds [Tooltip] widgets with the given `message`.
///
/// ## Sample code
///
/// ```dart
/// expect(find.byTooltip('Back'), findsOneWidget);
/// ```
///
/// If the `skipOffstage` argument is true (the default), then this skips
/// nodes that are [Offstage] or that are from inactive [Route]s.
Finder byTooltip(String message, { bool skipOffstage = true }) {
return byWidgetPredicate(
(Widget widget) => widget is Tooltip && widget.message == message,
skipOffstage: skipOffstage,
);
}
/// Finds widgets using an element `predicate`.
///
/// ## Sample code
///
/// ```dart
/// expect(find.byElementPredicate(
/// // Finds elements of type SingleChildRenderObjectElement, including
/// // those that are actually subclasses of that type.
/// // (contrast with byElementType, which only returns exact matches)
/// (Element element) => element is SingleChildRenderObjectElement,
/// description: '$SingleChildRenderObjectElement element',
/// ), findsOneWidget);
/// ```
///
/// If `description` is provided, then this uses it as the description of the
/// [Finder] and appears, for example, in the error message when the finder
/// fails to locate the desired widget. Otherwise, the description prints the
/// signature of the predicate function.
///
/// If the `skipOffstage` argument is true (the default), then this skips
/// nodes that are [Offstage] or that are from inactive [Route]s.
Finder byElementPredicate(ElementPredicate predicate, { String? description, bool skipOffstage = true }) {
return _ElementPredicateWidgetFinder(predicate, description: description, skipOffstage: skipOffstage);
}
/// Finds widgets that are descendants of the `of` parameter and that match
/// the `matching` parameter.
///
/// ## Sample code
///
/// ```dart
/// expect(find.descendant(
/// of: find.widgetWithText(Row, 'label_1'),
/// matching: find.text('value_1'),
/// ), findsOneWidget);
/// ```
///
/// If the `matchRoot` argument is true then the widget(s) specified by `of`
/// will be matched along with the descendants.
///
/// If the `skipOffstage` argument is true (the default), then nodes that are
/// [Offstage] or that are from inactive [Route]s are skipped.
Finder descendant({
required FinderBase<Element> of,
required FinderBase<Element> matching,
bool matchRoot = false,
bool skipOffstage = true,
}) {
return _DescendantWidgetFinder(of, matching, matchRoot: matchRoot, skipOffstage: skipOffstage);
}
/// Finds widgets that are ancestors of the `of` parameter and that match
/// the `matching` parameter.
///
/// ## Sample code
///
/// ```dart
/// // Test if a Text widget that contains 'faded' is the
/// // descendant of an Opacity widget with opacity 0.5:
/// expect(
/// tester.widget<Opacity>(
/// find.ancestor(
/// of: find.text('faded'),
/// matching: find.byType(Opacity),
/// )
/// ).opacity,
/// 0.5
/// );
/// ```
///
/// If the `matchRoot` argument is true then the widget(s) specified by `of`
/// will be matched along with the ancestors.
Finder ancestor({
required FinderBase<Element> of,
required FinderBase<Element> matching,
bool matchRoot = false,
}) {
return _AncestorWidgetFinder(of, matching, matchLeaves: matchRoot);
}
/// Finds [Semantics] widgets matching the given `label`, either by
/// [RegExp.hasMatch] or string equality.
///
/// The framework may combine semantics labels in certain scenarios, such as
/// when multiple [Text] widgets are in a [MaterialButton] widget. In such a
/// case, it may be preferable to match by regular expression. Consumers of
/// this API __must not__ introduce unsuitable content into the semantics tree
/// for the purposes of testing; in particular, you should prefer matching by
/// regular expression rather than by string if the framework has combined
/// your semantics, and not try to force the framework to break up the
/// semantics nodes. Breaking up the nodes would have an undesirable effect on
/// screen readers and other accessibility services.
///
/// ## Sample code
///
/// ```dart
/// expect(find.bySemanticsLabel('Back'), findsOneWidget);
/// ```
///
/// If the `skipOffstage` argument is true (the default), then this skips
/// nodes that are [Offstage] or that are from inactive [Route]s.
Finder bySemanticsLabel(Pattern label, { bool skipOffstage = true }) {
if (!SemanticsBinding.instance.semanticsEnabled) {
throw StateError('Semantics are not enabled. '
'Make sure to call tester.ensureSemantics() before using '
'this finder, and call dispose on its return value after.');
}
return byElementPredicate(
(Element element) {
// Multiple elements can have the same renderObject - we want the "owner"
// of the renderObject, i.e. the RenderObjectElement.
if (element is! RenderObjectElement) {
return false;
}
final String? semanticsLabel = element.renderObject.debugSemantics?.label;
if (semanticsLabel == null) {
return false;
}
return label is RegExp
? label.hasMatch(semanticsLabel)
: label == semanticsLabel;
},
skipOffstage: skipOffstage,
);
}
}
/// Provides lightweight syntax for getting frequently used semantics finders.
///
/// This class is instantiated once, as [CommonFinders.semantics], under [find].
class CommonSemanticsFinders {
const CommonSemanticsFinders._();
/// Finds an ancestor of `of` that matches `matching`.
///
/// If `matchRoot` is true, then the results of `of` are included in the
/// search and results.
FinderBase<SemanticsNode> ancestor({
required FinderBase<SemanticsNode> of,
required FinderBase<SemanticsNode> matching,
bool matchRoot = false,
}) {
return _AncestorSemanticsFinder(of, matching, matchRoot);
}
/// Finds a descendant of `of` that matches `matching`.
///
/// If `matchRoot` is true, then the results of `of` are included in the
/// search and results.
FinderBase<SemanticsNode> descendant({
required FinderBase<SemanticsNode> of,
required FinderBase<SemanticsNode> matching,
bool matchRoot = false,
}) {
return _DescendantSemanticsFinder(of, matching, matchRoot: matchRoot);
}
/// Finds any [SemanticsNode]s matching the given `predicate`.
///
/// If `describeMatch` is provided, it will be used to describe the
/// [FinderBase] and [FinderResult]s.
/// {@macro flutter_test.finders.FinderBase.describeMatch}
///
/// {@template flutter_test.finders.CommonSemanticsFinders.viewParameter}
/// The `view` provided will be used to determine the semantics tree where
/// the search will be evaluated. If not provided, the search will be
/// evaluated against the semantics tree of [WidgetTester.view].
/// {@endtemplate}
SemanticsFinder byPredicate(
SemanticsNodePredicate predicate, {
DescribeMatchCallback? describeMatch,
FlutterView? view,
}) {
return _PredicateSemanticsFinder(
predicate,
describeMatch,
view,
);
}
/// Finds any [SemanticsNode]s that has a [SemanticsNode.label] that matches
/// the given `label`.
///
/// {@macro flutter_test.finders.CommonSemanticsFinders.viewParameter}
SemanticsFinder byLabel(Pattern label, {FlutterView? view}) {
return byPredicate(
(SemanticsNode node) => _matchesPattern(node.label, label),
describeMatch: (Plurality plurality) => '${switch (plurality) {
Plurality.one => 'SemanticsNode',
Plurality.zero || Plurality.many => 'SemanticsNodes',
}} with label "$label"',
view: view,
);
}
/// Finds any [SemanticsNode]s that has a [SemanticsNode.value] that matches
/// the given `value`.
///
/// {@macro flutter_test.finders.CommonSemanticsFinders.viewParameter}
SemanticsFinder byValue(Pattern value, {FlutterView? view}) {
return byPredicate(
(SemanticsNode node) => _matchesPattern(node.value, value),
describeMatch: (Plurality plurality) => '${switch (plurality) {
Plurality.one => 'SemanticsNode',
Plurality.zero || Plurality.many => 'SemanticsNodes',
}} with value "$value"',
view: view,
);
}
/// Finds any [SemanticsNode]s that has a [SemanticsNode.hint] that matches
/// the given `hint`.
///
/// {@macro flutter_test.finders.CommonSemanticsFinders.viewParameter}
SemanticsFinder byHint(Pattern hint, {FlutterView? view}) {
return byPredicate(
(SemanticsNode node) => _matchesPattern(node.hint, hint),
describeMatch: (Plurality plurality) => '${switch (plurality) {
Plurality.one => 'SemanticsNode',
Plurality.zero || Plurality.many => 'SemanticsNodes',
}} with hint "$hint"',
view: view,
);
}
/// Finds any [SemanticsNode]s that has the given [SemanticsAction].
///
/// {@macro flutter_test.finders.CommonSemanticsFinders.viewParameter}
SemanticsFinder byAction(SemanticsAction action, {FlutterView? view}) {
return byPredicate(
(SemanticsNode node) => node.getSemanticsData().hasAction(action),
describeMatch: (Plurality plurality) => '${switch (plurality) {
Plurality.one => 'SemanticsNode',
Plurality.zero || Plurality.many => 'SemanticsNodes',
}} with action "$action"',
view: view,
);
}
/// Finds any [SemanticsNode]s that has at least one of the given
/// [SemanticsAction]s.
///
/// {@macro flutter_test.finders.CommonSemanticsFinders.viewParameter}
SemanticsFinder byAnyAction(List<SemanticsAction> actions, {FlutterView? view}) {
final int actionsInt = actions.fold(0, (int value, SemanticsAction action) => value | action.index);
return byPredicate(
(SemanticsNode node) => node.getSemanticsData().actions & actionsInt != 0,
describeMatch: (Plurality plurality) => '${switch (plurality) {
Plurality.one => 'SemanticsNode',
Plurality.zero || Plurality.many => 'SemanticsNodes',
}} with any of the following actions: $actions',
view: view,
);
}
/// Finds any [SemanticsNode]s that has the given [SemanticsFlag].
///
/// {@macro flutter_test.finders.CommonSemanticsFinders.viewParameter}
SemanticsFinder byFlag(SemanticsFlag flag, {FlutterView? view}) {
return byPredicate(
(SemanticsNode node) => node.hasFlag(flag),
describeMatch: (Plurality plurality) => '${switch (plurality) {
Plurality.one => 'SemanticsNode',
Plurality.zero || Plurality.many => 'SemanticsNodes',
}} with flag "$flag"',
view: view,
);
}
/// Finds any [SemanticsNode]s that has at least one of the given
/// [SemanticsFlag]s.
///
/// {@macro flutter_test.finders.CommonSemanticsFinders.viewParameter}
SemanticsFinder byAnyFlag(List<SemanticsFlag> flags, {FlutterView? view}) {
final int flagsInt = flags.fold(0, (int value, SemanticsFlag flag) => value | flag.index);
return byPredicate(
(SemanticsNode node) => node.getSemanticsData().flags & flagsInt != 0,
describeMatch: (Plurality plurality) => '${switch (plurality) {
Plurality.one => 'SemanticsNode',
Plurality.zero || Plurality.many => 'SemanticsNodes',
}} with any of the following flags: $flags',
view: view,
);
}
/// Finds any [SemanticsNode]s that can scroll in at least one direction.
///
/// If `axis` is provided, then the search will be limited to scrollable nodes
/// that can scroll in the given axis. If `axis` is not provided, then both
/// horizontal and vertical scrollable nodes will be found.
///
/// {@macro flutter_test.finders.CommonSemanticsFinders.viewParameter}
SemanticsFinder scrollable({Axis? axis, FlutterView? view}) {
return byAnyAction(<SemanticsAction>[
if (axis == null || axis == Axis.vertical) ...<SemanticsAction>[
SemanticsAction.scrollUp,
SemanticsAction.scrollDown,
],
if (axis == null || axis == Axis.horizontal) ...<SemanticsAction>[
SemanticsAction.scrollLeft,
SemanticsAction.scrollRight,
],
]);
}
bool _matchesPattern(String target, Pattern pattern) {
if (pattern is RegExp) {
return pattern.hasMatch(target);
} else {
return pattern == target;
}
}
}
/// Provides lightweight syntax for getting frequently used text range finders.
///
/// This class is instantiated once, as [CommonFinders.textRange], under [find].
final class CommonTextRangeFinders {
const CommonTextRangeFinders._();
/// Finds all non-overlapping occurrences of the given `substring` in the
/// static text widgets and returns the [TextRange]s.
///
/// If the `skipOffstage` argument is true (the default), then this skips
/// static text inside widgets that are [Offstage], or that are from inactive
/// [Route]s.
///
/// If the `descendentOf` argument is non-null, this method only searches in
/// the descendants of that parameter for the given substring.
///
/// This finder uses the [Pattern.allMatches] method to match the substring in
/// the text. After finding a matching substring in the text, the method
/// continues the search from the end of the match, thus skipping overlapping
/// occurrences of the substring.
FinderBase<TextRangeContext> ofSubstring(String substring, { bool skipOffstage = true, FinderBase<Element>? descendentOf }) {
final _TextContainingWidgetFinder textWidgetFinder = _TextContainingWidgetFinder(substring, skipOffstage: skipOffstage, findRichText: true);
final Finder elementFinder = descendentOf == null
? textWidgetFinder
: _DescendantWidgetFinder(descendentOf, textWidgetFinder, matchRoot: true, skipOffstage: skipOffstage);
return _StaticTextRangeFinder(elementFinder, substring);
}
}
/// Describes how a string of text should be pluralized.
enum Plurality {
/// Text should be pluralized to describe zero items.
zero,
/// Text should be pluralized to describe a single item.
one,
/// Text should be pluralized to describe more than one item.
many;
static Plurality _fromNum(num source) {
assert(source >= 0, 'A Plurality can only be created with a positive number.');
return switch (source) {
0 => Plurality.zero,
1 => Plurality.one,
_ => Plurality.many,
};
}
}
/// Encapsulates the logic for searching a list of candidates and filtering the
/// candidates to only those that meet the requirements defined by the finder.
///
/// Implementations will need to implement [allCandidates] to define the total
/// possible search space and [findInCandidates] to define the requirements of
/// the finder.
///
/// This library contains [Finder] and [SemanticsFinder] for searching
/// Flutter's element and semantics trees respectively.
///
/// If the search can be represented as a predicate, then consider using
/// [MatchFinderMixin] along with the [Finder] or [SemanticsFinder] base class.
///
/// If the search further filters the results from another finder, consider using
/// [ChainedFinderMixin] along with the [Finder] or [SemanticsFinder] base class.
abstract class FinderBase<CandidateType> {
bool _cached = false;
/// The results of the latest [evaluate] or [tryEvaluate] call.
///
/// Unlike [evaluate] and [tryEvaluate], [found] will not re-execute the
/// search for this finder. Either [evaluate] or [tryEvaluate] must be called
/// before accessing [found].
FinderResult<CandidateType> get found {
assert(
_found != null,
'No results have been found yet. '
'Either `evaluate` or `tryEvaluate` must be called before accessing `found`',
);
return _found!;
}
FinderResult<CandidateType>? _found;
/// Whether or not this finder has any results in [found].
bool get hasFound => _found != null;
/// Describes zero, one, or more candidates that match the requirements of a
/// finder.
///
/// {@template flutter_test.finders.FinderBase.describeMatch}
/// The description returned should be a brief English phrase describing a
/// matching candidate with the proper plural form. As an example for a string
/// finder that is looking for strings starting with "hello":
///
/// ```dart
/// String describeMatch(Plurality plurality) {
/// return switch (plurality) {
/// Plurality.zero || Plurality.many => 'strings starting with "hello"',
/// Plurality.one => 'string starting with "hello"',
/// };
/// }
/// ```
/// {@endtemplate}
///
/// This will be used both to describe a finder and the results of searching
/// with that finder.
///
/// See also:
///
/// * [FinderBase.toString] where this is used to fully describe the finder
/// * [FinderResult.toString] where this is used to provide context to the
/// results of a search
String describeMatch(Plurality plurality);
/// Returns all of the items that will be considered by this finder.
@protected
Iterable<CandidateType> get allCandidates;
/// Returns a variant of this finder that only matches the first item
/// found by this finder.
FinderBase<CandidateType> get first => _FirstFinder<CandidateType>(this);
/// Returns a variant of this finder that only matches the last item
/// found by this finder.
FinderBase<CandidateType> get last => _LastFinder<CandidateType>(this);
/// Returns a variant of this finder that only matches the item at the
/// given index found by this finder.
FinderBase<CandidateType> at(int index) => _IndexFinder<CandidateType>(this, index);
/// Returns all the items in the given list that match this
/// finder's requirements.
///
/// This is overridden to define the requirements of the finder when
/// implementing finders that directly extend [FinderBase]. If a finder can
/// be efficiently described just in terms of a predicate function, consider
/// mixing in [MatchFinderMixin] and implementing [MatchFinderMixin.matches]
/// instead.
@protected
Iterable<CandidateType> findInCandidates(Iterable<CandidateType> candidates);
/// Searches a set of candidates for those that meet the requirements set by
/// this finder and returns the result of that search.
///
/// See also:
///
/// * [found] which will return the latest results without re-executing the
/// search.
/// * [tryEvaluate] which will indicate whether any results were found rather
/// than directly returning results.
FinderResult<CandidateType> evaluate() {
if (!_cached || _found == null) {
_found = FinderResult<CandidateType>(describeMatch, findInCandidates(allCandidates));
}
return found;
}
/// Searches a set of candidates for those that meet the requirements set by
/// this finder and returns whether the search found any matching candidates.
///
/// This is useful in cases where an action needs to be repeated while or
/// until a finder has results. The results from the search can be accessed
/// using the [found] property without re-executing the search.
///
/// ## Sample code
///
/// ```dart
/// testWidgets('Top text loads first', (WidgetTester tester) async {
/// // Assume a widget is pumped with a top and bottom loading area, with
/// // the texts "Top loaded" and "Bottom loaded" when loading is complete.
/// // await tester.pumpWidget(...)
///
/// // Wait until at least one loaded widget is available
/// Finder loadedFinder = find.textContaining('loaded');
/// while (!loadedFinder.tryEvaluate()) {
/// await tester.pump(const Duration(milliseconds: 100));
/// }
///
/// expect(loadedFinder.found, hasLength(1));
/// expect(tester.widget<Text>(loadedFinder).data, contains('Top'));
/// });
/// ```
bool tryEvaluate() {
evaluate();
return found.isNotEmpty;
}
/// Runs the given callback using cached results.
///
/// While in this callback, this [FinderBase] will cache the results from the
/// next call to [evaluate] or [tryEvaluate] and then no longer evaluate new results
/// until the callback completes. After the first call, all calls to [evaluate],
/// [tryEvaluate] or [found] will return the same results without evaluating.
void runCached(VoidCallback run) {
reset();
_cached = true;
try {
run();
} finally {
reset();
_cached = false;
}
}
/// Resets all state of this [FinderBase].
///
/// Generally used between tests to reset the state of [found] if a finder is
/// used across multiple tests.
void reset() {
_found = null;
}
/// A string representation of this finder or its results.
///
/// By default, this describes the results of the search in order to play
/// nicely with [expect] and its output when a failure occurs. If you wish
/// to get a string representation of the finder itself, pass [describeSelf]
/// as `true`.
@override
String toString({bool describeSelf = false}) {
if (describeSelf) {
return 'A finder that searches for ${describeMatch(Plurality.many)}.';
} else {
if (!hasFound) {
evaluate();
}
return found.toString();
}
}
}
/// The results of searching with a [FinderBase].
class FinderResult<CandidateType> extends Iterable<CandidateType> {
/// Creates a new [FinderResult] that describes the `values` using the given
/// `describeMatch` callback.
///
/// {@macro flutter_test.finders.FinderBase.describeMatch}
FinderResult(DescribeMatchCallback describeMatch, Iterable<CandidateType> values)
: _describeMatch = describeMatch, _values = values;
final DescribeMatchCallback _describeMatch;
final Iterable<CandidateType> _values;
@override
Iterator<CandidateType> get iterator => _values.iterator;
@override
String toString() {
final List<CandidateType> valuesList = _values.toList();
// This will put each value on its own line with a comma and indentation
final String valuesString = valuesList.fold(
'',
(String current, CandidateType candidate) => '$current\n $candidate,',
);
return 'Found ${valuesList.length} ${_describeMatch(Plurality._fromNum(valuesList.length))}: ['
'${valuesString.isNotEmpty ? '$valuesString\n' : ''}'
']';
}
}
/// Provides backwards compatibility with the original [Finder] API.
mixin _LegacyFinderMixin on FinderBase<Element> {
Iterable<Element>? _precacheResults;
/// Describes what the finder is looking for. The description should be
/// a brief English noun phrase describing the finder's requirements.
@Deprecated(
'Use FinderBase.describeMatch instead. '
'FinderBase.describeMatch allows for more readable descriptions and removes ambiguity about pluralization. '
'This feature was deprecated after v3.13.0-0.2.pre.'
)
String get description;
/// Returns all the elements in the given list that match this
/// finder's pattern.
///
/// When implementing Finders that inherit directly from
/// [Finder], [findInCandidates] is the main method to override. This method
/// is maintained for backwards compatibility and will be removed in a future
/// version of Flutter. If the finder can efficiently be described just in
/// terms of a predicate function, consider mixing in [MatchFinderMixin]
/// instead.
@Deprecated(
'Override FinderBase.findInCandidates instead. '
'Using the FinderBase API allows for more consistent caching behavior and cleaner options for interacting with the widget tree. '
'This feature was deprecated after v3.13.0-0.2.pre.'
)
Iterable<Element> apply(Iterable<Element> candidates) {
return findInCandidates(candidates);
}
/// Attempts to evaluate the finder. Returns whether any elements in the tree
/// matched the finder. If any did, then the result is cached and can be obtained
/// from [evaluate].
///
/// If this returns true, you must call [evaluate] before you call [precache] again.
@Deprecated(
'Use FinderBase.tryFind or FinderBase.runCached instead. '
'Using the FinderBase API allows for more consistent caching behavior and cleaner options for interacting with the widget tree. '
'This feature was deprecated after v3.13.0-0.2.pre.'
)
bool precache() {
assert(_precacheResults == null);
if (tryEvaluate()) {
return true;
}
_precacheResults = null;
return false;
}
@override
Iterable<Element> findInCandidates(Iterable<Element> candidates) {
return apply(candidates);
}
}
/// A base class for creating finders that search the [Element] tree for
/// [Widget]s.
///
/// The [findInCandidates] method must be overridden and will be enforced at
/// compilation after [apply] is removed.
abstract class Finder extends FinderBase<Element> with _LegacyFinderMixin {
/// Creates a new [Finder] with the given `skipOffstage` value.
Finder({this.skipOffstage = true});
/// Whether this finder skips nodes that are offstage.
///
/// If this is true, then the elements are walked using
/// [Element.debugVisitOnstageChildren]. This skips offstage children of
/// [Offstage] widgets, as well as children of inactive [Route]s.
final bool skipOffstage;
@override
Finder get first => _FirstWidgetFinder(this);
@override
Finder get last => _LastWidgetFinder(this);
@override
Finder at(int index) => _IndexWidgetFinder(this, index);
@override
Iterable<Element> get allCandidates {
return collectAllElementsFrom(
WidgetsBinding.instance.rootElement!,
skipOffstage: skipOffstage,
);
}
@override
String describeMatch(Plurality plurality) {
return switch (plurality) {
Plurality.zero || Plurality.many => 'widgets with $description',
Plurality.one => 'widget with $description',
};
}
/// Returns a variant of this finder that only matches elements reachable by
/// a hit test.
///
/// The `at` parameter specifies the location relative to the size of the
/// target element where the hit test is performed.
Finder hitTestable({ Alignment at = Alignment.center }) => _HitTestableWidgetFinder(this, at);
}
/// A base class for creating finders that search the semantics tree.
abstract class SemanticsFinder extends FinderBase<SemanticsNode> {
/// Creates a new [SemanticsFinder] that will search within the given [view] or
/// within all views if [view] is null.
SemanticsFinder(this.view);
/// The [FlutterView] whose semantics tree this finder will search.
///
/// If null, the finder will search within all views.
final FlutterView? view;
/// Returns the root [SemanticsNode]s of all the semantics trees that this
/// finder will search.
Iterable<SemanticsNode> get roots {
if (view == null) {
return _allRoots;
}
final RenderView renderView = TestWidgetsFlutterBinding.instance.renderViews
.firstWhere((RenderView r) => r.flutterView == view);
return <SemanticsNode>[
renderView.owner!.semanticsOwner!.rootSemanticsNode!
];
}
@override
Iterable<SemanticsNode> get allCandidates {
return roots.expand((SemanticsNode root) => collectAllSemanticsNodesFrom(root));
}
static Iterable<SemanticsNode> get _allRoots {
final List<SemanticsNode> roots = <SemanticsNode>[];
void collectSemanticsRoots(PipelineOwner owner) {
final SemanticsNode? root = owner.semanticsOwner?.rootSemanticsNode;
if (root != null) {
roots.add(root);
}
owner.visitChildren(collectSemanticsRoots);
}
collectSemanticsRoots(TestWidgetsFlutterBinding.instance.rootPipelineOwner);
return roots;
}
}
/// A base class for creating finders that search for static text rendered by a
/// [RenderParagraph].
class _StaticTextRangeFinder extends FinderBase<TextRangeContext> {
/// Creates a new [_StaticTextRangeFinder] that searches for the given
/// `pattern` in the [Element]s found by `_parent`.
_StaticTextRangeFinder(this._parent, this.pattern);
final FinderBase<Element> _parent;
final Pattern pattern;
Iterable<TextRangeContext> _flatMap(Element from) {
final RenderObject? renderObject = from.renderObject;
// This is currently only exposed on text matchers. Only consider RenderBoxes.
if (renderObject is! RenderBox) {
return const Iterable<TextRangeContext>.empty();
}
final View view = from.findAncestorWidgetOfExactType<View>()!;
final List<RenderParagraph> paragraphs = <RenderParagraph>[];
void visitor(RenderObject child) {
switch (child) {
case RenderParagraph():
paragraphs.add(child);
// No need to continue, we are piggybacking off of a text matcher, so
// inline text widgets will be reported separately.
case RenderBox():
child.visitChildren(visitor);
case _:
}
}
visitor(renderObject);
Iterable<TextRangeContext> searchInParagraph(RenderParagraph paragraph) {
final String text = paragraph.text.toPlainText(includeSemanticsLabels: false);
return pattern.allMatches(text)
.map((Match match) => TextRangeContext._(view, paragraph, TextRange(start: match.start, end: match.end)));
}
return paragraphs.expand(searchInParagraph);
}
@override
Iterable<TextRangeContext> findInCandidates(Iterable<TextRangeContext> candidates) => candidates;
@override
Iterable<TextRangeContext> get allCandidates => _parent.evaluate().expand(_flatMap);
@override
String describeMatch(Plurality plurality) {
return switch (plurality) {
Plurality.zero || Plurality.many => 'non-overlapping TextRanges that match the Pattern "$pattern"',
Plurality.one => 'non-overlapping TextRange that matches the Pattern "$pattern"',
};
}
}
/// A mixin that applies additional filtering to the results of a parent [Finder].
mixin ChainedFinderMixin<CandidateType> on FinderBase<CandidateType> {
/// Another finder whose results will be further filtered.
FinderBase<CandidateType> get parent;
/// Return another [Iterable] when given an [Iterable] of candidates from a
/// parent [FinderBase].
///
/// This is the main method to implement when mixing in [ChainedFinderMixin].
Iterable<CandidateType> filter(Iterable<CandidateType> parentCandidates);
@override
Iterable<CandidateType> findInCandidates(Iterable<CandidateType> candidates) {
return filter(parent.findInCandidates(candidates));
}
@override
Iterable<CandidateType> get allCandidates => parent.allCandidates;
}
/// Applies additional filtering against a [parent] widget finder.
abstract class ChainedFinder extends Finder with ChainedFinderMixin<Element> {
/// Create a Finder chained against the candidates of another `parent` [Finder].
ChainedFinder(this.parent);
@override
final FinderBase<Element> parent;
}
mixin _FirstFinderMixin<CandidateType> on ChainedFinderMixin<CandidateType>{
@override
String describeMatch(Plurality plurality) {
return '${parent.describeMatch(plurality)} (ignoring all but first)';
}
@override
Iterable<CandidateType> filter(Iterable<CandidateType> parentCandidates) sync* {
yield parentCandidates.first;
}
}
class _FirstFinder<CandidateType> extends FinderBase<CandidateType>
with ChainedFinderMixin<CandidateType>, _FirstFinderMixin<CandidateType> {
_FirstFinder(this.parent);
@override
final FinderBase<CandidateType> parent;
}
class _FirstWidgetFinder extends ChainedFinder with _FirstFinderMixin<Element> {
_FirstWidgetFinder(super.parent);
@override
String get description => describeMatch(Plurality.many);
}
mixin _LastFinderMixin<CandidateType> on ChainedFinderMixin<CandidateType> {
@override
String describeMatch(Plurality plurality) {
return '${parent.describeMatch(plurality)} (ignoring all but first)';
}
@override
Iterable<CandidateType> filter(Iterable<CandidateType> parentCandidates) sync* {
yield parentCandidates.last;
}
}
class _LastFinder<CandidateType> extends FinderBase<CandidateType>
with ChainedFinderMixin<CandidateType>, _LastFinderMixin<CandidateType>{
_LastFinder(this.parent);
@override
final FinderBase<CandidateType> parent;
}
class _LastWidgetFinder extends ChainedFinder with _LastFinderMixin<Element> {
_LastWidgetFinder(super.parent);
@override
String get description => describeMatch(Plurality.many);
}
mixin _IndexFinderMixin<CandidateType> on ChainedFinderMixin<CandidateType> {
int get index;
@override
String describeMatch(Plurality plurality) {
return '${parent.describeMatch(plurality)} (ignoring all but index $index)';
}
@override
Iterable<CandidateType> filter(Iterable<CandidateType> parentCandidates) sync* {
yield parentCandidates.elementAt(index);
}
}
class _IndexFinder<CandidateType> extends FinderBase<CandidateType>
with ChainedFinderMixin<CandidateType>, _IndexFinderMixin<CandidateType> {
_IndexFinder(this.parent, this.index);
@override
final int index;
@override
final FinderBase<CandidateType> parent;
}
class _IndexWidgetFinder extends ChainedFinder with _IndexFinderMixin<Element> {
_IndexWidgetFinder(super.parent, this.index);
@override
final int index;
@override
String get description => describeMatch(Plurality.many);
}
class _HitTestableWidgetFinder extends ChainedFinder {
_HitTestableWidgetFinder(super.parent, this.alignment);
final Alignment alignment;
@override
String describeMatch(Plurality plurality) {
return '${parent.describeMatch(plurality)} (considering only hit-testable ones)';
}
@override
String get description => describeMatch(Plurality.many);
@override
Iterable<Element> filter(Iterable<Element> parentCandidates) sync* {
for (final Element candidate in parentCandidates) {
final int viewId = candidate.findAncestorWidgetOfExactType<View>()!.view.viewId;
final RenderBox box = candidate.renderObject! as RenderBox;
final Offset absoluteOffset = box.localToGlobal(alignment.alongSize(box.size));
final HitTestResult hitResult = HitTestResult();
WidgetsBinding.instance.hitTestInView(hitResult, absoluteOffset, viewId);
for (final HitTestEntry entry in hitResult.path) {
if (entry.target == candidate.renderObject) {
yield candidate;
break;
}
}
}
}
}
/// A mixin for creating finders that search candidates for those that match
/// a given pattern.
mixin MatchFinderMixin<CandidateType> on FinderBase<CandidateType> {
/// Returns true if the given element matches the pattern.
///
/// When implementing a MatchFinder, this is the main method to override.
bool matches(CandidateType candidate);
@override
Iterable<CandidateType> findInCandidates(Iterable<CandidateType> candidates) {
return candidates.where(matches);
}
}
/// Searches candidates for any that match a particular pattern.
abstract class MatchFinder extends Finder with MatchFinderMixin<Element> {
/// Initializes a predicate-based Finder. Used by subclasses to initialize the
/// `skipOffstage` property.
MatchFinder({ super.skipOffstage });
}
abstract class _MatchTextFinder extends MatchFinder {
_MatchTextFinder({
this.findRichText = false,
super.skipOffstage,
});
/// Whether standalone [RichText] widgets should be found or not.
///
/// Defaults to `false`.
///
/// If disabled, only [Text] widgets will be matched. [RichText] widgets
/// *without* a [Text] ancestor will be ignored.
/// If enabled, only [RichText] widgets will be matched. This *implicitly*
/// matches [Text] widgets as well since they always insert a [RichText]
/// child.
///
/// In either case, [EditableText] widgets will also be matched.
final bool findRichText;
bool matchesText(String textToMatch);
@override
bool matches(Element candidate) {
final Widget widget = candidate.widget;
if (widget is EditableText) {
return _matchesEditableText(widget);
}
if (!findRichText) {
return _matchesNonRichText(widget);
}
// It would be sufficient to always use _matchesRichText if we wanted to
// match both standalone RichText widgets as well as Text widgets. However,
// the find.text() finder used to always ignore standalone RichText widgets,
// which is why we need the _matchesNonRichText method in order to not be
// backwards-compatible and not break existing tests.
return _matchesRichText(widget);
}
bool _matchesRichText(Widget widget) {
if (widget is RichText) {
return matchesText(widget.text.toPlainText());
}
return false;
}
bool _matchesNonRichText(Widget widget) {
if (widget is Text) {
if (widget.data != null) {
return matchesText(widget.data!);
}
assert(widget.textSpan != null);
return matchesText(widget.textSpan!.toPlainText());
}
return false;
}
bool _matchesEditableText(EditableText widget) {
return matchesText(widget.controller.text);
}
}
class _TextWidgetFinder extends _MatchTextFinder {
_TextWidgetFinder(
this.text, {
super.findRichText,
super.skipOffstage,
});
final String text;
@override
String get description => 'text "$text"';
@override
bool matchesText(String textToMatch) {
return textToMatch == text;
}
}
class _TextContainingWidgetFinder extends _MatchTextFinder {
_TextContainingWidgetFinder(
this.pattern, {
super.findRichText,
super.skipOffstage,
});
final Pattern pattern;
@override
String get description => 'text containing $pattern';
@override
bool matchesText(String textToMatch) {
return textToMatch.contains(pattern);
}
}
class _KeyWidgetFinder extends MatchFinder {
_KeyWidgetFinder(this.key, { super.skipOffstage });
final Key key;
@override
String get description => 'key $key';
@override
bool matches(Element candidate) {
return candidate.widget.key == key;
}
}
class _SubtypeWidgetFinder<T extends Widget> extends MatchFinder {
_SubtypeWidgetFinder({ super.skipOffstage });
@override
String get description => 'is "$T"';
@override
bool matches(Element candidate) {
return candidate.widget is T;
}
}
class _TypeWidgetFinder extends MatchFinder {
_TypeWidgetFinder(this.widgetType, { super.skipOffstage });
final Type widgetType;
@override
String get description => 'type "$widgetType"';
@override
bool matches(Element candidate) {
return candidate.widget.runtimeType == widgetType;
}
}
class _ImageWidgetFinder extends MatchFinder {
_ImageWidgetFinder(this.image, { super.skipOffstage });
final ImageProvider image;
@override
String get description => 'image "$image"';
@override
bool matches(Element candidate) {
final Widget widget = candidate.widget;
if (widget is Image) {
return widget.image == image;
} else if (widget is FadeInImage) {
return widget.image == image;
}
return false;
}
}
class _IconWidgetFinder extends MatchFinder {
_IconWidgetFinder(this.icon, { super.skipOffstage });
final IconData icon;
@override
String get description => 'icon "$icon"';
@override
bool matches(Element candidate) {
final Widget widget = candidate.widget;
return widget is Icon && widget.icon == icon;
}
}
class _ElementTypeWidgetFinder extends MatchFinder {
_ElementTypeWidgetFinder(this.elementType, { super.skipOffstage });
final Type elementType;
@override
String get description => 'type "$elementType"';
@override
bool matches(Element candidate) {
return candidate.runtimeType == elementType;
}
}
class _ExactWidgetFinder extends MatchFinder {
_ExactWidgetFinder(this.widget, { super.skipOffstage });
final Widget widget;
@override
String get description => 'the given widget ($widget)';
@override
bool matches(Element candidate) {
return candidate.widget == widget;
}
}
class _WidgetPredicateWidgetFinder extends MatchFinder {
_WidgetPredicateWidgetFinder(this.predicate, { String? description, super.skipOffstage })
: _description = description;
final WidgetPredicate predicate;
final String? _description;
@override
String get description => _description ?? 'widget matching predicate';
@override
bool matches(Element candidate) {
return predicate(candidate.widget);
}
}
class _ElementPredicateWidgetFinder extends MatchFinder {
_ElementPredicateWidgetFinder(this.predicate, { String? description, super.skipOffstage })
: _description = description;
final ElementPredicate predicate;
final String? _description;
@override
String get description => _description ?? 'element matching predicate';
@override
bool matches(Element candidate) {
return predicate(candidate);
}
}
class _PredicateSemanticsFinder extends SemanticsFinder
with MatchFinderMixin<SemanticsNode> {
_PredicateSemanticsFinder(this.predicate, DescribeMatchCallback? describeMatch, super.view)
: _describeMatch = describeMatch;
final SemanticsNodePredicate predicate;
final DescribeMatchCallback? _describeMatch;
@override
String describeMatch(Plurality plurality) {
return _describeMatch?.call(plurality) ??
'matching semantics predicate';
}
@override
bool matches(SemanticsNode candidate) {
return predicate(candidate);
}
}
mixin _DescendantFinderMixin<CandidateType> on FinderBase<CandidateType> {
FinderBase<CandidateType> get ancestor;
FinderBase<CandidateType> get descendant;
bool get matchRoot;
@override
String describeMatch(Plurality plurality) {
return '${descendant.describeMatch(plurality)} descending from '
'${ancestor.describeMatch(plurality)}'
'${matchRoot ? ' inclusive' : ''}';
}
@override
Iterable<CandidateType> findInCandidates(Iterable<CandidateType> candidates) {
final Iterable<CandidateType> descendants = descendant.evaluate();
return candidates.where((CandidateType candidate) => descendants.contains(candidate));
}
@override
Iterable<CandidateType> get allCandidates {
final Iterable<CandidateType> ancestors = ancestor.evaluate();
final List<CandidateType> candidates = ancestors.expand<CandidateType>(
(CandidateType ancestor) => _collectDescendants(ancestor)
).toSet().toList();
if (matchRoot) {
candidates.insertAll(0, ancestors);
}
return candidates;
}
Iterable<CandidateType> _collectDescendants(CandidateType root);
}
class _DescendantWidgetFinder extends Finder
with _DescendantFinderMixin<Element> {
_DescendantWidgetFinder(
this.ancestor,
this.descendant, {
this.matchRoot = false,
super.skipOffstage,
});
@override
final FinderBase<Element> ancestor;
@override
final FinderBase<Element> descendant;
@override
final bool matchRoot;
@override
String get description => describeMatch(Plurality.many);
@override
Iterable<Element> _collectDescendants(Element root) {
return collectAllElementsFrom(root, skipOffstage: skipOffstage);
}
}
class _DescendantSemanticsFinder extends FinderBase<SemanticsNode>
with _DescendantFinderMixin<SemanticsNode> {
_DescendantSemanticsFinder(this.ancestor, this.descendant, {this.matchRoot = false});
@override
final FinderBase<SemanticsNode> ancestor;
@override
final FinderBase<SemanticsNode> descendant;
@override
final bool matchRoot;
@override
Iterable<SemanticsNode> _collectDescendants(SemanticsNode root) {
return collectAllSemanticsNodesFrom(root);
}
}
mixin _AncestorFinderMixin<CandidateType> on FinderBase<CandidateType> {
FinderBase<CandidateType> get ancestor;
FinderBase<CandidateType> get descendant;
bool get matchLeaves;
@override
String describeMatch(Plurality plurality) {
return '${ancestor.describeMatch(plurality)} that are ancestors of '
'${descendant.describeMatch(plurality)}'
'${matchLeaves ? ' inclusive' : ''}';
}
@override
Iterable<CandidateType> findInCandidates(Iterable<CandidateType> candidates) {
final Iterable<CandidateType> ancestors = ancestor.evaluate();
return candidates.where((CandidateType element) => ancestors.contains(element));
}
@override
Iterable<CandidateType> get allCandidates {
final List<CandidateType> candidates = <CandidateType>[];
for (final CandidateType leaf in descendant.evaluate()) {
if (matchLeaves) {
candidates.add(leaf);
}
candidates.addAll(_collectAncestors(leaf));
}
return candidates;
}
Iterable<CandidateType> _collectAncestors(CandidateType child);
}
class _AncestorWidgetFinder extends Finder
with _AncestorFinderMixin<Element> {
_AncestorWidgetFinder(this.descendant, this.ancestor, { this.matchLeaves = false }) : super(skipOffstage: false);
@override
final FinderBase<Element> ancestor;
@override
final FinderBase<Element> descendant;
@override
final bool matchLeaves;
@override
String get description => describeMatch(Plurality.many);
@override
Iterable<Element> _collectAncestors(Element child) {
final List<Element> ancestors = <Element>[];
child.visitAncestorElements((Element element) {
ancestors.add(element);
return true;
});
return ancestors;
}
}
class _AncestorSemanticsFinder extends FinderBase<SemanticsNode>
with _AncestorFinderMixin<SemanticsNode> {
_AncestorSemanticsFinder(this.descendant, this.ancestor, this.matchLeaves);
@override
final FinderBase<SemanticsNode> ancestor;
@override
final FinderBase<SemanticsNode> descendant;
@override
final bool matchLeaves;
@override
Iterable<SemanticsNode> _collectAncestors(SemanticsNode child) {
final List<SemanticsNode> ancestors = <SemanticsNode>[];
while (child.parent != null) {
ancestors.add(child.parent!);
child = child.parent!;
}
return ancestors;
}
}
| flutter/packages/flutter_test/lib/src/finders.dart/0 | {
"file_path": "flutter/packages/flutter_test/lib/src/finders.dart",
"repo_id": "flutter",
"token_count": 18495
} | 757 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'test_async_utils.dart';
export 'dart:ui' show Offset;
/// A class for generating coherent artificial pointer events.
///
/// You can use this to manually simulate individual events, but the simplest
/// way to generate coherent gestures is to use [TestGesture].
class TestPointer {
/// Creates a [TestPointer]. By default, the pointer identifier used is 1,
/// however this can be overridden by providing an argument to the
/// constructor.
///
/// Multiple [TestPointer]s created with the same pointer identifier will
/// interfere with each other if they are used in parallel.
TestPointer([
this.pointer = 1,
this.kind = PointerDeviceKind.touch,
int? device,
int buttons = kPrimaryButton,
]) : _buttons = buttons {
switch (kind) {
case PointerDeviceKind.mouse:
_device = device ?? 1;
case PointerDeviceKind.stylus:
case PointerDeviceKind.invertedStylus:
case PointerDeviceKind.touch:
case PointerDeviceKind.trackpad:
case PointerDeviceKind.unknown:
_device = device ?? 0;
}
}
/// The device identifier used for events generated by this object.
///
/// Set when the object is constructed. Defaults to 1 if the [kind] is
/// [PointerDeviceKind.mouse], and 0 otherwise.
int get device => _device;
late int _device;
/// The pointer identifier used for events generated by this object.
///
/// Set when the object is constructed. Defaults to 1.
final int pointer;
/// The kind of pointing device to simulate. Defaults to
/// [PointerDeviceKind.touch].
final PointerDeviceKind kind;
/// The kind of buttons to simulate on Down and Move events. Defaults to
/// [kPrimaryButton].
int get buttons => _buttons;
int _buttons;
/// Whether the pointer simulated by this object is currently down.
///
/// A pointer is released (goes up) by calling [up] or [cancel].
///
/// Once a pointer is released, it can no longer generate events.
bool get isDown => _isDown;
bool _isDown = false;
/// Whether the pointer simulated by this object currently has
/// an active pan/zoom gesture.
///
/// A pan/zoom gesture begins when [panZoomStart] is called, and
/// ends when [panZoomEnd] is called.
bool get isPanZoomActive => _isPanZoomActive;
bool _isPanZoomActive = false;
/// The position of the last event sent by this object.
///
/// If no event has ever been sent by this object, returns null.
Offset? get location => _location;
Offset? _location;
/// The pan offset of the last pointer pan/zoom event sent by this object.
///
/// If no pan/zoom event has ever been sent by this object, returns null.
Offset? get pan => _pan;
Offset? _pan;
/// If a custom event is created outside of this class, this function is used
/// to set the [isDown].
bool setDownInfo(
PointerEvent event,
Offset newLocation, {
int? buttons,
}) {
_location = newLocation;
if (buttons != null) {
_buttons = buttons;
}
switch (event.runtimeType) {
case const (PointerDownEvent):
assert(!isDown);
_isDown = true;
case const (PointerUpEvent):
case const (PointerCancelEvent):
assert(isDown);
_isDown = false;
default:
break;
}
return isDown;
}
/// Create a [PointerDownEvent] at the given location.
///
/// By default, the time stamp on the event is [Duration.zero]. You can give a
/// specific time stamp by passing the `timeStamp` argument.
///
/// By default, the set of buttons in the last down or move event is used.
/// You can give a specific set of buttons by passing the `buttons` argument.
PointerDownEvent down(
Offset newLocation, {
Duration timeStamp = Duration.zero,
int? buttons,
}) {
assert(!isDown);
assert(!isPanZoomActive);
_isDown = true;
_location = newLocation;
if (buttons != null) {
_buttons = buttons;
}
return PointerDownEvent(
timeStamp: timeStamp,
kind: kind,
device: _device,
pointer: pointer,
position: location!,
buttons: _buttons,
);
}
/// Create a [PointerMoveEvent] to the given location.
///
/// By default, the time stamp on the event is [Duration.zero]. You can give a
/// specific time stamp by passing the `timeStamp` argument.
///
/// [isDown] must be true when this is called, since move events can only
/// be generated when the pointer is down.
///
/// By default, the set of buttons in the last down or move event is used.
/// You can give a specific set of buttons by passing the `buttons` argument.
PointerMoveEvent move(
Offset newLocation, {
Duration timeStamp = Duration.zero,
int? buttons,
}) {
assert(
isDown,
'Move events can only be generated when the pointer is down. To '
'create a movement event simulating a pointer move when the pointer is '
'up, use hover() instead.');
assert(!isPanZoomActive);
final Offset delta = newLocation - location!;
_location = newLocation;
if (buttons != null) {
_buttons = buttons;
}
return PointerMoveEvent(
timeStamp: timeStamp,
kind: kind,
device: _device,
pointer: pointer,
position: newLocation,
delta: delta,
buttons: _buttons,
);
}
/// Create a [PointerUpEvent].
///
/// By default, the time stamp on the event is [Duration.zero]. You can give a
/// specific time stamp by passing the `timeStamp` argument.
///
/// The object is no longer usable after this method has been called.
PointerUpEvent up({ Duration timeStamp = Duration.zero }) {
assert(!isPanZoomActive);
assert(isDown);
_isDown = false;
return PointerUpEvent(
timeStamp: timeStamp,
kind: kind,
device: _device,
pointer: pointer,
position: location!,
);
}
/// Create a [PointerCancelEvent].
///
/// By default, the time stamp on the event is [Duration.zero]. You can give a
/// specific time stamp by passing the `timeStamp` argument.
///
/// The object is no longer usable after this method has been called.
PointerCancelEvent cancel({ Duration timeStamp = Duration.zero }) {
assert(isDown);
_isDown = false;
return PointerCancelEvent(
timeStamp: timeStamp,
kind: kind,
device: _device,
pointer: pointer,
position: location!,
);
}
/// Create a [PointerAddedEvent] with the [PointerDeviceKind] the pointer was
/// created with.
///
/// By default, the time stamp on the event is [Duration.zero]. You can give a
/// specific time stamp by passing the `timeStamp` argument.
PointerAddedEvent addPointer({
Duration timeStamp = Duration.zero,
Offset? location,
}) {
_location = location ?? _location;
return PointerAddedEvent(
timeStamp: timeStamp,
kind: kind,
device: _device,
position: _location ?? Offset.zero,
);
}
/// Create a [PointerRemovedEvent] with the [PointerDeviceKind] the pointer
/// was created with.
///
/// By default, the time stamp on the event is [Duration.zero]. You can give a
/// specific time stamp by passing the `timeStamp` argument.
PointerRemovedEvent removePointer({
Duration timeStamp = Duration.zero,
Offset? location,
}) {
_location = location ?? _location;
return PointerRemovedEvent(
timeStamp: timeStamp,
kind: kind,
device: _device,
pointer: pointer,
position: _location ?? Offset.zero,
);
}
/// Create a [PointerHoverEvent] to the given location.
///
/// By default, the time stamp on the event is [Duration.zero]. You can give a
/// specific time stamp by passing the `timeStamp` argument.
///
/// [isDown] must be false, since hover events can't be sent when the pointer
/// is up.
PointerHoverEvent hover(
Offset newLocation, {
Duration timeStamp = Duration.zero,
}) {
assert(
!isDown,
'Hover events can only be generated when the pointer is up. To '
'simulate movement when the pointer is down, use move() instead.');
final Offset delta = location != null ? newLocation - location! : Offset.zero;
_location = newLocation;
return PointerHoverEvent(
timeStamp: timeStamp,
kind: kind,
device: _device,
pointer: pointer,
position: newLocation,
delta: delta,
);
}
/// Create a [PointerScrollEvent] (e.g., scroll wheel scroll; not finger-drag
/// scroll) with the given delta.
///
/// By default, the time stamp on the event is [Duration.zero]. You can give a
/// specific time stamp by passing the `timeStamp` argument.
PointerScrollEvent scroll(
Offset scrollDelta, {
Duration timeStamp = Duration.zero,
}) {
assert(kind != PointerDeviceKind.touch, "Touch pointers can't generate pointer signal events");
assert(location != null);
return PointerScrollEvent(
timeStamp: timeStamp,
kind: kind,
device: _device,
position: location!,
scrollDelta: scrollDelta,
);
}
/// Create a [PointerScrollInertiaCancelEvent] (e.g., user resting their finger on the trackpad).
///
/// By default, the time stamp on the event is [Duration.zero]. You can give a
/// specific time stamp by passing the `timeStamp` argument.
PointerScrollInertiaCancelEvent scrollInertiaCancel({
Duration timeStamp = Duration.zero,
}) {
assert(kind != PointerDeviceKind.touch, "Touch pointers can't generate pointer signal events");
assert(location != null);
return PointerScrollInertiaCancelEvent(
timeStamp: timeStamp,
kind: kind,
device: _device,
position: location!
);
}
/// Create a [PointerScaleEvent] (e.g., legacy pinch-to-zoom).
///
/// By default, the time stamp on the event is [Duration.zero]. You can give a
/// specific time stamp by passing the `timeStamp` argument.
PointerScaleEvent scale(
double scale, {
Duration timeStamp = Duration.zero,
}) {
assert(kind != PointerDeviceKind.touch, "Touch pointers can't generate pointer signal events");
assert(location != null);
return PointerScaleEvent(
timeStamp: timeStamp,
kind: kind,
device: _device,
position: location!,
scale: scale,
);
}
/// Create a [PointerPanZoomStartEvent] (e.g., trackpad scroll; not scroll wheel
/// or finger-drag scroll) with the given delta.
///
/// By default, the time stamp on the event is [Duration.zero]. You can give a
/// specific time stamp by passing the `timeStamp` argument.
PointerPanZoomStartEvent panZoomStart(
Offset location, {
Duration timeStamp = Duration.zero
}) {
assert(!isPanZoomActive);
assert(kind == PointerDeviceKind.trackpad);
_location = location;
_pan = Offset.zero;
_isPanZoomActive = true;
return PointerPanZoomStartEvent(
timeStamp: timeStamp,
device: _device,
pointer: pointer,
position: location,
);
}
/// Create a [PointerPanZoomUpdateEvent] to update the active pan/zoom sequence
/// on this pointer with updated pan, scale, and/or rotation values.
///
/// [rotation] is in units of radians.
///
/// By default, the time stamp on the event is [Duration.zero]. You can give a
/// specific time stamp by passing the `timeStamp` argument.
PointerPanZoomUpdateEvent panZoomUpdate(
Offset location, {
Offset pan = Offset.zero,
double scale = 1,
double rotation = 0,
Duration timeStamp = Duration.zero,
}) {
assert(isPanZoomActive);
assert(kind == PointerDeviceKind.trackpad);
_location = location;
final Offset panDelta = pan - _pan!;
_pan = pan;
return PointerPanZoomUpdateEvent(
timeStamp: timeStamp,
device: _device,
pointer: pointer,
position: location,
pan: pan,
panDelta: panDelta,
scale: scale,
rotation: rotation,
);
}
/// Create a [PointerPanZoomEndEvent] to end the active pan/zoom sequence
/// on this pointer.
///
/// By default, the time stamp on the event is [Duration.zero]. You can give a
/// specific time stamp by passing the `timeStamp` argument.
PointerPanZoomEndEvent panZoomEnd({
Duration timeStamp = Duration.zero
}) {
assert(isPanZoomActive);
assert(kind == PointerDeviceKind.trackpad);
_isPanZoomActive = false;
_pan = null;
return PointerPanZoomEndEvent(
timeStamp: timeStamp,
device: _device,
pointer: pointer,
position: location!,
);
}
}
/// Signature for a callback that can dispatch events and returns a future that
/// completes when the event dispatch is complete.
typedef EventDispatcher = Future<void> Function(PointerEvent event);
/// Signature for callbacks that perform hit-testing at a given location.
typedef HitTester = HitTestResult Function(Offset location);
/// A class for performing gestures in tests.
///
/// The simplest way to create a [TestGesture] is to call
/// [WidgetTester.startGesture].
class TestGesture {
/// Create a [TestGesture] without dispatching any events from it.
/// The [TestGesture] can then be manipulated to perform future actions.
///
/// By default, the pointer identifier used is 1. This can be overridden by
/// providing the `pointer` argument.
///
/// A function to use for hit testing must be provided via the `hitTester`
/// argument, and a function to use for dispatching events must be provided
/// via the `dispatcher` argument.
///
/// The device `kind` defaults to [PointerDeviceKind.touch], but move events
/// when the pointer is "up" require a kind other than
/// [PointerDeviceKind.touch], like [PointerDeviceKind.mouse], for example,
/// because touch devices can't produce movement events when they are "up".
///
/// None of the arguments may be null. The `dispatcher` and `hitTester`
/// arguments are required.
TestGesture({
required EventDispatcher dispatcher,
int pointer = 1,
PointerDeviceKind kind = PointerDeviceKind.touch,
int? device,
int buttons = kPrimaryButton,
}) : _dispatcher = dispatcher,
_pointer = TestPointer(pointer, kind, device, buttons);
/// Dispatch a pointer down event at the given `downLocation`, caching the
/// hit test result.
Future<void> down(Offset downLocation, { Duration timeStamp = Duration.zero }) async {
assert(_pointer.kind != PointerDeviceKind.trackpad, 'Trackpads are expected to send panZoomStart events, not down events.');
return TestAsyncUtils.guard<void>(() async {
return _dispatcher(_pointer.down(downLocation, timeStamp: timeStamp));
});
}
/// Dispatch a pointer down event at the given `downLocation`, caching the
/// hit test result with a custom down event.
Future<void> downWithCustomEvent(Offset downLocation, PointerDownEvent event) async {
assert(_pointer.kind != PointerDeviceKind.trackpad, 'Trackpads are expected to send panZoomStart events, not down events');
_pointer.setDownInfo(event, downLocation);
return TestAsyncUtils.guard<void>(() async {
return _dispatcher(event);
});
}
final EventDispatcher _dispatcher;
final TestPointer _pointer;
/// In a test, send a move event that moves the pointer by the given offset.
@visibleForTesting
Future<void> updateWithCustomEvent(PointerEvent event, { Duration timeStamp = Duration.zero }) {
_pointer.setDownInfo(event, event.position);
return TestAsyncUtils.guard<void>(() {
return _dispatcher(event);
});
}
/// In a test, send a pointer add event for this pointer.
Future<void> addPointer({ Duration timeStamp = Duration.zero, Offset? location }) {
return TestAsyncUtils.guard<void>(() {
return _dispatcher(_pointer.addPointer(timeStamp: timeStamp, location: location ?? _pointer.location));
});
}
/// In a test, send a pointer remove event for this pointer.
Future<void> removePointer({ Duration timeStamp = Duration.zero, Offset? location }) {
return TestAsyncUtils.guard<void>(() {
return _dispatcher(_pointer.removePointer(timeStamp: timeStamp, location: location ?? _pointer.location));
});
}
/// Send a move event moving the pointer by the given offset.
///
/// If the pointer is down, then a move event is dispatched. If the pointer is
/// up, then a hover event is dispatched.
///
/// 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<void> moveBy(Offset offset, { Duration timeStamp = Duration.zero }) {
assert(_pointer.location != null);
if (_pointer.isPanZoomActive) {
return panZoomUpdate(
_pointer.location!,
pan: (_pointer.pan ?? Offset.zero) + offset,
timeStamp: timeStamp
);
} else {
return moveTo(_pointer.location! + offset, timeStamp: timeStamp);
}
}
/// Send a move event moving the pointer to the given location.
///
/// If the pointer is down, then a move event is dispatched. If the pointer is
/// up, then a hover event is dispatched.
///
/// 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<void> moveTo(Offset location, { Duration timeStamp = Duration.zero }) {
assert(_pointer.kind != PointerDeviceKind.trackpad);
return TestAsyncUtils.guard<void>(() {
if (_pointer._isDown) {
return _dispatcher(_pointer.move(location, timeStamp: timeStamp));
} else {
return _dispatcher(_pointer.hover(location, timeStamp: timeStamp));
}
});
}
/// End the gesture by releasing the pointer. For trackpad pointers this
/// will send a panZoomEnd event instead of an up event.
Future<void> up({ Duration timeStamp = Duration.zero }) {
return TestAsyncUtils.guard<void>(() async {
if (_pointer.kind == PointerDeviceKind.trackpad) {
assert(_pointer._isPanZoomActive);
await _dispatcher(_pointer.panZoomEnd(timeStamp: timeStamp));
assert(!_pointer._isPanZoomActive);
} else {
assert(_pointer._isDown);
await _dispatcher(_pointer.up(timeStamp: timeStamp));
assert(!_pointer._isDown);
}
});
}
/// End the gesture by canceling the pointer (as would happen if the
/// system showed a modal dialog on top of the Flutter application,
/// for instance).
Future<void> cancel({ Duration timeStamp = Duration.zero }) {
assert(_pointer.kind != PointerDeviceKind.trackpad, 'Trackpads do not send cancel events.');
return TestAsyncUtils.guard<void>(() async {
assert(_pointer._isDown);
await _dispatcher(_pointer.cancel(timeStamp: timeStamp));
assert(!_pointer._isDown);
});
}
/// Dispatch a pointer pan zoom start event at the given `location`, caching the
/// hit test result.
Future<void> panZoomStart(Offset location, { Duration timeStamp = Duration.zero }) async {
assert(_pointer.kind == PointerDeviceKind.trackpad, 'Only trackpads can send PointerPanZoom events.');
return TestAsyncUtils.guard<void>(() async {
return _dispatcher(_pointer.panZoomStart(location, timeStamp: timeStamp));
});
}
/// Dispatch a pointer pan zoom update event at the given `location`, caching the
/// hit test result.
Future<void> panZoomUpdate(Offset location, {
Offset pan = Offset.zero,
double scale = 1,
double rotation = 0,
Duration timeStamp = Duration.zero
}) async {
assert(_pointer.kind == PointerDeviceKind.trackpad, 'Only trackpads can send PointerPanZoom events.');
return TestAsyncUtils.guard<void>(() async {
return _dispatcher(_pointer.panZoomUpdate(location,
pan: pan,
scale: scale,
rotation: rotation,
timeStamp: timeStamp
));
});
}
/// Dispatch a pointer pan zoom end event, caching the hit test result.
Future<void> panZoomEnd({
Duration timeStamp = Duration.zero
}) async {
assert(_pointer.kind == PointerDeviceKind.trackpad, 'Only trackpads can send PointerPanZoom events.');
return TestAsyncUtils.guard<void>(() async {
return _dispatcher(_pointer.panZoomEnd(
timeStamp: timeStamp
));
});
}
}
/// A record of input [PointerEvent] list with the timeStamp of when it is
/// injected.
///
/// The [timeDelay] is used to indicate the time when the event packet should
/// be sent.
///
/// This is a simulation of how the framework is receiving input events from
/// the engine. See [GestureBinding] and [PointerDataPacket].
class PointerEventRecord {
/// Creates a pack of [PointerEvent]s.
PointerEventRecord(this.timeDelay, this.events);
/// The time delay of when the event record should be sent.
///
/// This value is used as the time delay relative to the start of
/// [WidgetTester.handlePointerEventRecord] call.
final Duration timeDelay;
/// The event list of the record.
///
/// This can be considered as a simulation of the events expanded from the
/// [PointerDataPacket].
///
/// See [PointerEventConverter.expand].
final List<PointerEvent> events;
}
| flutter/packages/flutter_test/lib/src/test_pointer.dart/0 | {
"file_path": "flutter/packages/flutter_test/lib/src/test_pointer.dart",
"repo_id": "flutter",
"token_count": 7217
} | 758 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('$WidgetsBinding initializes with $LiveTestWidgetsFlutterBinding when the environment does not contain FLUTTER_TEST', () {
TestWidgetsFlutterBinding.ensureInitialized(<String, String>{});
expect(WidgetsBinding.instance, isA<LiveTestWidgetsFlutterBinding>());
});
}
| flutter/packages/flutter_test/test/bindings_environment/no_flutter_test_variable_test.dart/0 | {
"file_path": "flutter/packages/flutter_test/test/bindings_environment/no_flutter_test_variable_test.dart",
"repo_id": "flutter",
"token_count": 175
} | 759 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
// This file is for testings that require a `LiveTestWidgetsFlutterBinding`
void main() {
final LiveTestWidgetsFlutterBinding binding = LiveTestWidgetsFlutterBinding();
testWidgets('Input PointerAddedEvent', (WidgetTester tester) async {
await tester.pumpWidget(const MaterialApp(home: Text('Test')));
await tester.pump();
final TestGesture gesture = await tester.createGesture();
// This mimics the start of a gesture as seen on a device, where inputs
// starts with a PointerAddedEvent.
await gesture.addPointer();
// The expected result of the test is not to trigger any assert.
});
testWidgets('Input PointerHoverEvent', (WidgetTester tester) async {
PointerHoverEvent? hoverEvent;
await tester.pumpWidget(MaterialApp(home: MouseRegion(
child: const Text('Test'),
onHover: (PointerHoverEvent event) {
hoverEvent = event;
},
)));
await tester.pump();
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
final Offset location = tester.getCenter(find.text('Test'));
// for mouse input without a down event, moveTo generates a hover event
await gesture.moveTo(location);
expect(hoverEvent, isNotNull);
expect(hoverEvent!.position, location);
});
testWidgets('hitTesting works when using setSurfaceSize', (WidgetTester tester) async {
int invocations = 0;
await tester.pumpWidget(
MaterialApp(
home: Center(
child: GestureDetector(
onTap: () {
invocations++;
},
child: const Text('Test'),
),
),
),
);
await tester.tap(find.byType(Text));
await tester.pump();
expect(invocations, 1);
await tester.binding.setSurfaceSize(const Size(200, 300));
await tester.pump();
await tester.tap(find.byType(Text));
await tester.pump();
expect(invocations, 2);
await tester.binding.setSurfaceSize(null);
await tester.pump();
await tester.tap(find.byType(Text));
await tester.pump();
expect(invocations, 3);
});
testWidgets('setSurfaceSize works', (WidgetTester tester) async {
await tester.pumpWidget(const MaterialApp(home: Center(child: Text('Test'))));
final Size windowCenter = tester.view.physicalSize /
tester.view.devicePixelRatio /
2;
final double windowCenterX = windowCenter.width;
final double windowCenterY = windowCenter.height;
Offset widgetCenter = tester.getRect(find.byType(Text)).center;
expect(widgetCenter.dx, windowCenterX);
expect(widgetCenter.dy, windowCenterY);
await tester.binding.setSurfaceSize(const Size(200, 300));
await tester.pump();
widgetCenter = tester.getRect(find.byType(Text)).center;
expect(widgetCenter.dx, 100);
expect(widgetCenter.dy, 150);
await tester.binding.setSurfaceSize(null);
await tester.pump();
widgetCenter = tester.getRect(find.byType(Text)).center;
expect(widgetCenter.dx, windowCenterX);
expect(widgetCenter.dy, windowCenterY);
});
testWidgets("reassembleApplication doesn't get stuck", (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/79150
await expectLater(tester.binding.reassembleApplication(), completes);
}, timeout: const Timeout(Duration(seconds: 30)));
testWidgets('shouldPropagateDevicePointerEvents can override events from ${TestBindingEventSource.device}', (WidgetTester tester) async {
binding.shouldPropagateDevicePointerEvents = true;
await tester.pumpWidget(_ShowNumTaps());
final Offset position = tester.getCenter(find.text('0'));
// Simulates a real device tap.
//
// `handlePointerEventForSource defaults to sending events using
// TestBindingEventSource.device. This will not be forwarded to the actual
// gesture handlers, unless `shouldPropagateDevicePointerEvents` is true.
binding.handlePointerEventForSource(
PointerDownEvent(position: position),
);
binding.handlePointerEventForSource(
PointerUpEvent(position: position),
);
await tester.pump();
expect(find.text('1'), findsOneWidget);
// Reset the value, otherwise the test will fail when it checks that this
// has not been changed as an invariant.
binding.shouldPropagateDevicePointerEvents = false;
});
}
/// A widget that shows the number of times it has been tapped.
class _ShowNumTaps extends StatefulWidget {
@override
_ShowNumTapsState createState() => _ShowNumTapsState();
}
class _ShowNumTapsState extends State<_ShowNumTaps> {
int _counter = 0;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
setState(() {
_counter++;
});
},
child: Directionality(
textDirection: TextDirection.ltr,
child: Text(_counter.toString()),
),
);
}
}
| flutter/packages/flutter_test/test/live_binding_test.dart/0 | {
"file_path": "flutter/packages/flutter_test/test/live_binding_test.dart",
"repo_id": "flutter",
"token_count": 1852
} | 760 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_test/flutter_test.dart' as flutter_test show expect;
import 'package:matcher/expect.dart' as matcher show expect;
// We have to use matcher's expect because the flutter_test expect() goes
// out of its way to check that we're not leaking APIs and the whole point
// of this test is to see how we handle leaking APIs.
class TestAPI {
Future<Object?> testGuard1() {
return TestAsyncUtils.guard<Object?>(() async { return null; });
}
Future<Object?> testGuard2() {
return TestAsyncUtils.guard<Object?>(() async { return null; });
}
}
class TestAPISubclass extends TestAPI {
Future<Object?> testGuard3() {
return TestAsyncUtils.guard<Object?>(() async { return null; });
}
}
class RecognizableTestException implements Exception {
const RecognizableTestException();
}
Future<Object> _guardedThrower() {
return TestAsyncUtils.guard<Object>(() async {
throw const RecognizableTestException();
});
}
void main() {
test('TestAsyncUtils - one class', () async {
final TestAPI testAPI = TestAPI();
Future<Object?>? f1, f2;
f1 = testAPI.testGuard1();
try {
f2 = testAPI.testGuard2();
fail('unexpectedly did not throw');
} on FlutterError catch (e) {
final List<String> lines = e.message.split('\n');
matcher.expect(lines[0], 'Guarded function conflict.');
matcher.expect(lines[1], 'You must use "await" with all Future-returning test APIs.');
matcher.expect(lines[2], matches(r'The guarded method "testGuard1" from class TestAPI was called from .*test_async_utils_test.dart on line [0-9]+\.'));
matcher.expect(lines[3], matches(r'Then, the "testGuard2" method \(also from class TestAPI\) was called from .*test_async_utils_test.dart on line [0-9]+\.'));
matcher.expect(lines[4], 'The first method (TestAPI.testGuard1) had not yet finished executing at the time that the second method (TestAPI.testGuard2) was called. Since both are guarded, and the second was not a nested call inside the first, the first must complete its execution before the second can be called. Typically, this is achieved by putting an "await" statement in front of the call to the first.');
matcher.expect(lines[5], '');
matcher.expect(lines[6], 'When the first method (TestAPI.testGuard1) was called, this was the stack:');
matcher.expect(lines.length, greaterThan(6));
}
expect(await f1, isNull);
expect(f2, isNull);
}, skip: kIsWeb); // [intended] depends on platform-specific stack traces.
test('TestAsyncUtils - two classes, all callers in superclass', () async {
final TestAPI testAPI = TestAPISubclass();
Future<Object?>? f1, f2;
f1 = testAPI.testGuard1();
try {
f2 = testAPI.testGuard2();
fail('unexpectedly did not throw');
} on FlutterError catch (e) {
final List<String> lines = e.message.split('\n');
matcher.expect(lines[0], 'Guarded function conflict.');
matcher.expect(lines[1], 'You must use "await" with all Future-returning test APIs.');
matcher.expect(lines[2], matches(r'^The guarded method "testGuard1" from class TestAPI was called from .*test_async_utils_test.dart on line [0-9]+\.$'));
matcher.expect(lines[3], matches(r'^Then, the "testGuard2" method \(also from class TestAPI\) was called from .*test_async_utils_test.dart on line [0-9]+\.$'));
matcher.expect(lines[4], 'The first method (TestAPI.testGuard1) had not yet finished executing at the time that the second method (TestAPI.testGuard2) was called. Since both are guarded, and the second was not a nested call inside the first, the first must complete its execution before the second can be called. Typically, this is achieved by putting an "await" statement in front of the call to the first.');
matcher.expect(lines[5], '');
matcher.expect(lines[6], 'When the first method (TestAPI.testGuard1) was called, this was the stack:');
matcher.expect(lines.length, greaterThan(7));
}
expect(await f1, isNull);
expect(f2, isNull);
}, skip: kIsWeb); // [intended] depends on platform-specific stack traces.
test('TestAsyncUtils - two classes, mixed callers', () async {
final TestAPISubclass testAPI = TestAPISubclass();
Future<Object?>? f1, f2;
f1 = testAPI.testGuard1();
try {
f2 = testAPI.testGuard3();
fail('unexpectedly did not throw');
} on FlutterError catch (e) {
final List<String> lines = e.message.split('\n');
matcher.expect(lines[0], 'Guarded function conflict.');
matcher.expect(lines[1], 'You must use "await" with all Future-returning test APIs.');
matcher.expect(lines[2], matches(r'^The guarded method "testGuard1" from class TestAPI was called from .*test_async_utils_test.dart on line [0-9]+\.$'));
matcher.expect(lines[3], matches(r'^Then, the "testGuard3" method from class TestAPISubclass was called from .*test_async_utils_test.dart on line [0-9]+\.$'));
matcher.expect(lines[4], 'The first method (TestAPI.testGuard1) had not yet finished executing at the time that the second method (TestAPISubclass.testGuard3) was called. Since both are guarded, and the second was not a nested call inside the first, the first must complete its execution before the second can be called. Typically, this is achieved by putting an "await" statement in front of the call to the first.');
matcher.expect(lines[5], '');
matcher.expect(lines[6], 'When the first method (TestAPI.testGuard1) was called, this was the stack:');
matcher.expect(lines.length, greaterThan(7));
}
expect(await f1, isNull);
expect(f2, isNull);
}, skip: kIsWeb); // [intended] depends on platform-specific stack traces.
test('TestAsyncUtils - expect() catches pending async work', () async {
final TestAPI testAPI = TestAPISubclass();
Future<Object?>? f1;
f1 = testAPI.testGuard1();
try {
flutter_test.expect(0, 0);
fail('unexpectedly did not throw');
} on FlutterError catch (e) {
final List<String> lines = e.message.split('\n');
matcher.expect(lines[0], 'Guarded function conflict.');
matcher.expect(lines[1], 'You must use "await" with all Future-returning test APIs.');
matcher.expect(lines[2], matches(r'^The guarded method "testGuard1" from class TestAPI was called from .*test_async_utils_test.dart on line [0-9]+\.$'));
matcher.expect(lines[3], matches(r'^Then, the "expect" function was called from .*test_async_utils_test.dart on line [0-9]+\.$'));
matcher.expect(lines[4], 'The first method (TestAPI.testGuard1) had not yet finished executing at the time that the second function (expect) was called. Since both are guarded, and the second was not a nested call inside the first, the first must complete its execution before the second can be called. Typically, this is achieved by putting an "await" statement in front of the call to the first.');
matcher.expect(lines[5], 'If you are confident that all test APIs are being called using "await", and this expect() call is not being called at the top level but is itself being called from some sort of callback registered before the testGuard1 method was called, then consider using expectSync() instead.');
matcher.expect(lines[6], '');
matcher.expect(lines[7], 'When the first method (TestAPI.testGuard1) was called, this was the stack:');
matcher.expect(lines.length, greaterThan(7));
}
expect(await f1, isNull);
}, skip: kIsWeb); // [intended] depends on platform-specific stack traces.
testWidgets('TestAsyncUtils - expect() catches pending async work', (WidgetTester tester) async {
Future<Object?>? f1, f2;
try {
f1 = tester.pump();
f2 = tester.pump();
fail('unexpectedly did not throw');
} on FlutterError catch (e) {
final List<String> lines = e.message.split('\n');
matcher.expect(lines[0], 'Guarded function conflict.');
matcher.expect(lines[1], 'You must use "await" with all Future-returning test APIs.');
matcher.expect(lines[2], matches(r'^The guarded method "pump" from class WidgetTester was called from .*test_async_utils_test.dart on line [0-9]+\.$'));
matcher.expect(lines[3], matches(r'^Then, it was called from .*test_async_utils_test.dart on line [0-9]+\.$'));
matcher.expect(lines[4], 'The first method had not yet finished executing at the time that the second method was called. Since both are guarded, and the second was not a nested call inside the first, the first must complete its execution before the second can be called. Typically, this is achieved by putting an "await" statement in front of the call to the first.');
matcher.expect(lines[5], '');
matcher.expect(lines[6], 'When the first method was called, this was the stack:');
matcher.expect(lines.length, greaterThan(7));
// TODO(jacobr): add more tests like this if they are useful.
final DiagnosticPropertiesBuilder propertiesBuilder = DiagnosticPropertiesBuilder();
e.debugFillProperties(propertiesBuilder);
final List<DiagnosticsNode> information = propertiesBuilder.properties;
matcher.expect(information.length, 6);
matcher.expect(information[0].level, DiagnosticLevel.summary);
matcher.expect(information[1].level, DiagnosticLevel.hint);
matcher.expect(information[2].level, DiagnosticLevel.info);
matcher.expect(information[3].level, DiagnosticLevel.info);
matcher.expect(information[4].level, DiagnosticLevel.info);
matcher.expect(information[5].level, DiagnosticLevel.info);
matcher.expect(information[0], isA<DiagnosticsProperty<void>>());
matcher.expect(information[1], isA<DiagnosticsProperty<void>>());
matcher.expect(information[2], isA<DiagnosticsProperty<void>>());
matcher.expect(information[3], isA<DiagnosticsProperty<void>>());
matcher.expect(information[4], isA<DiagnosticsProperty<void>>());
matcher.expect(information[5], isA<DiagnosticsStackTrace>());
final DiagnosticsStackTrace stackTraceProperty = information[5] as DiagnosticsStackTrace;
matcher.expect(stackTraceProperty.name, '\nWhen the first method was called, this was the stack');
matcher.expect(stackTraceProperty.value, isA<StackTrace>());
}
await f1;
await f2;
}, skip: kIsWeb); // [intended] depends on platform-specific stack traces.
testWidgets('TestAsyncUtils - expect() catches pending async work', (WidgetTester tester) async {
Future<Object?>? f1;
try {
f1 = tester.pump();
TestAsyncUtils.verifyAllScopesClosed();
fail('unexpectedly did not throw');
} on FlutterError catch (e) {
final List<String> lines = e.message.split('\n');
matcher.expect(lines[0], 'Asynchronous call to guarded function leaked.');
matcher.expect(lines[1], 'You must use "await" with all Future-returning test APIs.');
matcher.expect(lines[2], matches(r'^The guarded method "pump" from class WidgetTester was called from .*test_async_utils_test.dart on line [0-9]+, but never completed before its parent scope closed\.$'));
matcher.expect(lines[3], matches(r'^The guarded method "pump" from class AutomatedTestWidgetsFlutterBinding was called from [^ ]+ on line [0-9]+, but never completed before its parent scope closed\.'));
matcher.expect(lines.length, 4);
final DiagnosticPropertiesBuilder propertiesBuilder = DiagnosticPropertiesBuilder();
e.debugFillProperties(propertiesBuilder);
final List<DiagnosticsNode> information = propertiesBuilder.properties;
matcher.expect(information.length, 4);
matcher.expect(information[0].level, DiagnosticLevel.summary);
matcher.expect(information[1].level, DiagnosticLevel.hint);
matcher.expect(information[2].level, DiagnosticLevel.info);
matcher.expect(information[3].level, DiagnosticLevel.info);
}
await f1;
}, skip: kIsWeb); // [intended] depends on platform-specific stack traces.
testWidgets('TestAsyncUtils - expect() catches pending async work', (WidgetTester tester) async {
Future<Object?>? f1;
try {
f1 = tester.pump();
TestAsyncUtils.verifyAllScopesClosed();
fail('unexpectedly did not throw');
} on FlutterError catch (e) {
final List<String> lines = e.message.split('\n');
matcher.expect(lines[0], 'Asynchronous call to guarded function leaked.');
matcher.expect(lines[1], 'You must use "await" with all Future-returning test APIs.');
matcher.expect(lines[2], matches(r'^The guarded method "pump" from class WidgetTester was called from .*test_async_utils_test.dart on line [0-9]+, but never completed before its parent scope closed\.$'));
matcher.expect(lines[3], matches(r'^The guarded method "pump" from class AutomatedTestWidgetsFlutterBinding was called from [^ ]+ on line [0-9]+, but never completed before its parent scope closed\.'));
matcher.expect(lines.length, 4);
final DiagnosticPropertiesBuilder propertiesBuilder = DiagnosticPropertiesBuilder();
e.debugFillProperties(propertiesBuilder);
final List<DiagnosticsNode> information = propertiesBuilder.properties;
matcher.expect(information.length, 4);
matcher.expect(information[0].level, DiagnosticLevel.summary);
matcher.expect(information[1].level, DiagnosticLevel.hint);
matcher.expect(information[2].level, DiagnosticLevel.info);
matcher.expect(information[3].level, DiagnosticLevel.info);
}
await f1;
}, skip: kIsWeb); // [intended] depends on platform-specific stack traces.
testWidgets('TestAsyncUtils - guard body can throw', (WidgetTester tester) async {
try {
await _guardedThrower();
expect(false, true); // _guardedThrower should throw and we shouldn't reach here
} on RecognizableTestException catch (e) {
expect(e, const RecognizableTestException());
}
});
test('TestAsyncUtils - web', () async {
final TestAPI testAPI = TestAPI();
Future<Object?>? f1, f2;
f1 = testAPI.testGuard1();
try {
f2 = testAPI.testGuard2();
fail('unexpectedly did not throw');
} on FlutterError catch (e) {
final List<String> lines = e.message.split('\n');
matcher.expect(lines[0], 'Guarded function conflict.');
matcher.expect(lines[1], 'You must use "await" with all Future-returning test APIs.');
matcher.expect(lines[2], '');
matcher.expect(lines[3], 'When the first function was called, this was the stack:');
matcher.expect(lines.length, greaterThan(3));
}
expect(await f1, isNull);
expect(f2, isNull);
}, skip: !kIsWeb); // [intended] depends on platform-specific stack traces.
// see also dev/manual_tests/test_data which contains tests run by the flutter_tools tests for 'flutter test'
}
| flutter/packages/flutter_test/test/test_async_utils_test.dart/0 | {
"file_path": "flutter/packages/flutter_test/test/test_async_utils_test.dart",
"repo_id": "flutter",
"token_count": 5200
} | 761 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
// Only check the initial lines of the message, since the message walks the
// entire widget tree back, and any changes to the widget tree break these
// tests if we check the entire message.
void _expectStartsWith(List<String?> actual, List<String?> matcher) {
expect(actual.sublist(0, matcher.length), equals(matcher));
}
void main() {
final _MockLiveTestWidgetsFlutterBinding binding = _MockLiveTestWidgetsFlutterBinding();
testWidgets('Should print message on pointer events', (WidgetTester tester) async {
final List<String?> printedMessages = <String?>[];
int invocations = 0;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: GestureDetector(
onTap: () {
invocations++;
},
child: const Text('Test'),
),
),
),
);
final Size windowCenter = tester.view.physicalSize /
tester.view.devicePixelRatio /
2;
final double windowCenterX = windowCenter.width;
final double windowCenterY = windowCenter.height;
final Offset widgetCenter = tester.getRect(find.byType(Text)).center;
expect(widgetCenter.dx, windowCenterX);
expect(widgetCenter.dy, windowCenterY);
await binding.collectDebugPrints(printedMessages, () async {
await tester.tap(find.byType(Text));
});
await tester.pump();
expect(invocations, 0);
_expectStartsWith(printedMessages, '''
Some possible finders for the widgets at Offset(400.0, 300.0):
find.text('Test')
'''.trim().split('\n'));
printedMessages.clear();
await binding.collectDebugPrints(printedMessages, () async {
await tester.tapAt(const Offset(1, 1));
});
expect(printedMessages, equals('''
No widgets found at Offset(1.0, 1.0).
'''.trim().split('\n')));
});
testWidgets('Should print message on pointer events with setSurfaceSize', (WidgetTester tester) async {
final List<String?> printedMessages = <String?>[];
int invocations = 0;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child:GestureDetector(
onTap: () {
invocations++;
},
child: const Text('Test'),
),
),
),
);
final Size originalSize = tester.binding.renderView.size;
await tester.binding.setSurfaceSize(const Size(2000, 1800));
try {
await tester.pump();
final Offset widgetCenter = tester.getRect(find.byType(Text)).center;
expect(widgetCenter.dx, 1000);
expect(widgetCenter.dy, 900);
await binding.collectDebugPrints(printedMessages, () async {
await tester.tap(find.byType(Text));
});
await tester.pump();
expect(invocations, 0);
_expectStartsWith(printedMessages, '''
Some possible finders for the widgets at Offset(1000.0, 900.0):
find.text('Test')
'''.trim().split('\n'));
printedMessages.clear();
await binding.collectDebugPrints(printedMessages, () async {
await tester.tapAt(const Offset(1, 1));
});
expect(printedMessages, equals('''
No widgets found at Offset(1.0, 1.0).
'''.trim().split('\n')));
} finally {
await tester.binding.setSurfaceSize(originalSize);
}
});
}
class _MockLiveTestWidgetsFlutterBinding extends LiveTestWidgetsFlutterBinding {
@override
void handlePointerEventForSource(
PointerEvent event, {
TestBindingEventSource source = TestBindingEventSource.device,
}) {
// In this test we use `WidgetTester.tap` to simulate real device touches.
// `WidgetTester.tap` sends events in the local coordinate system, while
// real devices touches sends event in the global coordinate system.
// See the documentation of [handlePointerEventForSource] for details.
if (source == TestBindingEventSource.test) {
final RenderView renderView = renderViews.firstWhere((RenderView r) => r.flutterView.viewId == event.viewId);
final PointerEvent globalEvent = event.copyWith(position: localToGlobal(event.position, renderView));
return super.handlePointerEventForSource(globalEvent);
}
return super.handlePointerEventForSource(event, source: source);
}
List<String?>? _storeDebugPrints;
@override
DebugPrintCallback get debugPrintOverride {
return _storeDebugPrints == null
? super.debugPrintOverride
: ((String? message, { int? wrapWidth }) => _storeDebugPrints!.add(message));
}
// Execute `task` while redirecting [debugPrint] to appending to `store`.
Future<void> collectDebugPrints(List<String?>? store, AsyncValueGetter<void> task) async {
_storeDebugPrints = store;
try {
await task();
} finally {
_storeDebugPrints = null;
}
}
}
| flutter/packages/flutter_test/test/widget_tester_live_device_test.dart/0 | {
"file_path": "flutter/packages/flutter_test/test/widget_tester_live_device_test.dart",
"repo_id": "flutter",
"token_count": 1907
} | 762 |
# Flutter Attach
## Overview
A Flutter-command that attaches to applications that have been launched
without `flutter run` and provides a HotRunner (enabling hot reload/restart).
## Usage
There are three ways for the attach command to discover a running app:
1. If the platform is Fuchsia the module name must be provided, e.g. `$
flutter attach --module=mod_name`. This can be called either before or after
the application is started, attach will poll the device if it cannot
immediately discover the port
1. On Android and iOS, just running `flutter attach` suffices. Flutter tools
will search for an already running Flutter app or module if available.
Otherwise, the tool will wait for the next Flutter app or module to launch
before attaching.
1. If the app or module is already running and the specific VM Service port is
known, it can be explicitly provided to attach via the command-line, e.g.
`$ flutter attach --debug-port 12345`
## Source
See the [source](https://github.com/flutter/flutter/blob/master/packages/flutter_tools/lib/src/commands/attach.dart) for the attach command.
| flutter/packages/flutter_tools/doc/attach.md/0 | {
"file_path": "flutter/packages/flutter_tools/doc/attach.md",
"repo_id": "flutter",
"token_count": 289
} | 763 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import groovy.json.JsonSlurper
class NativePluginLoader {
// This string must match _kFlutterPluginsHasNativeBuildKey defined in
// packages/flutter_tools/lib/src/flutter_plugins.dart.
static final String nativeBuildKey = "native_build"
static final String flutterPluginsDependenciesFile = ".flutter-plugins-dependencies"
/**
* Gets the list of plugins that support the Android platform.
* The list contains map elements with the following content:
* {
* "name": "plugin-a",
* "path": "/path/to/plugin-a",
* "dependencies": ["plugin-b", "plugin-c"],
* "native_build": true
* }
*
* Therefore the map value can either be a `String`, a `List<String>` or a `boolean`.
*/
List<Map<String, Object>> getPlugins(File flutterSourceDirectory) {
List<Map<String, Object>> nativePlugins = []
def meta = getDependenciesMetadata(flutterSourceDirectory)
if (meta == null) {
return nativePlugins
}
assert(meta.plugins instanceof Map<String, Object>)
def androidPlugins = meta.plugins.android
assert(androidPlugins instanceof List<Map>)
// Includes the Flutter plugins that support the Android platform.
androidPlugins.each { Map<String, Object> androidPlugin ->
// The property types can be found in _filterPluginsByPlatform defined in
// packages/flutter_tools/lib/src/flutter_plugins.dart.
assert(androidPlugin.name instanceof String)
assert(androidPlugin.path instanceof String)
assert(androidPlugin.dependencies instanceof List<String>)
// Skip plugins that have no native build (such as a Dart-only implementation
// of a federated plugin).
def needsBuild = androidPlugin.containsKey(nativeBuildKey) ? androidPlugin[nativeBuildKey] : true
if (needsBuild) {
nativePlugins.add(androidPlugin)
}
}
return nativePlugins
}
private Map<String, Object> parsedFlutterPluginsDependencies
/**
* Parses <project-src>/.flutter-plugins-dependencies
*/
Map<String, Object> getDependenciesMetadata(File flutterSourceDirectory) {
// Consider a `.flutter-plugins-dependencies` file with the following content:
// {
// "plugins": {
// "android": [
// {
// "name": "plugin-a",
// "path": "/path/to/plugin-a",
// "dependencies": ["plugin-b", "plugin-c"],
// "native_build": true
// },
// {
// "name": "plugin-b",
// "path": "/path/to/plugin-b",
// "dependencies": ["plugin-c"],
// "native_build": true
// },
// {
// "name": "plugin-c",
// "path": "/path/to/plugin-c",
// "dependencies": [],
// "native_build": true
// },
// ],
// },
// "dependencyGraph": [
// {
// "name": "plugin-a",
// "dependencies": ["plugin-b","plugin-c"]
// },
// {
// "name": "plugin-b",
// "dependencies": ["plugin-c"]
// },
// {
// "name": "plugin-c",
// "dependencies": []
// }
// ]
// }
// This means, `plugin-a` depends on `plugin-b` and `plugin-c`.
// `plugin-b` depends on `plugin-c`.
// `plugin-c` doesn't depend on anything.
if (parsedFlutterPluginsDependencies) {
return parsedFlutterPluginsDependencies
}
File pluginsDependencyFile = new File(flutterSourceDirectory, flutterPluginsDependenciesFile)
if (pluginsDependencyFile.exists()) {
def object = new JsonSlurper().parseText(pluginsDependencyFile.text)
assert(object instanceof Map<String, Object>)
parsedFlutterPluginsDependencies = object
return object
}
return null
}
}
// TODO(135392): Remove and use declarative form when migrated
ext {
nativePluginLoader = new NativePluginLoader()
}
| flutter/packages/flutter_tools/gradle/src/main/groovy/native_plugin_loader.groovy/0 | {
"file_path": "flutter/packages/flutter_tools/gradle/src/main/groovy/native_plugin_loader.groovy",
"repo_id": "flutter",
"token_count": 2067
} | 764 |
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="hello_world" type="FlutterRunConfigurationType" factoryName="Flutter">
<option name="filePath" value="$PROJECT_DIR$/examples/hello_world/lib/main.dart" />
<method />
</configuration>
</component> | flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/hello_world.xml.copy.tmpl/0 | {
"file_path": "flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/hello_world.xml.copy.tmpl",
"repo_id": "flutter",
"token_count": 90
} | 765 |
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="manual_tests - material_arc" type="FlutterRunConfigurationType" factoryName="Flutter">
<option name="filePath" value="$PROJECT_DIR$/dev/manual_tests/lib/material_arc.dart" />
<method />
</configuration>
</component> | flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/manual_tests___material_arc.xml.copy.tmpl/0 | {
"file_path": "flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/manual_tests___material_arc.xml.copy.tmpl",
"repo_id": "flutter",
"token_count": 97
} | 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 'dart:async';
import 'package:process/process.dart';
import '../base/common.dart';
import '../base/context.dart';
import '../base/io.dart';
import '../base/logger.dart';
import '../base/platform.dart';
import '../base/user_messages.dart';
import '../base/version.dart';
import '../convert.dart';
import '../doctor_validator.dart';
import '../features.dart';
import 'android_sdk.dart';
import 'java.dart';
const int kAndroidSdkMinVersion = 29;
final Version kAndroidJavaMinVersion = Version(1, 8, 0);
final Version kAndroidSdkBuildToolsMinVersion = Version(28, 0, 3);
AndroidWorkflow? get androidWorkflow => context.get<AndroidWorkflow>();
AndroidValidator? get androidValidator => context.get<AndroidValidator>();
AndroidLicenseValidator? get androidLicenseValidator => context.get<AndroidLicenseValidator>();
enum LicensesAccepted {
none,
some,
all,
unknown,
}
final RegExp licenseCounts = RegExp(r'(\d+) of (\d+) SDK package licenses? not accepted.');
final RegExp licenseNotAccepted = RegExp(r'licenses? not accepted', caseSensitive: false);
final RegExp licenseAccepted = RegExp(r'All SDK package licenses accepted.');
class AndroidWorkflow implements Workflow {
AndroidWorkflow({
required AndroidSdk? androidSdk,
required FeatureFlags featureFlags,
}) : _androidSdk = androidSdk,
_featureFlags = featureFlags;
final AndroidSdk? _androidSdk;
final FeatureFlags _featureFlags;
@override
bool get appliesToHostPlatform => _featureFlags.isAndroidEnabled;
@override
bool get canListDevices => appliesToHostPlatform && _androidSdk != null
&& _androidSdk.adbPath != null;
@override
bool get canLaunchDevices => appliesToHostPlatform && _androidSdk != null
&& _androidSdk.adbPath != null
&& _androidSdk.validateSdkWellFormed().isEmpty;
@override
bool get canListEmulators => canListDevices && _androidSdk?.emulatorPath != null;
}
/// A validator that checks if the Android SDK and Java SDK are available and
/// installed correctly.
///
/// Android development requires the Android SDK, and at least one Java SDK. While
/// newer Java compilers can be used to compile the Java application code, the SDK
/// tools themselves required JDK 1.8. This older JDK is normally bundled with
/// Android Studio.
class AndroidValidator extends DoctorValidator {
AndroidValidator({
required Java? java,
required AndroidSdk? androidSdk,
required Logger logger,
required Platform platform,
required UserMessages userMessages,
}) : _java = java,
_androidSdk = androidSdk,
_logger = logger,
_platform = platform,
_userMessages = userMessages,
super('Android toolchain - develop for Android devices');
final Java? _java;
final AndroidSdk? _androidSdk;
final Logger _logger;
final Platform _platform;
final UserMessages _userMessages;
@override
String get slowWarning => '${_task ?? 'This'} is taking a long time...';
String? _task;
/// Returns false if we cannot determine the Java version or if the version
/// is older that the minimum allowed version of 1.8.
Future<bool> _checkJavaVersion(List<ValidationMessage> messages) async {
_task = 'Checking Java status';
try {
if (_java?.binaryPath == null) {
messages.add(ValidationMessage.error(_userMessages.androidMissingJdk));
return false;
}
messages.add(ValidationMessage(_userMessages.androidJdkLocation(_java!.binaryPath)));
if (!_java.canRun()) {
messages.add(ValidationMessage.error(_userMessages.androidCantRunJavaBinary(_java.binaryPath)));
return false;
}
Version? javaVersion;
try {
javaVersion = _java.version;
} on Exception catch (error) {
_logger.printTrace(error.toString());
}
if (javaVersion == null) {
// Could not determine the java version.
messages.add(ValidationMessage.error(_userMessages.androidUnknownJavaVersion));
return false;
}
if (javaVersion < kAndroidJavaMinVersion) {
messages.add(ValidationMessage.error(_userMessages.androidJavaMinimumVersion(javaVersion.toString())));
return false;
}
messages.add(ValidationMessage(_userMessages.androidJavaVersion(javaVersion.toString())));
return true;
} finally {
_task = null;
}
}
@override
Future<ValidationResult> validate() async {
final List<ValidationMessage> messages = <ValidationMessage>[];
final AndroidSdk? androidSdk = _androidSdk;
if (androidSdk == null) {
// No Android SDK found.
if (_platform.environment.containsKey(kAndroidHome)) {
final String androidHomeDir = _platform.environment[kAndroidHome]!;
messages.add(ValidationMessage.error(_userMessages.androidBadSdkDir(kAndroidHome, androidHomeDir)));
} else {
// Instruct user to set [kAndroidSdkRoot] and not deprecated [kAndroidHome]
// See https://github.com/flutter/flutter/issues/39301
messages.add(ValidationMessage.error(_userMessages.androidMissingSdkInstructions(_platform)));
}
return ValidationResult(ValidationType.missing, messages);
}
messages.add(ValidationMessage(_userMessages.androidSdkLocation(androidSdk.directory.path)));
_task = 'Validating Android SDK command line tools are available';
if (!androidSdk.cmdlineToolsAvailable) {
messages.add(ValidationMessage.error(_userMessages.androidMissingCmdTools));
return ValidationResult(ValidationType.missing, messages);
}
_task = 'Validating Android SDK licenses';
if (androidSdk.licensesAvailable && !androidSdk.platformToolsAvailable) {
messages.add(ValidationMessage.hint(_userMessages.androidSdkLicenseOnly(kAndroidHome)));
return ValidationResult(ValidationType.partial, messages);
}
String? sdkVersionText;
final AndroidSdkVersion? androidSdkLatestVersion = androidSdk.latestVersion;
if (androidSdkLatestVersion != null) {
if (androidSdkLatestVersion.sdkLevel < kAndroidSdkMinVersion || androidSdkLatestVersion.buildToolsVersion < kAndroidSdkBuildToolsMinVersion) {
messages.add(ValidationMessage.error(
_userMessages.androidSdkBuildToolsOutdated(
kAndroidSdkMinVersion,
kAndroidSdkBuildToolsMinVersion.toString(),
_platform,
)),
);
return ValidationResult(ValidationType.missing, messages);
}
sdkVersionText = _userMessages.androidStatusInfo(androidSdkLatestVersion.buildToolsVersionName);
messages.add(ValidationMessage(_userMessages.androidSdkPlatformToolsVersion(
androidSdkLatestVersion.platformName,
androidSdkLatestVersion.buildToolsVersionName)));
} else {
messages.add(ValidationMessage.error(_userMessages.androidMissingSdkInstructions(_platform)));
}
if (_platform.environment.containsKey(kAndroidHome)) {
final String androidHomeDir = _platform.environment[kAndroidHome]!;
messages.add(ValidationMessage('$kAndroidHome = $androidHomeDir'));
}
if (_platform.environment.containsKey(kAndroidSdkRoot)) {
final String androidSdkRoot = _platform.environment[kAndroidSdkRoot]!;
messages.add(ValidationMessage('$kAndroidSdkRoot = $androidSdkRoot'));
}
_task = 'Validating Android SDK';
final List<String> validationResult = androidSdk.validateSdkWellFormed();
if (validationResult.isNotEmpty) {
// Android SDK is not functional.
messages.addAll(validationResult.map<ValidationMessage>((String message) {
return ValidationMessage.error(message);
}));
messages.add(ValidationMessage(_userMessages.androidSdkInstallHelp(_platform)));
return ValidationResult(ValidationType.partial, messages, statusInfo: sdkVersionText);
}
_task = 'Finding Java binary';
// Check JDK version.
if (!await _checkJavaVersion(messages)) {
return ValidationResult(ValidationType.partial, messages, statusInfo: sdkVersionText);
}
// Success.
return ValidationResult(ValidationType.success, messages, statusInfo: sdkVersionText);
}
}
/// A subvalidator that checks if the licenses within the detected Android
/// SDK have been accepted.
class AndroidLicenseValidator extends DoctorValidator {
AndroidLicenseValidator({
required Java? java,
required AndroidSdk? androidSdk,
required Platform platform,
required ProcessManager processManager,
required Logger logger,
required Stdio stdio,
required UserMessages userMessages,
}) : _java = java,
_androidSdk = androidSdk,
_platform = platform,
_processManager = processManager,
_logger = logger,
_stdio = stdio,
_userMessages = userMessages,
super('Android license subvalidator');
final Java? _java;
final AndroidSdk? _androidSdk;
final Stdio _stdio;
final Platform _platform;
final ProcessManager _processManager;
final Logger _logger;
final UserMessages _userMessages;
@override
String get slowWarning => 'Checking Android licenses is taking an unexpectedly long time...';
@override
Future<ValidationResult> validate() async {
final List<ValidationMessage> messages = <ValidationMessage>[];
// Match pre-existing early termination behavior
if (_androidSdk == null || _androidSdk.latestVersion == null ||
_androidSdk.validateSdkWellFormed().isNotEmpty ||
! await _checkJavaVersionNoOutput()) {
return ValidationResult(ValidationType.missing, messages);
}
final String sdkVersionText = _userMessages.androidStatusInfo(_androidSdk.latestVersion!.buildToolsVersionName);
// Check for licenses.
switch (await licensesAccepted) {
case LicensesAccepted.all:
messages.add(ValidationMessage(_userMessages.androidLicensesAll));
case LicensesAccepted.some:
messages.add(ValidationMessage.hint(_userMessages.androidLicensesSome));
return ValidationResult(ValidationType.partial, messages, statusInfo: sdkVersionText);
case LicensesAccepted.none:
messages.add(ValidationMessage.error(_userMessages.androidLicensesNone));
return ValidationResult(ValidationType.partial, messages, statusInfo: sdkVersionText);
case LicensesAccepted.unknown:
messages.add(ValidationMessage.error(_userMessages.androidLicensesUnknown(_platform)));
return ValidationResult(ValidationType.partial, messages, statusInfo: sdkVersionText);
}
return ValidationResult(ValidationType.success, messages, statusInfo: sdkVersionText);
}
Future<bool> _checkJavaVersionNoOutput() async {
final String? javaBinary = _java?.binaryPath;
if (javaBinary == null) {
return false;
}
if (!_processManager.canRun(javaBinary)) {
return false;
}
String? javaVersion;
try {
final ProcessResult result = await _processManager.run(<String>[javaBinary, '-version']);
if (result.exitCode == 0) {
final List<String> versionLines = (result.stderr as String).split('\n');
javaVersion = versionLines.length >= 2 ? versionLines[1] : versionLines[0];
}
} on Exception catch (error) {
_logger.printTrace(error.toString());
}
if (javaVersion == null) {
// Could not determine the java version.
return false;
}
return true;
}
Future<LicensesAccepted> get licensesAccepted async {
LicensesAccepted? status;
void handleLine(String line) {
if (licenseCounts.hasMatch(line)) {
final Match? match = licenseCounts.firstMatch(line);
if (match?.group(1) != match?.group(2)) {
status = LicensesAccepted.some;
} else {
status = LicensesAccepted.none;
}
} else if (licenseNotAccepted.hasMatch(line)) {
// The licenseNotAccepted pattern is trying to match the same line as
// licenseCounts, but is more general. In case the format changes, a
// more general match may keep doctor mostly working.
status = LicensesAccepted.none;
} else if (licenseAccepted.hasMatch(line)) {
status ??= LicensesAccepted.all;
}
}
if (!_canRunSdkManager()) {
return LicensesAccepted.unknown;
}
try {
final Process process = await _processManager.start(
<String>[_androidSdk!.sdkManagerPath!, '--licenses'],
environment: _java?.environment,
);
process.stdin.write('n\n');
// We expect logcat streams to occasionally contain invalid utf-8,
// see: https://github.com/flutter/flutter/pull/8864.
final Future<void> output = process.stdout
.transform<String>(const Utf8Decoder(reportErrors: false))
.transform<String>(const LineSplitter())
.listen(handleLine)
.asFuture<void>();
final Future<void> errors = process.stderr
.transform<String>(const Utf8Decoder(reportErrors: false))
.transform<String>(const LineSplitter())
.listen(handleLine)
.asFuture<void>();
await Future.wait<void>(<Future<void>>[output, errors]);
return status ?? LicensesAccepted.unknown;
} on ProcessException catch (e) {
_logger.printTrace('Failed to run Android sdk manager: $e');
return LicensesAccepted.unknown;
}
}
/// Run the Android SDK manager tool in order to accept SDK licenses.
Future<bool> runLicenseManager() async {
if (_androidSdk == null) {
_logger.printStatus(_userMessages.androidSdkShort);
return false;
}
if (!_canRunSdkManager()) {
throwToolExit(
'Android sdkmanager not found. Update to the latest Android SDK and ensure that '
'the cmdline-tools are installed to resolve this.'
);
}
try {
final Process process = await _processManager.start(
<String>[_androidSdk.sdkManagerPath!, '--licenses'],
environment: _java?.environment,
);
// The real stdin will never finish streaming. Pipe until the child process
// finishes.
unawaited(process.stdin.addStream(_stdio.stdin)
// If the process exits unexpectedly with an error, that will be
// handled by the caller.
.then(
(Object? socket) => socket,
onError: (dynamic err, StackTrace stack) {
_logger.printTrace('Echoing stdin to the licenses subprocess failed:');
_logger.printTrace('$err\n$stack');
},
),
);
final List<String> stderrLines = <String>[];
// Wait for stdout and stderr to be fully processed, because process.exitCode
// may complete first.
try {
await Future.wait<void>(<Future<void>>[
_stdio.addStdoutStream(process.stdout),
process.stderr.forEach((List<int> event) {
_stdio.stderr.add(event);
stderrLines.add(utf8.decode(event));
}),
]);
} on Exception catch (err, stack) {
_logger.printTrace('Echoing stdout or stderr from the license subprocess failed:');
_logger.printTrace('$err\n$stack');
}
final int exitCode = await process.exitCode;
if (exitCode != 0) {
throwToolExit(_messageForSdkManagerError(stderrLines, exitCode));
}
return true;
} on ProcessException catch (e) {
throwToolExit(_userMessages.androidCannotRunSdkManager(
_androidSdk.sdkManagerPath ?? '',
e.toString(),
_platform,
));
}
}
bool _canRunSdkManager() {
final String? sdkManagerPath = _androidSdk?.sdkManagerPath;
if (sdkManagerPath == null) {
return false;
}
return _processManager.canRun(sdkManagerPath);
}
String _messageForSdkManagerError(
List<String> androidSdkStderr,
int exitCode,
) {
final String sdkManagerPath = _androidSdk!.sdkManagerPath!;
final bool failedDueToJdkIncompatibility = androidSdkStderr.join().contains(
RegExp(r'java\.lang\.UnsupportedClassVersionError.*SdkManagerCli '
r'has been compiled by a more recent version of the Java Runtime'));
if (failedDueToJdkIncompatibility) {
return 'Android sdkmanager tool was found, but failed to run ($sdkManagerPath): "exited code $exitCode".\n'
'It appears the version of the Java binary used (${_java!.binaryPath}) is '
'too out-of-date and is incompatible with the Android sdkmanager tool.\n'
'If the Java binary came bundled with Android Studio, consider updating '
'your installation of Android studio. Alternatively, you can uninstall '
'the Android SDK command-line tools and install an earlier version. ';
}
return _userMessages.androidCannotRunSdkManager(
sdkManagerPath,
'exited code $exitCode',
_platform,
);
}
}
| flutter/packages/flutter_tools/lib/src/android/android_workflow.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/android/android_workflow.dart",
"repo_id": "flutter",
"token_count": 6047
} | 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:archive/archive.dart';
import 'package:archive/archive_io.dart';
import 'package:meta/meta.dart';
import 'package:unified_analytics/unified_analytics.dart';
import 'package:vm_snapshot_analysis/treemap.dart';
import '../convert.dart';
import '../reporting/reporting.dart';
import 'common.dart';
import 'file_system.dart';
import 'logger.dart';
import 'terminal.dart';
/// A class to analyze APK and AOT snapshot and generate a breakdown of the data.
class SizeAnalyzer {
SizeAnalyzer({
required FileSystem fileSystem,
required Logger logger,
required Usage flutterUsage,
required Analytics analytics,
Pattern appFilenamePattern = 'libapp.so',
}) : _flutterUsage = flutterUsage,
_analytics = analytics,
_fileSystem = fileSystem,
_logger = logger,
_appFilenamePattern = appFilenamePattern;
final FileSystem _fileSystem;
final Logger _logger;
final Pattern _appFilenamePattern;
final Usage _flutterUsage;
final Analytics _analytics;
String? _appFilename;
static const String aotSnapshotFileName = 'aot-snapshot.json';
static const int tableWidth = 80;
static const int _kAotSizeMaxDepth = 2;
static const int _kZipSizeMaxDepth = 1;
/// Analyze the [aotSnapshot] in an uncompressed output directory.
Future<Map<String, Object?>> analyzeAotSnapshot({
required Directory outputDirectory,
required File aotSnapshot,
required File precompilerTrace,
required String type,
String? excludePath,
}) async {
_logger.printStatus('▒' * tableWidth);
_logger.printStatus('━' * tableWidth);
final _SymbolNode aotAnalysisJson = _parseDirectory(
outputDirectory,
outputDirectory.parent.path,
excludePath,
);
// Convert an AOT snapshot file into a map.
final Object? decodedAotSnapshot = json.decode(aotSnapshot.readAsStringSync());
if (decodedAotSnapshot == null) {
throwToolExit('AOT snapshot is invalid for analysis');
}
final Map<String, Object?> processedAotSnapshotJson = treemapFromJson(decodedAotSnapshot);
final _SymbolNode? aotSnapshotJsonRoot = _parseAotSnapshot(processedAotSnapshotJson);
for (final _SymbolNode firstLevelPath in aotAnalysisJson.children) {
_printEntitySize(
firstLevelPath.name,
byteSize: firstLevelPath.byteSize,
level: 1,
);
// Print the expansion of lib directory to show more info for `appFilename`.
if (firstLevelPath.name == _fileSystem.path.basename(outputDirectory.path) && aotSnapshotJsonRoot != null) {
_printLibChildrenPaths(firstLevelPath, '', aotSnapshotJsonRoot, _kAotSizeMaxDepth, 0);
}
}
_logger.printStatus('▒' * tableWidth);
Map<String, Object?> apkAnalysisJson = aotAnalysisJson.toJson();
apkAnalysisJson['type'] = type; // one of apk, aab, ios, macos, windows, or linux.
apkAnalysisJson = _addAotSnapshotDataToAnalysis(
apkAnalysisJson: apkAnalysisJson,
path: _locatedAotFilePath,
aotSnapshotJson: processedAotSnapshotJson,
precompilerTrace: json.decode(precompilerTrace.readAsStringSync()) as Map<String, Object?>? ?? <String, Object?>{},
);
assert(_appFilename != null);
CodeSizeEvent(type, flutterUsage: _flutterUsage).send();
_analytics.send(Event.codeSizeAnalysis(platform: type));
return apkAnalysisJson;
}
/// Analyzes [apk] and [aotSnapshot] to output a [Map] object that includes
/// the breakdown of the both files, where the breakdown of [aotSnapshot] is placed
/// under 'lib/arm64-v8a/$_appFilename'.
///
/// [kind] must be one of 'apk' or 'aab'.
/// The [aotSnapshot] can be either instruction sizes snapshot or a v8 snapshot.
Future<Map<String, Object?>> analyzeZipSizeAndAotSnapshot({
required File zipFile,
required File aotSnapshot,
required File precompilerTrace,
required String kind,
}) async {
assert(kind == 'apk' || kind == 'aab');
_logger.printStatus('▒' * tableWidth);
_printEntitySize(
'${zipFile.basename} (total compressed)',
byteSize: zipFile.lengthSync(),
level: 0,
showColor: false,
);
_logger.printStatus('━' * tableWidth);
final _SymbolNode apkAnalysisRoot = _parseUnzipFile(zipFile);
// Convert an AOT snapshot file into a map.
final Object? decodedAotSnapshot = json.decode(aotSnapshot.readAsStringSync());
if (decodedAotSnapshot == null) {
throwToolExit('AOT snapshot is invalid for analysis');
}
final Map<String, Object?> processedAotSnapshotJson = treemapFromJson(decodedAotSnapshot);
final _SymbolNode? aotSnapshotJsonRoot = _parseAotSnapshot(processedAotSnapshotJson);
if (aotSnapshotJsonRoot != null) {
for (final _SymbolNode firstLevelPath in apkAnalysisRoot.children) {
_printLibChildrenPaths(firstLevelPath, '', aotSnapshotJsonRoot, _kZipSizeMaxDepth, 0);
}
}
_logger.printStatus('▒' * tableWidth);
Map<String, Object?> apkAnalysisJson = apkAnalysisRoot.toJson();
apkAnalysisJson['type'] = kind;
assert(_appFilename != null);
apkAnalysisJson = _addAotSnapshotDataToAnalysis(
apkAnalysisJson: apkAnalysisJson,
path: _locatedAotFilePath,
aotSnapshotJson: processedAotSnapshotJson,
precompilerTrace: json.decode(precompilerTrace.readAsStringSync()) as Map<String, Object?>? ?? <String, Object?>{},
);
CodeSizeEvent(kind, flutterUsage: _flutterUsage).send();
_analytics.send(Event.codeSizeAnalysis(platform: kind));
return apkAnalysisJson;
}
_SymbolNode _parseUnzipFile(File zipFile) {
final Archive archive = ZipDecoder().decodeBytes(zipFile.readAsBytesSync());
final Map<List<String>, int> pathsToSize = <List<String>, int>{};
for (final ArchiveFile archiveFile in archive.files) {
final InputStreamBase? rawContent = archiveFile.rawContent;
if (rawContent != null) {
pathsToSize[_fileSystem.path.split(archiveFile.name)] = rawContent.length;
}
}
return _buildSymbolTree(pathsToSize);
}
_SymbolNode _parseDirectory(Directory directory, String relativeTo, String? excludePath) {
final Map<List<String>, int> pathsToSize = <List<String>, int>{};
for (final File file in directory.listSync(recursive: true).whereType<File>()) {
if (excludePath != null && file.uri.pathSegments.contains(excludePath)) {
continue;
}
final List<String> path = _fileSystem.path.split(
_fileSystem.path.relative(file.path, from: relativeTo));
pathsToSize[path] = file.lengthSync();
}
return _buildSymbolTree(pathsToSize);
}
List<String> _locatedAotFilePath = <String>[];
List<String> _buildNodeName(_SymbolNode start, _SymbolNode? parent) {
final List<String> results = <String>[start.name];
while (parent != null && parent.name != 'Root') {
results.insert(0, parent.name);
parent = parent.parent;
}
return results;
}
_SymbolNode _buildSymbolTree(Map<List<String>, int> pathsToSize) {
final _SymbolNode rootNode = _SymbolNode('Root');
_SymbolNode currentNode = rootNode;
for (final List<String> paths in pathsToSize.keys) {
for (final String path in paths) {
_SymbolNode? childWithPathAsName = currentNode.childByName(path);
if (childWithPathAsName == null) {
childWithPathAsName = _SymbolNode(path);
if (matchesPattern(path, pattern: _appFilenamePattern) != null) {
_appFilename = path;
childWithPathAsName.name += ' (Dart AOT)';
_locatedAotFilePath = _buildNodeName(childWithPathAsName, currentNode);
} else if (path == 'libflutter.so') {
childWithPathAsName.name += ' (Flutter Engine)';
}
currentNode.addChild(childWithPathAsName);
}
childWithPathAsName.addSize(pathsToSize[paths] ?? 0);
currentNode = childWithPathAsName;
}
currentNode = rootNode;
}
return rootNode;
}
/// Prints all children paths for the lib/ directory in an APK.
///
/// A brief summary of aot snapshot is printed under 'lib/arm64-v8a/$_appFilename'.
void _printLibChildrenPaths(
_SymbolNode currentNode,
String totalPath,
_SymbolNode aotSnapshotJsonRoot,
int maxDepth,
int currentDepth,
) {
totalPath += currentNode.name;
assert(_appFilename != null);
if (currentNode.children.isNotEmpty
&& currentNode.name != '$_appFilename (Dart AOT)'
&& currentDepth < maxDepth
&& currentNode.byteSize >= 1000) {
for (final _SymbolNode child in currentNode.children) {
_printLibChildrenPaths(child, '$totalPath/', aotSnapshotJsonRoot, maxDepth, currentDepth + 1);
}
_leadingPaths = totalPath.split('/')
..removeLast();
} else {
// Print total path and size if currentNode does not have any children and is
// larger than 1KB
final bool isAotSnapshotPath = _locatedAotFilePath.join('/').contains(totalPath);
if (currentNode.byteSize >= 1000 || isAotSnapshotPath) {
_printEntitySize(totalPath, byteSize: currentNode.byteSize, level: 1, emphasis: currentNode.children.isNotEmpty);
if (isAotSnapshotPath) {
_printAotSnapshotSummary(aotSnapshotJsonRoot, level: totalPath.split('/').length);
}
_leadingPaths = totalPath.split('/')
..removeLast();
}
}
}
/// Go through the AOT gen snapshot size JSON and print out a collapsed summary
/// for the first package level.
void _printAotSnapshotSummary(_SymbolNode aotSnapshotRoot, {int maxDirectoriesShown = 20, required int level}) {
_printEntitySize(
'Dart AOT symbols accounted decompressed size',
byteSize: aotSnapshotRoot.byteSize,
level: level,
emphasis: true,
);
final List<_SymbolNode> sortedSymbols = aotSnapshotRoot.children.toList()
// Remove entries like @unknown, @shared, and @stubs as well as private dart libraries
// which are not interpretable by end users.
..removeWhere((_SymbolNode node) => node.name.startsWith('@') || node.name.startsWith('dart:_'))
..sort((_SymbolNode a, _SymbolNode b) => b.byteSize.compareTo(a.byteSize));
for (final _SymbolNode node in sortedSymbols.take(maxDirectoriesShown)) {
// Node names will have an extra leading `package:*` name, remove it to
// avoid extra nesting.
_printEntitySize(_formatExtraLeadingPackages(node.name), byteSize: node.byteSize, level: level + 1);
}
}
String _formatExtraLeadingPackages(String name) {
if (!name.startsWith('package')) {
return name;
}
final List<String> chunks = name.split('/');
if (chunks.length < 2) {
return name;
}
chunks.removeAt(0);
return chunks.join('/');
}
/// Adds breakdown of aot snapshot data as the children of the node at the given path.
Map<String, Object?> _addAotSnapshotDataToAnalysis({
required Map<String, Object?> apkAnalysisJson,
required List<String> path,
required Map<String, Object?> aotSnapshotJson,
required Map<String, Object?> precompilerTrace,
}) {
Map<String, Object?> currentLevel = apkAnalysisJson;
currentLevel['precompiler-trace'] = precompilerTrace;
while (path.isNotEmpty) {
final List<Map<String, Object?>>? children = currentLevel['children'] as List<Map<String, Object?>>?;
final Map<String, Object?> childWithPathAsName = children?.firstWhere(
(Map<String, Object?> child) => (child['n'] as String?) == path.first,
) ?? <String, Object?>{};
path.removeAt(0);
currentLevel = childWithPathAsName;
}
currentLevel['children'] = aotSnapshotJson['children'];
return apkAnalysisJson;
}
List<String> _leadingPaths = <String>[];
/// Print an entity's name with its size on the same line.
void _printEntitySize(
String entityName, {
required int byteSize,
required int level,
bool showColor = true,
bool emphasis = false,
}) {
final String formattedSize = _prettyPrintBytes(byteSize);
TerminalColor color = TerminalColor.green;
if (formattedSize.endsWith('MB')) {
color = TerminalColor.cyan;
} else if (formattedSize.endsWith('KB')) {
color = TerminalColor.yellow;
}
// Compute any preceding directories, and compare this to the stored
// directories (in _leadingPaths) for the last entity that was printed. The
// similarly determines whether or not leading directory information needs to
// be printed.
final List<String> localSegments = entityName.split('/')
..removeLast();
int i = 0;
while (i < _leadingPaths.length && i < localSegments.length && _leadingPaths[i] == localSegments[i]) {
i += 1;
}
for (; i < localSegments.length; i += 1) {
_logger.printStatus(
'${localSegments[i]}/',
indent: (level + i) * 2,
emphasis: true,
);
}
_leadingPaths = localSegments;
final String baseName = _fileSystem.path.basename(entityName);
final int spaceInBetween = tableWidth - (level + i) * 2 - baseName.length - formattedSize.length;
_logger.printStatus(
baseName + ' ' * spaceInBetween,
newline: false,
emphasis: emphasis,
indent: (level + i) * 2,
);
_logger.printStatus(formattedSize, color: showColor ? color : null);
}
String _prettyPrintBytes(int numBytes) {
const int kB = 1024;
const int mB = kB * 1024;
if (numBytes < kB) {
return '$numBytes B';
} else if (numBytes < mB) {
return '${(numBytes / kB).round()} KB';
} else {
return '${(numBytes / mB).round()} MB';
}
}
_SymbolNode? _parseAotSnapshot(Map<String, Object?> aotSnapshotJson) {
final bool isLeafNode = aotSnapshotJson['children'] == null;
if (!isLeafNode) {
return _buildNodeWithChildren(aotSnapshotJson);
} else {
// TODO(peterdjlee): Investigate why there are leaf nodes with size of null.
final int? byteSize = aotSnapshotJson['value'] as int?;
if (byteSize == null) {
return null;
}
return _buildNode(aotSnapshotJson, byteSize);
}
}
_SymbolNode _buildNode(
Map<String, Object?> aotSnapshotJson,
int byteSize, {
List<_SymbolNode> children = const <_SymbolNode>[],
}) {
final String name = aotSnapshotJson['n']! as String;
final Map<String, _SymbolNode> childrenMap = <String, _SymbolNode>{};
for (final _SymbolNode child in children) {
childrenMap[child.name] = child;
}
return _SymbolNode(
name,
byteSize: byteSize,
)..addAllChildren(children);
}
/// Builds a node by recursively building all of its children first
/// in order to calculate the sum of its children's sizes.
_SymbolNode? _buildNodeWithChildren(Map<String, Object?> aotSnapshotJson) {
final List<Object?> rawChildren = aotSnapshotJson['children'] as List<Object?>? ?? <Object?>[];
final List<_SymbolNode> symbolNodeChildren = <_SymbolNode>[];
int totalByteSize = 0;
// Given a child, build its subtree.
for (final Object? child in rawChildren) {
if (child == null) {
continue;
}
final _SymbolNode? childTreemapNode = _parseAotSnapshot(child as Map<String, Object?>);
if (childTreemapNode != null) {
symbolNodeChildren.add(childTreemapNode);
totalByteSize += childTreemapNode.byteSize;
}
}
// If none of the children matched the diff tree type
if (totalByteSize == 0) {
return null;
} else {
return _buildNode(
aotSnapshotJson,
totalByteSize,
children: symbolNodeChildren,
);
}
}
}
/// A node class that represents a single symbol for AOT size snapshots.
class _SymbolNode {
_SymbolNode(
this.name, {
this.byteSize = 0,
}) : _children = <String, _SymbolNode>{};
/// The human friendly identifier for this node.
String name;
int byteSize;
void addSize(int sizeToBeAdded) {
byteSize += sizeToBeAdded;
}
_SymbolNode? get parent => _parent;
_SymbolNode? _parent;
Iterable<_SymbolNode> get children => _children.values;
final Map<String, _SymbolNode> _children;
_SymbolNode? childByName(String name) => _children[name];
_SymbolNode addChild(_SymbolNode child) {
assert(child.parent == null);
assert(!_children.containsKey(child.name),
'Cannot add duplicate child key ${child.name}');
child._parent = this;
_children[child.name] = child;
return child;
}
void addAllChildren(List<_SymbolNode> children) {
children.forEach(addChild);
}
Map<String, Object?> toJson() {
final Map<String, Object?> json = <String, Object?>{
'n': name,
'value': byteSize,
};
final List<Map<String, Object?>> childrenAsJson = <Map<String, Object?>>[];
for (final _SymbolNode child in children) {
childrenAsJson.add(child.toJson());
}
if (childrenAsJson.isNotEmpty) {
json['children'] = childrenAsJson;
}
return json;
}
}
/// Matches `pattern` against the entirety of `string`.
@visibleForTesting
Match? matchesPattern(String string, {required Pattern pattern}) {
final Match? match = pattern.matchAsPrefix(string);
return (match != null && match.end == string.length) ? match : null;
}
| flutter/packages/flutter_tools/lib/src/base/analyze_size.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/base/analyze_size.dart",
"repo_id": "flutter",
"token_count": 6518
} | 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 'dart:async';
import 'package:meta/meta.dart';
import '../convert.dart';
import 'common.dart';
import 'file_system.dart';
import 'io.dart';
import 'logger.dart';
import 'platform.dart';
const int kNetworkProblemExitCode = 50;
const String kFlutterStorageBaseUrl = 'FLUTTER_STORAGE_BASE_URL';
typedef HttpClientFactory = HttpClient Function();
typedef UrlTunneller = Future<String> Function(String url);
/// If [httpClientFactory] is null, a default [HttpClient] is used.
class Net {
Net({
HttpClientFactory? httpClientFactory,
required Logger logger,
required Platform platform,
}) :
_httpClientFactory = httpClientFactory ?? (() => HttpClient()),
_logger = logger,
_platform = platform;
final HttpClientFactory _httpClientFactory;
final Logger _logger;
final Platform _platform;
/// Download a file from the given URL.
///
/// If a destination file is not provided, returns the bytes.
///
/// If a destination file is provided, streams the bytes to that file and
/// returns an empty list.
///
/// If [maxAttempts] is exceeded, returns null.
Future<List<int>?> fetchUrl(Uri url, {
int? maxAttempts,
File? destFile,
@visibleForTesting Duration? durationOverride,
}) async {
int attempts = 0;
int durationSeconds = 1;
while (true) {
attempts += 1;
_MemoryIOSink? memorySink;
IOSink sink;
if (destFile == null) {
memorySink = _MemoryIOSink();
sink = memorySink;
} else {
sink = destFile.openWrite();
}
final bool result = await _attempt(
url,
destSink: sink,
);
if (result) {
return memorySink?.writes.takeBytes() ?? <int>[];
}
if (maxAttempts != null && attempts >= maxAttempts) {
_logger.printStatus('Download failed -- retry $attempts');
return null;
}
_logger.printStatus(
'Download failed -- attempting retry $attempts in '
'$durationSeconds second${ durationSeconds == 1 ? "" : "s"}...',
);
await Future<void>.delayed(durationOverride ?? Duration(seconds: durationSeconds));
if (durationSeconds < 64) {
durationSeconds *= 2;
}
}
}
/// Check if the given URL points to a valid endpoint.
Future<bool> doesRemoteFileExist(Uri url) => _attempt(url, onlyHeaders: true);
// Returns true on success and false on failure.
Future<bool> _attempt(Uri url, {
IOSink? destSink,
bool onlyHeaders = false,
}) async {
assert(onlyHeaders || destSink != null);
_logger.printTrace('Downloading: $url');
final HttpClient httpClient = _httpClientFactory();
HttpClientRequest request;
HttpClientResponse? response;
try {
if (onlyHeaders) {
request = await httpClient.headUrl(url);
} else {
request = await httpClient.getUrl(url);
}
response = await request.close();
} on ArgumentError catch (error) {
final String? overrideUrl = _platform.environment[kFlutterStorageBaseUrl];
if (overrideUrl != null && url.toString().contains(overrideUrl)) {
_logger.printError(error.toString());
throwToolExit(
'The value of $kFlutterStorageBaseUrl ($overrideUrl) could not be '
'parsed as a valid url. Please see https://flutter.dev/community/china '
'for an example of how to use it.\n'
'Full URL: $url',
exitCode: kNetworkProblemExitCode,
);
}
_logger.printError(error.toString());
rethrow;
} on HandshakeException catch (error) {
_logger.printTrace(error.toString());
throwToolExit(
'Could not authenticate download server. You may be experiencing a man-in-the-middle attack,\n'
'your network may be compromised, or you may have malware installed on your computer.\n'
'URL: $url',
exitCode: kNetworkProblemExitCode,
);
} on SocketException catch (error) {
_logger.printTrace('Download error: $error');
return false;
} on HttpException catch (error) {
_logger.printTrace('Download error: $error');
return false;
}
// If we're making a HEAD request, we're only checking to see if the URL is
// valid.
if (onlyHeaders) {
return response.statusCode == HttpStatus.ok;
}
if (response.statusCode != HttpStatus.ok) {
if (response.statusCode > 0 && response.statusCode < 500) {
throwToolExit(
'Download failed.\n'
'URL: $url\n'
'Error: ${response.statusCode} ${response.reasonPhrase}',
exitCode: kNetworkProblemExitCode,
);
}
// 5xx errors are server errors and we can try again
_logger.printTrace('Download error: ${response.statusCode} ${response.reasonPhrase}');
return false;
}
_logger.printTrace('Received response from server, collecting bytes...');
try {
assert(destSink != null);
await response.forEach(destSink!.add);
return true;
} on IOException catch (error) {
_logger.printTrace('Download error: $error');
return false;
} finally {
await destSink?.flush();
await destSink?.close();
}
}
}
/// An IOSink that collects whatever is written to it.
class _MemoryIOSink implements IOSink {
@override
Encoding encoding = utf8;
final BytesBuilder writes = BytesBuilder(copy: false);
@override
void add(List<int> data) {
writes.add(data);
}
@override
Future<void> addStream(Stream<List<int>> stream) {
final Completer<void> completer = Completer<void>();
stream.listen(add).onDone(completer.complete);
return completer.future;
}
@override
void writeCharCode(int charCode) {
add(<int>[charCode]);
}
@override
void write(Object? obj) {
add(encoding.encode('$obj'));
}
@override
void writeln([ Object? obj = '' ]) {
add(encoding.encode('$obj\n'));
}
@override
void writeAll(Iterable<dynamic> objects, [ String separator = '' ]) {
bool addSeparator = false;
for (final dynamic object in objects) {
if (addSeparator) {
write(separator);
}
write(object);
addSeparator = true;
}
}
@override
void addError(dynamic error, [ StackTrace? stackTrace ]) {
throw UnimplementedError();
}
@override
Future<void> get done => close();
@override
Future<void> close() async { }
@override
Future<void> flush() async { }
}
/// Returns [true] if [address] is an IPv6 address.
bool isIPv6Address(String address) {
try {
Uri.parseIPv6Address(address);
return true;
} on FormatException {
return false;
}
}
| flutter/packages/flutter_tools/lib/src/base/net.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/base/net.dart",
"repo_id": "flutter",
"token_count": 2613
} | 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 '../base/file_system.dart';
import '../web/compiler_config.dart';
import './build_system.dart';
/// Commonly used build [Target]s.
abstract class BuildTargets {
const BuildTargets();
Target get copyFlutterBundle;
Target get releaseCopyFlutterBundle;
Target get generateLocalizationsTarget;
Target get dartPluginRegistrantTarget;
Target webServiceWorker(FileSystem fileSystem, List<WebCompilerConfig> compileConfigs);
}
/// BuildTargets that return NoOpTarget for every action.
class NoOpBuildTargets extends BuildTargets {
const NoOpBuildTargets();
@override
Target get copyFlutterBundle => const _NoOpTarget();
@override
Target get releaseCopyFlutterBundle => const _NoOpTarget();
@override
Target get generateLocalizationsTarget => const _NoOpTarget();
@override
Target get dartPluginRegistrantTarget => const _NoOpTarget();
@override
Target webServiceWorker(FileSystem fileSystem, List<WebCompilerConfig> compileConfigs) => const _NoOpTarget();
}
/// A [Target] that does nothing.
class _NoOpTarget extends Target {
const _NoOpTarget();
@override
String get name => 'no_op';
@override
List<Source> get inputs => const <Source>[];
@override
List<Source> get outputs => const <Source>[];
@override
List<Target> get dependencies => const <Target>[];
@override
Future<void> build(Environment environment) async {}
}
| flutter/packages/flutter_tools/lib/src/build_system/build_targets.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/build_system/build_targets.dart",
"repo_id": "flutter",
"token_count": 460
} | 770 |
// 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 '../../artifacts.dart';
import '../../base/build.dart';
import '../../base/file_system.dart';
import '../../base/io.dart';
import '../../base/process.dart';
import '../../build_info.dart';
import '../../globals.dart' as globals show xcode;
import '../../reporting/reporting.dart';
import '../build_system.dart';
import '../depfile.dart';
import '../exceptions.dart';
import 'assets.dart';
import 'common.dart';
import 'icon_tree_shaker.dart';
/// Copy the macOS 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.
///
/// The real implementations are:
/// * [DebugUnpackMacOS]
/// * [ProfileUnpackMacOS]
/// * [ReleaseUnpackMacOS]
abstract class UnpackMacOS extends Target {
const UnpackMacOS();
@override
List<Source> get inputs => const <Source>[
Source.pattern('{FLUTTER_ROOT}/packages/flutter_tools/lib/src/build_system/targets/macos.dart'),
];
@override
List<Source> get outputs => const <Source>[
Source.pattern('{OUTPUT_DIR}/FlutterMacOS.framework/Versions/A/FlutterMacOS'),
];
@override
List<Target> get dependencies => <Target>[];
@override
Future<void> build(Environment environment) async {
final String? buildModeEnvironment = environment.defines[kBuildMode];
if (buildModeEnvironment == null) {
throw MissingDefineException(kBuildMode, 'unpack_macos');
}
final BuildMode buildMode = BuildMode.fromCliName(buildModeEnvironment);
final String basePath = environment.artifacts.getArtifactPath(Artifact.flutterMacOSFramework, mode: buildMode);
final ProcessResult result = environment.processManager.runSync(<String>[
'rsync',
'-av',
'--delete',
'--filter',
'- .DS_Store/',
basePath,
environment.outputDir.path,
]);
_removeDenylistedFiles(environment.outputDir);
if (result.exitCode != 0) {
throw Exception(
'Failed to copy framework (exit ${result.exitCode}:\n'
'${result.stdout}\n---\n${result.stderr}',
);
}
final File frameworkBinary = environment.outputDir
.childDirectory('FlutterMacOS.framework')
.childDirectory('Versions')
.childDirectory('A')
.childFile('FlutterMacOS');
final String frameworkBinaryPath = frameworkBinary.path;
if (!frameworkBinary.existsSync()) {
throw Exception('Binary $frameworkBinaryPath does not exist, cannot thin');
}
await _thinFramework(environment, frameworkBinaryPath);
}
static const List<String> _copyDenylist = <String>['entitlements.txt', 'without_entitlements.txt'];
void _removeDenylistedFiles(Directory directory) {
for (final FileSystemEntity entity in directory.listSync(recursive: true)) {
if (entity is! File) {
continue;
}
if (_copyDenylist.contains(entity.basename)) {
entity.deleteSync();
}
}
}
Future<void> _thinFramework(
Environment environment,
String frameworkBinaryPath,
) async {
final String archs = environment.defines[kDarwinArchs] ?? 'x86_64 arm64';
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 = environment.processManager.runSync(<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 ReleaseUnpackMacOS extends UnpackMacOS {
const ReleaseUnpackMacOS();
@override
String get name => 'release_unpack_macos';
@override
List<Source> get inputs => <Source>[
...super.inputs,
const Source.artifact(Artifact.flutterMacOSXcframework, mode: BuildMode.release),
];
}
/// Unpack the profile prebuilt engine framework.
class ProfileUnpackMacOS extends UnpackMacOS {
const ProfileUnpackMacOS();
@override
String get name => 'profile_unpack_macos';
@override
List<Source> get inputs => <Source>[
...super.inputs,
const Source.artifact(Artifact.flutterMacOSXcframework, mode: BuildMode.profile),
];
}
/// Unpack the debug prebuilt engine framework.
class DebugUnpackMacOS extends UnpackMacOS {
const DebugUnpackMacOS();
@override
String get name => 'debug_unpack_macos';
@override
List<Source> get inputs => <Source>[
...super.inputs,
const Source.artifact(Artifact.flutterMacOSXcframework, mode: BuildMode.debug),
];
}
/// Create an App.framework for debug macOS 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.
class DebugMacOSFramework extends Target {
const DebugMacOSFramework();
@override
String get name => 'debug_macos_framework';
@override
Future<void> build(Environment environment) async {
final File outputFile = environment.fileSystem.file(environment.fileSystem.path.join(
environment.buildDir.path, 'App.framework', 'App'));
final Iterable<DarwinArch> darwinArchs = environment.defines[kDarwinArchs]
?.split(' ')
.map(getDarwinArchForName)
?? <DarwinArch>[DarwinArch.x86_64, DarwinArch.arm64];
final Iterable<String> darwinArchArguments =
darwinArchs.expand((DarwinArch arch) => <String>['-arch', arch.name]);
outputFile.createSync(recursive: true);
final File debugApp = environment.buildDir.childFile('debug_app.cc')
..writeAsStringSync(r'''
static const int Moo = 88;
''');
final RunResult result = await globals.xcode!.clang(<String>[
'-x',
'c',
debugApp.path,
...darwinArchArguments,
'-dynamiclib',
'-Xlinker', '-rpath', '-Xlinker', '@executable_path/Frameworks',
'-Xlinker', '-rpath', '-Xlinker', '@loader_path/Frameworks',
'-fapplication-extension',
'-install_name', '@rpath/App.framework/App',
'-o', outputFile.path,
]);
if (result.exitCode != 0) {
throw Exception('Failed to compile debug App.framework');
}
}
@override
List<Target> get dependencies => const <Target>[];
@override
List<Source> get inputs => const <Source>[
Source.pattern('{FLUTTER_ROOT}/packages/flutter_tools/lib/src/build_system/targets/macos.dart'),
];
@override
List<Source> get outputs => const <Source>[
Source.pattern('{BUILD_DIR}/App.framework/App'),
];
}
class CompileMacOSFramework extends Target {
const CompileMacOSFramework();
@override
String get name => 'compile_macos_framework';
@override
Future<void> build(Environment environment) async {
final String? buildModeEnvironment = environment.defines[kBuildMode];
if (buildModeEnvironment == null) {
throw MissingDefineException(kBuildMode, 'compile_macos_framework');
}
final String? targetPlatformEnvironment = environment.defines[kTargetPlatform];
if (targetPlatformEnvironment == null) {
throw MissingDefineException(kTargetPlatform, 'kernel_snapshot');
}
final BuildMode buildMode = BuildMode.fromCliName(buildModeEnvironment);
if (buildMode == BuildMode.debug) {
throw Exception('precompiled macOS framework only supported in release/profile builds.');
}
final String buildOutputPath = environment.buildDir.path;
final String? codeSizeDirectory = environment.defines[kCodeSizeDirectory];
final String? splitDebugInfo = environment.defines[kSplitDebugInfo];
final bool dartObfuscation = environment.defines[kDartObfuscation] == 'true';
final List<String> extraGenSnapshotOptions = decodeCommaSeparated(environment.defines, kExtraGenSnapshotOptions);
final TargetPlatform targetPlatform = getTargetPlatformForName(targetPlatformEnvironment);
final List<DarwinArch> darwinArchs = environment.defines[kDarwinArchs]
?.split(' ')
.map(getDarwinArchForName)
.toList()
?? <DarwinArch>[DarwinArch.x86_64, DarwinArch.arm64];
if (targetPlatform != TargetPlatform.darwin) {
throw Exception('compile_macos_framework is only supported for darwin TargetPlatform.');
}
final AOTSnapshotter snapshotter = AOTSnapshotter(
fileSystem: environment.fileSystem,
logger: environment.logger,
xcode: globals.xcode!,
artifacts: environment.artifacts,
processManager: environment.processManager
);
final List<Future<int>> pending = <Future<int>>[];
for (final DarwinArch darwinArch in darwinArchs) {
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');
extraGenSnapshotOptions.add('--write-v8-snapshot-profile-to=${codeSizeFile.path}');
extraGenSnapshotOptions.add('--trace-precompiler-to=${precompilerTraceFile.path}');
}
pending.add(snapshotter.build(
buildMode: buildMode,
mainPath: environment.buildDir.childFile('app.dill').path,
outputPath: environment.fileSystem.path.join(buildOutputPath, darwinArch.name),
platform: TargetPlatform.darwin,
darwinArch: darwinArch,
splitDebugInfo: splitDebugInfo,
dartObfuscation: dartObfuscation,
extraGenSnapshotOptions: extraGenSnapshotOptions,
));
}
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,
);
}
@override
List<Target> get dependencies => const <Target>[
KernelSnapshot(),
];
@override
List<Source> get inputs => const <Source>[
Source.pattern('{BUILD_DIR}/app.dill'),
Source.pattern('{FLUTTER_ROOT}/packages/flutter_tools/lib/src/build_system/targets/macos.dart'),
Source.artifact(Artifact.genSnapshot, mode: BuildMode.release, platform: TargetPlatform.darwin),
];
@override
List<Source> get outputs => const <Source>[
Source.pattern('{BUILD_DIR}/App.framework/App'),
Source.pattern('{BUILD_DIR}/App.framework.dSYM/Contents/Resources/DWARF/App'),
];
}
/// Bundle the flutter assets into the App.framework.
///
/// In debug mode, also include the app.dill and precompiled runtimes.
///
/// See https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/BPFrameworks/Concepts/FrameworkAnatomy.html
/// for more information on Framework structure.
abstract class MacOSBundleFlutterAssets extends Target {
const MacOSBundleFlutterAssets();
@override
List<Source> get inputs => const <Source>[
Source.pattern('{BUILD_DIR}/App.framework/App'),
...IconTreeShaker.inputs,
];
@override
List<Source> get outputs => const <Source>[
Source.pattern('{OUTPUT_DIR}/App.framework/Versions/A/App'),
Source.pattern('{OUTPUT_DIR}/App.framework/Versions/A/Resources/Info.plist'),
];
@override
List<String> get depfiles => const <String>[
'flutter_assets.d',
];
@override
Future<void> build(Environment environment) async {
final String? buildModeEnvironment = environment.defines[kBuildMode];
if (buildModeEnvironment == null) {
throw MissingDefineException(kBuildMode, 'compile_macos_framework');
}
final BuildMode buildMode = BuildMode.fromCliName(buildModeEnvironment);
final Directory frameworkRootDirectory = environment
.outputDir
.childDirectory('App.framework');
final Directory outputDirectory = frameworkRootDirectory
.childDirectory('Versions')
.childDirectory('A')
..createSync(recursive: true);
// Copy App into framework directory.
environment.buildDir
.childDirectory('App.framework')
.childFile('App')
.copySync(outputDirectory.childFile('App').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);
}
// Copy assets into asset directory.
final Directory assetDirectory = outputDirectory
.childDirectory('Resources')
.childDirectory('flutter_assets');
assetDirectory.createSync(recursive: true);
final Depfile assetDepfile = await copyAssets(
environment,
assetDirectory,
targetPlatform: TargetPlatform.darwin,
flavor: environment.defines[kFlavor],
);
environment.depFileService.writeToFile(
assetDepfile,
environment.buildDir.childFile('flutter_assets.d'),
);
// Copy Info.plist template.
assetDirectory.parent.childFile('Info.plist')
..createSync()
..writeAsStringSync(r'''
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>App</string>
<key>CFBundleIdentifier</key>
<string>io.flutter.flutter.app</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>App</string>
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1.0</string>
</dict>
</plist>
''');
if (buildMode == BuildMode.debug) {
// Copy dill file.
try {
final File sourceFile = environment.buildDir.childFile('app.dill');
sourceFile.copySync(assetDirectory.childFile('kernel_blob.bin').path);
} on Exception catch (err) {
throw Exception('Failed to copy app.dill: $err');
}
// Copy precompiled runtimes.
try {
final String vmSnapshotData = environment.artifacts.getArtifactPath(Artifact.vmSnapshotData,
platform: TargetPlatform.darwin, mode: BuildMode.debug);
final String isolateSnapshotData = environment.artifacts.getArtifactPath(Artifact.isolateSnapshotData,
platform: TargetPlatform.darwin, mode: BuildMode.debug);
environment.fileSystem.file(vmSnapshotData).copySync(
assetDirectory.childFile('vm_snapshot_data').path);
environment.fileSystem.file(isolateSnapshotData).copySync(
assetDirectory.childFile('isolate_snapshot_data').path);
} on Exception catch (err) {
throw Exception('Failed to copy precompiled runtimes: $err');
}
}
// Create symlink to current version. These must be relative, from the
// framework root for Resources/App and from the versions root for
// Current.
try {
final Link currentVersion = outputDirectory.parent
.childLink('Current');
if (!currentVersion.existsSync()) {
final String linkPath = environment.fileSystem.path.relative(outputDirectory.path,
from: outputDirectory.parent.path);
currentVersion.createSync(linkPath);
}
// Create symlink to current resources.
final Link currentResources = frameworkRootDirectory
.childLink('Resources');
if (!currentResources.existsSync()) {
final String linkPath = environment.fileSystem.path.relative(environment.fileSystem.path.join(currentVersion.path, 'Resources'),
from: frameworkRootDirectory.path);
currentResources.createSync(linkPath);
}
// Create symlink to current binary.
final Link currentFramework = frameworkRootDirectory
.childLink('App');
if (!currentFramework.existsSync()) {
final String linkPath = environment.fileSystem.path.relative(environment.fileSystem.path.join(currentVersion.path, 'App'),
from: frameworkRootDirectory.path);
currentFramework.createSync(linkPath);
}
} on FileSystemException {
throw Exception('Failed to create symlinks for framework. try removing '
'the "${environment.outputDir.path}" directory and rerunning');
}
}
}
/// Bundle the debug flutter assets into the App.framework.
class DebugMacOSBundleFlutterAssets extends MacOSBundleFlutterAssets {
const DebugMacOSBundleFlutterAssets();
@override
String get name => 'debug_macos_bundle_flutter_assets';
@override
List<Target> get dependencies => const <Target>[
KernelSnapshot(),
DebugMacOSFramework(),
DebugUnpackMacOS(),
];
@override
List<Source> get inputs => <Source>[
...super.inputs,
const Source.pattern('{BUILD_DIR}/app.dill'),
const Source.artifact(Artifact.isolateSnapshotData, platform: TargetPlatform.darwin, mode: BuildMode.debug),
const Source.artifact(Artifact.vmSnapshotData, platform: TargetPlatform.darwin, mode: BuildMode.debug),
];
@override
List<Source> get outputs => <Source>[
...super.outputs,
const Source.pattern('{OUTPUT_DIR}/App.framework/Versions/A/Resources/flutter_assets/kernel_blob.bin'),
const Source.pattern('{OUTPUT_DIR}/App.framework/Versions/A/Resources/flutter_assets/vm_snapshot_data'),
const Source.pattern('{OUTPUT_DIR}/App.framework/Versions/A/Resources/flutter_assets/isolate_snapshot_data'),
];
}
/// Bundle the profile flutter assets into the App.framework.
class ProfileMacOSBundleFlutterAssets extends MacOSBundleFlutterAssets {
const ProfileMacOSBundleFlutterAssets();
@override
String get name => 'profile_macos_bundle_flutter_assets';
@override
List<Target> get dependencies => const <Target>[
CompileMacOSFramework(),
ProfileUnpackMacOS(),
];
@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'),
];
}
/// Bundle the release flutter assets into the App.framework.
class ReleaseMacOSBundleFlutterAssets extends MacOSBundleFlutterAssets {
const ReleaseMacOSBundleFlutterAssets();
@override
String get name => 'release_macos_bundle_flutter_assets';
@override
List<Target> get dependencies => const <Target>[
CompileMacOSFramework(),
ReleaseUnpackMacOS(),
];
@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'),
];
@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 from Xcode.
if (environment.defines[kXcodeAction]?.toLowerCase() == 'install') {
environment.logger.printTrace('Sending archive event if usage enabled.');
UsageEvent(
'assemble',
'macos-archive',
label: buildSuccess ? 'success' : 'fail',
flutterUsage: environment.usage,
).send();
environment.analytics.send(Event.appleUsageEvent(
workflow: 'assemble',
parameter: 'macos-archive',
result: buildSuccess ? 'success' : 'fail',
));
}
}
}
}
| flutter/packages/flutter_tools/lib/src/build_system/targets/macos.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/build_system/targets/macos.dart",
"repo_id": "flutter",
"token_count": 7925
} | 771 |
// 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 '../base/file_system.dart';
import '../base/logger.dart';
import '../convert.dart';
import '../project.dart';
/// The type of analysis to perform.
enum AndroidAnalyzeOption {
/// Prints out available build variants of the Android sub-project.
///
/// An example output:
/// ["debug", "profile", "release"]
listBuildVariant,
/// Outputs app link settings of the Android sub-project into a file.
///
/// The file path will be printed after the command is run successfully.
outputAppLinkSettings,
}
/// Analyze the Android sub-project of a Flutter project.
///
/// The [userPath] must be point to a flutter project.
class AndroidAnalyze {
AndroidAnalyze({
required this.fileSystem,
required this.option,
required this.userPath,
this.buildVariant,
required this.logger,
}) : assert(option == AndroidAnalyzeOption.listBuildVariant || buildVariant != null);
final FileSystem fileSystem;
final AndroidAnalyzeOption option;
final String? buildVariant;
final String userPath;
final Logger logger;
Future<void> analyze() async {
final FlutterProject project = FlutterProject.fromDirectory(fileSystem.directory(userPath));
switch (option) {
case AndroidAnalyzeOption.listBuildVariant:
logger.printStatus(jsonEncode(await project.android.getBuildVariants()));
case AndroidAnalyzeOption.outputAppLinkSettings:
assert(buildVariant != null);
final String filePath = await project.android.outputsAppLinkSettings(variant: buildVariant!);
logger.printStatus('result saved in $filePath');
}
}
}
| flutter/packages/flutter_tools/lib/src/commands/android_analyze.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/commands/android_analyze.dart",
"repo_id": "flutter",
"token_count": 548
} | 772 |
// 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/process.dart';
import '../cache.dart';
import '../globals.dart' as globals;
import '../runner/flutter_command.dart';
import '../runner/flutter_command_runner.dart';
import '../version.dart';
import 'upgrade.dart' show precacheArtifacts;
class ChannelCommand extends FlutterCommand {
ChannelCommand({ bool verboseHelp = false }) {
argParser.addFlag(
'all',
abbr: 'a',
help: 'Include all the available branches (including local branches) when listing channels.',
hide: !verboseHelp,
);
argParser.addFlag(
'cache-artifacts',
help: 'After switching channels, download all required binary artifacts. '
'This is the equivalent of running "flutter precache" with the "--all-platforms" flag.',
defaultsTo: true,
);
}
@override
final String name = 'channel';
@override
final String description = 'List or switch Flutter channels.';
@override
final String category = FlutterCommandCategory.sdk;
@override
String get invocation => '${runner?.executableName} $name [<channel-name>]';
@override
Future<Set<DevelopmentArtifact>> get requiredArtifacts async => const <DevelopmentArtifact>{};
@override
Future<FlutterCommandResult> runCommand() async {
final List<String> rest = argResults?.rest ?? <String>[];
switch (rest.length) {
case 0:
await _listChannels(
showAll: boolArg('all'),
verbose: globalResults?[FlutterGlobalOptions.kVerboseFlag] == true,
);
return FlutterCommandResult.success();
case 1:
await _switchChannel(rest[0]);
return FlutterCommandResult.success();
default:
throw ToolExit('Too many arguments.\n$usage');
}
}
Future<void> _listChannels({ required bool showAll, required bool verbose }) async {
// Beware: currentBranch could contain PII. See getBranchName().
final String currentChannel = globals.flutterVersion.channel; // limited to known branch names
assert(kOfficialChannels.contains(currentChannel) || kObsoleteBranches.containsKey(currentChannel) || currentChannel == kUserBranch, 'potential PII leak in channel name: "$currentChannel"');
final String currentBranch = globals.flutterVersion.getBranchName();
final Set<String> seenUnofficialChannels = <String>{};
final List<String> rawOutput = <String>[];
globals.printStatus('Flutter channels:');
final int result = await globals.processUtils.stream(
<String>['git', 'branch', '-r'],
workingDirectory: Cache.flutterRoot,
mapFunction: (String line) {
rawOutput.add(line);
return null;
},
);
if (result != 0) {
final String details = verbose ? '\n${rawOutput.join('\n')}' : '';
throwToolExit('List channels failed: $result$details', exitCode: result);
}
final Set<String> availableChannels = <String>{};
for (final String line in rawOutput) {
final List<String> split = line.split('/');
if (split.length != 2) {
// We don't know how to parse this line, skip it.
continue;
}
final String branch = split[1];
if (kOfficialChannels.contains(branch)) {
availableChannels.add(branch);
} else if (showAll) {
seenUnofficialChannels.add(branch);
}
}
bool currentChannelIsOfficial = false;
// print all available official channels in sorted manner
for (final String channel in kOfficialChannels) {
// only print non-missing channels
if (availableChannels.contains(channel)) {
String currentIndicator = ' ';
if (channel == currentChannel) {
currentIndicator = '*';
currentChannelIsOfficial = true;
}
globals.printStatus('$currentIndicator $channel (${kChannelDescriptions[channel]})');
}
}
// print all remaining channels if showAll is true
if (showAll) {
for (final String branch in seenUnofficialChannels) {
if (currentBranch == branch) {
globals.printStatus('* $branch');
} else if (!branch.startsWith('HEAD ')) {
globals.printStatus(' $branch');
}
}
} else if (!currentChannelIsOfficial) {
globals.printStatus('* $currentBranch');
}
if (!currentChannelIsOfficial) {
assert(currentChannel == kUserBranch, 'Current channel is "$currentChannel", which is not an official branch. (Current branch is "$currentBranch".)');
globals.printStatus('');
globals.printStatus('Currently not on an official channel.');
}
}
Future<void> _switchChannel(String branchName) async {
globals.printStatus("Switching to flutter channel '$branchName'...");
if (kObsoleteBranches.containsKey(branchName)) {
final String alternative = kObsoleteBranches[branchName]!;
globals.printStatus("This channel is obsolete. Consider switching to the '$alternative' channel instead.");
} else if (!kOfficialChannels.contains(branchName)) {
globals.printStatus('This is not an official channel. For a list of available channels, try "flutter channel".');
}
await _checkout(branchName);
if (boolArg('cache-artifacts')) {
await precacheArtifacts(Cache.flutterRoot);
}
globals.printStatus("Successfully switched to flutter channel '$branchName'.");
globals.printStatus("To ensure that you're on the latest build from this channel, run 'flutter upgrade'");
}
static Future<void> upgradeChannel(FlutterVersion currentVersion) async {
final String channel = currentVersion.channel;
if (kObsoleteBranches.containsKey(channel)) {
final String alternative = kObsoleteBranches[channel]!;
globals.printStatus("Transitioning from '$channel' to '$alternative'...");
return _checkout(alternative);
}
}
static Future<void> _checkout(String branchName) async {
// Get latest refs from upstream.
RunResult runResult = await globals.processUtils.run(
<String>['git', 'fetch'],
workingDirectory: Cache.flutterRoot,
);
if (runResult.processResult.exitCode == 0) {
runResult = await globals.processUtils.run(
<String>['git', 'show-ref', '--verify', '--quiet', 'refs/heads/$branchName'],
workingDirectory: Cache.flutterRoot,
);
if (runResult.processResult.exitCode == 0) {
// branch already exists, try just switching to it
runResult = await globals.processUtils.run(
<String>['git', 'checkout', branchName, '--'],
workingDirectory: Cache.flutterRoot,
);
} else {
// branch does not exist, we have to create it
runResult = await globals.processUtils.run(
<String>['git', 'checkout', '--track', '-b', branchName, 'origin/$branchName'],
workingDirectory: Cache.flutterRoot,
);
}
}
if (runResult.processResult.exitCode != 0) {
throwToolExit(
'Switching channels failed\n$runResult.',
exitCode: runResult.processResult.exitCode,
);
} else {
// Remove the version check stamp, since it could contain out-of-date
// information that pertains to the previous channel.
await FlutterVersion.resetFlutterVersionFreshnessCheck();
}
}
}
| flutter/packages/flutter_tools/lib/src/commands/channel.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/commands/channel.dart",
"repo_id": "flutter",
"token_count": 2689
} | 773 |
// 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 '../android/android_device.dart';
import '../application_package.dart';
import '../base/common.dart';
import '../base/file_system.dart';
import '../base/io.dart';
import '../device.dart';
import '../globals.dart' as globals;
import '../runner/flutter_command.dart';
class InstallCommand extends FlutterCommand with DeviceBasedDevelopmentArtifacts {
InstallCommand({
required bool verboseHelp,
}) {
addBuildModeFlags(verboseHelp: verboseHelp);
requiresPubspecYaml();
usesApplicationBinaryOption();
usesDeviceTimeoutOption();
usesDeviceConnectionOption();
usesDeviceUserOption();
usesFlavorOption();
argParser.addFlag('uninstall-only',
help: 'Uninstall the app if already on the device. Skip install.',
);
}
@override
final String name = 'install';
@override
final String description = 'Install a Flutter app on an attached device.';
@override
final String category = FlutterCommandCategory.tools;
@override
bool get refreshWirelessDevices => true;
Device? device;
bool get uninstallOnly => boolArg('uninstall-only');
String? get userIdentifier => stringArg(FlutterOptions.kDeviceUser);
String? get _applicationBinaryPath => stringArg(FlutterOptions.kUseApplicationBinary);
File? get _applicationBinary => _applicationBinaryPath == null ? null : globals.fs.file(_applicationBinaryPath);
@override
Future<void> validateCommand() async {
await super.validateCommand();
device = await findTargetDevice();
if (device == null) {
throwToolExit('No target device found');
}
if (userIdentifier != null && device is! AndroidDevice) {
throwToolExit('--${FlutterOptions.kDeviceUser} is only supported for Android');
}
if (_applicationBinaryPath != null && !(_applicationBinary?.existsSync() ?? true)) {
throwToolExit('Prebuilt binary $_applicationBinaryPath does not exist');
}
}
@override
Future<FlutterCommandResult> runCommand() async {
final Device targetDevice = device!;
final ApplicationPackage? package = await applicationPackages?.getPackageForPlatform(
await targetDevice.targetPlatform,
applicationBinary: _applicationBinary,
buildInfo: await getBuildInfo(),
);
if (package == null) {
throwToolExit('Could not find or build package');
}
if (uninstallOnly) {
await _uninstallApp(package, targetDevice);
} else {
await _installApp(package, targetDevice);
}
return FlutterCommandResult.success();
}
Future<void> _uninstallApp(ApplicationPackage package, Device device) async {
if (await device.isAppInstalled(package, userIdentifier: userIdentifier)) {
globals.printStatus('Uninstalling $package from $device...');
if (!await device.uninstallApp(package, userIdentifier: userIdentifier)) {
globals.printError('Uninstalling old version failed');
}
} else {
globals.printStatus('$package not found on $device, skipping uninstall');
}
}
Future<void> _installApp(ApplicationPackage package, Device device) async {
globals.printStatus('Installing $package to $device...');
if (!await installApp(device, package, userIdentifier: userIdentifier)) {
throwToolExit('Install failed');
}
}
}
Future<bool> installApp(
Device device,
ApplicationPackage package, {
String? userIdentifier,
bool uninstall = true
}) async {
try {
if (uninstall && await device.isAppInstalled(package, userIdentifier: userIdentifier)) {
globals.printStatus('Uninstalling old version...');
if (!await device.uninstallApp(package, userIdentifier: userIdentifier)) {
globals.printWarning('Warning: uninstalling old version failed');
}
}
} on ProcessException catch (e) {
globals.printError('Error accessing device ${device.id}:\n${e.message}');
}
return device.installApp(package, userIdentifier: userIdentifier);
}
| flutter/packages/flutter_tools/lib/src/commands/install.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/commands/install.dart",
"repo_id": "flutter",
"token_count": 1300
} | 774 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Hide the original utf8 [Codec] so that we can export our own implementation
// which adds additional error handling.
import 'dart:convert' hide utf8;
import 'dart:convert' as cnv show Utf8Decoder, utf8;
import 'package:meta/meta.dart';
import 'base/common.dart';
export 'dart:convert' hide Utf8Codec, Utf8Decoder, utf8;
/// The original utf8 encoding for testing overrides only.
///
/// Attempting to use the flutter tool utf8 decoder will surface an analyzer
/// warning that overrides cannot change the default value of a named
/// parameter.
@visibleForTesting
const Encoding utf8ForTesting = cnv.utf8;
/// A [Codec] which reports malformed bytes when decoding.
///
/// Occasionally people end up in a situation where we try to decode bytes
/// that aren't UTF-8 and we're not quite sure how this is happening.
/// This tells people to report a bug when they see this.
class Utf8Codec extends Encoding {
const Utf8Codec({this.reportErrors = true});
final bool reportErrors;
@override
Converter<List<int>, String> get decoder => reportErrors
? const Utf8Decoder()
: const Utf8Decoder(reportErrors: false);
@override
Converter<String, List<int>> get encoder => cnv.utf8.encoder;
@override
String get name => cnv.utf8.name;
}
const Encoding utf8 = Utf8Codec();
class Utf8Decoder extends Converter<List<int>, String> {
const Utf8Decoder({this.reportErrors = true});
static const cnv.Utf8Decoder _systemDecoder =
cnv.Utf8Decoder(allowMalformed: true);
final bool reportErrors;
@override
String convert(List<int> input, [int start = 0, int? end]) {
final String result = _systemDecoder.convert(input, start, end);
// Finding a Unicode replacement character indicates that the input
// was malformed.
if (reportErrors && result.contains('\u{FFFD}')) {
throwToolExit(
'Bad UTF-8 encoding (U+FFFD; REPLACEMENT CHARACTER) found while decoding string: $result. '
'The Flutter team would greatly appreciate if you could file a bug explaining '
'exactly what you were doing when this happened:\n'
'https://github.com/flutter/flutter/issues/new/choose\n'
'The source bytes were:\n$input\n\n');
}
return result;
}
@override
ByteConversionSink startChunkedConversion(Sink<String> sink) =>
_systemDecoder.startChunkedConversion(sink);
@override
Stream<String> bind(Stream<List<int>> stream) => _systemDecoder.bind(stream);
@override
Converter<List<int>, T> fuse<T>(Converter<String, T> other) =>
_systemDecoder.fuse(other);
}
| flutter/packages/flutter_tools/lib/src/convert.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/convert.dart",
"repo_id": "flutter",
"token_count": 917
} | 775 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:dds/dap.dart' hide PidTracker;
import 'package:vm_service/vm_service.dart' as vm;
import '../base/file_system.dart';
import '../base/io.dart';
import '../base/platform.dart';
import '../cache.dart';
import 'flutter_adapter_args.dart';
import 'mixins.dart';
/// A base DAP Debug Adapter for Flutter applications and tests.
abstract class FlutterBaseDebugAdapter extends DartDebugAdapter<FlutterLaunchRequestArguments, FlutterAttachRequestArguments>
with PidTracker {
FlutterBaseDebugAdapter(
super.channel, {
required this.fileSystem,
required this.platform,
super.ipv6,
this.enableFlutterDds = true,
super.enableAuthCodes,
super.logger,
super.onError,
}) : flutterSdkRoot = Cache.flutterRoot!,
// Always disable in the DAP layer as it's handled in the spawned
// 'flutter' process.
super(enableDds: false) {
configureOrgDartlangSdkMappings();
}
FileSystem fileSystem;
Platform platform;
Process? process;
final String flutterSdkRoot;
/// Whether DDS should be enabled in the Flutter process.
///
/// We never enable DDS in the DAP process for Flutter, so this value is not
/// the same as what is passed to the base class, which is always provided 'false'.
final bool enableFlutterDds;
@override
final FlutterLaunchRequestArguments Function(Map<String, Object?> obj)
parseLaunchArgs = FlutterLaunchRequestArguments.fromJson;
@override
final FlutterAttachRequestArguments Function(Map<String, Object?> obj)
parseAttachArgs = FlutterAttachRequestArguments.fromJson;
/// Whether the VM Service closing should be used as a signal to terminate the debug session.
///
/// Since we always have a process for Flutter (whether run or attach) we'll
/// always use its termination instead, so this is always false.
@override
bool get terminateOnVmServiceClose => false;
/// Whether or not the user requested debugging be enabled.
///
/// For debugging to be enabled, the user must have chosen "Debug" (and not
/// "Run") in the editor (which maps to the DAP `noDebug` field).
bool get enableDebugger {
final DartCommonLaunchAttachRequestArguments args = this.args;
if (args is FlutterLaunchRequestArguments) {
// Invert DAP's noDebug flag, treating it as false (so _do_ debug) if not
// provided.
return !(args.noDebug ?? false);
}
// Otherwise (attach), always debug.
return true;
}
void configureOrgDartlangSdkMappings() {
/// When a user navigates into 'dart:xxx' sources in their editor (via the
/// analysis server) they will land in flutter_sdk/bin/cache/pkg/sky_engine.
///
/// The running VM knows nothing about these paths and will resolve these
/// libraries to 'org-dartlang-sdk://' URIs. We need to map between these
/// to ensure that if a user puts a breakpoint inside sky_engine the VM can
/// apply it to the correct place and once hit, we can navigate the user
/// back to the correct file on their disk.
///
/// The mapping is handled by the base adapter but we need to override the
/// paths to match the layout used by Flutter.
///
/// In future this might become unnecessary if
/// https://github.com/dart-lang/sdk/issues/48435 is implemented. Until
/// then, providing these mappings improves the debugging experience.
// Clear original Dart SDK mappings because they're not valid here.
orgDartlangSdkMappings.clear();
// 'dart:ui' maps to /flutter/lib/ui
final String flutterRoot = fileSystem.path.join(flutterSdkRoot, 'bin', 'cache', 'pkg', 'sky_engine', 'lib', 'ui');
orgDartlangSdkMappings[flutterRoot] = Uri.parse('org-dartlang-sdk:///flutter/lib/ui');
// The rest of the Dart SDK maps to /third_party/dart/sdk
final String dartRoot = fileSystem.path.join(flutterSdkRoot, 'bin', 'cache', 'pkg', 'sky_engine');
orgDartlangSdkMappings[dartRoot] = Uri.parse('org-dartlang-sdk:///third_party/dart/sdk');
}
@override
Future<void> debuggerConnected(vm.VM vmInfo) async {
// Usually we'd capture the pid from the VM here and record it for
// terminating, however for Flutter apps it may be running on a remote
// device so it's not valid to terminate a process with that pid locally.
// For attach, pids should never be collected as terminateRequest() should
// not terminate the debugger.
}
/// Called by [disconnectRequest] to request that we forcefully shut down the app being run (or in the case of an attach, disconnect).
///
/// Client IDEs/editors should send a terminateRequest before a
/// disconnectRequest to allow a graceful shutdown. This method must terminate
/// quickly and therefore may leave orphaned processes.
@override
Future<void> disconnectImpl() async {
if (isAttach) {
await handleDetach();
}
terminatePids(ProcessSignal.sigkill);
}
Future<void> launchAsProcess({
required String executable,
required List<String> processArgs,
required Map<String, String>? env,
}) async {
final Process process = await (
String executable,
List<String> processArgs, {
required Map<String, String>? env,
}) async {
logger?.call('Spawning $executable with $processArgs in ${args.cwd}');
final Process process = await Process.start(
executable,
processArgs,
workingDirectory: args.cwd,
environment: env,
);
pidsToTerminate.add(process.pid);
return process;
}(executable, processArgs, env: env);
this.process = process;
process.stdout.transform(ByteToLineTransformer()).listen(handleStdout);
process.stderr.listen(handleStderr);
unawaited(process.exitCode.then(handleExitCode));
}
void handleExitCode(int code);
void handleStderr(List<int> data);
void handleStdout(String data);
}
| flutter/packages/flutter_tools/lib/src/debug_adapters/flutter_base_adapter.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/debug_adapters/flutter_base_adapter.dart",
"repo_id": "flutter",
"token_count": 1957
} | 776 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:meta/meta.dart';
import 'package:package_config/package_config.dart';
import 'android/java.dart';
import 'base/common.dart';
import 'base/error_handling_io.dart';
import 'base/file_system.dart';
import 'base/logger.dart';
import 'base/os.dart' show OperatingSystemUtils;
import 'base/platform.dart';
import 'base/process.dart';
import 'cache.dart';
import 'dart/package_map.dart';
import 'dart/pub.dart';
import 'globals.dart' as globals;
import 'project.dart';
/// An implementation of the [Cache] which provides all of Flutter's default artifacts.
class FlutterCache extends Cache {
/// [rootOverride] is configurable for testing.
/// [artifacts] is configurable for testing.
FlutterCache({
required Logger logger,
required super.fileSystem,
required Platform platform,
required super.osUtils,
required FlutterProjectFactory projectFactory,
}) : super(logger: logger, platform: platform, artifacts: <ArtifactSet>[]) {
registerArtifact(MaterialFonts(this));
registerArtifact(GradleWrapper(this));
registerArtifact(AndroidGenSnapshotArtifacts(this, platform: platform));
registerArtifact(AndroidInternalBuildArtifacts(this));
registerArtifact(IOSEngineArtifacts(this, platform: platform));
registerArtifact(FlutterWebSdk(this));
registerArtifact(LegacyCanvasKitRemover(this));
registerArtifact(FlutterSdk(this, platform: platform));
registerArtifact(WindowsEngineArtifacts(this, platform: platform));
registerArtifact(MacOSEngineArtifacts(this, platform: platform));
registerArtifact(LinuxEngineArtifacts(this, platform: platform));
registerArtifact(LinuxFuchsiaSDKArtifacts(this, platform: platform));
registerArtifact(MacOSFuchsiaSDKArtifacts(this, platform: platform));
registerArtifact(FlutterRunnerSDKArtifacts(this, platform: platform));
registerArtifact(FlutterRunnerDebugSymbols(this, platform: platform));
for (final String artifactName in IosUsbArtifacts.artifactNames) {
registerArtifact(IosUsbArtifacts(artifactName, this, platform: platform));
}
registerArtifact(FontSubsetArtifacts(this, platform: platform));
registerArtifact(PubDependencies(
logger: logger,
// flutter root and pub must be lazily initialized to avoid accessing
// before the version is determined.
flutterRoot: () => Cache.flutterRoot!,
pub: () => pub,
projectFactory: projectFactory,
));
}
}
/// Ensures that the source files for all of the dependencies for the
/// flutter_tool are present.
///
/// This does not handle cases where the source files are modified or the
/// directory contents are incomplete.
class PubDependencies extends ArtifactSet {
PubDependencies({
// Needs to be lazy to avoid reading from the cache before the root is initialized.
required String Function() flutterRoot,
required Logger logger,
required Pub Function() pub,
required FlutterProjectFactory projectFactory,
}) : _logger = logger,
_flutterRoot = flutterRoot,
_pub = pub,
_projectFactory = projectFactory,
super(DevelopmentArtifact.universal);
final String Function() _flutterRoot;
final Logger _logger;
final Pub Function() _pub;
final FlutterProjectFactory _projectFactory;
@override
Future<bool> isUpToDate(
FileSystem fileSystem,
) async {
final File toolPackageConfig = fileSystem.file(
fileSystem.path.join(_flutterRoot(), 'packages', 'flutter_tools', '.dart_tool', 'package_config.json'),
);
if (!toolPackageConfig.existsSync()) {
return false;
}
final PackageConfig packageConfig = await loadPackageConfigWithLogging(
toolPackageConfig,
logger: _logger,
throwOnError: false,
);
if (packageConfig == PackageConfig.empty) {
return false;
}
for (final Package package in packageConfig.packages) {
if (!fileSystem.directory(package.root).childFile('pubspec.yaml').existsSync()) {
return false;
}
}
return true;
}
@override
String get name => 'pub_dependencies';
@override
Future<void> update(
ArtifactUpdater artifactUpdater,
Logger logger,
FileSystem fileSystem,
OperatingSystemUtils operatingSystemUtils,
{bool offline = false}
) async {
await _pub().get(
context: PubContext.pubGet,
project: _projectFactory.fromDirectory(
fileSystem.directory(fileSystem.path.join(_flutterRoot(), 'packages', 'flutter_tools'))
),
offline: offline,
outputMode: PubOutputMode.none,
);
}
}
/// A cached artifact containing fonts used for Material Design.
class MaterialFonts extends CachedArtifact {
MaterialFonts(Cache cache) : super(
'material_fonts',
cache,
DevelopmentArtifact.universal,
);
@override
Future<void> updateInner(
ArtifactUpdater artifactUpdater,
FileSystem fileSystem,
OperatingSystemUtils operatingSystemUtils,
) async {
final Uri archiveUri = _toStorageUri(version!);
return artifactUpdater.downloadZipArchive('Downloading Material fonts...', archiveUri, location);
}
Uri _toStorageUri(String path) => Uri.parse('${cache.storageBaseUrl}/$path');
}
/// A cached artifact containing the web dart:ui sources, platform dill files,
/// and libraries.json.
///
/// This SDK references code within the regular Dart sdk to reduce download size.
class FlutterWebSdk extends CachedArtifact {
FlutterWebSdk(Cache cache)
: super(
'flutter_web_sdk',
cache,
DevelopmentArtifact.web,
);
@override
Directory get location => cache.getWebSdkDirectory();
@override
String? get version => cache.getVersionFor('engine');
@override
Future<void> updateInner(
ArtifactUpdater artifactUpdater,
FileSystem fileSystem,
OperatingSystemUtils operatingSystemUtils,
) async {
final Uri url = Uri.parse('${cache.storageBaseUrl}/flutter_infra_release/flutter/$version/flutter-web-sdk.zip');
ErrorHandlingFileSystem.deleteIfExists(location, recursive: true);
await artifactUpdater.downloadZipArchive('Downloading Web SDK...', url, location);
}
}
// In previous builds, CanvasKit artifacts were stored in a different location
// than they are now. Leaving those old artifacts in the cache confuses the
// in-memory filesystem that the web runner uses, so this artifact will evict
// them from our cache if they are there.
class LegacyCanvasKitRemover extends ArtifactSet {
LegacyCanvasKitRemover(this.cache) : super(DevelopmentArtifact.web);
final Cache cache;
@override
String get name => 'legacy_canvaskit_remover';
Directory _getLegacyCanvasKitDirectory(FileSystem fileSystem) =>
fileSystem.directory(fileSystem.path.join(
cache.getRoot().path,
'canvaskit',
));
@override
Future<bool> isUpToDate(FileSystem fileSystem) async =>
!(await _getLegacyCanvasKitDirectory(fileSystem).exists());
@override
Future<void> update(
ArtifactUpdater artifactUpdater,
Logger logger,
FileSystem fileSystem,
OperatingSystemUtils operatingSystemUtils,
{bool offline = false}
) => _getLegacyCanvasKitDirectory(fileSystem).delete(recursive: true);
}
/// A cached artifact containing the dart:ui source code.
class FlutterSdk extends EngineCachedArtifact {
FlutterSdk(Cache cache, {
required Platform platform,
}) : _platform = platform,
super(
'flutter_sdk',
cache,
DevelopmentArtifact.universal,
);
final Platform _platform;
@override
List<String> getPackageDirs() => const <String>['sky_engine'];
@override
List<List<String>> getBinaryDirs() {
// Linux and Windows both support arm64 and x64.
final String arch = cache.getHostPlatformArchName();
return <List<String>>[
<String>['common', 'flutter_patched_sdk.zip'],
<String>['common', 'flutter_patched_sdk_product.zip'],
if (cache.includeAllPlatforms) ...<List<String>>[
<String>['windows-$arch', 'windows-$arch/artifacts.zip'],
<String>['linux-$arch', 'linux-$arch/artifacts.zip'],
<String>['darwin-x64', 'darwin-$arch/artifacts.zip'],
]
else if (_platform.isWindows)
<String>['windows-$arch', 'windows-$arch/artifacts.zip']
else if (_platform.isMacOS)
<String>['darwin-x64', 'darwin-$arch/artifacts.zip']
else if (_platform.isLinux)
<String>['linux-$arch', 'linux-$arch/artifacts.zip'],
];
}
@override
List<String> getLicenseDirs() => const <String>[];
}
class MacOSEngineArtifacts extends EngineCachedArtifact {
MacOSEngineArtifacts(Cache cache, {
required Platform platform,
}) : _platform = platform,
super(
'macos-sdk',
cache,
DevelopmentArtifact.macOS,
);
final Platform _platform;
@override
List<String> getPackageDirs() => const <String>[];
@override
List<List<String>> getBinaryDirs() {
if (_platform.isMacOS || ignorePlatformFiltering) {
return _macOSDesktopBinaryDirs;
}
return const <List<String>>[];
}
@override
List<String> getLicenseDirs() => const <String>[];
}
/// Artifacts required for desktop Windows builds.
class WindowsEngineArtifacts extends EngineCachedArtifact {
WindowsEngineArtifacts(Cache cache, {
required Platform platform,
}) : _platform = platform,
super(
'windows-sdk',
cache,
DevelopmentArtifact.windows,
);
final Platform _platform;
@override
List<String> getPackageDirs() => const <String>[];
@override
List<List<String>> getBinaryDirs() {
if (_platform.isWindows || ignorePlatformFiltering) {
final String arch = cache.getHostPlatformArchName();
return _getWindowsDesktopBinaryDirs(arch);
}
return const <List<String>>[];
}
@override
List<String> getLicenseDirs() => const <String>[];
}
/// Artifacts required for desktop Linux builds.
class LinuxEngineArtifacts extends EngineCachedArtifact {
LinuxEngineArtifacts(Cache cache, {
required Platform platform
}) : _platform = platform,
super(
'linux-sdk',
cache,
DevelopmentArtifact.linux,
);
final Platform _platform;
@override
List<String> getPackageDirs() => const <String>[];
@override
List<List<String>> getBinaryDirs() {
if (_platform.isLinux || ignorePlatformFiltering) {
final String arch = cache.getHostPlatformArchName();
return <List<String>>[
<String>['linux-$arch', 'linux-$arch-debug/linux-$arch-flutter-gtk.zip'],
<String>['linux-$arch-profile', 'linux-$arch-profile/linux-$arch-flutter-gtk.zip'],
<String>['linux-$arch-release', 'linux-$arch-release/linux-$arch-flutter-gtk.zip'],
];
}
return const <List<String>>[];
}
@override
List<String> getLicenseDirs() => const <String>[];
}
/// The artifact used to generate snapshots for Android builds.
class AndroidGenSnapshotArtifacts extends EngineCachedArtifact {
AndroidGenSnapshotArtifacts(Cache cache, {
required Platform platform,
}) : _platform = platform,
super(
'android-sdk',
cache,
DevelopmentArtifact.androidGenSnapshot,
);
final Platform _platform;
@override
List<String> getPackageDirs() => const <String>[];
@override
List<List<String>> getBinaryDirs() {
return <List<String>>[
if (cache.includeAllPlatforms) ...<List<String>>[
..._osxBinaryDirs,
..._linuxBinaryDirs,
..._windowsBinaryDirs,
..._dartSdks,
] else if (_platform.isWindows)
..._windowsBinaryDirs
else if (_platform.isMacOS)
..._osxBinaryDirs
else if (_platform.isLinux)
..._linuxBinaryDirs,
];
}
@override
List<String> getLicenseDirs() { return <String>[]; }
}
/// A cached artifact containing the Maven dependencies used to build Android projects.
///
/// This is a no-op if the android SDK is not available.
///
/// Set [Java] to `null` to indicate that no Java/JDK installation could be found.
class AndroidMavenArtifacts extends ArtifactSet {
AndroidMavenArtifacts(this.cache, {
required Java? java,
required Platform platform,
}) : _java = java,
_platform = platform,
super(DevelopmentArtifact.androidMaven);
final Java? _java;
final Platform _platform;
final Cache cache;
@override
Future<void> update(
ArtifactUpdater artifactUpdater,
Logger logger,
FileSystem fileSystem,
OperatingSystemUtils operatingSystemUtils,
{bool offline = false}
) async {
// TODO(andrewkolos): Should this really be no-op if the Android SDK
// is unavailable? https://github.com/flutter/flutter/issues/127848
if (globals.androidSdk == null) {
return;
}
final Directory tempDir = cache.getRoot().createTempSync('flutter_gradle_wrapper.');
globals.gradleUtils?.injectGradleWrapperIfNeeded(tempDir);
final Status status = logger.startProgress('Downloading Android Maven dependencies...');
final File gradle = tempDir.childFile(
_platform.isWindows ? 'gradlew.bat' : 'gradlew',
);
try {
final String gradleExecutable = gradle.absolute.path;
final String flutterSdk = globals.fsUtils.escapePath(Cache.flutterRoot!);
final RunResult processResult = await globals.processUtils.run(
<String>[
gradleExecutable,
'-b', globals.fs.path.join(flutterSdk, 'packages', 'flutter_tools', 'gradle', 'resolve_dependencies.gradle'),
'--project-cache-dir', tempDir.path,
'resolveDependencies',
],
environment: _java?.environment,
);
if (processResult.exitCode != 0) {
logger.printError('Failed to download the Android dependencies');
}
} finally {
status.stop();
tempDir.deleteSync(recursive: true);
globals.androidSdk?.reinitialize();
}
}
@override
Future<bool> isUpToDate(FileSystem fileSystem) async {
// The dependencies are downloaded and cached by Gradle.
// The tool doesn't know if the dependencies are already cached at this point.
// Therefore, call Gradle to figure this out.
return false;
}
@override
String get name => 'android-maven-artifacts';
}
/// Artifacts used for internal builds. The flutter tool builds Android projects
/// using the artifacts cached by [AndroidMavenArtifacts].
class AndroidInternalBuildArtifacts extends EngineCachedArtifact {
AndroidInternalBuildArtifacts(Cache cache) : super(
'android-internal-build-artifacts',
cache,
DevelopmentArtifact.androidInternalBuild,
);
@override
List<String> getPackageDirs() => const <String>[];
@override
List<List<String>> getBinaryDirs() {
return _androidBinaryDirs;
}
@override
List<String> getLicenseDirs() { return <String>[]; }
}
class IOSEngineArtifacts extends EngineCachedArtifact {
IOSEngineArtifacts(Cache cache, {
required Platform platform,
}) : _platform = platform,
super(
'ios-sdk',
cache,
DevelopmentArtifact.iOS,
);
final Platform _platform;
@override
List<List<String>> getBinaryDirs() {
return <List<String>>[
if (_platform.isMacOS || ignorePlatformFiltering)
..._iosBinaryDirs,
];
}
@override
List<String> getLicenseDirs() {
if (_platform.isMacOS || ignorePlatformFiltering) {
return const <String>['ios', 'ios-profile', 'ios-release'];
}
return const <String>[];
}
@override
List<String> getPackageDirs() {
return <String>[];
}
}
/// A cached artifact containing Gradle Wrapper scripts and binaries.
///
/// While this is only required for Android, we need to always download it due
/// the ensurePlatformSpecificTooling logic.
class GradleWrapper extends CachedArtifact {
GradleWrapper(Cache cache) : super(
'gradle_wrapper',
cache,
DevelopmentArtifact.universal,
);
List<String> get _gradleScripts => <String>['gradlew', 'gradlew.bat'];
Uri _toStorageUri(String path) => Uri.parse('${cache.storageBaseUrl}/$path');
@override
Future<void> updateInner(
ArtifactUpdater artifactUpdater,
FileSystem fileSystem,
OperatingSystemUtils operatingSystemUtils,
) async {
final Uri archiveUri = _toStorageUri(version!);
await artifactUpdater.downloadZippedTarball('Downloading Gradle Wrapper...', archiveUri, location);
// Delete property file, allowing templates to provide it.
// Remove NOTICE file. Should not be part of the template.
final File propertiesFile = fileSystem.file(fileSystem.path.join(location.path, 'gradle', 'wrapper', 'gradle-wrapper.properties'));
final File noticeFile = fileSystem.file(fileSystem.path.join(location.path, 'NOTICE'));
ErrorHandlingFileSystem.deleteIfExists(propertiesFile);
ErrorHandlingFileSystem.deleteIfExists(noticeFile);
}
@override
bool isUpToDateInner(
FileSystem fileSystem,
) {
final String gradleWrapper = fileSystem.path.join('gradle', 'wrapper', 'gradle-wrapper.jar');
final Directory wrapperDir = cache.getCacheDir(fileSystem.path.join('artifacts', 'gradle_wrapper'));
if (!fileSystem.directory(wrapperDir).existsSync()) {
return false;
}
for (final String scriptName in _gradleScripts) {
final File scriptFile = fileSystem.file(fileSystem.path.join(wrapperDir.path, scriptName));
if (!scriptFile.existsSync()) {
return false;
}
}
final File gradleWrapperJar = fileSystem.file(fileSystem.path.join(wrapperDir.path, gradleWrapper));
if (!gradleWrapperJar.existsSync()) {
return false;
}
return true;
}
}
/// Common functionality for pulling Fuchsia SDKs.
abstract class _FuchsiaSDKArtifacts extends CachedArtifact {
_FuchsiaSDKArtifacts(Cache cache, String platform) :
_path = 'fuchsia/sdk/core/$platform-amd64',
super(
'fuchsia-$platform',
cache,
DevelopmentArtifact.fuchsia,
);
final String _path;
@override
Directory get location => cache.getArtifactDirectory('fuchsia');
Future<void> _doUpdate(ArtifactUpdater artifactUpdater) {
final String url = '${cache.cipdBaseUrl}/$_path/+/$version';
return artifactUpdater.downloadZipArchive('Downloading package fuchsia SDK...',
Uri.parse(url), location);
}
}
/// The pre-built flutter runner for Fuchsia development.
class FlutterRunnerSDKArtifacts extends CachedArtifact {
FlutterRunnerSDKArtifacts(Cache cache, {
required Platform platform,
}) : _platform = platform,
super(
'flutter_runner',
cache,
DevelopmentArtifact.flutterRunner,
);
final Platform _platform;
@override
Directory get location => cache.getArtifactDirectory('flutter_runner');
@override
String? get version => cache.getVersionFor('engine');
@override
Future<void> updateInner(
ArtifactUpdater artifactUpdater,
FileSystem fileSystem,
OperatingSystemUtils operatingSystemUtils,
) async {
if (!_platform.isLinux && !_platform.isMacOS) {
return;
}
final String url = '${cache.cipdBaseUrl}/flutter/fuchsia/+/git_revision:$version';
await artifactUpdater.downloadZipArchive('Downloading package flutter runner...', Uri.parse(url), location);
}
}
/// Implementations of this class can resolve URLs for packages that are versioned.
///
/// See also [CipdArchiveResolver].
abstract class VersionedPackageResolver {
const VersionedPackageResolver();
/// Returns the URL for the artifact.
String resolveUrl(String packageName, String version);
}
/// Resolves the CIPD archive URL for a given package and version.
class CipdArchiveResolver extends VersionedPackageResolver {
const CipdArchiveResolver(this.cache);
final Cache cache;
@override
String resolveUrl(String packageName, String version) {
return '${cache.cipdBaseUrl}/flutter/$packageName/+/git_revision:$version';
}
}
/// The debug symbols for flutter runner for Fuchsia development.
class FlutterRunnerDebugSymbols extends CachedArtifact {
FlutterRunnerDebugSymbols(Cache cache, {
required Platform platform,
VersionedPackageResolver? packageResolver,
}) : _platform = platform,
packageResolver = packageResolver ?? CipdArchiveResolver(cache),
super('flutter_runner_debug_symbols', cache, DevelopmentArtifact.flutterRunner);
final VersionedPackageResolver packageResolver;
final Platform _platform;
@override
Directory get location => cache.getArtifactDirectory(name);
@override
String? get version => cache.getVersionFor('engine');
Future<void> _downloadDebugSymbols(String targetArch, ArtifactUpdater artifactUpdater) async {
final String packageName = 'fuchsia-debug-symbols-$targetArch';
final String url = packageResolver.resolveUrl(packageName, version!);
await artifactUpdater.downloadZipArchive(
'Downloading debug symbols for flutter runner - arch:$targetArch...',
Uri.parse(url),
location,
);
}
@override
Future<void> updateInner(
ArtifactUpdater artifactUpdater,
FileSystem fileSystem,
OperatingSystemUtils operatingSystemUtils,
) async {
if (!_platform.isLinux && !_platform.isMacOS) {
return;
}
await _downloadDebugSymbols('x64', artifactUpdater);
await _downloadDebugSymbols('arm64', artifactUpdater);
}
}
/// The Fuchsia core SDK for Linux.
class LinuxFuchsiaSDKArtifacts extends _FuchsiaSDKArtifacts {
LinuxFuchsiaSDKArtifacts(Cache cache, {
required Platform platform,
}) : _platform = platform,
super(cache, 'linux');
final Platform _platform;
@override
Future<void> updateInner(
ArtifactUpdater artifactUpdater,
FileSystem fileSystem,
OperatingSystemUtils operatingSystemUtils,
) async {
if (!_platform.isLinux) {
return;
}
return _doUpdate(artifactUpdater);
}
}
/// The Fuchsia core SDK for MacOS.
class MacOSFuchsiaSDKArtifacts extends _FuchsiaSDKArtifacts {
MacOSFuchsiaSDKArtifacts(Cache cache, {
required Platform platform,
}) : _platform = platform,
super(cache, 'mac');
final Platform _platform;
@override
Future<void> updateInner(
ArtifactUpdater artifactUpdater,
FileSystem fileSystem,
OperatingSystemUtils operatingSystemUtils,
) async {
if (!_platform.isMacOS) {
return;
}
return _doUpdate(artifactUpdater);
}
}
/// Cached artifacts for font subsetting.
class FontSubsetArtifacts extends EngineCachedArtifact {
FontSubsetArtifacts(Cache cache, {
required Platform platform,
}) : _platform = platform,
super(artifactName, cache, DevelopmentArtifact.universal);
final Platform _platform;
static const String artifactName = 'font-subset';
@override
List<List<String>> getBinaryDirs() {
// Linux and Windows both support arm64 and x64.
final String arch = cache.getHostPlatformArchName();
final Map<String, List<String>> artifacts = <String, List<String>> {
'macos': <String>['darwin-x64', 'darwin-$arch/$artifactName.zip'],
'linux': <String>['linux-$arch', 'linux-$arch/$artifactName.zip'],
'windows': <String>['windows-$arch', 'windows-$arch/$artifactName.zip'],
};
if (cache.includeAllPlatforms) {
return artifacts.values.toList();
} else {
final List<String>? binaryDirs = artifacts[_platform.operatingSystem];
if (binaryDirs == null) {
throwToolExit('Unsupported operating system: ${_platform.operatingSystem}');
}
return <List<String>>[binaryDirs];
}
}
@override
List<String> getLicenseDirs() => const <String>[];
@override
List<String> getPackageDirs() => const <String>[];
}
/// Cached iOS/USB binary artifacts.
class IosUsbArtifacts extends CachedArtifact {
IosUsbArtifacts(String name, Cache cache, {
required Platform platform,
}) : _platform = platform,
super(
name,
cache,
DevelopmentArtifact.universal,
);
final Platform _platform;
static const List<String> artifactNames = <String>[
'libimobiledevice',
'usbmuxd',
'libplist',
'openssl',
'ios-deploy',
];
// For unknown reasons, users are getting into bad states where libimobiledevice is
// downloaded but some executables are missing from the zip. The names here are
// used for additional download checks below, so we can re-download if they are
// missing.
static const Map<String, List<String>> _kExecutables = <String, List<String>>{
'libimobiledevice': <String>[
'idevicescreenshot',
'idevicesyslog',
],
'usbmuxd': <String>[
'iproxy',
],
};
@override
Map<String, String> get environment {
return <String, String>{
'DYLD_LIBRARY_PATH': cache.getArtifactDirectory(name).path,
};
}
@override
bool isUpToDateInner(FileSystem fileSystem) {
final List<String>? executables =_kExecutables[name];
if (executables == null) {
return true;
}
for (final String executable in executables) {
if (!location.childFile(executable).existsSync()) {
return false;
}
}
return true;
}
@override
Future<void> updateInner(
ArtifactUpdater artifactUpdater,
FileSystem fileSystem,
OperatingSystemUtils operatingSystemUtils,
) async {
if (!_platform.isMacOS && !ignorePlatformFiltering) {
return;
}
if (location.existsSync()) {
location.deleteSync(recursive: true);
}
await artifactUpdater.downloadZipArchive('Downloading $name...', archiveUri, location);
}
@visibleForTesting
Uri get archiveUri => Uri.parse(
'${cache.realmlessStorageBaseUrl}/flutter_infra_release/'
'ios-usb-dependencies${cache.useUnsignedMacBinaries ? '/unsigned' : ''}'
'/$name/$version/$name.zip',
);
}
// TODO(zanderso): upload debug desktop artifacts to host-debug and
// remove from existing host folder.
// https://github.com/flutter/flutter/issues/38935
List<List<String>> _getWindowsDesktopBinaryDirs(String arch) {
return <List<String>>[
<String>['windows-$arch', 'windows-$arch-debug/windows-$arch-flutter.zip'],
<String>['windows-$arch', 'windows-$arch/flutter-cpp-client-wrapper.zip'],
<String>['windows-$arch-profile', 'windows-$arch-profile/windows-$arch-flutter.zip'],
<String>['windows-$arch-release', 'windows-$arch-release/windows-$arch-flutter.zip'],
];
}
const List<List<String>> _macOSDesktopBinaryDirs = <List<String>>[
<String>['darwin-x64', 'darwin-x64/framework.zip'],
<String>['darwin-x64', 'darwin-x64/gen_snapshot.zip'],
<String>['darwin-x64-profile', 'darwin-x64-profile/framework.zip'],
<String>['darwin-x64-profile', 'darwin-x64-profile/artifacts.zip'],
<String>['darwin-x64-profile', 'darwin-x64-profile/gen_snapshot.zip'],
<String>['darwin-x64-release', 'darwin-x64-release/framework.zip'],
<String>['darwin-x64-release', 'darwin-x64-release/artifacts.zip'],
<String>['darwin-x64-release', 'darwin-x64-release/gen_snapshot.zip'],
];
const List<List<String>> _osxBinaryDirs = <List<String>>[
<String>['android-arm-profile/darwin-x64', 'android-arm-profile/darwin-x64.zip'],
<String>['android-arm-release/darwin-x64', 'android-arm-release/darwin-x64.zip'],
<String>['android-arm64-profile/darwin-x64', 'android-arm64-profile/darwin-x64.zip'],
<String>['android-arm64-release/darwin-x64', 'android-arm64-release/darwin-x64.zip'],
<String>['android-x64-profile/darwin-x64', 'android-x64-profile/darwin-x64.zip'],
<String>['android-x64-release/darwin-x64', 'android-x64-release/darwin-x64.zip'],
];
const List<List<String>> _linuxBinaryDirs = <List<String>>[
<String>['android-arm-profile/linux-x64', 'android-arm-profile/linux-x64.zip'],
<String>['android-arm-release/linux-x64', 'android-arm-release/linux-x64.zip'],
<String>['android-arm64-profile/linux-x64', 'android-arm64-profile/linux-x64.zip'],
<String>['android-arm64-release/linux-x64', 'android-arm64-release/linux-x64.zip'],
<String>['android-x64-profile/linux-x64', 'android-x64-profile/linux-x64.zip'],
<String>['android-x64-release/linux-x64', 'android-x64-release/linux-x64.zip'],
];
const List<List<String>> _windowsBinaryDirs = <List<String>>[
<String>['android-arm-profile/windows-x64', 'android-arm-profile/windows-x64.zip'],
<String>['android-arm-release/windows-x64', 'android-arm-release/windows-x64.zip'],
<String>['android-arm64-profile/windows-x64', 'android-arm64-profile/windows-x64.zip'],
<String>['android-arm64-release/windows-x64', 'android-arm64-release/windows-x64.zip'],
<String>['android-x64-profile/windows-x64', 'android-x64-profile/windows-x64.zip'],
<String>['android-x64-release/windows-x64', 'android-x64-release/windows-x64.zip'],
];
const List<List<String>> _iosBinaryDirs = <List<String>>[
<String>['ios', 'ios/artifacts.zip'],
<String>['ios-profile', 'ios-profile/artifacts.zip'],
<String>['ios-release', 'ios-release/artifacts.zip'],
];
const List<List<String>> _androidBinaryDirs = <List<String>>[
<String>['android-x86', 'android-x86/artifacts.zip'],
<String>['android-x64', 'android-x64/artifacts.zip'],
<String>['android-arm', 'android-arm/artifacts.zip'],
<String>['android-arm-profile', 'android-arm-profile/artifacts.zip'],
<String>['android-arm-release', 'android-arm-release/artifacts.zip'],
<String>['android-arm64', 'android-arm64/artifacts.zip'],
<String>['android-arm64-profile', 'android-arm64-profile/artifacts.zip'],
<String>['android-arm64-release', 'android-arm64-release/artifacts.zip'],
<String>['android-x64-profile', 'android-x64-profile/artifacts.zip'],
<String>['android-x64-release', 'android-x64-release/artifacts.zip'],
<String>['android-x86-jit-release', 'android-x86-jit-release/artifacts.zip'],
];
const List<List<String>> _dartSdks = <List<String>> [
<String>['darwin-x64', 'dart-sdk-darwin-x64.zip'],
<String>['linux-x64', 'dart-sdk-linux-x64.zip'],
<String>['windows-x64', 'dart-sdk-windows-x64.zip'],
];
| flutter/packages/flutter_tools/lib/src/flutter_cache.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/flutter_cache.dart",
"repo_id": "flutter",
"token_count": 10625
} | 777 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:archive/archive.dart';
import '../base/file_system.dart';
import '../base/version.dart';
import '../convert.dart';
import '../doctor_validator.dart';
/// A parser for the Intellij and Android Studio plugin JAR files.
///
/// This searches on the provided plugin path for a JAR archive, then
/// unzips it to parse the META-INF/plugin.xml for version information.
///
/// In particular, the Intellij Flutter plugin has a different structure depending on the version.
///
/// For flutter-intellij plugin v49 or lower:
/// flutter-intellij/lib/flutter-intellij.jar ( includes META-INF/plugin.xml )
///
/// For flutter-intellij plugin v50 or higher and for Intellij 2020.2:
/// flutter-intellij/lib/flutter-intellij-X.Y.Z.jar
/// flutter-idea-X.Y.Z.jar ( includes META-INF/plugin.xml )
/// flutter-studio-X.Y.Z.jar
///
/// For flutter-intellij plugin v50 or higher and for Intellij 2020.3:
/// flutter-intellij/lib/flutter-intellij-X.Y.Z.jar
/// flutter-idea-X.Y.Z.jar ( includes META-INF/plugin.xml )
///
/// where X.Y.Z is the version number.
///
/// Intellij Flutter plugin's files can be found here:
/// https://plugins.jetbrains.com/plugin/9212-flutter/versions/stable
///
/// See also:
/// * [IntellijValidator], the validator base class that uses this to check
/// plugin versions.
class IntelliJPlugins {
IntelliJPlugins(this.pluginsPath, {
required FileSystem fileSystem
}) : _fileSystem = fileSystem;
final FileSystem _fileSystem;
final String pluginsPath;
static final Version kMinFlutterPluginVersion = Version(16, 0, 0);
static const String kIntellijDartPluginUrl = 'https://plugins.jetbrains.com/plugin/6351-dart';
static const String kIntellijFlutterPluginUrl = 'https://plugins.jetbrains.com/plugin/9212-flutter';
void validatePackage(
List<ValidationMessage> messages,
List<String> packageNames,
String title,
String url, {
Version? minVersion,
}) {
for (final String packageName in packageNames) {
if (!_hasPackage(packageName)) {
continue;
}
final String? versionText = _readPackageVersion(packageName);
final Version? version = Version.parse(versionText);
if (version != null && minVersion != null && version < minVersion) {
messages.add(ValidationMessage.error(
'$title plugin version $versionText - the recommended minimum version is $minVersion'),
);
} else {
messages.add(ValidationMessage(
'$title plugin ${version != null ? "version $version" : "installed"}'),
);
}
return;
}
messages.add(ValidationMessage(
'$title plugin can be installed from:',
contextUrl: url,
));
}
bool _hasPackage(String packageName) {
final String packagePath = _fileSystem.path.join(pluginsPath, packageName);
if (packageName.endsWith('.jar')) {
return _fileSystem.isFileSync(packagePath);
}
return _fileSystem.isDirectorySync(packagePath);
}
ArchiveFile? _findPluginXml(String packageName) {
final List<File> mainJarFileList = <File>[];
if (packageName.endsWith('.jar')) {
// package exists (checked in _hasPackage)
mainJarFileList.add(_fileSystem.file(_fileSystem.path.join(pluginsPath, packageName)));
} else {
final String packageLibPath =
_fileSystem.path.join(pluginsPath, packageName, 'lib');
if (!_fileSystem.isDirectorySync(packageLibPath)) {
return null;
}
// Collect the files with a file suffix of .jar/.zip that contains the plugin.xml file
final List<File> pluginJarFiles = _fileSystem
.directory(_fileSystem.path.join(pluginsPath, packageName, 'lib'))
.listSync()
.whereType<File>()
.where((File file) {
final String fileExt= _fileSystem.path.extension(file.path);
return fileExt == '.jar' || fileExt == '.zip';
})
.toList();
if (pluginJarFiles.isEmpty) {
return null;
}
// Prefer file with the same suffix as the package name
pluginJarFiles.sort((File a, File b) {
final bool aStartWithPackageName =
a.basename.toLowerCase().startsWith(packageName.toLowerCase());
final bool bStartWithPackageName =
b.basename.toLowerCase().startsWith(packageName.toLowerCase());
if (bStartWithPackageName != aStartWithPackageName) {
return bStartWithPackageName ? 1 : -1;
}
return a.basename.length - b.basename.length;
});
mainJarFileList.addAll(pluginJarFiles);
}
for (final File file in mainJarFileList) {
final Archive archive = ZipDecoder().decodeBytes(file.readAsBytesSync());
final ArchiveFile? archiveFile = archive.findFile('META-INF/plugin.xml');
if (archiveFile != null) {
return archiveFile;
}
}
return null;
}
String? _readPackageVersion(String packageName) {
try {
final ArchiveFile? archiveFile = _findPluginXml(packageName);
if (archiveFile == null) {
return null;
}
final String content = utf8.decode(archiveFile.content as List<int>);
const String versionStartTag = '<version>';
final int start = content.indexOf(versionStartTag);
final int end = content.indexOf('</version>', start);
return content.substring(start + versionStartTag.length, end);
} on ArchiveException {
return null;
}
}
}
| flutter/packages/flutter_tools/lib/src/intellij/intellij.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/intellij/intellij.dart",
"repo_id": "flutter",
"token_count": 2144
} | 778 |
// 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/common.dart';
import '../../base/file_system.dart';
import '../../base/project_migrator.dart';
import '../../reporting/reporting.dart';
import '../../xcode_project.dart';
// Xcode 11.4 requires linked and embedded frameworks to contain all targeted architectures before build phases are run.
// This caused issues switching between a real device and simulator due to architecture mismatch.
// Remove the linking and embedding logic from the Xcode project to give the tool more control over these.
class RemoveFrameworkLinkAndEmbeddingMigration extends ProjectMigrator {
RemoveFrameworkLinkAndEmbeddingMigration(
IosProject project,
super.logger,
Usage usage,
Analytics analytics,
) : _xcodeProjectInfoFile = project.xcodeProjectInfoFile,
_usage = usage,
_analytics = analytics;
final File _xcodeProjectInfoFile;
final Usage _usage;
final Analytics _analytics;
@override
void migrate() {
if (!_xcodeProjectInfoFile.existsSync()) {
logger.printTrace('Xcode project not found, skipping framework link and embedding migration');
return;
}
processFileLines(_xcodeProjectInfoFile);
}
@override
String? migrateLine(String line) {
// App.framework Frameworks reference.
// isa = PBXFrameworksBuildPhase;
// files = (
// 3B80C3941E831B6300D905FE /* App.framework in Frameworks */,
if (line.contains('3B80C3941E831B6300D905FE')) {
return null;
}
// App.framework Embed Framework reference (build phase to embed framework).
// 3B80C3951E831B6300D905FE /* App.framework in Embed Frameworks */,
if (line.contains('3B80C3951E831B6300D905FE')
|| line.contains('741F496821356857001E2961')) { // Ephemeral add-to-app variant.
return null;
}
// App.framework project file reference (seen in Xcode navigator pane).
// isa = PBXGroup;
// children = (
// 3B80C3931E831B6300D905FE /* App.framework */,
if (line.contains('3B80C3931E831B6300D905FE')
|| line.contains('741F496521356807001E2961')) { // Ephemeral add-to-app variant.
return null;
}
// Flutter.framework Frameworks reference.
// isa = PBXFrameworksBuildPhase;
// files = (
// 9705A1C61CF904A100538489 /* Flutter.framework in Frameworks */,
if (line.contains('9705A1C61CF904A100538489')) {
return null;
}
// Flutter.framework Embed Framework reference (build phase to embed framework).
// 9705A1C71CF904A300538489 /* Flutter.framework in Embed Frameworks */,
if (line.contains('9705A1C71CF904A300538489')
|| line.contains('741F496221355F47001E2961')) { // Ephemeral add-to-app variant.
return null;
}
// Flutter.framework project file reference (seen in Xcode navigator pane).
// isa = PBXGroup;
// children = (
// 9740EEBA1CF902C7004384FC /* Flutter.framework */,
if (line.contains('9740EEBA1CF902C7004384FC')
|| line.contains('741F495E21355F27001E2961')) { // Ephemeral add-to-app variant.
return null;
}
// Embed and thin frameworks in a script instead of using Xcode's link / embed build phases.
const String thinBinaryScript = r'xcode_backend.sh\" thin';
if (line.contains(thinBinaryScript) && !line.contains(' embed')) {
return line.replaceFirst(thinBinaryScript, r'xcode_backend.sh\" embed_and_thin');
}
if (line.contains('/* App.framework ') || line.contains('/* Flutter.framework ')) {
// Print scary message.
UsageEvent('ios-migration', 'remove-frameworks', label: 'failure', flutterUsage: _usage).send();
_analytics.send(Event.appleUsageEvent(
workflow: 'ios-migration',
parameter: 'remove-frameworks',
result: 'failure',
));
throwToolExit('Your Xcode project requires migration. See https://flutter.dev/docs/development/ios-project-migration for details.');
}
return line;
}
}
| flutter/packages/flutter_tools/lib/src/ios/migrations/remove_framework_link_and_embedding_migration.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/ios/migrations/remove_framework_link_and_embedding_migration.dart",
"repo_id": "flutter",
"token_count": 1519
} | 779 |
// 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.
// Shared logic between iOS and macOS implementations of native assets.
import 'package:native_assets_cli/native_assets_cli_internal.dart'
hide BuildMode;
import '../../../base/common.dart';
import '../../../base/file_system.dart';
import '../../../base/io.dart';
import '../../../build_info.dart';
import '../../../convert.dart';
import '../../../globals.dart' as globals;
/// Create an `Info.plist` in [target] for a framework with a single dylib.
///
/// The framework must be named [name].framework and the dylib [name].
Future<void> createInfoPlist(
String name,
Directory target,
) async {
final File infoPlistFile = target.childFile('Info.plist');
await infoPlistFile.writeAsString('''
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>$name</string>
<key>CFBundleIdentifier</key>
<string>io.flutter.flutter.native_assets.$name</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$name</string>
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1.0</string>
</dict>
</plist>
''');
}
/// Combines dylibs from [sources] into a fat binary at [targetFullPath].
///
/// The dylibs must have different architectures. E.g. a dylib targeting
/// arm64 ios simulator cannot be combined with a dylib targeting arm64
/// ios device or macos arm64.
Future<void> lipoDylibs(File target, List<Uri> sources) async {
final ProcessResult lipoResult = await globals.processManager.run(
<String>[
'lipo',
'-create',
'-output',
target.path,
for (final Uri source in sources) source.toFilePath(),
],
);
if (lipoResult.exitCode != 0) {
throwToolExit('Failed to create universal binary:\n${lipoResult.stderr}');
}
globals.logger.printTrace(lipoResult.stdout as String);
globals.logger.printTrace(lipoResult.stderr as String);
}
/// Sets the install name in a dylib with a Mach-O format.
///
/// On macOS and iOS, opening a dylib at runtime fails if the path inside the
/// dylib itself does not correspond to the path that the file is at. Therefore,
/// native assets copied into their final location also need their install name
/// updated with the `install_name_tool`.
Future<void> setInstallNameDylib(File dylibFile) async {
final String fileName = dylibFile.basename;
final ProcessResult installNameResult = await globals.processManager.run(
<String>[
'install_name_tool',
'-id',
'@rpath/$fileName.framework/$fileName',
dylibFile.path,
],
);
if (installNameResult.exitCode != 0) {
throwToolExit(
'Failed to change the install name of $dylibFile:\n${installNameResult.stderr}',
);
}
}
Future<void> codesignDylib(
String? codesignIdentity,
BuildMode buildMode,
FileSystemEntity target,
) async {
if (codesignIdentity == null || codesignIdentity.isEmpty) {
codesignIdentity = '-';
}
final List<String> codesignCommand = <String>[
'codesign',
'--force',
'--sign',
codesignIdentity,
if (buildMode != BuildMode.release) ...<String>[
// Mimic Xcode's timestamp codesigning behavior on non-release binaries.
'--timestamp=none',
],
target.path,
];
globals.logger.printTrace(codesignCommand.join(' '));
final ProcessResult codesignResult = await globals.processManager.run(
codesignCommand,
);
if (codesignResult.exitCode != 0) {
throwToolExit(
'Failed to code sign binary: exit code: ${codesignResult.exitCode} '
'${codesignResult.stdout} ${codesignResult.stderr}',
);
}
globals.logger.printTrace(codesignResult.stdout as String);
globals.logger.printTrace(codesignResult.stderr as String);
}
/// Flutter expects `xcrun` to be on the path on macOS hosts.
///
/// Use the `clang`, `ar`, and `ld` that would be used if run with `xcrun`.
Future<CCompilerConfig> cCompilerConfigMacOS() async {
final ProcessResult xcrunResult = await globals.processManager.run(
<String>['xcrun', 'clang', '--version'],
);
if (xcrunResult.exitCode != 0) {
throwToolExit('Failed to find clang with xcrun:\n${xcrunResult.stderr}');
}
final String installPath = LineSplitter.split(xcrunResult.stdout as String)
.firstWhere((String s) => s.startsWith('InstalledDir: '))
.split(' ')
.last;
return CCompilerConfig(
cc: Uri.file('$installPath/clang'),
ar: Uri.file('$installPath/ar'),
ld: Uri.file('$installPath/ld'),
);
}
/// Converts [fileName] into a suitable framework name.
///
/// On MacOS and iOS, dylibs need to be packaged in a framework.
///
/// In order for resolution to work, the file name inside the framework must be
/// equal to the framework name.
///
/// Dylib names on MacOS/iOS usually have a dylib extension. If so, remove it.
///
/// Dylib names on MacOS/iOS are usually prefixed with 'lib'. So, if the file is
/// a dylib, try to remove the prefix.
///
/// The bundle ID string must contain only alphanumeric characters
/// (A–Z, a–z, and 0–9), hyphens (-), and periods (.).
/// https://developer.apple.com/documentation/bundleresources/information_property_list/cfbundleidentifier
///
/// The [alreadyTakenNames] are used to ensure that the framework name does not
/// conflict with previously chosen names.
Uri frameworkUri(String fileName, Set<String> alreadyTakenNames) {
final List<String> splitFileName = fileName.split('.');
final bool isDylib;
if (splitFileName.length >= 2) {
isDylib = splitFileName.last == 'dylib';
if (isDylib) {
fileName = splitFileName.sublist(0, splitFileName.length - 1).join('.');
}
} else {
isDylib = false;
}
if (isDylib && fileName.startsWith('lib')) {
fileName = fileName.replaceFirst('lib', '');
}
fileName = fileName.replaceAll(RegExp(r'[^A-Za-z0-9_-]'), '');
if (alreadyTakenNames.contains(fileName)) {
final String prefixName = fileName;
for (int i = 1; i < 1000; i++) {
fileName = '$prefixName$i';
if (!alreadyTakenNames.contains(fileName)) {
break;
}
}
if (alreadyTakenNames.contains(fileName)) {
throwToolExit('Failed to rename $fileName in native assets packaging.');
}
}
alreadyTakenNames.add(fileName);
return Uri(path: '$fileName.framework/$fileName');
}
| flutter/packages/flutter_tools/lib/src/isolated/native_assets/macos/native_assets_host.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/isolated/native_assets/macos/native_assets_host.dart",
"repo_id": "flutter",
"token_count": 2422
} | 780 |
// 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.
// The whole design for the lexing and parsing step can be found in this design doc.
// See https://flutter.dev/go/icu-message-parser.
// Symbol Types
import '../base/logger.dart';
import 'gen_l10n_types.dart';
enum ST {
// Terminal Types
openBrace,
closeBrace,
comma,
equalSign,
other,
plural,
select,
string,
number,
identifier,
empty,
colon,
date,
time,
// Nonterminal Types
message,
placeholderExpr,
argumentExpr,
pluralExpr,
pluralParts,
pluralPart,
selectExpr,
selectParts,
selectPart,
argType,
}
// The grammar of the syntax.
Map<ST, List<List<ST>>> grammar = <ST, List<List<ST>>>{
ST.message: <List<ST>>[
<ST>[ST.string, ST.message],
<ST>[ST.placeholderExpr, ST.message],
<ST>[ST.pluralExpr, ST.message],
<ST>[ST.selectExpr, ST.message],
<ST>[ST.argumentExpr, ST.message],
<ST>[ST.empty],
],
ST.placeholderExpr: <List<ST>>[
<ST>[ST.openBrace, ST.identifier, ST.closeBrace],
],
ST.pluralExpr: <List<ST>>[
<ST>[ST.openBrace, ST.identifier, ST.comma, ST.plural, ST.comma, ST.pluralParts, ST.closeBrace],
],
ST.pluralParts: <List<ST>>[
<ST>[ST.pluralPart, ST.pluralParts],
<ST>[ST.empty],
],
ST.pluralPart: <List<ST>>[
<ST>[ST.identifier, ST.openBrace, ST.message, ST.closeBrace],
<ST>[ST.equalSign, ST.number, ST.openBrace, ST.message, ST.closeBrace],
<ST>[ST.other, ST.openBrace, ST.message, ST.closeBrace],
],
ST.selectExpr: <List<ST>>[
<ST>[ST.openBrace, ST.identifier, ST.comma, ST.select, ST.comma, ST.selectParts, ST.closeBrace],
<ST>[ST.other, ST.openBrace, ST.message, ST.closeBrace],
],
ST.selectParts: <List<ST>>[
<ST>[ST.selectPart, ST.selectParts],
<ST>[ST.empty],
],
ST.selectPart: <List<ST>>[
<ST>[ST.identifier, ST.openBrace, ST.message, ST.closeBrace],
<ST>[ST.number, ST.openBrace, ST.message, ST.closeBrace],
<ST>[ST.other, ST.openBrace, ST.message, ST.closeBrace],
],
ST.argumentExpr: <List<ST>>[
<ST>[ST.openBrace, ST.identifier, ST.comma, ST.argType, ST.comma, ST.colon, ST.colon, ST.identifier, ST.closeBrace],
],
ST.argType: <List<ST>>[
<ST>[ST.date],
<ST>[ST.time],
],
};
class Node {
Node(this.type, this.positionInMessage, { this.expectedSymbolCount = 0, this.value, List<Node>? children }): children = children ?? <Node>[];
// Token constructors.
Node.openBrace(this.positionInMessage): type = ST.openBrace, value = '{';
Node.closeBrace(this.positionInMessage): type = ST.closeBrace, value = '}';
Node.brace(this.positionInMessage, String this.value) {
if (value == '{') {
type = ST.openBrace;
} else if (value == '}') {
type = ST.closeBrace;
} else {
// We should never arrive here.
throw L10nException('Provided value $value is not a brace.');
}
}
Node.equalSign(this.positionInMessage): type = ST.equalSign, value = '=';
Node.comma(this.positionInMessage): type = ST.comma, value = ',';
Node.string(this.positionInMessage, String this.value): type = ST.string;
Node.number(this.positionInMessage, String this.value): type = ST.number;
Node.identifier(this.positionInMessage, String this.value): type = ST.identifier;
Node.pluralKeyword(this.positionInMessage): type = ST.plural, value = 'plural';
Node.selectKeyword(this.positionInMessage): type = ST.select, value = 'select';
Node.otherKeyword(this.positionInMessage): type = ST.other, value = 'other';
Node.empty(this.positionInMessage): type = ST.empty, value = '';
Node.dateKeyword(this.positionInMessage): type = ST.date, value = 'date';
Node.timeKeyword(this.positionInMessage): type = ST.time, value = 'time';
String? value;
late ST type;
List<Node> children = <Node>[];
int positionInMessage;
int expectedSymbolCount = 0;
@override
String toString() {
return _toStringHelper(0);
}
String _toStringHelper(int indentLevel) {
final String indent = List<String>.filled(indentLevel, ' ').join();
if (children.isEmpty) {
return '''
${indent}Node($type, $positionInMessage${value == null ? '' : ", value: '$value'"})''';
}
final String childrenString = children.map((Node child) => child._toStringHelper(indentLevel + 1)).join(',\n');
return '''
${indent}Node($type, $positionInMessage${value == null ? '' : ", value: '$value'"}, children: <Node>[
$childrenString,
$indent])''';
}
// Only used for testing. We don't compare expectedSymbolCount because
// it is an auxiliary member used during the parse function but doesn't
// have meaning after calling compress.
@override
// ignore: avoid_equals_and_hash_code_on_mutable_classes, hash_and_equals
bool operator==(covariant Node other) {
if (value != other.value
|| type != other.type
|| positionInMessage != other.positionInMessage
|| children.length != other.children.length
) {
return false;
}
for (int i = 0; i < children.length; i++) {
if (children[i] != other.children[i]) {
return false;
}
}
return true;
}
bool get isFull {
return children.length >= expectedSymbolCount;
}
}
RegExp escapedString = RegExp(r"'[^']*'");
RegExp unescapedString = RegExp(r"[^{}']+");
RegExp normalString = RegExp(r'[^{}]+');
RegExp brace = RegExp(r'{|}');
RegExp whitespace = RegExp(r'\s+');
RegExp numeric = RegExp(r'[0-9]+');
RegExp alphanumeric = RegExp(r'[a-zA-Z0-9|_]+');
RegExp comma = RegExp(r',');
RegExp equalSign = RegExp(r'=');
RegExp colon = RegExp(r':');
// List of token matchers ordered by precedence
Map<ST, RegExp> matchers = <ST, RegExp>{
ST.empty: whitespace,
ST.number: numeric,
ST.comma: comma,
ST.equalSign: equalSign,
ST.colon: colon,
ST.identifier: alphanumeric,
};
class Parser {
Parser(
this.messageId,
this.filename,
this.messageString,
{
this.useEscaping = false,
this.logger,
this.placeholders,
}
);
final String messageId;
final String messageString;
final String filename;
final bool useEscaping;
final Logger? logger;
final List<String>? placeholders;
static String indentForError(int position) {
return '${List<String>.filled(position, ' ').join()}^';
}
// Lexes the message into a list of typed tokens. General idea is that
// every instance of "{" and "}" toggles the isString boolean and every
// instance of "'" toggles the isEscaped boolean (and treats a double
// single quote "''" as a single quote "'"). When !isString and !isEscaped
// delimit tokens by whitespace and special characters. When placeholders
// is passed, relax the syntax so that "{" and "}" can be used as strings in
// certain cases.
List<Node> lexIntoTokens() {
final bool useRelaxedLexer = placeholders != null;
final List<Node> tokens = <Node>[];
bool isString = true;
// Index specifying where to match from
int startIndex = 0;
int depth = 0;
// At every iteration, we should be able to match a new token until we
// reach the end of the string. If for some reason we don't match a
// token in any iteration of the loop, throw an error.
while (startIndex < messageString.length) {
Match? match;
if (isString) {
if (useEscaping) {
// This case is slightly involved. Essentially, wrapping any syntax in
// single quotes escapes the syntax except when there are consecutive pair of single
// quotes. For example, "Hello! 'Flutter''s amazing'. { unescapedPlaceholder }"
// converts the '' in "Flutter's" to a single quote for convenience, since technically,
// we should interpret this as two strings 'Flutter' and 's amazing'. To get around this,
// we also check if the previous character is a ', and if so, add a single quote at the beginning
// of the token.
match = escapedString.matchAsPrefix(messageString, startIndex);
if (match != null) {
final String string = match.group(0)!;
if (string == "''") {
tokens.add(Node.string(startIndex, "'"));
} else if (startIndex > 1 && messageString[startIndex - 1] == "'") {
// Include a single quote in the beginning of the token.
tokens.add(Node.string(startIndex, string.substring(0, string.length - 1)));
} else {
tokens.add(Node.string(startIndex, string.substring(1, string.length - 1)));
}
startIndex = match.end;
continue;
}
match = unescapedString.matchAsPrefix(messageString, startIndex);
if (match != null) {
tokens.add(Node.string(startIndex, match.group(0)!));
startIndex = match.end;
continue;
}
} else {
match = normalString.matchAsPrefix(messageString, startIndex);
if (match != null) {
tokens.add(Node.string(startIndex, match.group(0)!));
startIndex = match.end;
continue;
}
}
match = brace.matchAsPrefix(messageString, startIndex);
if (match != null) {
final String matchedBrace = match.group(0)!;
if (useRelaxedLexer) {
final Match? whitespaceMatch = whitespace.matchAsPrefix(messageString, match.end);
final int endOfWhitespace = whitespaceMatch?.group(0) == null ? match.end : whitespaceMatch!.end;
final Match? identifierMatch = alphanumeric.matchAsPrefix(messageString, endOfWhitespace);
// If we match a "}" and the depth is 0, treat it as a string.
// If we match a "{" and the next token is not a valid placeholder, treat it as a string.
if (matchedBrace == '}' && depth == 0) {
tokens.add(Node.string(startIndex, matchedBrace));
startIndex = match.end;
continue;
}
if (matchedBrace == '{' && (identifierMatch == null || !placeholders!.contains(identifierMatch.group(0)))) {
tokens.add(Node.string(startIndex, matchedBrace));
startIndex = match.end;
continue;
}
}
tokens.add(Node.brace(startIndex, match.group(0)!));
isString = false;
startIndex = match.end;
depth += 1;
continue;
}
// Theoretically, we only reach this point because of unmatched single quotes because
// 1. If it begins with single quotes, then we match the longest string contained in single quotes.
// 2. If it begins with braces, then we match those braces.
// 3. Else the first character is neither single quote or brace so it is matched by RegExp "unescapedString"
throw L10nParserException(
'ICU Lexing Error: Unmatched single quotes.',
filename,
messageId,
messageString,
startIndex,
);
} else {
RegExp matcher;
ST? matchedType;
// Try to match tokens until we succeed
for (matchedType in matchers.keys) {
matcher = matchers[matchedType]!;
match = matcher.matchAsPrefix(messageString, startIndex);
if (match != null) {
break;
}
}
if (match == null) {
match = brace.matchAsPrefix(messageString, startIndex);
if (match != null) {
final String matchedBrace = match.group(0)!;
tokens.add(Node.brace(startIndex, matchedBrace));
isString = true;
startIndex = match.end;
if (matchedBrace == '{') {
depth += 1;
} else {
depth -= 1;
}
continue;
}
// This should only happen when there are special characters we are unable to match.
throw L10nParserException(
'ICU Lexing Error: Unexpected character.',
filename,
messageId,
messageString,
startIndex
);
} else if (matchedType == ST.empty) {
// Do not add whitespace as a token.
startIndex = match.end;
continue;
} else if (<ST>[ST.identifier].contains(matchedType) && tokens.last.type == ST.openBrace) {
// Treat any token as identifier if it comes right after an open brace, whether it's a keyword or not.
tokens.add(Node(ST.identifier, startIndex, value: match.group(0)));
startIndex = match.end;
continue;
} else {
// Handle keywords separately. Otherwise, lexer will assume parts of identifiers may be keywords.
final String tokenStr = match.group(0)!;
switch (tokenStr) {
case 'plural':
matchedType = ST.plural;
case 'select':
matchedType = ST.select;
case 'other':
matchedType = ST.other;
case 'date':
matchedType = ST.date;
case 'time':
matchedType = ST.time;
}
tokens.add(Node(matchedType!, startIndex, value: match.group(0)));
startIndex = match.end;
continue;
}
}
}
return tokens;
}
Node parseIntoTree() {
final List<Node> tokens = lexIntoTokens();
final List<ST> parsingStack = <ST>[ST.message];
final Node syntaxTree = Node(ST.empty, 0, expectedSymbolCount: 1);
final List<Node> treeTraversalStack = <Node>[syntaxTree];
// Helper function for parsing and constructing tree.
void parseAndConstructNode(ST nonterminal, int ruleIndex) {
final Node parent = treeTraversalStack.last;
final List<ST> grammarRule = grammar[nonterminal]![ruleIndex];
// When we run out of tokens, just use -1 to represent the last index.
final int positionInMessage = tokens.isNotEmpty ? tokens.first.positionInMessage : -1;
final Node node = Node(nonterminal, positionInMessage, expectedSymbolCount: grammarRule.length);
parsingStack.addAll(grammarRule.reversed);
// For tree construction, add nodes to the parent until the parent has all
// the children it is expecting.
parent.children.add(node);
if (parent.isFull) {
treeTraversalStack.removeLast();
}
treeTraversalStack.add(node);
}
while (parsingStack.isNotEmpty) {
final ST symbol = parsingStack.removeLast();
// Figure out which production rule to use.
switch (symbol) {
case ST.message:
if (tokens.isEmpty) {
parseAndConstructNode(ST.message, 5);
} else if (tokens[0].type == ST.closeBrace) {
parseAndConstructNode(ST.message, 5);
} else if (tokens[0].type == ST.string) {
parseAndConstructNode(ST.message, 0);
} else if (tokens[0].type == ST.openBrace) {
if (3 < tokens.length && tokens[3].type == ST.plural) {
parseAndConstructNode(ST.message, 2);
} else if (3 < tokens.length && tokens[3].type == ST.select) {
parseAndConstructNode(ST.message, 3);
} else if (3 < tokens.length && (tokens[3].type == ST.date || tokens[3].type == ST.time)) {
parseAndConstructNode(ST.message, 4);
} else {
parseAndConstructNode(ST.message, 1);
}
} else {
// Theoretically, we can never get here.
throw L10nException('ICU Syntax Error.');
}
case ST.placeholderExpr:
parseAndConstructNode(ST.placeholderExpr, 0);
case ST.argumentExpr:
parseAndConstructNode(ST.argumentExpr, 0);
case ST.argType:
if (tokens.isNotEmpty && tokens[0].type == ST.date) {
parseAndConstructNode(ST.argType, 0);
} else if (tokens.isNotEmpty && tokens[0].type == ST.time) {
parseAndConstructNode(ST.argType, 1);
} else {
throw L10nException('ICU Syntax Error. Found unknown argument type.');
}
case ST.pluralExpr:
parseAndConstructNode(ST.pluralExpr, 0);
case ST.pluralParts:
if (tokens.isNotEmpty && (
tokens[0].type == ST.identifier ||
tokens[0].type == ST.other ||
tokens[0].type == ST.equalSign
)
) {
parseAndConstructNode(ST.pluralParts, 0);
} else {
parseAndConstructNode(ST.pluralParts, 1);
}
case ST.pluralPart:
if (tokens.isNotEmpty && tokens[0].type == ST.identifier) {
parseAndConstructNode(ST.pluralPart, 0);
} else if (tokens.isNotEmpty && tokens[0].type == ST.equalSign) {
parseAndConstructNode(ST.pluralPart, 1);
} else if (tokens.isNotEmpty && tokens[0].type == ST.other) {
parseAndConstructNode(ST.pluralPart, 2);
} else {
throw L10nParserException(
'ICU Syntax Error: Plural parts must be of the form "identifier { message }" or "= number { message }"',
filename,
messageId,
messageString,
tokens[0].positionInMessage,
);
}
case ST.selectExpr:
parseAndConstructNode(ST.selectExpr, 0);
case ST.selectParts:
if (tokens.isNotEmpty && (
tokens[0].type == ST.identifier ||
tokens[0].type == ST.number ||
tokens[0].type == ST.other
)) {
parseAndConstructNode(ST.selectParts, 0);
} else {
parseAndConstructNode(ST.selectParts, 1);
}
case ST.selectPart:
if (tokens.isNotEmpty && tokens[0].type == ST.identifier) {
parseAndConstructNode(ST.selectPart, 0);
} else if (tokens.isNotEmpty && tokens[0].type == ST.number) {
parseAndConstructNode(ST.selectPart, 1);
} else if (tokens.isNotEmpty && tokens[0].type == ST.other) {
parseAndConstructNode(ST.selectPart, 2);
} else {
throw L10nParserException(
'ICU Syntax Error: Select parts must be of the form "identifier { message }"',
filename,
messageId,
messageString,
tokens[0].positionInMessage
);
}
// At this point, we are only handling terminal symbols.
// ignore: no_default_cases
default:
final Node parent = treeTraversalStack.last;
// If we match a terminal symbol, then remove it from tokens and
// add it to the tree.
if (symbol == ST.empty) {
parent.children.add(Node.empty(-1));
} else if (tokens.isEmpty) {
throw L10nParserException(
'ICU Syntax Error: Expected "${terminalTypeToString[symbol]}" but found no tokens.',
filename,
messageId,
messageString,
messageString.length + 1,
);
} else if (symbol == tokens[0].type) {
final Node token = tokens.removeAt(0);
parent.children.add(token);
} else {
throw L10nParserException(
'ICU Syntax Error: Expected "${terminalTypeToString[symbol]}" but found "${tokens[0].value}".',
filename,
messageId,
messageString,
tokens[0].positionInMessage,
);
}
if (parent.isFull) {
treeTraversalStack.removeLast();
}
}
}
return syntaxTree.children[0];
}
final Map<ST, String> terminalTypeToString = <ST, String>{
ST.openBrace: '{',
ST.closeBrace: '}',
ST.comma: ',',
ST.empty: '',
ST.identifier: 'identifier',
ST.number: 'number',
ST.plural: 'plural',
ST.select: 'select',
ST.equalSign: '=',
ST.other: 'other',
};
// Compress the syntax tree.
//
// After `parse(lex(message))`, the individual parts (`ST.string`,
// `ST.placeholderExpr`, `ST.pluralExpr`, and `ST.selectExpr`) are structured
// as a linked list (see diagram below). This function compresses these parts
// into a single children array (and does this for `ST.pluralParts` and
// `ST.selectParts` as well). Then it checks extra syntax rules. Essentially, it
// converts:
//
// Message
// / \
// PluralExpr Message
// / \
// String Message
// / \
// SelectExpr ...
//
// ...to:
//
// Message
// / | \
// PluralExpr String SelectExpr ...
//
// Keep in mind that this modifies the tree in place and the values of
// expectedSymbolCount and isFull is no longer useful after this operation.
Node compress(Node syntaxTree) {
Node node = syntaxTree;
final List<Node> children = <Node>[];
switch (syntaxTree.type) {
case ST.message:
case ST.pluralParts:
case ST.selectParts:
while (node.children.length == 2) {
children.add(node.children[0]);
compress(node.children[0]);
node = node.children[1];
}
syntaxTree.children = children;
// ignore: no_default_cases
default:
node.children.forEach(compress);
}
return syntaxTree;
}
// Takes in a compressed syntax tree and checks extra rules on
// plural parts and select parts.
void checkExtraRules(Node syntaxTree) {
final List<Node> children = syntaxTree.children;
switch (syntaxTree.type) {
case ST.pluralParts:
// Must have an "other" case.
if (children.every((Node node) => node.children[0].type != ST.other)) {
throw L10nParserException(
'ICU Syntax Error: Plural expressions must have an "other" case.',
filename,
messageId,
messageString,
syntaxTree.positionInMessage
);
}
// Identifier must be one of "zero", "one", "two", "few", "many".
for (final Node node in children) {
final Node pluralPartFirstToken = node.children[0];
const List<String> validIdentifiers = <String>['zero', 'one', 'two', 'few', 'many'];
if (pluralPartFirstToken.type == ST.identifier && !validIdentifiers.contains(pluralPartFirstToken.value)) {
throw L10nParserException(
'ICU Syntax Error: Plural expressions case must be one of "zero", "one", "two", "few", "many", or "other".',
filename,
messageId,
messageString,
node.positionInMessage,
);
}
}
case ST.selectParts:
if (children.every((Node node) => node.children[0].type != ST.other)) {
throw L10nParserException(
'ICU Syntax Error: Select expressions must have an "other" case.',
filename,
messageId,
messageString,
syntaxTree.positionInMessage,
);
}
// ignore: no_default_cases
default:
break;
}
children.forEach(checkExtraRules);
}
Node parse() {
final Node syntaxTree = compress(parseIntoTree());
checkExtraRules(syntaxTree);
return syntaxTree;
}
}
| flutter/packages/flutter_tools/lib/src/localizations/message_parser.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/localizations/message_parser.dart",
"repo_id": "flutter",
"token_count": 10070
} | 781 |
// 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 '../cmake_project.dart';
// CMake's add_custom_command() should use VERBATIM to handle escaping of spaces
// and special characters correctly.
// See https://github.com/flutter/flutter/issues/67270.
class CmakeCustomCommandMigration extends ProjectMigrator {
CmakeCustomCommandMigration(CmakeBasedProject project, super.logger)
: _cmakeFile = project.managedCmakeFile;
final File _cmakeFile;
@override
void migrate() {
if (!_cmakeFile.existsSync()) {
logger.printTrace('CMake project not found, skipping add_custom_command() VERBATIM migration');
return;
}
final String originalProjectContents = _cmakeFile.readAsStringSync();
// Example:
//
// add_custom_command(
// OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS}
// ${CMAKE_CURRENT_BINARY_DIR}/_phony_
// COMMAND ${CMAKE_COMMAND} -E env
// ${FLUTTER_TOOL_ENVIRONMENT}
// "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh"
// linux-x64 ${CMAKE_BUILD_TYPE}
// )
// Match the whole add_custom_command() and append VERBATIM unless it
// already exists.
final RegExp addCustomCommand = RegExp(
r'add_custom_command\(\s*(.*?)\s*\)',
multiLine: true,
dotAll: true,
);
String newProjectContents = originalProjectContents;
final Iterable<RegExpMatch> matches = addCustomCommand.allMatches(originalProjectContents);
for (final RegExpMatch match in matches) {
final String? addCustomCommandOriginal = match.group(1);
if (addCustomCommandOriginal != null && !addCustomCommandOriginal.contains('VERBATIM')) {
final String addCustomCommandReplacement = '$addCustomCommandOriginal\n VERBATIM';
newProjectContents = newProjectContents.replaceAll(addCustomCommandOriginal, addCustomCommandReplacement);
}
// CMake's add_custom_command() should add FLUTTER_TARGET_PLATFORM to support multi-architecture.
// However, developers would get the following warning every time if we do nothing.
// ------------------------------
// CMake Warning:
// Manually-specified variables were not used by the project:
// FLUTTER_TARGET_PLATFORM
// ------------------------------
if (addCustomCommandOriginal?.contains('linux-x64') ?? false) {
newProjectContents = newProjectContents.replaceAll('linux-x64', r'${FLUTTER_TARGET_PLATFORM}');
}
}
if (originalProjectContents != newProjectContents) {
logger.printStatus('add_custom_command() missing VERBATIM or FLUTTER_TARGET_PLATFORM, updating.');
_cmakeFile.writeAsStringSync(newProjectContents);
}
}
}
| flutter/packages/flutter_tools/lib/src/migrations/cmake_custom_command_migration.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/migrations/cmake_custom_command_migration.dart",
"repo_id": "flutter",
"token_count": 1021
} | 782 |
// 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 'base/io.dart';
import 'base/logger.dart';
import 'device.dart';
import 'device_port_forwarder.dart';
import 'globals.dart' as globals;
/// Discovers a specific service protocol on a device, and forwards the service
/// protocol device port to the host.
class ProtocolDiscovery {
ProtocolDiscovery._(
this.logReader,
this.serviceName, {
this.portForwarder,
required this.throttleDuration,
this.hostPort,
this.devicePort,
required bool ipv6,
required Logger logger,
}) : _logger = logger,
_ipv6 = ipv6 {
_deviceLogSubscription = logReader.logLines.listen(
_handleLine,
onDone: _stopScrapingLogs,
);
}
factory ProtocolDiscovery.vmService(
DeviceLogReader logReader, {
DevicePortForwarder? portForwarder,
Duration? throttleDuration,
int? hostPort,
int? devicePort,
required bool ipv6,
required Logger logger,
}) {
const String kVmServiceService = 'VM Service';
return ProtocolDiscovery._(
logReader,
kVmServiceService,
portForwarder: portForwarder,
throttleDuration: throttleDuration ?? const Duration(milliseconds: 200),
hostPort: hostPort,
devicePort: devicePort,
ipv6: ipv6,
logger: logger,
);
}
final DeviceLogReader logReader;
final String serviceName;
final DevicePortForwarder? portForwarder;
final int? hostPort;
final int? devicePort;
final bool _ipv6;
final Logger _logger;
/// The time to wait before forwarding a new VM Service URIs from [logReader].
final Duration throttleDuration;
StreamSubscription<String>? _deviceLogSubscription;
final _BufferedStreamController<Uri> _uriStreamController = _BufferedStreamController<Uri>();
/// The discovered service URL.
///
/// Returns null if the log reader shuts down before any uri is found.
///
/// Use [uris] instead.
// TODO(egarciad): replace `uri` for `uris`.
Future<Uri?> get uri async {
try {
return await uris.first;
} on StateError {
return null;
}
}
/// The discovered service URLs.
///
/// When a new VM Service URL: is available in [logReader],
/// the URLs are forwarded at most once every [throttleDuration].
/// Returns when no event has been observed for [throttleTimeout].
///
/// Port forwarding is only attempted when this is invoked,
/// for each VM Service URL in the stream.
Stream<Uri> get uris {
final Stream<Uri> uriStream = _uriStreamController.stream
.transform(_throttle<Uri>(
waitDuration: throttleDuration,
));
return uriStream.asyncMap<Uri>(_forwardPort);
}
Future<void> cancel() => _stopScrapingLogs();
Future<void> _stopScrapingLogs() async {
await _uriStreamController.close();
await _deviceLogSubscription?.cancel();
_deviceLogSubscription = null;
}
Match? _getPatternMatch(String line) {
return globals.kVMServiceMessageRegExp.firstMatch(line);
}
Uri? _getVmServiceUri(String line) {
final Match? match = _getPatternMatch(line);
if (match != null) {
return Uri.parse(match[1]!);
}
return null;
}
void _handleLine(String line) {
Uri? uri;
try {
uri = _getVmServiceUri(line);
} on FormatException catch (error, stackTrace) {
_uriStreamController.addError(error, stackTrace);
}
if (uri == null || uri.host.isEmpty) {
return;
}
if (devicePort != null && uri.port != devicePort) {
_logger.printTrace('skipping potential VM Service $uri due to device port mismatch');
return;
}
_uriStreamController.add(uri);
}
Future<Uri> _forwardPort(Uri deviceUri) async {
_logger.printTrace('$serviceName URL on device: $deviceUri');
Uri hostUri = deviceUri;
final DevicePortForwarder? forwarder = portForwarder;
if (forwarder != null) {
final int actualDevicePort = deviceUri.port;
final int actualHostPort = await forwarder.forward(actualDevicePort, hostPort: hostPort);
_logger.printTrace('Forwarded host port $actualHostPort to device port $actualDevicePort for $serviceName');
hostUri = deviceUri.replace(port: actualHostPort);
}
if (InternetAddress(hostUri.host).isLoopback && _ipv6) {
hostUri = hostUri.replace(host: InternetAddress.loopbackIPv6.host);
}
return hostUri;
}
}
/// Provides a broadcast stream controller that buffers the events
/// if there isn't a listener attached.
/// The events are then delivered when a listener is attached to the stream.
class _BufferedStreamController<T> {
_BufferedStreamController() : _events = <dynamic>[];
/// The stream that this controller is controlling.
Stream<T> get stream {
return _streamController.stream;
}
late final StreamController<T> _streamController = () {
final StreamController<T> streamControllerInstance = StreamController<T>.broadcast();
streamControllerInstance.onListen = () {
for (final dynamic event in _events) {
if (event is T) {
streamControllerInstance.add(event);
} else {
streamControllerInstance.addError(
(event as Iterable<dynamic>).first as Object,
event.last as StackTrace,
);
}
}
_events.clear();
};
return streamControllerInstance;
}();
final List<dynamic> _events;
/// Sends [event] if there is a listener attached to the broadcast stream.
/// Otherwise, it enqueues [event] until a listener is attached.
void add(T event) {
if (_streamController.hasListener) {
_streamController.add(event);
} else {
_events.add(event);
}
}
/// Sends or enqueues an error event.
void addError(Object error, [StackTrace? stackTrace]) {
if (_streamController.hasListener) {
_streamController.addError(error, stackTrace);
} else {
_events.add(<dynamic>[error, stackTrace]);
}
}
/// Closes the stream.
Future<void> close() {
return _streamController.close();
}
}
/// This transformer will produce an event at most once every [waitDuration].
///
/// For example, consider a `waitDuration` of `10ms`, and list of event names
/// and arrival times: `a (0ms), b (5ms), c (11ms), d (21ms)`.
/// The events `a`, `c`, and `d` will be produced as a result.
StreamTransformer<S, S> _throttle<S>({
required Duration waitDuration,
}) {
S latestLine;
int? lastExecution;
Future<void>? throttleFuture;
bool done = false;
return StreamTransformer<S, S>
.fromHandlers(
handleData: (S value, EventSink<S> sink) {
latestLine = value;
final bool isFirstMessage = lastExecution == null;
final int currentTime = DateTime.now().millisecondsSinceEpoch;
lastExecution ??= currentTime;
final int remainingTime = currentTime - lastExecution!;
// Always send the first event immediately.
final int nextExecutionTime = isFirstMessage || remainingTime > waitDuration.inMilliseconds
? 0
: waitDuration.inMilliseconds - remainingTime;
throttleFuture ??= Future<void>
.delayed(Duration(milliseconds: nextExecutionTime))
.whenComplete(() {
if (done) {
return;
}
sink.add(latestLine);
throttleFuture = null;
lastExecution = DateTime.now().millisecondsSinceEpoch;
});
},
handleDone: (EventSink<S> sink) {
done = true;
sink.close();
}
);
}
| flutter/packages/flutter_tools/lib/src/protocol_discovery.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/protocol_discovery.dart",
"repo_id": "flutter",
"token_count": 2784
} | 783 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:dds/dds.dart' as dds;
import 'package:meta/meta.dart';
import 'package:package_config/package_config.dart';
import 'package:vm_service/vm_service.dart' as vm_service;
import 'application_package.dart';
import 'artifacts.dart';
import 'asset.dart';
import 'base/command_help.dart';
import 'base/common.dart';
import 'base/context.dart';
import 'base/file_system.dart';
import 'base/io.dart' as io;
import 'base/logger.dart';
import 'base/platform.dart';
import 'base/signals.dart';
import 'base/terminal.dart';
import 'base/utils.dart';
import 'build_info.dart';
import 'build_system/build_system.dart';
import 'build_system/tools/scene_importer.dart';
import 'build_system/tools/shader_compiler.dart';
import 'bundle.dart';
import 'cache.dart';
import 'compile.dart';
import 'convert.dart';
import 'devfs.dart';
import 'device.dart';
import 'globals.dart' as globals;
import 'ios/application_package.dart';
import 'ios/devices.dart';
import 'project.dart';
import 'resident_devtools_handler.dart';
import 'run_cold.dart';
import 'run_hot.dart';
import 'sksl_writer.dart';
import 'vmservice.dart';
class FlutterDevice {
FlutterDevice(
this.device, {
required this.buildInfo,
TargetModel targetModel = TargetModel.flutter,
this.targetPlatform,
ResidentCompiler? generator,
this.userIdentifier,
required this.developmentShaderCompiler,
this.developmentSceneImporter,
}) : generator = generator ?? ResidentCompiler(
globals.artifacts!.getArtifactPath(
Artifact.flutterPatchedSdkPath,
platform: targetPlatform,
mode: buildInfo.mode,
),
buildMode: buildInfo.mode,
trackWidgetCreation: buildInfo.trackWidgetCreation,
fileSystemRoots: buildInfo.fileSystemRoots,
fileSystemScheme: buildInfo.fileSystemScheme,
targetModel: targetModel,
dartDefines: buildInfo.dartDefines,
packagesPath: buildInfo.packagesPath,
frontendServerStarterPath: buildInfo.frontendServerStarterPath,
extraFrontEndOptions: buildInfo.extraFrontEndOptions,
artifacts: globals.artifacts!,
processManager: globals.processManager,
logger: globals.logger,
platform: globals.platform,
fileSystem: globals.fs,
);
/// Create a [FlutterDevice] with optional code generation enabled.
static Future<FlutterDevice> create(
Device device, {
required String? target,
required BuildInfo buildInfo,
required Platform platform,
TargetModel targetModel = TargetModel.flutter,
List<String>? experimentalFlags,
String? userIdentifier,
}) async {
final TargetPlatform targetPlatform = await device.targetPlatform;
if (device.platformType == PlatformType.fuchsia) {
targetModel = TargetModel.flutterRunner;
}
final DevelopmentShaderCompiler shaderCompiler = DevelopmentShaderCompiler(
shaderCompiler: ShaderCompiler(
artifacts: globals.artifacts!,
logger: globals.logger,
processManager: globals.processManager,
fileSystem: globals.fs,
),
fileSystem: globals.fs,
);
final DevelopmentSceneImporter sceneImporter = DevelopmentSceneImporter(
sceneImporter: SceneImporter(
artifacts: globals.artifacts!,
logger: globals.logger,
processManager: globals.processManager,
fileSystem: globals.fs,
),
fileSystem: globals.fs,
);
final ResidentCompiler generator;
// For both web and non-web platforms we initialize dill to/from
// a shared location for faster bootstrapping. If the compiler fails
// due to a kernel target or version mismatch, no error is reported
// and the compiler starts up as normal. Unexpected errors will print
// a warning message and dump some debug information which can be
// used to file a bug, but the compiler will still start up correctly.
if (targetPlatform == TargetPlatform.web_javascript) {
// TODO(zanderso): consistently provide these flags across platforms.
final String platformDillName;
final List<String> extraFrontEndOptions = List<String>.of(buildInfo.extraFrontEndOptions);
switch (buildInfo.nullSafetyMode) {
case NullSafetyMode.unsound:
platformDillName = 'ddc_outline.dill';
if (!extraFrontEndOptions.contains('--no-sound-null-safety')) {
extraFrontEndOptions.add('--no-sound-null-safety');
}
case NullSafetyMode.sound:
platformDillName = 'ddc_outline_sound.dill';
if (!extraFrontEndOptions.contains('--sound-null-safety')) {
extraFrontEndOptions.add('--sound-null-safety');
}
case NullSafetyMode.autodetect:
throw StateError(
'Expected buildInfo.nullSafetyMode to be one of unsound or sound, '
'got NullSafetyMode.autodetect',
);
}
final String platformDillPath = globals.fs.path.join(
globals.artifacts!.getHostArtifact(HostArtifact.webPlatformKernelFolder).path,
platformDillName,
);
generator = ResidentCompiler(
globals.artifacts!.getHostArtifact(HostArtifact.flutterWebSdk).path,
buildMode: buildInfo.mode,
trackWidgetCreation: buildInfo.trackWidgetCreation,
fileSystemRoots: buildInfo.fileSystemRoots,
// Override the filesystem scheme so that the frontend_server can find
// the generated entrypoint code.
fileSystemScheme: 'org-dartlang-app',
initializeFromDill: buildInfo.initializeFromDill ?? getDefaultCachedKernelPath(
trackWidgetCreation: buildInfo.trackWidgetCreation,
dartDefines: buildInfo.dartDefines,
extraFrontEndOptions: extraFrontEndOptions,
),
assumeInitializeFromDillUpToDate: buildInfo.assumeInitializeFromDillUpToDate,
targetModel: TargetModel.dartdevc,
frontendServerStarterPath: buildInfo.frontendServerStarterPath,
extraFrontEndOptions: extraFrontEndOptions,
platformDill: globals.fs.file(platformDillPath).absolute.uri.toString(),
dartDefines: buildInfo.dartDefines,
librariesSpec: globals.fs.file(globals.artifacts!
.getHostArtifact(HostArtifact.flutterWebLibrariesJson)).uri.toString(),
packagesPath: buildInfo.packagesPath,
artifacts: globals.artifacts!,
processManager: globals.processManager,
logger: globals.logger,
fileSystem: globals.fs,
platform: platform,
);
} else {
List<String> extraFrontEndOptions = buildInfo.extraFrontEndOptions;
extraFrontEndOptions = <String>[
'--enable-experiment=alternative-invalidation-strategy',
...extraFrontEndOptions,
];
generator = ResidentCompiler(
globals.artifacts!.getArtifactPath(
Artifact.flutterPatchedSdkPath,
platform: targetPlatform,
mode: buildInfo.mode,
),
buildMode: buildInfo.mode,
trackWidgetCreation: buildInfo.trackWidgetCreation,
fileSystemRoots: buildInfo.fileSystemRoots,
fileSystemScheme: buildInfo.fileSystemScheme,
targetModel: targetModel,
dartDefines: buildInfo.dartDefines,
frontendServerStarterPath: buildInfo.frontendServerStarterPath,
extraFrontEndOptions: extraFrontEndOptions,
initializeFromDill: buildInfo.initializeFromDill ?? getDefaultCachedKernelPath(
trackWidgetCreation: buildInfo.trackWidgetCreation,
dartDefines: buildInfo.dartDefines,
extraFrontEndOptions: extraFrontEndOptions,
),
assumeInitializeFromDillUpToDate: buildInfo.assumeInitializeFromDillUpToDate,
packagesPath: buildInfo.packagesPath,
artifacts: globals.artifacts!,
processManager: globals.processManager,
logger: globals.logger,
platform: platform,
fileSystem: globals.fs,
);
}
return FlutterDevice(
device,
targetModel: targetModel,
targetPlatform: targetPlatform,
generator: generator,
buildInfo: buildInfo,
userIdentifier: userIdentifier,
developmentShaderCompiler: shaderCompiler,
developmentSceneImporter: sceneImporter,
);
}
final TargetPlatform? targetPlatform;
final Device? device;
final ResidentCompiler? generator;
final BuildInfo buildInfo;
final String? userIdentifier;
final DevelopmentShaderCompiler developmentShaderCompiler;
final DevelopmentSceneImporter? developmentSceneImporter;
DevFSWriter? devFSWriter;
Stream<Uri?>? vmServiceUris;
FlutterVmService? vmService;
DevFS? devFS;
ApplicationPackage? package;
StreamSubscription<String>? _loggingSubscription;
bool? _isListeningForVmServiceUri;
/// Whether the stream [vmServiceUris] is still open.
bool get isWaitingForVmService => _isListeningForVmServiceUri ?? false;
/// If the [reloadSources] parameter is not null the 'reloadSources' service
/// will be registered.
/// The 'reloadSources' service can be used by other Service Protocol clients
/// connected to the VM (e.g. VmService) to request a reload of the source
/// code of the running application (a.k.a. HotReload).
/// The 'compileExpression' service can be used to compile user-provided
/// expressions requested during debugging of the application.
/// This ensures that the reload process follows the normal orchestration of
/// the Flutter Tools and not just the VM internal service.
Future<void> connect({
ReloadSources? reloadSources,
Restart? restart,
CompileExpression? compileExpression,
GetSkSLMethod? getSkSLMethod,
PrintStructuredErrorLogMethod? printStructuredErrorLogMethod,
int? hostVmServicePort,
int? ddsPort,
bool disableServiceAuthCodes = false,
bool cacheStartupProfile = false,
bool enableDds = true,
required bool allowExistingDdsInstance,
bool ipv6 = false,
}) {
final Completer<void> completer = Completer<void>();
late StreamSubscription<void> subscription;
bool isWaitingForVm = false;
subscription = vmServiceUris!.listen((Uri? vmServiceUri) async {
// FYI, this message is used as a sentinel in tests.
globals.printTrace('Connecting to service protocol: $vmServiceUri');
isWaitingForVm = true;
bool existingDds = false;
FlutterVmService? service;
if (enableDds) {
void handleError(Exception e, StackTrace st) {
globals.printTrace('Fail to connect to service protocol: $vmServiceUri: $e');
if (!completer.isCompleted) {
completer.completeError('failed to connect to $vmServiceUri', st);
}
}
// First check if the VM service is actually listening on vmServiceUri as
// this may not be the case when scraping logcat for URIs. If this URI is
// from an old application instance, we shouldn't try and start DDS.
try {
service = await connectToVmService(vmServiceUri!, logger: globals.logger);
await service.dispose();
} on Exception catch (exception) {
globals.printTrace('Fail to connect to service protocol: $vmServiceUri: $exception');
if (!completer.isCompleted && !_isListeningForVmServiceUri!) {
completer.completeError('failed to connect to $vmServiceUri');
}
return;
}
// This first try block is meant to catch errors that occur during DDS startup
// (e.g., failure to bind to a port, failure to connect to the VM service,
// attaching to a VM service with existing clients, etc.).
try {
await device!.dds.startDartDevelopmentService(
vmServiceUri,
hostPort: ddsPort,
ipv6: ipv6,
disableServiceAuthCodes: disableServiceAuthCodes,
logger: globals.logger,
cacheStartupProfile: cacheStartupProfile,
);
} on dds.DartDevelopmentServiceException catch (e, st) {
if (!allowExistingDdsInstance ||
(e.errorCode != dds.DartDevelopmentServiceException.existingDdsInstanceError)) {
handleError(e, st);
return;
} else {
existingDds = true;
}
} on ToolExit {
rethrow;
} on Exception catch (e, st) {
handleError(e, st);
return;
}
}
// This second try block handles cases where the VM service connection goes down
// before flutter_tools connects to DDS. The DDS `done` future completes when DDS
// shuts down, including after an error. If `done` completes before `connectToVmService`,
// something went wrong that caused DDS to shutdown early.
try {
service = await Future.any<dynamic>(
<Future<dynamic>>[
connectToVmService(
enableDds ? (device!.dds.uri ?? vmServiceUri!): vmServiceUri!,
reloadSources: reloadSources,
restart: restart,
compileExpression: compileExpression,
getSkSLMethod: getSkSLMethod,
flutterProject: FlutterProject.current(),
printStructuredErrorLogMethod: printStructuredErrorLogMethod,
device: device,
logger: globals.logger,
),
if (!existingDds)
device!.dds.done.whenComplete(() => throw Exception('DDS shut down too early')),
]
) as FlutterVmService?;
} on Exception catch (exception) {
globals.printTrace('Fail to connect to service protocol: $vmServiceUri: $exception');
if (!completer.isCompleted && !_isListeningForVmServiceUri!) {
completer.completeError('failed to connect to $vmServiceUri');
}
return;
}
if (completer.isCompleted) {
return;
}
globals.printTrace('Successfully connected to service protocol: $vmServiceUri');
vmService = service;
(await device!.getLogReader(app: package)).connectedVMService = vmService;
completer.complete();
await subscription.cancel();
}, onError: (dynamic error) {
globals.printTrace('Fail to handle VM Service URI: $error');
}, onDone: () {
_isListeningForVmServiceUri = false;
if (!completer.isCompleted && !isWaitingForVm) {
completer.completeError(Exception('connection to device ended too early'));
}
});
_isListeningForVmServiceUri = true;
return completer.future;
}
Future<void> exitApps({
@visibleForTesting Duration timeoutDelay = const Duration(seconds: 10),
}) async {
// TODO(zanderso): https://github.com/flutter/flutter/issues/83127
// When updating `flutter attach` to support running without a device,
// this will need to be changed to fall back to io exit.
await device!.stopApp(package, userIdentifier: userIdentifier);
}
Future<Uri?> setupDevFS(
String fsName,
Directory rootDirectory,
) {
// One devFS per device. Shared by all running instances.
devFS = DevFS(
vmService!,
fsName,
rootDirectory,
osUtils: globals.os,
fileSystem: globals.fs,
logger: globals.logger,
processManager: globals.processManager,
artifacts: globals.artifacts!,
);
return devFS!.create();
}
Future<void> startEchoingDeviceLog(DebuggingOptions debuggingOptions) async {
if (_loggingSubscription != null) {
return;
}
final Stream<String> logStream;
if (device is IOSDevice) {
logStream = (device! as IOSDevice).getLogReader(
app: package as IOSApp?,
usingCISystem: debuggingOptions.usingCISystem,
).logLines;
} else {
logStream = (await device!.getLogReader(app: package)).logLines;
}
_loggingSubscription = logStream.listen((String line) {
if (!line.contains(globals.kVMServiceMessageRegExp)) {
globals.printStatus(line, wrap: false);
}
});
}
Future<void> stopEchoingDeviceLog() async {
if (_loggingSubscription == null) {
return;
}
await _loggingSubscription!.cancel();
_loggingSubscription = null;
}
Future<void> initLogReader() async {
final vm_service.VM vm = await vmService!.service.getVM();
final DeviceLogReader logReader = await device!.getLogReader(app: package);
logReader.appPid = vm.pid;
}
Future<int> runHot({
required HotRunner hotRunner,
String? route,
}) async {
final bool prebuiltMode = hotRunner.applicationBinary != null;
final String modeName = hotRunner.debuggingOptions.buildInfo.friendlyModeName;
globals.printStatus(
'Launching ${getDisplayPath(hotRunner.mainPath, globals.fs)} '
'on ${device!.name} in $modeName mode...',
);
final TargetPlatform targetPlatform = await device!.targetPlatform;
package = await ApplicationPackageFactory.instance!.getPackageForPlatform(
targetPlatform,
buildInfo: hotRunner.debuggingOptions.buildInfo,
applicationBinary: hotRunner.applicationBinary,
);
final ApplicationPackage? applicationPackage = package;
if (applicationPackage == null) {
String message = 'No application found for $targetPlatform.';
final String? hint = await getMissingPackageHintForPlatform(targetPlatform);
if (hint != null) {
message += '\n$hint';
}
globals.printError(message);
return 1;
}
devFSWriter = device!.createDevFSWriter(applicationPackage, userIdentifier);
final Map<String, dynamic> platformArgs = <String, dynamic>{};
await startEchoingDeviceLog(hotRunner.debuggingOptions);
// Start the application.
final Future<LaunchResult> futureResult = device!.startApp(
applicationPackage,
mainPath: hotRunner.mainPath,
debuggingOptions: hotRunner.debuggingOptions,
platformArgs: platformArgs,
route: route,
prebuiltApplication: prebuiltMode,
ipv6: hotRunner.ipv6!,
userIdentifier: userIdentifier,
);
final LaunchResult result = await futureResult;
if (!result.started) {
globals.printError('Error launching application on ${device!.name}.');
await stopEchoingDeviceLog();
return 2;
}
if (result.hasVmService) {
vmServiceUris = Stream<Uri?>
.value(result.vmServiceUri)
.asBroadcastStream();
} else {
vmServiceUris = const Stream<Uri>
.empty()
.asBroadcastStream();
}
return 0;
}
Future<int> runCold({
required ColdRunner coldRunner,
String? route,
}) async {
final TargetPlatform targetPlatform = await device!.targetPlatform;
package = await ApplicationPackageFactory.instance!.getPackageForPlatform(
targetPlatform,
buildInfo: coldRunner.debuggingOptions.buildInfo,
applicationBinary: coldRunner.applicationBinary,
);
final ApplicationPackage? applicationPackage = package;
if (applicationPackage == null) {
String message = 'No application found for $targetPlatform.';
final String? hint = await getMissingPackageHintForPlatform(targetPlatform);
if (hint != null) {
message += '\n$hint';
}
globals.printError(message);
return 1;
}
devFSWriter = device!.createDevFSWriter(applicationPackage, userIdentifier);
final String modeName = coldRunner.debuggingOptions.buildInfo.friendlyModeName;
final bool prebuiltMode = coldRunner.applicationBinary != null;
globals.printStatus(
'Launching ${getDisplayPath(coldRunner.mainPath, globals.fs)} '
'on ${device!.name} in $modeName mode...',
);
final Map<String, dynamic> platformArgs = <String, dynamic>{};
platformArgs['trace-startup'] = coldRunner.traceStartup;
await startEchoingDeviceLog(coldRunner.debuggingOptions);
final LaunchResult result = await device!.startApp(
applicationPackage,
mainPath: coldRunner.mainPath,
debuggingOptions: coldRunner.debuggingOptions,
platformArgs: platformArgs,
route: route,
prebuiltApplication: prebuiltMode,
ipv6: coldRunner.ipv6!,
userIdentifier: userIdentifier,
);
if (!result.started) {
globals.printError('Error running application on ${device!.name}.');
await stopEchoingDeviceLog();
return 2;
}
if (result.hasVmService) {
vmServiceUris = Stream<Uri?>
.value(result.vmServiceUri)
.asBroadcastStream();
} else {
vmServiceUris = const Stream<Uri>
.empty()
.asBroadcastStream();
}
return 0;
}
Future<UpdateFSReport> updateDevFS({
required Uri mainUri,
String? target,
AssetBundle? bundle,
bool bundleFirstUpload = false,
bool bundleDirty = false,
bool fullRestart = false,
required String pathToReload,
required String dillOutputPath,
required List<Uri> invalidatedFiles,
required PackageConfig packageConfig,
}) async {
final Status devFSStatus = globals.logger.startProgress(
'Syncing files to device ${device!.name}...',
);
UpdateFSReport report;
try {
report = await devFS!.update(
mainUri: mainUri,
target: target,
bundle: bundle,
bundleFirstUpload: bundleFirstUpload,
generator: generator!,
fullRestart: fullRestart,
dillOutputPath: dillOutputPath,
trackWidgetCreation: buildInfo.trackWidgetCreation,
pathToReload: pathToReload,
invalidatedFiles: invalidatedFiles,
packageConfig: packageConfig,
devFSWriter: devFSWriter,
shaderCompiler: developmentShaderCompiler,
sceneImporter: developmentSceneImporter,
dartPluginRegistrant: FlutterProject.current().dartPluginRegistrant,
);
} on DevFSException {
devFSStatus.cancel();
return UpdateFSReport();
}
devFSStatus.stop();
globals.printTrace('Synced ${getSizeAsMB(report.syncedBytes)}.');
return report;
}
Future<void> updateReloadStatus(bool wasReloadSuccessful) async {
if (wasReloadSuccessful) {
generator?.accept();
} else {
await generator?.reject();
}
}
}
/// A subset of the [ResidentRunner] for delegating to attached flutter devices.
abstract class ResidentHandlers {
List<FlutterDevice?> get flutterDevices;
/// Whether the resident runner has hot reload and restart enabled.
bool get hotMode;
/// Whether the resident runner is connect to the device's VM Service.
bool get supportsServiceProtocol;
/// The application is running in debug mode.
bool get isRunningDebug;
/// The application is running in profile mode.
bool get isRunningProfile;
/// The application is running in release mode.
bool get isRunningRelease;
/// The resident runner should stay resident after establishing a connection with the
/// application.
bool get stayResident;
/// Whether all of the connected devices support hot restart.
///
/// To prevent scenarios where only a subset of devices are hot restarted,
/// the runner requires that all attached devices can support hot restart
/// before enabling it.
bool get supportsRestart;
/// Whether all of the connected devices support gathering SkSL.
bool get supportsWriteSkSL;
/// Whether all of the connected devices support hot reload.
bool get canHotReload;
ResidentDevtoolsHandler? get residentDevtoolsHandler;
@protected
Logger get logger;
@protected
FileSystem? get fileSystem;
/// Called to print help to the terminal.
void printHelp({ required bool details });
/// Perform a hot reload or hot restart of all attached applications.
///
/// If [fullRestart] is true, a hot restart is performed. Otherwise a hot reload
/// is run instead. On web devices, this only performs a hot restart regardless of
/// the value of [fullRestart].
Future<OperationResult> restart({ bool fullRestart = false, bool pause = false, String? reason }) {
final String mode = isRunningProfile ? 'profile' :isRunningRelease ? 'release' : 'this';
throw Exception('${fullRestart ? 'Restart' : 'Reload'} is not supported in $mode mode');
}
/// Dump the application's current widget tree to the terminal.
Future<bool> debugDumpApp() async {
if (!supportsServiceProtocol) {
return false;
}
for (final FlutterDevice? device in flutterDevices) {
final List<FlutterView> views = await device!.vmService!.getFlutterViews();
for (final FlutterView view in views) {
final String data = await device.vmService!.flutterDebugDumpApp(
isolateId: view.uiIsolate!.id!,
);
logger.printStatus(data);
}
}
return true;
}
/// Dump the application's current render tree to the terminal.
Future<bool> debugDumpRenderTree() async {
if (!supportsServiceProtocol) {
return false;
}
for (final FlutterDevice? device in flutterDevices) {
final List<FlutterView> views = await device!.vmService!.getFlutterViews();
for (final FlutterView view in views) {
final String data = await device.vmService!.flutterDebugDumpRenderTree(
isolateId: view.uiIsolate!.id!,
);
logger.printStatus(data);
}
}
return true;
}
/// Dump frame rasterization metrics for the last rendered frame.
///
/// The last frames gets re-painted while recording additional tracing info
/// pertaining to the various draw calls issued by the frame. The timings
/// recorded here are not indicative of production performance. The intended
/// use case is to look at the various layers in proportion to see what
/// contributes the most towards raster performance.
Future<bool> debugFrameJankMetrics() async {
if (!supportsServiceProtocol) {
return false;
}
for (final FlutterDevice? device in flutterDevices) {
if (device?.targetPlatform == TargetPlatform.web_javascript) {
logger.printWarning('Unable to get jank metrics for web');
continue;
}
final List<FlutterView> views = await device!.vmService!.getFlutterViews();
try {
for (final FlutterView view in views) {
final Map<String, Object?>? rasterData =
await device.vmService!.renderFrameWithRasterStats(
viewId: view.id,
uiIsolateId: view.uiIsolate!.id,
);
if (rasterData != null) {
final File tempFile = globals.fsUtils.getUniqueFile(
globals.fs.currentDirectory,
'flutter_jank_metrics',
'json',
);
tempFile.writeAsStringSync(jsonEncode(rasterData), flush: true);
logger.printStatus('Wrote jank metrics to ${tempFile.absolute.path}');
} else {
logger.printWarning('Unable to get jank metrics.');
}
}
} on vm_service.RPCError catch (err) {
if (err.code != RPCErrorCodes.kServerError || !err.message.contains('Raster status not supported on Impeller backend')) {
rethrow;
}
logger.printWarning('Unable to get jank metrics for Impeller renderer');
}
}
return true;
}
/// Dump the application's current layer tree to the terminal.
Future<bool> debugDumpLayerTree() async {
if (!supportsServiceProtocol || !isRunningDebug) {
return false;
}
for (final FlutterDevice? device in flutterDevices) {
final List<FlutterView> views = await device!.vmService!.getFlutterViews();
for (final FlutterView view in views) {
final String data = await device.vmService!.flutterDebugDumpLayerTree(
isolateId: view.uiIsolate!.id!,
);
logger.printStatus(data);
}
}
return true;
}
Future<bool> debugDumpFocusTree() async {
if (!supportsServiceProtocol || !isRunningDebug) {
return false;
}
for (final FlutterDevice? device in flutterDevices) {
final List<FlutterView> views = await device!.vmService!.getFlutterViews();
for (final FlutterView view in views) {
final String data = await device.vmService!.flutterDebugDumpFocusTree(
isolateId: view.uiIsolate!.id!,
);
logger.printStatus(data);
}
}
return true;
}
/// Dump the application's current semantics tree to the terminal.
///
/// If semantics are not enabled, nothing is returned.
Future<bool> debugDumpSemanticsTreeInTraversalOrder() async {
if (!supportsServiceProtocol) {
return false;
}
for (final FlutterDevice? device in flutterDevices) {
final List<FlutterView> views = await device!.vmService!.getFlutterViews();
for (final FlutterView view in views) {
final String data = await device.vmService!.flutterDebugDumpSemanticsTreeInTraversalOrder(
isolateId: view.uiIsolate!.id!,
);
logger.printStatus(data);
}
}
return true;
}
/// Dump the application's current semantics tree to the terminal.
///
/// If semantics are not enabled, nothing is returned.
Future<bool> debugDumpSemanticsTreeInInverseHitTestOrder() async {
if (!supportsServiceProtocol) {
return false;
}
for (final FlutterDevice? device in flutterDevices) {
final List<FlutterView> views = await device!.vmService!.getFlutterViews();
for (final FlutterView view in views) {
final String data = await device.vmService!.flutterDebugDumpSemanticsTreeInInverseHitTestOrder(
isolateId: view.uiIsolate!.id!,
);
logger.printStatus(data);
}
}
return true;
}
/// Toggle the "paint size" debugging feature.
Future<bool> debugToggleDebugPaintSizeEnabled() async {
if (!supportsServiceProtocol || !isRunningDebug) {
return false;
}
for (final FlutterDevice? device in flutterDevices) {
final List<FlutterView> views = await device!.vmService!.getFlutterViews();
for (final FlutterView view in views) {
await device.vmService!.flutterToggleDebugPaintSizeEnabled(
isolateId: view.uiIsolate!.id!,
);
}
}
return true;
}
/// Toggle the performance overlay.
///
/// This is not supported in web mode.
Future<bool> debugTogglePerformanceOverlayOverride() async {
if (!supportsServiceProtocol) {
return false;
}
for (final FlutterDevice? device in flutterDevices) {
if (device!.targetPlatform == TargetPlatform.web_javascript) {
continue;
}
final List<FlutterView> views = await device.vmService!.getFlutterViews();
for (final FlutterView view in views) {
await device.vmService!.flutterTogglePerformanceOverlayOverride(
isolateId: view.uiIsolate!.id!,
);
}
}
return true;
}
/// Toggle the widget inspector.
Future<bool> debugToggleWidgetInspector() async {
if (!supportsServiceProtocol) {
return false;
}
for (final FlutterDevice? device in flutterDevices) {
final List<FlutterView> views = await device!.vmService!.getFlutterViews();
for (final FlutterView view in views) {
await device.vmService!.flutterToggleWidgetInspector(
isolateId: view.uiIsolate!.id!,
);
}
}
return true;
}
/// Toggle the "invert images" debugging feature.
Future<bool> debugToggleInvertOversizedImages() async {
if (!supportsServiceProtocol || !isRunningDebug) {
return false;
}
for (final FlutterDevice? device in flutterDevices) {
final List<FlutterView> views = await device!.vmService!.getFlutterViews();
for (final FlutterView view in views) {
await device.vmService!.flutterToggleInvertOversizedImages(
isolateId: view.uiIsolate!.id!,
);
}
}
return true;
}
/// Toggle the "profile widget builds" debugging feature.
Future<bool> debugToggleProfileWidgetBuilds() async {
if (!supportsServiceProtocol) {
return false;
}
for (final FlutterDevice? device in flutterDevices) {
final List<FlutterView> views = await device!.vmService!.getFlutterViews();
for (final FlutterView view in views) {
await device.vmService!.flutterToggleProfileWidgetBuilds(
isolateId: view.uiIsolate!.id!,
);
}
}
return true;
}
/// Toggle the operating system brightness (light or dark).
Future<bool> debugToggleBrightness() async {
if (!supportsServiceProtocol) {
return false;
}
final List<FlutterView> views = await flutterDevices.first!.vmService!.getFlutterViews();
final Brightness? current = await flutterDevices.first!.vmService!.flutterBrightnessOverride(
isolateId: views.first.uiIsolate!.id!,
);
Brightness next;
if (current == Brightness.light) {
next = Brightness.dark;
} else {
next = Brightness.light;
}
for (final FlutterDevice? device in flutterDevices) {
final List<FlutterView> views = await device!.vmService!.getFlutterViews();
for (final FlutterView view in views) {
await device.vmService!.flutterBrightnessOverride(
isolateId: view.uiIsolate!.id!,
brightness: next,
);
}
logger.printStatus('Changed brightness to $next.');
}
return true;
}
/// Rotate the application through different `defaultTargetPlatform` values.
Future<bool> debugTogglePlatform() async {
if (!supportsServiceProtocol || !isRunningDebug) {
return false;
}
final List<FlutterView> views = await flutterDevices.first!.vmService!.getFlutterViews();
final String from = await flutterDevices
.first!.vmService!.flutterPlatformOverride(
isolateId: views.first.uiIsolate!.id!,
);
final String to = nextPlatform(from);
for (final FlutterDevice? device in flutterDevices) {
final List<FlutterView> views = await device!.vmService!.getFlutterViews();
for (final FlutterView view in views) {
await device.vmService!.flutterPlatformOverride(
platform: to,
isolateId: view.uiIsolate!.id!,
);
}
}
logger.printStatus('Switched operating system to $to');
return true;
}
/// Write the SkSL shaders to a zip file in build directory.
///
/// Returns the name of the file, or `null` on failures.
Future<String?> writeSkSL() async {
if (!supportsWriteSkSL) {
throw Exception('writeSkSL is not supported by this runner.');
}
final FlutterDevice flutterDevice = flutterDevices.first!;
final FlutterVmService vmService = flutterDevice.vmService!;
final List<FlutterView> views = await vmService.getFlutterViews();
final Map<String, Object?>? data = await vmService.getSkSLs(
viewId: views.first.id,
);
final Device device = flutterDevice.device!;
return sharedSkSlWriter(device, data);
}
/// Take a screenshot on the provided [device].
///
/// If the device has a connected vmservice, this method will attempt to hide
/// and restore the debug banner before taking the screenshot.
///
/// If the device type does not support a "native" screenshot, then this
/// will fallback to a rasterizer screenshot from the engine. This has the
/// downside of being unable to display the contents of platform views.
///
/// This method will return without writing the screenshot file if any
/// RPC errors are encountered, printing them to stderr. This is true even
/// if an error occurs after the data has already been received, such as
/// from restoring the debug banner.
Future<void> screenshot(FlutterDevice device) async {
if (!device.device!.supportsScreenshot && !supportsServiceProtocol) {
return;
}
final Status status = logger.startProgress(
'Taking screenshot for ${device.device!.name}...',
);
final File outputFile = getUniqueFile(
fileSystem!.currentDirectory,
'flutter',
'png',
);
try {
bool result;
if (device.device!.supportsScreenshot) {
result = await _toggleDebugBanner(device, () => device.device!.takeScreenshot(outputFile));
} else {
result = await _takeVmServiceScreenshot(device, outputFile);
}
if (!result) {
return;
}
final int sizeKB = outputFile.lengthSync() ~/ 1024;
status.stop();
logger.printStatus(
'Screenshot written to ${fileSystem!.path.relative(outputFile.path)} (${sizeKB}kB).',
);
} on Exception catch (error) {
status.cancel();
logger.printError('Error taking screenshot: $error');
}
}
Future<bool> _takeVmServiceScreenshot(FlutterDevice device, File outputFile) async {
if (device.targetPlatform != TargetPlatform.web_javascript) {
return false;
}
assert(supportsServiceProtocol);
return _toggleDebugBanner(device, () async {
final vm_service.Response? response = await device.vmService!.callMethodWrapper('ext.dwds.screenshot');
if (response == null) {
throw Exception('Failed to take screenshot');
}
final String data = response.json!['data'] as String;
outputFile.writeAsBytesSync(base64.decode(data));
});
}
Future<bool> _toggleDebugBanner(FlutterDevice device, Future<void> Function() cb) async {
List<FlutterView> views = <FlutterView>[];
if (supportsServiceProtocol) {
views = await device.vmService!.getFlutterViews();
}
Future<bool> setDebugBanner(bool value) async {
try {
for (final FlutterView view in views) {
await device.vmService!.flutterDebugAllowBanner(
value,
isolateId: view.uiIsolate!.id!,
);
}
return true;
} on vm_service.RPCError catch (error) {
logger.printError('Error communicating with Flutter on the device: $error');
return false;
}
}
if (!await setDebugBanner(false)) {
return false;
}
bool succeeded = true;
try {
await cb();
} finally {
if (!await setDebugBanner(true)) {
succeeded = false;
}
}
return succeeded;
}
/// Remove sigusr signal handlers.
Future<void> cleanupAfterSignal();
/// Tear down the runner and leave the application running.
///
/// This is not supported on web devices where the runner is running
/// the application server as well.
Future<void> detach();
/// Tear down the runner and exit the application.
Future<void> exit();
/// Run any source generators, such as localizations.
///
/// These are automatically run during hot restart, but can be
/// triggered manually to see the updated generated code.
Future<void> runSourceGenerators();
}
// Shared code between different resident application runners.
abstract class ResidentRunner extends ResidentHandlers {
ResidentRunner(
this.flutterDevices, {
required this.target,
required this.debuggingOptions,
String? projectRootPath,
this.ipv6,
this.stayResident = true,
this.hotMode = true,
String? dillOutputPath,
this.machine = false,
ResidentDevtoolsHandlerFactory devtoolsHandler = createDefaultHandler,
}) : mainPath = globals.fs.file(target).absolute.path,
packagesFilePath = debuggingOptions.buildInfo.packagesPath,
projectRootPath = projectRootPath ?? globals.fs.currentDirectory.path,
_dillOutputPath = dillOutputPath,
artifactDirectory = dillOutputPath == null
? globals.fs.systemTempDirectory.createTempSync('flutter_tool.')
: globals.fs.file(dillOutputPath).parent,
assetBundle = AssetBundleFactory.instance.createBundle(),
commandHelp = CommandHelp(
logger: globals.logger,
terminal: globals.terminal,
platform: globals.platform,
outputPreferences: globals.outputPreferences,
) {
if (!artifactDirectory.existsSync()) {
artifactDirectory.createSync(recursive: true);
}
_residentDevtoolsHandler = devtoolsHandler(DevtoolsLauncher.instance, this, globals.logger);
}
@override
Logger get logger => globals.logger;
@override
FileSystem get fileSystem => globals.fs;
@override
final List<FlutterDevice> flutterDevices;
final String target;
final DebuggingOptions debuggingOptions;
@override
final bool stayResident;
final bool? ipv6;
final String? _dillOutputPath;
/// The parent location of the incremental artifacts.
final Directory artifactDirectory;
final String packagesFilePath;
final String projectRootPath;
final String mainPath;
final AssetBundle assetBundle;
final CommandHelp commandHelp;
final bool machine;
@override
ResidentDevtoolsHandler? get residentDevtoolsHandler => _residentDevtoolsHandler;
ResidentDevtoolsHandler? _residentDevtoolsHandler;
bool _exited = false;
Completer<int> _finished = Completer<int>();
BuildResult? _lastBuild;
Environment? _environment;
@override
bool hotMode;
/// Returns true if every device is streaming vmService URIs.
bool get isWaitingForVmService {
return flutterDevices.every((FlutterDevice? device) {
return device!.isWaitingForVmService;
});
}
String get dillOutputPath => _dillOutputPath ?? globals.fs.path.join(artifactDirectory.path, 'app.dill');
String getReloadPath({
bool fullRestart = false,
required bool swap,
}) {
if (!fullRestart) {
return 'main.dart.incremental.dill';
}
return 'main.dart${swap ? '.swap' : ''}.dill';
}
bool get debuggingEnabled => debuggingOptions.debuggingEnabled;
@override
bool get isRunningDebug => debuggingOptions.buildInfo.isDebug;
@override
bool get isRunningProfile => debuggingOptions.buildInfo.isProfile;
@override
bool get isRunningRelease => debuggingOptions.buildInfo.isRelease;
@override
bool get supportsServiceProtocol => isRunningDebug || isRunningProfile;
@override
bool get supportsWriteSkSL => supportsServiceProtocol;
bool get trackWidgetCreation => debuggingOptions.buildInfo.trackWidgetCreation;
/// True if the shared Dart plugin registry (which is different than the one
/// used for web) should be generated during source generation.
bool get generateDartPluginRegistry => true;
// Returns the Uri of the first connected device for mobile,
// and only connected device for web.
//
// Would be null if there is no device connected or
// there is no devFS associated with the first device.
Uri? get uri => flutterDevices.first.devFS?.baseUri;
/// Returns [true] if the resident runner exited after invoking [exit()].
bool get exited => _exited;
@override
bool get supportsRestart {
return isRunningDebug && flutterDevices.every((FlutterDevice? device) {
return device!.device!.supportsHotRestart;
});
}
@override
bool get canHotReload => hotMode;
/// Start the app and keep the process running during its lifetime.
///
/// Returns the exit code that we should use for the flutter tool process; 0
/// for success, 1 for user error (e.g. bad arguments), 2 for other failures.
Future<int?> run({
Completer<DebugConnectionInfo>? connectionInfoCompleter,
Completer<void>? appStartedCompleter,
bool enableDevTools = false,
String? route,
});
/// Connect to a flutter application.
///
/// [needsFullRestart] defaults to `true`, and controls if the frontend server should
/// compile a full dill. This should be set to `false` if this is called in [ResidentRunner.run], since that method already performs an initial compilation.
Future<int?> attach({
Completer<DebugConnectionInfo>? connectionInfoCompleter,
Completer<void>? appStartedCompleter,
bool allowExistingDdsInstance = false,
bool enableDevTools = false,
bool needsFullRestart = true,
});
@override
Future<void> runSourceGenerators() async {
_environment ??= Environment(
artifacts: globals.artifacts!,
logger: globals.logger,
cacheDir: globals.cache.getRoot(),
engineVersion: globals.flutterVersion.engineRevision,
fileSystem: globals.fs,
flutterRootDir: globals.fs.directory(Cache.flutterRoot),
outputDir: globals.fs.directory(getBuildDirectory()),
processManager: globals.processManager,
platform: globals.platform,
usage: globals.flutterUsage,
analytics: globals.analytics,
projectDir: globals.fs.currentDirectory,
generateDartPluginRegistry: generateDartPluginRegistry,
defines: <String, String>{
// Needed for Dart plugin registry generation.
kTargetFile: mainPath,
},
);
final CompositeTarget compositeTarget = CompositeTarget(<Target>[
globals.buildTargets.generateLocalizationsTarget,
globals.buildTargets.dartPluginRegistrantTarget,
]);
_lastBuild = await globals.buildSystem.buildIncremental(
compositeTarget,
_environment!,
_lastBuild,
);
if (!_lastBuild!.success) {
for (final ExceptionMeasurement exceptionMeasurement in _lastBuild!.exceptions.values) {
globals.printError(
exceptionMeasurement.exception.toString(),
stackTrace: globals.logger.isVerbose
? exceptionMeasurement.stackTrace
: null,
);
}
}
globals.printTrace('complete');
}
@protected
void writeVmServiceFile() {
if (debuggingOptions.vmserviceOutFile != null) {
try {
final String address = flutterDevices.first.vmService!.wsAddress.toString();
final File vmserviceOutFile = globals.fs.file(debuggingOptions.vmserviceOutFile);
vmserviceOutFile.createSync(recursive: true);
vmserviceOutFile.writeAsStringSync(address);
} on FileSystemException {
globals.printError('Failed to write vmservice-out-file at ${debuggingOptions.vmserviceOutFile}');
}
}
}
@override
Future<void> exit() async {
_exited = true;
await residentDevtoolsHandler!.shutdown();
await stopEchoingDeviceLog();
await preExit();
await exitApp(); // calls appFinished
await shutdownDartDevelopmentService();
}
@override
Future<void> detach() async {
await residentDevtoolsHandler!.shutdown();
await stopEchoingDeviceLog();
await preExit();
await shutdownDartDevelopmentService();
appFinished();
}
Future<void> stopEchoingDeviceLog() async {
await Future.wait<void>(
flutterDevices.map<Future<void>>((FlutterDevice? device) => device!.stopEchoingDeviceLog())
);
}
Future<void> shutdownDartDevelopmentService() async {
await Future.wait<void>(
flutterDevices.map<Future<void>>(
(FlutterDevice? device) => device?.device?.dds.shutdown() ?? Future<void>.value()
)
);
}
@protected
void cacheInitialDillCompilation() {
if (_dillOutputPath != null) {
return;
}
globals.printTrace('Caching compiled dill');
final File outputDill = globals.fs.file(dillOutputPath);
if (outputDill.existsSync()) {
final String copyPath = getDefaultCachedKernelPath(
trackWidgetCreation: trackWidgetCreation,
dartDefines: debuggingOptions.buildInfo.dartDefines,
extraFrontEndOptions: debuggingOptions.buildInfo.extraFrontEndOptions,
);
globals.fs
.file(copyPath)
.parent
.createSync(recursive: true);
outputDill.copySync(copyPath);
}
}
void printStructuredErrorLog(vm_service.Event event) {
if (event.extensionKind == 'Flutter.Error' && !machine) {
final Map<String, Object?>? json = event.extensionData?.data;
if (json != null && json.containsKey('renderedErrorText')) {
final int errorsSinceReload;
if (json.containsKey('errorsSinceReload') && json['errorsSinceReload'] is int) {
errorsSinceReload = json['errorsSinceReload']! as int;
} else {
errorsSinceReload = 0;
}
if (errorsSinceReload == 0) {
// We print a blank line around the first error, to more clearly emphasize it
// in the output. (Other errors don't get this.)
globals.printStatus('');
}
globals.printStatus('${json['renderedErrorText']}');
if (errorsSinceReload == 0) {
globals.printStatus('');
}
} else {
globals.printError('Received an invalid ${globals.logger.terminal.bolden("Flutter.Error")} message from app: $json');
}
}
}
/// If the [reloadSources] parameter is not null the 'reloadSources' service
/// will be registered.
//
// Failures should be indicated by completing the future with an error, using
// a string as the error object, which will be used by the caller (attach())
// to display an error message.
Future<void> connectToServiceProtocol({
ReloadSources? reloadSources,
Restart? restart,
CompileExpression? compileExpression,
GetSkSLMethod? getSkSLMethod,
required bool allowExistingDdsInstance,
}) async {
if (!debuggingOptions.debuggingEnabled) {
throw Exception('The service protocol is not enabled.');
}
_finished = Completer<int>();
// Listen for service protocol connection to close.
for (final FlutterDevice? device in flutterDevices) {
await device!.connect(
reloadSources: reloadSources,
restart: restart,
compileExpression: compileExpression,
enableDds: debuggingOptions.enableDds,
ddsPort: debuggingOptions.ddsPort,
allowExistingDdsInstance: allowExistingDdsInstance,
hostVmServicePort: debuggingOptions.hostVmServicePort,
getSkSLMethod: getSkSLMethod,
printStructuredErrorLogMethod: printStructuredErrorLog,
ipv6: ipv6 ?? false,
disableServiceAuthCodes: debuggingOptions.disableServiceAuthCodes,
cacheStartupProfile: debuggingOptions.cacheStartupProfile,
);
await device.vmService!.getFlutterViews();
// This hooks up callbacks for when the connection stops in the future.
// We don't want to wait for them. We don't handle errors in those callbacks'
// futures either because they just print to logger and is not critical.
unawaited(device.vmService!.service.onDone.then<void>(
_serviceProtocolDone,
onError: _serviceProtocolError,
).whenComplete(_serviceDisconnected));
}
}
Future<void> _serviceProtocolDone(dynamic object) async {
globals.printTrace('Service protocol connection closed.');
}
Future<void> _serviceProtocolError(Object error, StackTrace stack) {
globals.printTrace('Service protocol connection closed with an error: $error\n$stack');
return Future<void>.error(error, stack);
}
void _serviceDisconnected() {
if (_exited) {
// User requested the application exit.
return;
}
if (_finished.isCompleted) {
return;
}
globals.printStatus('Lost connection to device.');
_finished.complete(0);
}
Future<void> enableObservatory() async {
assert(debuggingOptions.serveObservatory);
final List<Future<vm_service.Response?>> serveObservatoryRequests = <Future<vm_service.Response?>>[];
for (final FlutterDevice? device in flutterDevices) {
if (device == null) {
continue;
}
// Notify the VM service if the user wants Observatory to be served.
serveObservatoryRequests.add(
device.vmService?.callMethodWrapper('_serveObservatory') ??
Future<vm_service.Response?>.value(),
);
}
try {
await Future.wait(serveObservatoryRequests);
} on vm_service.RPCError catch (e) {
globals.printWarning('Unable to enable Observatory: $e');
}
}
void appFinished() {
if (_finished.isCompleted) {
return;
}
globals.printStatus('Application finished.');
_finished.complete(0);
}
void appFailedToStart() {
if (!_finished.isCompleted) {
_finished.complete(1);
}
}
Future<int> waitForAppToFinish() async {
final int exitCode = await _finished.future;
await cleanupAtFinish();
return exitCode;
}
@mustCallSuper
Future<void> preExit() async {
// If _dillOutputPath is null, the tool created a temporary directory for
// the dill.
if (_dillOutputPath == null && artifactDirectory.existsSync()) {
artifactDirectory.deleteSync(recursive: true);
}
}
Future<void> exitApp() async {
final List<Future<void>> futures = <Future<void>>[
for (final FlutterDevice? device in flutterDevices) device!.exitApps(),
];
await Future.wait(futures);
appFinished();
}
bool get reportedDebuggers => _reportedDebuggers;
bool _reportedDebuggers = false;
void printDebuggerList({ bool includeVmService = true, bool includeDevtools = true }) {
final DevToolsServerAddress? devToolsServerAddress = residentDevtoolsHandler!.activeDevToolsServer;
if (!residentDevtoolsHandler!.readyToAnnounce) {
includeDevtools = false;
}
assert(!includeDevtools || devToolsServerAddress != null);
for (final FlutterDevice? device in flutterDevices) {
if (device!.vmService == null) {
continue;
}
if (includeVmService) {
// Caution: This log line is parsed by device lab tests.
globals.printStatus(
'A Dart VM Service on ${device.device!.name} is available at: '
'${device.vmService!.httpAddress}',
);
}
if (includeDevtools) {
final Uri? uri = devToolsServerAddress!.uri?.replace(
queryParameters: <String, dynamic>{'uri': '${device.vmService!.httpAddress}'},
);
if (uri != null) {
globals.printStatus(
'The Flutter DevTools debugger and profiler '
'on ${device.device!.name} is available at: ${urlToDisplayString(uri)}',
);
}
}
}
_reportedDebuggers = true;
}
void printHelpDetails() {
commandHelp.v.print();
if (flutterDevices.any((FlutterDevice? d) => d!.device!.supportsScreenshot)) {
commandHelp.s.print();
}
if (supportsServiceProtocol) {
commandHelp.w.print();
commandHelp.t.print();
if (isRunningDebug) {
commandHelp.L.print();
commandHelp.f.print();
commandHelp.S.print();
commandHelp.U.print();
commandHelp.i.print();
commandHelp.p.print();
commandHelp.I.print();
commandHelp.o.print();
commandHelp.b.print();
} else {
commandHelp.S.print();
commandHelp.U.print();
}
// Performance related features: `P` should precede `a`, which should precede `M`.
commandHelp.P.print();
commandHelp.a.print();
if (supportsWriteSkSL) {
commandHelp.M.print();
}
if (isRunningDebug) {
commandHelp.g.print();
}
commandHelp.j.print();
}
}
@override
Future<void> cleanupAfterSignal();
/// Called right before we exit.
Future<void> cleanupAtFinish();
}
class OperationResult {
OperationResult(this.code, this.message, { this.fatal = false, this.updateFSReport, this.extraTimings = const <OperationResultExtraTiming>[] });
/// The result of the operation; a non-zero code indicates a failure.
final int code;
/// A user facing message about the results of the operation.
final String message;
/// User facing extra timing information about the operation.
final List<OperationResultExtraTiming> extraTimings;
/// Whether this error should cause the runner to exit.
final bool fatal;
final UpdateFSReport? updateFSReport;
bool get isOk => code == 0;
static final OperationResult ok = OperationResult(0, '');
}
class OperationResultExtraTiming {
const OperationResultExtraTiming(this.description, this.timeInMs);
/// A user facing short description of this timing.
final String description;
/// The time this operation took in milliseconds.
final int timeInMs;
}
Future<String?> getMissingPackageHintForPlatform(TargetPlatform platform) async {
switch (platform) {
case TargetPlatform.android_arm:
case TargetPlatform.android_arm64:
case TargetPlatform.android_x64:
case TargetPlatform.android_x86:
final FlutterProject project = FlutterProject.current();
final String manifestPath = globals.fs.path.relative(project.android.appManifestFile.path);
return 'Is your project missing an $manifestPath?\nConsider running "flutter create ." to create one.';
case TargetPlatform.ios:
return 'Is your project missing an ios/Runner/Info.plist?\nConsider running "flutter create ." to create one.';
case TargetPlatform.android:
case TargetPlatform.darwin:
case TargetPlatform.fuchsia_arm64:
case TargetPlatform.fuchsia_x64:
case TargetPlatform.linux_arm64:
case TargetPlatform.linux_x64:
case TargetPlatform.tester:
case TargetPlatform.web_javascript:
case TargetPlatform.windows_x64:
case TargetPlatform.windows_arm64:
return null;
}
}
/// Redirects terminal commands to the correct resident runner methods.
class TerminalHandler {
TerminalHandler(this.residentRunner, {
required Logger logger,
required Terminal terminal,
required Signals signals,
required io.ProcessInfo processInfo,
required bool reportReady,
String? pidFile,
}) : _logger = logger,
_terminal = terminal,
_signals = signals,
_processInfo = processInfo,
_reportReady = reportReady,
_pidFile = pidFile;
final Logger _logger;
final Terminal _terminal;
final Signals _signals;
final io.ProcessInfo _processInfo;
final bool _reportReady;
final String? _pidFile;
final ResidentHandlers residentRunner;
bool _processingUserRequest = false;
StreamSubscription<void>? subscription;
File? _actualPidFile;
@visibleForTesting
String? lastReceivedCommand;
/// This is only a buffer logger in unit tests
@visibleForTesting
BufferLogger get logger => _logger as BufferLogger;
void setupTerminal() {
if (!_logger.quiet) {
_logger.printStatus('');
residentRunner.printHelp(details: false);
}
_terminal.singleCharMode = true;
subscription = _terminal.keystrokes.listen(processTerminalInput);
}
final Map<io.ProcessSignal, Object> _signalTokens = <io.ProcessSignal, Object>{};
void _addSignalHandler(io.ProcessSignal signal, SignalHandler handler) {
_signalTokens[signal] = _signals.addHandler(signal, handler);
}
void registerSignalHandlers() {
assert(residentRunner.stayResident);
_addSignalHandler(io.ProcessSignal.sigint, _cleanUp);
_addSignalHandler(io.ProcessSignal.sigterm, _cleanUp);
if (residentRunner.supportsServiceProtocol && residentRunner.supportsRestart) {
_addSignalHandler(io.ProcessSignal.sigusr1, _handleSignal);
_addSignalHandler(io.ProcessSignal.sigusr2, _handleSignal);
if (_pidFile != null) {
_logger.printTrace('Writing pid to: $_pidFile');
_actualPidFile = _processInfo.writePidFile(_pidFile);
}
}
}
/// Unregisters terminal signal and keystroke handlers.
void stop() {
assert(residentRunner.stayResident);
if (_actualPidFile != null) {
try {
_logger.printTrace('Deleting pid file (${_actualPidFile!.path}).');
_actualPidFile!.deleteSync();
} on FileSystemException catch (error) {
_logger.printWarning('Failed to delete pid file (${_actualPidFile!.path}): ${error.message}');
}
_actualPidFile = null;
}
for (final MapEntry<io.ProcessSignal, Object> entry in _signalTokens.entries) {
_signals.removeHandler(entry.key, entry.value);
}
_signalTokens.clear();
subscription?.cancel();
}
/// Returns [true] if the input has been handled by this function.
Future<bool> _commonTerminalInputHandler(String character) async {
_logger.printStatus(''); // the key the user tapped might be on this line
switch (character) {
case 'a':
return residentRunner.debugToggleProfileWidgetBuilds();
case 'b':
return residentRunner.debugToggleBrightness();
case 'c':
_logger.clear();
return true;
case 'd':
case 'D':
await residentRunner.detach();
return true;
case 'f':
return residentRunner.debugDumpFocusTree();
case 'g':
await residentRunner.runSourceGenerators();
return true;
case 'h':
case 'H':
case '?':
// help
residentRunner.printHelp(details: true);
return true;
case 'i':
return residentRunner.debugToggleWidgetInspector();
case 'I':
return residentRunner.debugToggleInvertOversizedImages();
case 'j':
case 'J':
return residentRunner.debugFrameJankMetrics();
case 'L':
return residentRunner.debugDumpLayerTree();
case 'o':
case 'O':
return residentRunner.debugTogglePlatform();
case 'M':
if (residentRunner.supportsWriteSkSL) {
await residentRunner.writeSkSL();
return true;
}
return false;
case 'p':
return residentRunner.debugToggleDebugPaintSizeEnabled();
case 'P':
return residentRunner.debugTogglePerformanceOverlayOverride();
case 'q':
case 'Q':
// exit
await residentRunner.exit();
return true;
case 'r':
if (!residentRunner.canHotReload) {
return false;
}
final OperationResult result = await residentRunner.restart();
if (result.fatal) {
throwToolExit(result.message);
}
if (!result.isOk) {
_logger.printStatus('Try again after fixing the above error(s).', emphasis: true);
}
return true;
case 'R':
// If hot restart is not supported for all devices, ignore the command.
if (!residentRunner.supportsRestart || !residentRunner.hotMode) {
return false;
}
final OperationResult result = await residentRunner.restart(fullRestart: true);
if (result.fatal) {
throwToolExit(result.message);
}
if (!result.isOk) {
_logger.printStatus('Try again after fixing the above error(s).', emphasis: true);
}
return true;
case 's':
for (final FlutterDevice? device in residentRunner.flutterDevices) {
await residentRunner.screenshot(device!);
}
return true;
case 'S':
return residentRunner.debugDumpSemanticsTreeInTraversalOrder();
case 't':
case 'T':
return residentRunner.debugDumpRenderTree();
case 'U':
return residentRunner.debugDumpSemanticsTreeInInverseHitTestOrder();
case 'v':
case 'V':
return residentRunner.residentDevtoolsHandler!.launchDevToolsInBrowser(flutterDevices: residentRunner.flutterDevices);
case 'w':
case 'W':
return residentRunner.debugDumpApp();
}
return false;
}
Future<void> processTerminalInput(String command) async {
// When terminal doesn't support line mode, '\n' can sneak into the input.
command = command.trim();
if (_processingUserRequest) {
_logger.printTrace('Ignoring terminal input: "$command" because we are busy.');
return;
}
_processingUserRequest = true;
try {
lastReceivedCommand = command;
await _commonTerminalInputHandler(command);
// Catch all exception since this is doing cleanup and rethrowing.
} catch (error, st) { // ignore: avoid_catches_without_on_clauses
// Don't print stack traces for known error types.
if (error is! ToolExit) {
_logger.printError('$error\n$st');
}
await _cleanUp(null);
rethrow;
} finally {
_processingUserRequest = false;
if (_reportReady) {
_logger.printStatus('ready');
}
}
}
Future<void> _handleSignal(io.ProcessSignal signal) async {
if (_processingUserRequest) {
_logger.printTrace('Ignoring signal: "$signal" because we are busy.');
return;
}
_processingUserRequest = true;
final bool fullRestart = signal == io.ProcessSignal.sigusr2;
try {
await residentRunner.restart(fullRestart: fullRestart);
} finally {
_processingUserRequest = false;
}
}
Future<void> _cleanUp(io.ProcessSignal? signal) async {
_terminal.singleCharMode = false;
await subscription?.cancel();
await residentRunner.cleanupAfterSignal();
}
}
class DebugConnectionInfo {
DebugConnectionInfo({ this.httpUri, this.wsUri, this.baseUri });
final Uri? httpUri;
final Uri? wsUri;
final String? baseUri;
}
/// Returns the next platform value for the switcher.
///
/// These values must match what is available in
/// `packages/flutter/lib/src/foundation/binding.dart`.
String nextPlatform(String currentPlatform) {
const List<String> platforms = <String>[
'android',
'iOS',
'windows',
'macOS',
'linux',
'fuchsia',
];
final int index = platforms.indexOf(currentPlatform);
assert(index >= 0, 'unknown platform "$currentPlatform"');
return platforms[(index + 1) % platforms.length];
}
/// A launcher for the devtools debugger and analysis tool.
abstract class DevtoolsLauncher {
static DevtoolsLauncher? get instance => context.get<DevtoolsLauncher>();
/// Serve Dart DevTools and return the host and port they are available on.
///
/// This method must return a future that is guaranteed not to fail, because it
/// will be used in unawaited contexts. It may, however, return null.
Future<DevToolsServerAddress?> serve();
/// Launch a Dart DevTools process, optionally targeting a specific VM Service
/// URI if [vmServiceUri] is non-null.
///
/// [additionalArguments] may be optionally specified and are passed directly
/// to the devtools run command.
///
/// This method must return a future that is guaranteed not to fail, because it
/// will be used in unawaited contexts.
Future<void> launch(Uri vmServiceUri, {List<String>? additionalArguments});
Future<void> close();
/// When measuring devtools memory via additional arguments, the launch process
/// will technically never complete.
///
/// Us this as an indicator that the process has started.
Future<void>? processStart;
/// Returns a future that completes when the DevTools server is ready.
///
/// Completes when [devToolsUrl] is set. That can be set either directly, or
/// by calling [serve].
Future<void> get ready => _readyCompleter.future;
Completer<void> _readyCompleter = Completer<void>();
Uri? get devToolsUrl => _devToolsUrl;
Uri? _devToolsUrl;
set devToolsUrl(Uri? value) {
assert((_devToolsUrl == null) != (value == null));
_devToolsUrl = value;
if (_devToolsUrl != null) {
_readyCompleter.complete();
} else {
_readyCompleter = Completer<void>();
}
}
/// The URL of the current DevTools server.
///
/// Returns null if [ready] is not complete.
DevToolsServerAddress? get activeDevToolsServer {
if (_devToolsUrl == null) {
return null;
}
return DevToolsServerAddress(devToolsUrl!.host, devToolsUrl!.port);
}
}
class DevToolsServerAddress {
DevToolsServerAddress(this.host, this.port);
final String host;
final int port;
Uri? get uri {
return Uri(scheme: 'http', host: host, port: port);
}
}
| flutter/packages/flutter_tools/lib/src/resident_runner.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/resident_runner.dart",
"repo_id": "flutter",
"token_count": 24576
} | 784 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:stream_channel/stream_channel.dart';
import 'package:vm_service/vm_service.dart' as vm_service;
import '../application_package.dart';
import '../build_info.dart';
import '../device.dart';
import '../globals.dart' as globals;
import '../vmservice.dart';
import 'test_device.dart';
const String kIntegrationTestExtension = 'Flutter.IntegrationTest';
const String kIntegrationTestData = 'data';
const String kIntegrationTestMethod = 'ext.flutter.integrationTest';
class IntegrationTestTestDevice implements TestDevice {
IntegrationTestTestDevice({
required this.id,
required this.device,
required this.debuggingOptions,
required this.userIdentifier,
required this.compileExpression,
});
final int id;
final Device device;
final DebuggingOptions debuggingOptions;
final String? userIdentifier;
final CompileExpression? compileExpression;
ApplicationPackage? _applicationPackage;
final Completer<void> _finished = Completer<void>();
final Completer<Uri> _gotProcessVmServiceUri = Completer<Uri>();
/// Starts the device.
///
/// [entrypointPath] must be a path to an un-compiled source file.
@override
Future<StreamChannel<String>> start(String entrypointPath) async {
final TargetPlatform targetPlatform = await device.targetPlatform;
_applicationPackage = await ApplicationPackageFactory.instance?.getPackageForPlatform(
targetPlatform,
buildInfo: debuggingOptions.buildInfo,
);
final ApplicationPackage? package = _applicationPackage;
if (package == null) {
throw TestDeviceException('No application found for $targetPlatform.', StackTrace.current);
}
final LaunchResult launchResult = await device.startApp(
package,
mainPath: entrypointPath,
platformArgs: <String, dynamic>{},
debuggingOptions: debuggingOptions,
userIdentifier: userIdentifier,
);
if (!launchResult.started) {
throw TestDeviceException('Unable to start the app on the device.', StackTrace.current);
}
final Uri? vmServiceUri = launchResult.vmServiceUri;
if (vmServiceUri == null) {
throw TestDeviceException('The VM Service is not available on the test device.', StackTrace.current);
}
// No need to set up the log reader because the logs are captured and
// streamed to the package:test_core runner.
_gotProcessVmServiceUri.complete(vmServiceUri);
globals.printTrace('test $id: Connecting to vm service');
final FlutterVmService vmService = await connectToVmService(
vmServiceUri,
logger: globals.logger,
compileExpression: compileExpression,
).timeout(
const Duration(seconds: 5),
onTimeout: () => throw TimeoutException('Connecting to the VM Service timed out.'),
);
globals.printTrace('test $id: Finding the correct isolate with the integration test service extension');
final vm_service.IsolateRef isolateRef = await vmService.findExtensionIsolate(
kIntegrationTestMethod,
);
await vmService.service.streamListen(vm_service.EventStreams.kExtension);
final Stream<String> remoteMessages = vmService.service.onExtensionEvent
.where((vm_service.Event e) => e.extensionKind == kIntegrationTestExtension)
.map((vm_service.Event e) => e.extensionData!.data[kIntegrationTestData] as String);
final StreamChannelController<String> controller = StreamChannelController<String>();
controller.local.stream.listen((String event) {
vmService.service.callServiceExtension(
kIntegrationTestMethod,
isolateId: isolateRef.id,
args: <String, String>{
kIntegrationTestData: event,
},
);
});
remoteMessages.listen(
(String s) => controller.local.sink.add(s),
onError: (Object error, StackTrace stack) => controller.local.sink.addError(error, stack),
);
unawaited(vmService.service.onDone.whenComplete(
() => controller.local.sink.close(),
));
return controller.foreign;
}
@override
Future<Uri> get vmServiceUri => _gotProcessVmServiceUri.future;
@override
Future<void> kill() async {
final ApplicationPackage? applicationPackage = _applicationPackage;
if (applicationPackage != null) {
if (!await device.stopApp(applicationPackage, userIdentifier: userIdentifier)) {
globals.printTrace('Could not stop the Integration Test app.');
}
if (!await device.uninstallApp(applicationPackage, userIdentifier: userIdentifier)) {
globals.printTrace('Could not uninstall the Integration Test app.');
}
}
await device.dispose();
_finished.complete();
}
@override
Future<void> get finished => _finished.future;
}
| flutter/packages/flutter_tools/lib/src/test/integration_test_device.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/test/integration_test_device.dart",
"repo_id": "flutter",
"token_count": 1616
} | 785 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:package_config/package_config.dart';
String generateDDCBootstrapScript({
required String entrypoint,
required String ddcModuleLoaderUrl,
required String mapperUrl,
required bool generateLoadingIndicator,
String appRootDirectory = '/',
}) {
return '''
${generateLoadingIndicator ? _generateLoadingIndicator() : ""}
// TODO(markzipan): This is safe if Flutter app roots are always equal to the
// host root '/'. Validate if this is true.
var _currentDirectory = "$appRootDirectory";
window.\$dartCreateScript = (function() {
// Find the nonce value. (Note, this is only computed once.)
var scripts = Array.from(document.getElementsByTagName("script"));
var nonce;
scripts.some(
script => (nonce = script.nonce || script.getAttribute("nonce")));
// If present, return a closure that automatically appends the nonce.
if (nonce) {
return function() {
var script = document.createElement("script");
script.nonce = nonce;
return script;
};
} else {
return function() {
return document.createElement("script");
};
}
})();
// Loads a module [relativeUrl] relative to [root].
//
// If not specified, [root] defaults to the directory serving the main app.
var forceLoadModule = function (relativeUrl, root) {
var actualRoot = root ?? _currentDirectory;
return new Promise(function(resolve, reject) {
var script = self.\$dartCreateScript();
let policy = {
createScriptURL: function(src) {return src;}
};
if (self.trustedTypes && self.trustedTypes.createPolicy) {
policy = self.trustedTypes.createPolicy('dartDdcModuleUrl', policy);
}
script.onload = resolve;
script.onerror = reject;
script.src = policy.createScriptURL(actualRoot + relativeUrl);
document.head.appendChild(script);
});
};
// A map containing the URLs for the bootstrap scripts in debug.
let _scriptUrls = {
"mapper": "$mapperUrl",
"moduleLoader": "$ddcModuleLoaderUrl"
};
(function() {
let appName = "$entrypoint";
// A uuid that identifies a subapp.
// Stubbed out since subapps aren't supported in Flutter.
let uuid = "00000000-0000-0000-0000-000000000000";
window.postMessage(
{type: "DDC_STATE_CHANGE", state: "initial_load", targetUuid: uuid}, "*");
// Load pre-requisite DDC scripts.
// We intentionally use invalid names to avoid namespace clashes.
let prerequisiteScripts = [
{
"src": "$ddcModuleLoaderUrl",
"id": "ddc_module_loader \x00"
},
{
"src": "$mapperUrl",
"id": "dart_stack_trace_mapper \x00"
}
];
// Load ddc_module_loader.js to access DDC's module loader API.
let prerequisiteLoads = [];
for (let i = 0; i < prerequisiteScripts.length; i++) {
prerequisiteLoads.push(forceLoadModule(prerequisiteScripts[i].src));
}
Promise.all(prerequisiteLoads).then((_) => afterPrerequisiteLogic());
// Save the current script so we can access it in a closure.
var _currentScript = document.currentScript;
var afterPrerequisiteLogic = function() {
window.\$dartLoader.rootDirectories.push(_currentDirectory);
let scripts = [
{
"src": "dart_sdk.js",
"id": "dart_sdk"
},
{
"src": "main_module.bootstrap.js",
"id": "data-main"
}
];
let loadConfig = new window.\$dartLoader.LoadConfiguration();
loadConfig.bootstrapScript = scripts[scripts.length - 1];
loadConfig.loadScriptFn = function(loader) {
loader.addScriptsToQueue(scripts, null);
loader.loadEnqueuedModules();
}
loadConfig.ddcEventForLoadStart = /* LOAD_ALL_MODULES_START */ 1;
loadConfig.ddcEventForLoadedOk = /* LOAD_ALL_MODULES_END_OK */ 2;
loadConfig.ddcEventForLoadedError = /* LOAD_ALL_MODULES_END_ERROR */ 3;
let loader = new window.\$dartLoader.DDCLoader(loadConfig);
// Record prerequisite scripts' fully resolved URLs.
prerequisiteScripts.forEach(script => loader.registerScript(script));
// Note: these variables should only be used in non-multi-app scenarios since
// they can be arbitrarily overridden based on multi-app load order.
window.\$dartLoader.loadConfig = loadConfig;
window.\$dartLoader.loader = loader;
loader.nextAttempt();
}
})();
''';
}
/// The JavaScript bootstrap script to support in-browser hot restart.
///
/// The [requireUrl] loads our cached RequireJS script file. The [mapperUrl]
/// loads the special Dart stack trace mapper. The [entrypoint] is the
/// actual main.dart file.
///
/// This file is served when the browser requests "main.dart.js" in debug mode,
/// and is responsible for bootstrapping the RequireJS modules and attaching
/// the hot reload hooks.
///
/// If `generateLoadingIndicator` is true, embeds a loading indicator onto the
/// web page that's visible while the Flutter app is loading.
String generateBootstrapScript({
required String requireUrl,
required String mapperUrl,
required bool generateLoadingIndicator,
}) {
return '''
"use strict";
${generateLoadingIndicator ? _generateLoadingIndicator() : ''}
// A map containing the URLs for the bootstrap scripts in debug.
let _scriptUrls = {
"mapper": "$mapperUrl",
"requireJs": "$requireUrl"
};
// Create a TrustedTypes policy so we can attach Scripts...
let _ttPolicy;
if (window.trustedTypes) {
_ttPolicy = trustedTypes.createPolicy("flutter-tools-bootstrap", {
createScriptURL: (url) => {
let scriptUrl = _scriptUrls[url];
if (!scriptUrl) {
console.error("Unknown Flutter Web bootstrap resource!", url);
}
return scriptUrl;
}
});
}
// Creates a TrustedScriptURL for a given `scriptName`.
// See `_scriptUrls` and `_ttPolicy` above.
function getTTScriptUrl(scriptName) {
let defaultUrl = _scriptUrls[scriptName];
return _ttPolicy ? _ttPolicy.createScriptURL(scriptName) : defaultUrl;
}
// Attach source mapping.
var mapperEl = document.createElement("script");
mapperEl.defer = true;
mapperEl.async = false;
mapperEl.src = getTTScriptUrl("mapper");
document.head.appendChild(mapperEl);
// Attach require JS.
var requireEl = document.createElement("script");
requireEl.defer = true;
requireEl.async = false;
requireEl.src = getTTScriptUrl("requireJs");
// This attribute tells require JS what to load as main (defined below).
requireEl.setAttribute("data-main", "main_module.bootstrap");
document.head.appendChild(requireEl);
''';
}
/// Creates a visual animated loading indicator and puts it on the page to
/// provide feedback to the developer that the app is being loaded. Otherwise,
/// the developer would be staring at a blank page wondering if the app will
/// come up or not.
///
/// This indicator should only be used when DWDS is enabled, e.g. with the
/// `-d chrome` option. Debug builds without DWDS, e.g. `flutter run -d web-server`
/// or `flutter build web --debug` should not use this indicator.
String _generateLoadingIndicator() {
return '''
var styles = `
.flutter-loader {
width: 100%;
height: 8px;
background-color: #13B9FD;
position: absolute;
top: 0px;
left: 0px;
overflow: hidden;
}
.indeterminate {
position: relative;
width: 100%;
height: 100%;
}
.indeterminate:before {
content: '';
position: absolute;
height: 100%;
background-color: #0175C2;
animation: indeterminate_first 2.0s infinite ease-out;
}
.indeterminate:after {
content: '';
position: absolute;
height: 100%;
background-color: #02569B;
animation: indeterminate_second 2.0s infinite ease-in;
}
@keyframes indeterminate_first {
0% {
left: -100%;
width: 100%;
}
100% {
left: 100%;
width: 10%;
}
}
@keyframes indeterminate_second {
0% {
left: -150%;
width: 100%;
}
100% {
left: 100%;
width: 10%;
}
}
`;
var styleSheet = document.createElement("style")
styleSheet.type = "text/css";
styleSheet.innerText = styles;
document.head.appendChild(styleSheet);
var loader = document.createElement('div');
loader.className = "flutter-loader";
document.body.append(loader);
var indeterminate = document.createElement('div');
indeterminate.className = "indeterminate";
loader.appendChild(indeterminate);
document.addEventListener('dart-app-ready', function (e) {
loader.parentNode.removeChild(loader);
styleSheet.parentNode.removeChild(styleSheet);
});
''';
}
String generateDDCMainModule({
required String entrypoint,
required bool nullAssertions,
required bool nativeNullAssertions,
String? exportedMain,
}) {
final String entrypointMainName = exportedMain ?? entrypoint.split('.')[0];
// The typo below in "EXTENTION" is load-bearing, package:build depends on it.
return '''
/* ENTRYPOINT_EXTENTION_MARKER */
(function() {
// Flutter Web uses a generated main entrypoint, which shares app and module names.
let appName = "$entrypoint";
let moduleName = "$entrypoint";
// Use a dummy UUID since multi-apps are not supported on Flutter Web.
let uuid = "00000000-0000-0000-0000-000000000000";
let child = {};
child.main = function() {
let dart = self.dart_library.import('dart_sdk', appName).dart;
dart.nonNullAsserts($nullAssertions);
dart.nativeNonNullAsserts($nativeNullAssertions);
self.dart_library.start(appName, uuid, moduleName, "$entrypointMainName");
}
/* MAIN_EXTENSION_MARKER */
child.main();
})();
''';
}
/// Generate a synthetic main module which captures the application's main
/// method.
///
/// If a [bootstrapModule] name is not provided, defaults to 'main_module.bootstrap'.
///
/// RE: Object.keys usage in app.main:
/// This attaches the main entrypoint and hot reload functionality to the window.
/// The app module will have a single property which contains the actual application
/// code. The property name is based off of the entrypoint that is generated, for example
/// the file `foo/bar/baz.dart` will generate a property named approximately
/// `foo__bar__baz`. Rather than attempt to guess, we assume the first property of
/// this object is the module.
String generateMainModule({
required String entrypoint,
required bool nullAssertions,
required bool nativeNullAssertions,
String bootstrapModule = 'main_module.bootstrap',
}) {
// The typo below in "EXTENTION" is load-bearing, package:build depends on it.
return '''
/* ENTRYPOINT_EXTENTION_MARKER */
// Disable require module timeout
require.config({
waitSeconds: 0
});
// Create the main module loaded below.
define("$bootstrapModule", ["$entrypoint", "dart_sdk"], function(app, dart_sdk) {
dart_sdk.dart.setStartAsyncSynchronously(true);
dart_sdk._debugger.registerDevtoolsFormatter();
dart_sdk.dart.nonNullAsserts($nullAssertions);
dart_sdk.dart.nativeNonNullAsserts($nativeNullAssertions);
// See the generateMainModule doc comment.
var child = {};
child.main = app[Object.keys(app)[0]].main;
/* MAIN_EXTENSION_MARKER */
child.main();
window.\$dartLoader = {};
window.\$dartLoader.rootDirectories = [];
if (window.\$requireLoader) {
window.\$requireLoader.getModuleLibraries = dart_sdk.dart.getModuleLibraries;
}
if (window.\$dartStackTraceUtility && !window.\$dartStackTraceUtility.ready) {
window.\$dartStackTraceUtility.ready = true;
let dart = dart_sdk.dart;
window.\$dartStackTraceUtility.setSourceMapProvider(function(url) {
var baseUrl = window.location.protocol + '//' + window.location.host;
url = url.replace(baseUrl + '/', '');
if (url == 'dart_sdk.js') {
return dart.getSourceMap('dart_sdk');
}
url = url.replace(".lib.js", "");
return dart.getSourceMap(url);
});
}
// Prevent DDC's requireJS to interfere with modern bundling.
if (typeof define === 'function' && define.amd) {
// Preserve a copy just in case...
define._amd = define.amd;
delete define.amd;
}
});
''';
}
/// Generates the bootstrap logic required for a flutter test running in a browser.
///
/// This hard-codes the device pixel ratio to 3.0 and a 2400 x 1800 window size.
String generateTestEntrypoint({
required String relativeTestPath,
required String absolutePath,
required String? testConfigPath,
required LanguageVersion languageVersion,
}) {
return '''
// @dart = ${languageVersion.major}.${languageVersion.minor}
import 'org-dartlang-app:///$relativeTestPath' as test;
import 'dart:ui' as ui;
import 'dart:ui_web' as ui_web;
import 'dart:html';
import 'dart:js';
${testConfigPath != null ? "import '${Uri.file(testConfigPath)}' as test_config;" : ""}
import 'package:stream_channel/stream_channel.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:test_api/backend.dart';
Future<void> main() async {
ui_web.debugEmulateFlutterTesterEnvironment = true;
await ui_web.bootstrapEngine();
webGoldenComparator = DefaultWebGoldenComparator(Uri.parse('${Uri.file(absolutePath)}'));
ui_web.debugOverrideDevicePixelRatio(3.0);
ui.window.debugPhysicalSizeOverride = const ui.Size(2400, 1800);
internalBootstrapBrowserTest(() {
return ${testConfigPath != null ? "() => test_config.testExecutable(test.main)" : "test.main"};
});
}
void internalBootstrapBrowserTest(Function getMain()) {
var channel = serializeSuite(getMain, hidePrints: false);
postMessageChannel().pipe(channel);
}
StreamChannel serializeSuite(Function getMain(), {bool hidePrints = true}) => RemoteListener.start(getMain, hidePrints: hidePrints);
StreamChannel postMessageChannel() {
var controller = StreamChannelController<Object?>(sync: true);
var channel = MessageChannel();
window.parent!.postMessage('port', window.location.origin, [channel.port2]);
var portSubscription = channel.port1.onMessage.listen((message) {
controller.local.sink.add(message.data);
});
controller.local.stream
.listen(channel.port1.postMessage, onDone: portSubscription.cancel);
return controller.foreign;
}
''';
}
/// Generate the unit test bootstrap file.
String generateTestBootstrapFileContents(
String mainUri, String requireUrl, String mapperUrl) {
return '''
(function() {
if (typeof document != 'undefined') {
var el = document.createElement("script");
el.defer = true;
el.async = false;
el.src = '$mapperUrl';
document.head.appendChild(el);
el = document.createElement("script");
el.defer = true;
el.async = false;
el.src = '$requireUrl';
el.setAttribute("data-main", '$mainUri');
document.head.appendChild(el);
} else {
importScripts('$mapperUrl', '$requireUrl');
require.config({
baseUrl: baseUrl,
});
window = self;
require(['$mainUri']);
}
})();
''';
}
String generateDefaultFlutterBootstrapScript() {
return '''
{{flutter_js}}
{{flutter_build_config}}
_flutter.loader.load({
serviceWorkerSettings: {
serviceWorkerVersion: {{flutter_service_worker_version}}
}
});
''';
}
| flutter/packages/flutter_tools/lib/src/web/bootstrap.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/web/bootstrap.dart",
"repo_id": "flutter",
"token_count": 5199
} | 786 |
// 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 '../artifacts.dart';
import '../base/analyze_size.dart';
import '../base/common.dart';
import '../base/file_system.dart';
import '../base/logger.dart';
import '../base/project_migrator.dart';
import '../base/terminal.dart';
import '../base/utils.dart';
import '../build_info.dart';
import '../cache.dart';
import '../cmake.dart';
import '../cmake_project.dart';
import '../convert.dart';
import '../flutter_plugins.dart';
import '../globals.dart' as globals;
import '../migrations/cmake_custom_command_migration.dart';
import '../migrations/cmake_native_assets_migration.dart';
import 'migrations/build_architecture_migration.dart';
import 'migrations/show_window_migration.dart';
import 'migrations/version_migration.dart';
import 'visual_studio.dart';
// These characters appear to be fine: @%()-+_{}[]`~
const String _kBadCharacters = r"'#!$^&*=|,;<>?";
/// Builds the Windows project using msbuild.
Future<void> buildWindows(
WindowsProject windowsProject,
BuildInfo buildInfo,
TargetPlatform targetPlatform, {
String? target,
VisualStudio? visualStudioOverride,
SizeAnalyzer? sizeAnalyzer,
}) async {
// MSBuild files generated by CMake do not properly escape some characters
// In the directories. This check produces more meaningful error messages
// on failure as pertains to https://github.com/flutter/flutter/issues/104802
final String projectPath = windowsProject.parent.directory.absolute.path;
final bool badPath = _kBadCharacters.runes
.any((int i) => projectPath.contains(String.fromCharCode(i)));
if (badPath) {
throwToolExit(
'Path $projectPath contains invalid characters in "$_kBadCharacters". '
'Please rename your directory so as to not include any of these characters '
'and retry.',
);
}
if (!windowsProject.cmakeFile.existsSync()) {
throwToolExit(
'No Windows desktop project configured. See '
'https://docs.flutter.dev/desktop#add-desktop-support-to-an-existing-flutter-app '
'to learn about adding Windows support to a project.');
}
final Directory buildDirectory = globals.fs.directory(globals.fs.path.join(
projectPath,
getWindowsBuildDirectory(targetPlatform),
));
final List<ProjectMigrator> migrators = <ProjectMigrator>[
CmakeCustomCommandMigration(windowsProject, globals.logger),
CmakeNativeAssetsMigration(windowsProject, 'windows', globals.logger),
VersionMigration(windowsProject, globals.logger),
ShowWindowMigration(windowsProject, globals.logger),
BuildArchitectureMigration(windowsProject, buildDirectory, globals.logger),
];
final ProjectMigration migration = ProjectMigration(migrators);
migration.run();
// Ensure that necessary ephemeral files are generated and up to date.
_writeGeneratedFlutterConfig(windowsProject, buildInfo, target);
createPluginSymlinks(windowsProject.parent);
final VisualStudio visualStudio = visualStudioOverride ?? VisualStudio(
fileSystem: globals.fs,
platform: globals.platform,
logger: globals.logger,
processManager: globals.processManager,
osUtils: globals.os,
);
final String? cmakePath = visualStudio.cmakePath;
final String? cmakeGenerator = visualStudio.cmakeGenerator;
if (cmakePath == null || cmakeGenerator == null) {
throwToolExit('Unable to find suitable Visual Studio toolchain. '
'Please run `flutter doctor` for more details.');
}
final String buildModeName = buildInfo.mode.cliName;
final Status status = globals.logger.startProgress(
'Building Windows application...',
);
try {
await _runCmakeGeneration(
cmakePath: cmakePath,
generator: cmakeGenerator,
targetPlatform: targetPlatform,
buildDir: buildDirectory,
sourceDir: windowsProject.cmakeFile.parent,
);
if (visualStudio.displayVersion == '17.1.0') {
_fixBrokenCmakeGeneration(buildDirectory);
}
await _runBuild(cmakePath, buildDirectory, buildModeName);
} finally {
status.stop();
}
final String? binaryName = getCmakeExecutableName(windowsProject);
final File appFile = buildDirectory
.childDirectory('runner')
.childDirectory(sentenceCase(buildModeName))
.childFile('$binaryName.exe');
if (appFile.existsSync()) {
final String appSize = (buildInfo.mode == BuildMode.debug)
? '' // Don't display the size when building a debug variant.
: ' (${getSizeAsMB(appFile.lengthSync())})';
globals.logger.printStatus(
'${globals.logger.terminal.successMark} '
'Built ${globals.fs.path.relative(appFile.path)}$appSize.',
color: TerminalColor.green,
);
}
if (buildInfo.codeSizeDirectory != null && sizeAnalyzer != null) {
final String arch = getNameForTargetPlatform(targetPlatform);
final File codeSizeFile = globals.fs.directory(buildInfo.codeSizeDirectory)
.childFile('snapshot.$arch.json');
final File precompilerTrace = globals.fs.directory(buildInfo.codeSizeDirectory)
.childFile('trace.$arch.json');
final Map<String, Object?> output = await sizeAnalyzer.analyzeAotSnapshot(
aotSnapshot: codeSizeFile,
// This analysis is only supported for release builds.
outputDirectory: globals.fs.directory(
globals.fs.path.join(
buildDirectory.path,
'runner',
'Release'
),
),
precompilerTrace: precompilerTrace,
type: 'windows',
);
final File outputFile = globals.fsUtils.getUniqueFile(
globals.fs
.directory(globals.fsUtils.homeDirPath)
.childDirectory('.flutter-devtools'), 'windows-code-size-analysis', 'json',
)..writeAsStringSync(jsonEncode(output));
// This message is used as a sentinel in analyze_apk_size_test.dart
globals.printStatus(
'A summary of your Windows bundle analysis can be found at: ${outputFile.path}',
);
// DevTools expects a file path relative to the .flutter-devtools/ dir.
final String relativeAppSizePath = outputFile.path.split('.flutter-devtools/').last.trim();
globals.printStatus(
'\nTo analyze your app size in Dart DevTools, run the following command:\n'
'dart devtools --appSizeBase=$relativeAppSizePath'
);
}
}
String getCmakeWindowsArch(TargetPlatform targetPlatform) {
return switch (targetPlatform) {
TargetPlatform.windows_x64 => 'x64',
TargetPlatform.windows_arm64 => 'ARM64',
_ => throw Exception('Unsupported target platform "$targetPlatform".'),
};
}
Future<void> _runCmakeGeneration({
required String cmakePath,
required String generator,
required TargetPlatform targetPlatform,
required Directory buildDir,
required Directory sourceDir,
}) async {
final Stopwatch sw = Stopwatch()..start();
await buildDir.create(recursive: true);
int result;
try {
result = await globals.processUtils.stream(
<String>[
cmakePath,
'-S',
sourceDir.path,
'-B',
buildDir.path,
'-G',
generator,
'-A',
getCmakeWindowsArch(targetPlatform),
'-DFLUTTER_TARGET_PLATFORM=${getNameForTargetPlatform(targetPlatform)}',
],
trace: true,
);
} on ArgumentError {
throwToolExit("cmake not found. Run 'flutter doctor' for more information.");
}
if (result != 0) {
throwToolExit('Unable to generate build files');
}
final Duration elapsedDuration = sw.elapsed;
globals.flutterUsage.sendTiming('build', 'windows-cmake-generation', elapsedDuration);
globals.analytics.send(Event.timing(
workflow: 'build',
variableName: 'windows-cmake-generation',
elapsedMilliseconds: elapsedDuration.inMilliseconds,
));
}
Future<void> _runBuild(
String cmakePath,
Directory buildDir,
String buildModeName,
{ bool install = true }
) async {
final Stopwatch sw = Stopwatch()..start();
// MSBuild sends all output to stdout, including build errors. This surfaces
// known error patterns.
final RegExp errorMatcher = RegExp(
<String>[
// Known error messages
r'(:\s*(?:warning|(?:fatal )?error).*?:)',
r'Error detected in pubspec\.yaml:',
// Known secondary error lines for pubspec.yaml
r'No file or variants found for asset:',
].join('|'),
);
int result;
try {
result = await globals.processUtils.stream(
<String>[
cmakePath,
'--build',
buildDir.path,
'--config',
sentenceCase(buildModeName),
if (install)
...<String>['--target', 'INSTALL'],
if (globals.logger.isVerbose)
'--verbose',
],
environment: <String, String>{
if (globals.logger.isVerbose)
'VERBOSE_SCRIPT_LOGGING': 'true',
},
trace: true,
stdoutErrorMatcher: errorMatcher,
);
} on ArgumentError {
throwToolExit("cmake not found. Run 'flutter doctor' for more information.");
}
if (result != 0) {
throwToolExit('Build process failed.');
}
final Duration elapsedDuration = sw.elapsed;
globals.flutterUsage.sendTiming('build', 'windows-cmake-build', elapsedDuration);
globals.analytics.send(Event.timing(
workflow: 'build',
variableName: 'windows-cmake-build',
elapsedMilliseconds: elapsedDuration.inMilliseconds,
));
}
/// Writes the generated CMake file with the configuration for the given build.
void _writeGeneratedFlutterConfig(
WindowsProject windowsProject,
BuildInfo buildInfo,
String? target,
) {
final Map<String, String> environment = <String, String>{
'FLUTTER_ROOT': Cache.flutterRoot!,
'FLUTTER_EPHEMERAL_DIR': windowsProject.ephemeralDirectory.path,
'PROJECT_DIR': windowsProject.parent.directory.path,
if (target != null)
'FLUTTER_TARGET': target,
...buildInfo.toEnvironmentConfig(),
};
final LocalEngineInfo? localEngineInfo = globals.artifacts?.localEngineInfo;
if (localEngineInfo != null) {
final String targetOutPath = localEngineInfo.targetOutPath;
// Get the engine source root $ENGINE/src/out/foo_bar_baz -> $ENGINE/src
environment['FLUTTER_ENGINE'] = globals.fs.path.dirname(globals.fs.path.dirname(targetOutPath));
environment['LOCAL_ENGINE'] = localEngineInfo.localTargetName;
environment['LOCAL_ENGINE_HOST'] = localEngineInfo.localHostName;
}
writeGeneratedCmakeConfig(Cache.flutterRoot!, windowsProject, buildInfo, environment, globals.logger);
}
// Works around the Visual Studio 17.1.0 CMake bug described in
// https://github.com/flutter/flutter/issues/97086
//
// Rather than attempt to remove all the duplicate entries within the
// <CustomBuild> element, which would require a more complicated parser, this
// just fixes the incorrect duplicates to have the correct `$<CONFIG>` value,
// making the duplication harmless.
//
// TODO(stuartmorgan): Remove this workaround either once 17.1.0 is
// sufficiently old that we no longer need to support it, or when
// dropping VS 2022 support.
void _fixBrokenCmakeGeneration(Directory buildDirectory) {
final File assembleProject = buildDirectory
.childDirectory('flutter')
.childFile('flutter_assemble.vcxproj');
if (assembleProject.existsSync()) {
// E.g.: <Command Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
final RegExp commandRegex = RegExp(
r'<Command Condition=.*\(Configuration\)\|\$\(Platform\).==.(Debug|Profile|Release)\|');
// E.g.: [...]/flutter_tools/bin/tool_backend.bat windows-x64 Debug
final RegExp assembleCallRegex = RegExp(
r'^.*/tool_backend\.bat windows[^ ]* (Debug|Profile|Release)');
String? lastCommandConditionConfig;
final StringBuffer newProjectContents = StringBuffer();
// vcxproj files contain a BOM, which readAsLinesSync drops; re-add it.
newProjectContents.writeCharCode(unicodeBomCharacterRune);
for (final String line in assembleProject.readAsLinesSync()) {
final RegExpMatch? commandMatch = commandRegex.firstMatch(line);
if (commandMatch != null) {
lastCommandConditionConfig = commandMatch.group(1);
} else if (lastCommandConditionConfig != null) {
final RegExpMatch? assembleCallMatch = assembleCallRegex.firstMatch(line);
if (assembleCallMatch != null) {
final String callConfig = assembleCallMatch.group(1)!;
if (callConfig != lastCommandConditionConfig) {
// The config is the end of the line; make sure to replace that one,
// in case config-matching strings appear anywhere else in the line
// (e.g., the project path).
final int badConfigIndex = line.lastIndexOf(assembleCallMatch.group(1)!);
final String correctedLine = line.replaceFirst(
callConfig, lastCommandConditionConfig, badConfigIndex);
newProjectContents.writeln('$correctedLine\r');
continue;
}
}
}
newProjectContents.writeln('$line\r');
}
assembleProject.writeAsStringSync(newProjectContents.toString());
}
}
| flutter/packages/flutter_tools/lib/src/windows/build_windows.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/windows/build_windows.dart",
"repo_id": "flutter",
"token_count": 4613
} | 787 |
package {{androidIdentifier}}
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity()
| flutter/packages/flutter_tools/templates/app_shared/android-kotlin.tmpl/app/src/main/kotlin/androidIdentifier/MainActivity.kt.tmpl/0 | {
"file_path": "flutter/packages/flutter_tools/templates/app_shared/android-kotlin.tmpl/app/src/main/kotlin/androidIdentifier/MainActivity.kt.tmpl",
"repo_id": "flutter",
"token_count": 33
} | 788 |
org.gradle.jvmargs=-Xmx4G -XX:+HeapDumpOnOutOfMemoryError
android.useAndroidX=true
android.enableJetifier=true
| flutter/packages/flutter_tools/templates/app_shared/android.tmpl/gradle.properties.tmpl/0 | {
"file_path": "flutter/packages/flutter_tools/templates/app_shared/android.tmpl/gradle.properties.tmpl",
"repo_id": "flutter",
"token_count": 43
} | 789 |
#include "Generated.xcconfig"
| flutter/packages/flutter_tools/templates/app_shared/ios.tmpl/Flutter/Debug.xcconfig/0 | {
"file_path": "flutter/packages/flutter_tools/templates/app_shared/ios.tmpl/Flutter/Debug.xcconfig",
"repo_id": "flutter",
"token_count": 12
} | 790 |
org.gradle.jvmargs=-Xmx4G -XX:+HeapDumpOnOutOfMemoryError
android.useAndroidX=true
android.enableJetifier=true
| flutter/packages/flutter_tools/templates/module/android/gradle/gradle.properties.tmpl/0 | {
"file_path": "flutter/packages/flutter_tools/templates/module/android/gradle/gradle.properties.tmpl",
"repo_id": "flutter",
"token_count": 43
} | 791 |
#import "AppDelegate.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
@end
| flutter/packages/flutter_tools/templates/module/ios/host_app_ephemeral/Runner.tmpl/AppDelegate.m/0 | {
"file_path": "flutter/packages/flutter_tools/templates/module/ios/host_app_ephemeral/Runner.tmpl/AppDelegate.m",
"repo_id": "flutter",
"token_count": 75
} | 792 |
name: {{projectName}}
description: {{description}}
version: 0.0.1
homepage:
environment:
sdk: {{dartSdkVersionBounds}}
dependencies:
cli_config: ^0.1.2
logging: ^1.2.0
native_assets_cli: ^0.4.2
native_toolchain_c: ^0.3.4+1
dev_dependencies:
ffi: ^2.1.0
ffigen: ^11.0.0
flutter_lints: ^3.0.0
test: ^1.24.9
| flutter/packages/flutter_tools/templates/package_ffi/pubspec.yaml.tmpl/0 | {
"file_path": "flutter/packages/flutter_tools/templates/package_ffi/pubspec.yaml.tmpl",
"repo_id": "flutter",
"token_count": 156
} | 793 |
#import <Flutter/Flutter.h>
@interface {{pluginClass}} : NSObject<FlutterPlugin>
@end
| flutter/packages/flutter_tools/templates/plugin/ios-objc.tmpl/Classes/pluginClass.h.tmpl/0 | {
"file_path": "flutter/packages/flutter_tools/templates/plugin/ios-objc.tmpl/Classes/pluginClass.h.tmpl",
"repo_id": "flutter",
"token_count": 31
} | 794 |
import Cocoa
import FlutterMacOS
public class {{pluginClass}}: NSObject, FlutterPlugin {
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "{{projectName}}", binaryMessenger: registrar.messenger)
let instance = {{pluginClass}}()
registrar.addMethodCallDelegate(instance, channel: channel)
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
switch call.method {
case "getPlatformVersion":
result("macOS " + ProcessInfo.processInfo.operatingSystemVersionString)
default:
result(FlutterMethodNotImplemented)
}
}
}
| flutter/packages/flutter_tools/templates/plugin/macos.tmpl/Classes/pluginClass.swift.tmpl/0 | {
"file_path": "flutter/packages/flutter_tools/templates/plugin/macos.tmpl/Classes/pluginClass.swift.tmpl",
"repo_id": "flutter",
"token_count": 207
} | 795 |
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/lib" isTestSource="false" />
<excludeFolder url="file://$MODULE_DIR$/.dart_tool" />
<excludeFolder url="file://$MODULE_DIR$/.idea" />
<excludeFolder url="file://$MODULE_DIR$/build" />
<excludeFolder url="file://$MODULE_DIR$/example/build" />
</content>
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Dart Packages" level="project" />
<orderEntry type="library" name="Dart SDK" level="project" />
<orderEntry type="library" name="Flutter Plugins" level="project" />
</component>
</module>
| flutter/packages/flutter_tools/templates/plugin_shared/projectName.iml.tmpl/0 | {
"file_path": "flutter/packages/flutter_tools/templates/plugin_shared/projectName.iml.tmpl",
"repo_id": "flutter",
"token_count": 313
} | 796 |
import 'package:flutter/material.dart';
import 'settings_controller.dart';
/// Displays the various settings that can be customized by the user.
///
/// When a user changes a setting, the SettingsController is updated and
/// Widgets that listen to the SettingsController are rebuilt.
class SettingsView extends StatelessWidget {
const SettingsView({super.key, required this.controller});
static const routeName = '/settings';
final SettingsController controller;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Settings'),
),
body: Padding(
padding: const EdgeInsets.all(16),
// Glue the SettingsController to the theme selection DropdownButton.
//
// When a user selects a theme from the dropdown list, the
// SettingsController is updated, which rebuilds the MaterialApp.
child: DropdownButton<ThemeMode>(
// Read the selected themeMode from the controller
value: controller.themeMode,
// Call the updateThemeMode method any time the user selects a theme.
onChanged: controller.updateThemeMode,
items: const [
DropdownMenuItem(
value: ThemeMode.system,
child: Text('System Theme'),
),
DropdownMenuItem(
value: ThemeMode.light,
child: Text('Light Theme'),
),
DropdownMenuItem(
value: ThemeMode.dark,
child: Text('Dark Theme'),
)
],
),
),
);
}
}
| flutter/packages/flutter_tools/templates/skeleton/lib/src/settings/settings_view.dart.tmpl/0 | {
"file_path": "flutter/packages/flutter_tools/templates/skeleton/lib/src/settings/settings_view.dart.tmpl",
"repo_id": "flutter",
"token_count": 638
} | 797 |
// 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:file/src/interface/file_system_entity.dart';
import '../integration.shard/test_utils.dart';
import '../src/common.dart';
import '../src/context.dart';
const String gradleSettingsFileContent = r'''
pluginManagement {
def flutterSdkPath = {
def properties = new Properties()
file("local.properties").withInputStream { properties.load(it) }
def flutterSdkPath = properties.getProperty("flutter.sdk")
assert flutterSdkPath != null, "flutter.sdk not set in local.properties"
return flutterSdkPath
}()
includeBuild("$flutterSdkPath/packages/flutter_tools/gradle")
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
}
plugins {
id "dev.flutter.flutter-plugin-loader" version "1.0.0"
id "com.android.application" version "AGP_REPLACE_ME" apply false
id "org.jetbrains.kotlin.android" version "KGP_REPLACE_ME" apply false
}
include ":app"
''';
const String agpReplacementString = 'AGP_REPLACE_ME';
const String kgpReplacementString = 'KGP_REPLACE_ME';
const String gradleWrapperPropertiesFileContent = r'''
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-GRADLE_REPLACE_ME-all.zip
''';
const String gradleReplacementString = 'GRADLE_REPLACE_ME';
// This test is currently on the preview shard (but not using the preview
// version of Android) because it is the only one using Java 11. This test
// requires Java 11 due to the intentionally low version of Gradle.
void main() {
late Directory tempDir;
setUpAll(() async {
tempDir = createResolvedTempDirectorySync('run_test.');
});
tearDownAll(() async {
tryToDelete(tempDir as FileSystemEntity);
});
testUsingContext(
'AGP version out of "warn" support band prints warning but still builds', () async {
// Create a new flutter project.
final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter');
ProcessResult result = await processManager.run(<String>[
flutterBin,
'create',
'dependency_checker_app',
'--platforms=android',
], workingDirectory: tempDir.path);
expect(result, const ProcessResultMatcher());
const String gradleVersion = '7.5';
const String agpVersion = '4.2.0';
const String kgpVersion = '1.7.10';
final Directory app = Directory(fileSystem.path.join(tempDir.path, 'dependency_checker_app'));
// Modify gradle version to passed in version.
final File gradleWrapperProperties = File(fileSystem.path.join(
app.path, 'android', 'gradle', 'wrapper', 'gradle-wrapper.properties'));
final String propertyContent = gradleWrapperPropertiesFileContent.replaceFirst(
gradleReplacementString,
gradleVersion,
);
await gradleWrapperProperties.writeAsString(propertyContent, flush: true);
final File gradleSettings = File(fileSystem.path.join(
app.path, 'android', 'settings.gradle'));
final String settingsContent = gradleSettingsFileContent
.replaceFirst(agpReplacementString, agpVersion)
.replaceFirst(kgpReplacementString, kgpVersion);
await gradleSettings.writeAsString(settingsContent, flush: true);
// Ensure that gradle files exists from templates.
result = await processManager.run(<String>[
flutterBin,
'build',
'apk',
'--debug',
], workingDirectory: app.path);
expect(result, const ProcessResultMatcher());
expect(result.stderr, contains('Please upgrade your Android Gradle '
'Plugin version'));
});
testUsingContext(
'Gradle version out of "warn" support band prints warning but still builds', () async {
// Create a new flutter project.
final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter');
ProcessResult result = await processManager.run(<String>[
flutterBin,
'create',
'dependency_checker_app',
'--platforms=android',
], workingDirectory: tempDir.path);
expect(result, const ProcessResultMatcher());
const String gradleVersion = '7.0';
const String agpVersion = '4.2.0';
const String kgpVersion = '1.7.10';
final Directory app = Directory(fileSystem.path.join(tempDir.path, 'dependency_checker_app'));
// Modify gradle version to passed in version.
final File gradleWrapperProperties = File(fileSystem.path.join(
app.path, 'android', 'gradle', 'wrapper', 'gradle-wrapper.properties'));
final String propertyContent = gradleWrapperPropertiesFileContent.replaceFirst(
gradleReplacementString,
gradleVersion,
);
await gradleWrapperProperties.writeAsString(propertyContent, flush: true);
final File gradleSettings = File(fileSystem.path.join(
app.path, 'android', 'settings.gradle'));
final String settingsContent = gradleSettingsFileContent
.replaceFirst(agpReplacementString, agpVersion)
.replaceFirst(kgpReplacementString, kgpVersion);
await gradleSettings.writeAsString(settingsContent, flush: true);
// Ensure that gradle files exists from templates.
result = await processManager.run(<String>[
flutterBin,
'build',
'apk',
'--debug',
], workingDirectory: app.path);
expect(result, const ProcessResultMatcher());
expect(result.stderr, contains('Please upgrade your Gradle version'));
});
testUsingContext(
'Kotlin version out of "warn" support band prints warning but still builds', () async {
// Create a new flutter project.
final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter');
ProcessResult result = await processManager.run(<String>[
flutterBin,
'create',
'dependency_checker_app',
'--platforms=android',
], workingDirectory: tempDir.path);
expect(result, const ProcessResultMatcher());
const String gradleVersion = '7.5';
const String agpVersion = '7.4.0';
const String kgpVersion = '1.4.10';
final Directory app = Directory(fileSystem.path.join(tempDir.path, 'dependency_checker_app'));
// Modify gradle version to passed in version.
final File gradleWrapperProperties = File(fileSystem.path.join(
app.path, 'android', 'gradle', 'wrapper', 'gradle-wrapper.properties'));
final String propertyContent = gradleWrapperPropertiesFileContent.replaceFirst(
gradleReplacementString,
gradleVersion,
);
await gradleWrapperProperties.writeAsString(propertyContent, flush: true);
final File gradleSettings = File(fileSystem.path.join(
app.path, 'android', 'settings.gradle'));
final String settingsContent = gradleSettingsFileContent
.replaceFirst(agpReplacementString, agpVersion)
.replaceFirst(kgpReplacementString, kgpVersion);
await gradleSettings.writeAsString(settingsContent, flush: true);
// Ensure that gradle files exists from templates.
result = await processManager.run(<String>[
flutterBin,
'build',
'apk',
'--debug',
], workingDirectory: app.path);
expect(result, const ProcessResultMatcher());
expect(result.stderr, contains('Please upgrade your Kotlin version'));
});
// TODO(gmackall): Add tests for build blocking when the
// corresponding error versions are enabled.
}
| flutter/packages/flutter_tools/test/android_preview_integration.shard/android_dependency_version_checking_test.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/android_preview_integration.shard/android_dependency_version_checking_test.dart",
"repo_id": "flutter",
"token_count": 2624
} | 798 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:args/command_runner.dart';
import 'package:file/memory.dart';
import 'package:flutter_tools/src/artifacts.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/base/platform.dart';
import 'package:flutter_tools/src/base/process.dart';
import 'package:flutter_tools/src/build_info.dart';
import 'package:flutter_tools/src/build_system/build_system.dart';
import 'package:flutter_tools/src/build_system/targets/web.dart';
import 'package:flutter_tools/src/cache.dart';
import 'package:flutter_tools/src/commands/build.dart';
import 'package:flutter_tools/src/commands/build_web.dart';
import 'package:flutter_tools/src/features.dart';
import 'package:flutter_tools/src/runner/flutter_command.dart';
import 'package:flutter_tools/src/web/compile.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';
void main() {
late FileSystem fileSystem;
final Platform fakePlatform = FakePlatform(
environment: <String, String>{
'FLUTTER_ROOT': '/',
},
);
late ProcessUtils processUtils;
late BufferLogger logger;
late ProcessManager processManager;
late Artifacts artifacts;
setUpAll(() {
Cache.flutterRoot = '';
Cache.disableLocking();
});
setUp(() {
fileSystem = MemoryFileSystem.test();
fileSystem.file('pubspec.yaml')
..createSync()
..writeAsStringSync('name: foo\n');
fileSystem.file('.packages').createSync();
fileSystem.file(fileSystem.path.join('web', 'index.html')).createSync(recursive: true);
fileSystem.file(fileSystem.path.join('lib', 'main.dart')).createSync(recursive: true);
artifacts = Artifacts.test(fileSystem: fileSystem);
logger = BufferLogger.test();
processManager = FakeProcessManager.empty();
processUtils = ProcessUtils(
logger: logger,
processManager: processManager,
);
});
testUsingContext('Refuses to build for web when missing index.html', () async {
fileSystem.file(fileSystem.path.join('web', 'index.html')).deleteSync();
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', 'web', '--no-pub']),
throwsToolExit(message: 'Missing index.html.')
);
}, overrides: <Type, Generator>{
Platform: () => fakePlatform,
FileSystem: () => fileSystem,
FeatureFlags: () => TestFeatureFlags(isWebEnabled: true),
ProcessManager: () => processManager,
});
testUsingContext('Refuses to build a debug build for web', () async {
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', 'web', '--debug', '--no-pub']),
throwsA(isA<UsageException>()));
}, overrides: <Type, Generator>{
Platform: () => fakePlatform,
FeatureFlags: () => TestFeatureFlags(isWebEnabled: true),
ProcessManager: () => processManager,
});
testUsingContext('Refuses to build for web when feature is disabled', () async {
final CommandRunner<void> runner = createTestCommandRunner(BuildCommand(
artifacts: artifacts,
androidSdk: FakeAndroidSdk(),
buildSystem: TestBuildSystem.all(BuildResult(success: true)),
fileSystem: MemoryFileSystem.test(),
logger: logger,
processUtils: processUtils,
osUtils: FakeOperatingSystemUtils(),
));
expect(
() => runner.run(<String>['build', 'web', '--no-pub']),
throwsToolExit(message: '"build web" is not currently supported. To enable, run "flutter config --enable-web".')
);
}, overrides: <Type, Generator>{
Platform: () => fakePlatform,
FileSystem: () => fileSystem,
FeatureFlags: () => TestFeatureFlags(),
ProcessManager: () => processManager,
});
testUsingContext('Setup for a web build with default output directory', () async {
final BuildCommand buildCommand = BuildCommand(
artifacts: artifacts,
androidSdk: FakeAndroidSdk(),
buildSystem: TestBuildSystem.all(BuildResult(success: true)),
fileSystem: fileSystem,
logger: logger,
processUtils: processUtils,
osUtils: FakeOperatingSystemUtils(),
);
final CommandRunner<void> runner = createTestCommandRunner(buildCommand);
setupFileSystemForEndToEndTest(fileSystem);
await runner.run(<String>['build', 'web', '--no-pub', '--no-web-resources-cdn', '--dart-define=foo=a', '--dart2js-optimization=O3']);
final Directory buildDir = fileSystem.directory(fileSystem.path.join('build', 'web'));
expect(buildDir.existsSync(), true);
}, overrides: <Type, Generator>{
Platform: () => fakePlatform,
FileSystem: () => fileSystem,
FeatureFlags: () => TestFeatureFlags(isWebEnabled: true),
ProcessManager: () => processManager,
BuildSystem: () => TestBuildSystem.all(BuildResult(success: true), (Target target, Environment environment) {
expect(environment.defines, <String, String>{
'TargetFile': 'lib/main.dart',
'HasWebPlugins': 'true',
'ServiceWorkerStrategy': 'offline-first',
'BuildMode': 'release',
'DartDefines': 'Zm9vPWE=',
'DartObfuscation': 'false',
'TrackWidgetCreation': 'false',
'TreeShakeIcons': 'true',
});
}),
});
testUsingContext('Does not allow -O0 optimization level', () async {
final BuildCommand buildCommand = BuildCommand(
artifacts: artifacts,
androidSdk: FakeAndroidSdk(),
buildSystem: TestBuildSystem.all(BuildResult(success: true)),
fileSystem: fileSystem,
logger: BufferLogger.test(),
osUtils: FakeOperatingSystemUtils(),
processUtils: processUtils,
);
final CommandRunner<void> runner = createTestCommandRunner(buildCommand);
setupFileSystemForEndToEndTest(fileSystem);
await expectLater(
() => runner.run(<String>[
'build',
'web',
'--no-pub', '--no-web-resources-cdn', '--dart-define=foo=a', '--dart2js-optimization=O0']),
throwsUsageException(message: '"O0" is not an allowed value for option "dart2js-optimization"'),
);
final Directory buildDir = fileSystem.directory(fileSystem.path.join('build', 'web'));
expect(buildDir.existsSync(), isFalse);
}, overrides: <Type, Generator>{
Platform: () => fakePlatform,
FileSystem: () => fileSystem,
FeatureFlags: () => TestFeatureFlags(isWebEnabled: true),
ProcessManager: () => FakeProcessManager.any(),
BuildSystem: () => TestBuildSystem.all(BuildResult(success: true), (Target target, Environment environment) {
expect(environment.defines, <String, String>{
'TargetFile': 'lib/main.dart',
'HasWebPlugins': 'true',
'cspMode': 'false',
'SourceMaps': 'false',
'NativeNullAssertions': 'true',
'ServiceWorkerStrategy': 'offline-first',
'Dart2jsDumpInfo': 'false',
'Dart2jsNoFrequencyBasedMinification': 'false',
'Dart2jsOptimization': 'O3',
'BuildMode': 'release',
'DartDefines': 'Zm9vPWE=,RkxVVFRFUl9XRUJfQVVUT19ERVRFQ1Q9dHJ1ZQ==',
'DartObfuscation': 'false',
'TrackWidgetCreation': 'false',
'TreeShakeIcons': 'true',
});
}),
});
testUsingContext('Setup for a web build with a user specified output directory',
() async {
final BuildCommand buildCommand = BuildCommand(
artifacts: artifacts,
androidSdk: FakeAndroidSdk(),
buildSystem: TestBuildSystem.all(BuildResult(success: true)),
fileSystem: fileSystem,
logger: logger,
processUtils: processUtils,
osUtils: FakeOperatingSystemUtils(),
);
final CommandRunner<void> runner = createTestCommandRunner(buildCommand);
setupFileSystemForEndToEndTest(fileSystem);
const String newBuildDir = 'new_dir';
final Directory buildDir = fileSystem.directory(fileSystem.path.join(newBuildDir));
expect(buildDir.existsSync(), false);
await runner.run(<String>[
'build',
'web',
'--no-pub',
'--no-web-resources-cdn',
'--output=$newBuildDir'
]);
expect(buildDir.existsSync(), true);
}, overrides: <Type, Generator>{
Platform: () => fakePlatform,
FileSystem: () => fileSystem,
FeatureFlags: () => TestFeatureFlags(isWebEnabled: true),
ProcessManager: () => processManager,
BuildSystem: () => TestBuildSystem.all(BuildResult(success: true), (Target target, Environment environment) {
expect(environment.defines, <String, String>{
'TargetFile': 'lib/main.dart',
'HasWebPlugins': 'true',
'ServiceWorkerStrategy': 'offline-first',
'BuildMode': 'release',
'DartObfuscation': 'false',
'TrackWidgetCreation': 'false',
'TreeShakeIcons': 'true',
});
}),
});
testUsingContext('hidden if feature flag is not enabled', () async {
expect(BuildWebCommand(fileSystem: fileSystem, logger: BufferLogger.test(), verboseHelp: false).hidden, true);
}, overrides: <Type, Generator>{
Platform: () => fakePlatform,
FileSystem: () => fileSystem,
FeatureFlags: () => TestFeatureFlags(),
ProcessManager: () => processManager,
});
testUsingContext('not hidden if feature flag is enabled', () async {
expect(BuildWebCommand(fileSystem: fileSystem, logger: BufferLogger.test(), verboseHelp: false).hidden, false);
}, overrides: <Type, Generator>{
Platform: () => fakePlatform,
FileSystem: () => fileSystem,
FeatureFlags: () => TestFeatureFlags(isWebEnabled: true),
ProcessManager: () => processManager,
});
testUsingContext('Defaults to web renderer auto mode when no option is specified', () async {
final TestWebBuildCommand buildCommand = TestWebBuildCommand(fileSystem: fileSystem);
final CommandRunner<void> runner = createTestCommandRunner(buildCommand);
setupFileSystemForEndToEndTest(fileSystem);
await runner.run(<String>['build', 'web', '--no-pub']);
}, overrides: <Type, Generator>{
Platform: () => fakePlatform,
FileSystem: () => fileSystem,
FeatureFlags: () => TestFeatureFlags(isWebEnabled: true),
ProcessManager: () => processManager,
BuildSystem: () => TestBuildSystem.all(BuildResult(success: true), (Target target, Environment environment) {
expect(target, isA<WebServiceWorker>());
final List<WebCompilerConfig> configs = (target as WebServiceWorker).compileConfigs;
expect(configs.length, 1);
expect(configs.first.renderer, WebRendererMode.auto);
}),
});
testUsingContext('Web build supports build-name and build-number', () async {
final TestWebBuildCommand buildCommand = TestWebBuildCommand(fileSystem: fileSystem);
final CommandRunner<void> runner = createTestCommandRunner(buildCommand);
setupFileSystemForEndToEndTest(fileSystem);
await runner.run(<String>[
'build',
'web',
'--no-pub',
'--build-name=1.2.3',
'--build-number=42',
]);
final BuildInfo buildInfo = await buildCommand.webCommand
.getBuildInfo(forcedBuildMode: BuildMode.debug);
expect(buildInfo.buildNumber, '42');
expect(buildInfo.buildName, '1.2.3');
}, overrides: <Type, Generator>{
Platform: () => fakePlatform,
FileSystem: () => fileSystem,
FeatureFlags: () => TestFeatureFlags(isWebEnabled: true),
ProcessManager: () => processManager,
BuildSystem: () => TestBuildSystem.all(BuildResult(success: true)),
});
testUsingContext('Defaults to gstatic CanvasKit artifacts', () async {
final TestWebBuildCommand buildCommand = TestWebBuildCommand(fileSystem: fileSystem);
final CommandRunner<void> runner = createTestCommandRunner(buildCommand);
setupFileSystemForEndToEndTest(fileSystem);
await runner.run(<String>['build', 'web', '--no-pub', '--web-resources-cdn']);
final BuildInfo buildInfo =
await buildCommand.webCommand.getBuildInfo(forcedBuildMode: BuildMode.debug);
expect(buildInfo.dartDefines, contains(startsWith('FLUTTER_WEB_CANVASKIT_URL=https://www.gstatic.com/flutter-canvaskit/')));
}, overrides: <Type, Generator>{
Platform: () => fakePlatform,
FileSystem: () => fileSystem,
FeatureFlags: () => TestFeatureFlags(isWebEnabled: true),
ProcessManager: () => processManager,
BuildSystem: () => TestBuildSystem.all(BuildResult(success: true)),
});
testUsingContext('Does not override custom CanvasKit URL', () async {
final TestWebBuildCommand buildCommand = TestWebBuildCommand(fileSystem: fileSystem);
final CommandRunner<void> runner = createTestCommandRunner(buildCommand);
setupFileSystemForEndToEndTest(fileSystem);
await runner.run(<String>['build', 'web', '--no-pub', '--web-resources-cdn', '--dart-define=FLUTTER_WEB_CANVASKIT_URL=abcdefg']);
final BuildInfo buildInfo =
await buildCommand.webCommand.getBuildInfo(forcedBuildMode: BuildMode.debug);
expect(buildInfo.dartDefines, contains('FLUTTER_WEB_CANVASKIT_URL=abcdefg'));
}, overrides: <Type, Generator>{
Platform: () => fakePlatform,
FileSystem: () => fileSystem,
FeatureFlags: () => TestFeatureFlags(isWebEnabled: true),
ProcessManager: () => processManager,
BuildSystem: () => TestBuildSystem.all(BuildResult(success: true)),
});
testUsingContext('Rejects --base-href value that does not start with /', () async {
final TestWebBuildCommand buildCommand = TestWebBuildCommand(fileSystem: fileSystem);
final CommandRunner<void> runner = createTestCommandRunner(buildCommand);
await expectLater(
runner.run(<String>[
'build',
'web',
'--no-pub',
'--base-href=i_dont_start_with_a_forward_slash',
]),
throwsToolExit(
message: 'Received a --base-href value of "i_dont_start_with_a_forward_slash"\n'
'--base-href should start and end with /',
),
);
}, overrides: <Type, Generator>{
Platform: () => fakePlatform,
FileSystem: () => fileSystem,
ProcessManager: () => processManager,
});
}
void setupFileSystemForEndToEndTest(FileSystem fileSystem) {
final List<String> dependencies = <String>[
fileSystem.path.join('packages', 'flutter_tools', 'lib', 'src', 'build_system', 'targets', 'web.dart'),
fileSystem.path.join('bin', 'cache', 'flutter_web_sdk'),
fileSystem.path.join('bin', 'cache', 'dart-sdk', 'bin', 'snapshots', 'dart2js.dart.snapshot'),
fileSystem.path.join('bin', 'cache', 'dart-sdk', 'bin', 'dart'),
fileSystem.path.join('bin', 'cache', 'dart-sdk '),
];
for (final String dependency in dependencies) {
fileSystem.file(dependency).createSync(recursive: true);
}
// Project files.
fileSystem.file('.packages')
.writeAsStringSync('''
foo:lib/
fizz:bar/lib/
''');
fileSystem.file('pubspec.yaml')
.writeAsStringSync('''
name: foo
dependencies:
flutter:
sdk: flutter
fizz:
path:
bar/
''');
fileSystem.file(fileSystem.path.join('bar', 'pubspec.yaml'))
..createSync(recursive: true)
..writeAsStringSync('''
name: bar
flutter:
plugin:
platforms:
web:
pluginClass: UrlLauncherPlugin
fileName: url_launcher_web.dart
''');
fileSystem.file(fileSystem.path.join('bar', 'lib', 'url_launcher_web.dart'))
..createSync(recursive: true)
..writeAsStringSync('''
class UrlLauncherPlugin {}
''');
fileSystem.file(fileSystem.path.join('lib', 'main.dart'))
.writeAsStringSync('void main() { }');
}
class TestWebBuildCommand extends FlutterCommand {
TestWebBuildCommand({ required FileSystem fileSystem, bool verboseHelp = false }) :
webCommand = BuildWebCommand(
fileSystem: fileSystem,
logger: BufferLogger.test(),
verboseHelp: verboseHelp) {
addSubcommand(webCommand);
}
final BuildWebCommand webCommand;
@override
final String name = 'build';
@override
final String description = 'Build a test executable app.';
@override
Future<FlutterCommandResult> runCommand() async => FlutterCommandResult.fail();
@override
bool get shouldRunPub => false;
}
| flutter/packages/flutter_tools/test/commands.shard/hermetic/build_web_test.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/commands.shard/hermetic/build_web_test.dart",
"repo_id": "flutter",
"token_count": 6037
} | 799 |
// 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:args/command_runner.dart';
import 'package:file/memory.dart';
import 'package:flutter_tools/src/artifacts.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/base/platform.dart';
import 'package:flutter_tools/src/base/terminal.dart';
import 'package:flutter_tools/src/cache.dart';
import 'package:flutter_tools/src/commands/analyze.dart';
import 'package:flutter_tools/src/commands/ios_analyze.dart';
import 'package:flutter_tools/src/ios/xcodeproj.dart';
import 'package:flutter_tools/src/project.dart';
import 'package:flutter_tools/src/project_validator.dart';
import 'package:test/fake.dart';
import '../../src/common.dart';
import '../../src/context.dart';
import '../../src/test_flutter_command_runner.dart';
void main() {
group('ios analyze command', () {
late BufferLogger logger;
late FileSystem fileSystem;
late Platform platform;
late FakeProcessManager processManager;
late Terminal terminal;
late AnalyzeCommand command;
late CommandRunner<void> runner;
setUpAll(() {
Cache.disableLocking();
});
setUp(() {
logger = BufferLogger.test();
fileSystem = MemoryFileSystem.test();
platform = FakePlatform();
processManager = FakeProcessManager.empty();
terminal = Terminal.test();
command = AnalyzeCommand(
artifacts: Artifacts.test(),
fileSystem: fileSystem,
logger: logger,
platform: platform,
processManager: processManager,
terminal: terminal,
allProjectValidators: <ProjectValidator>[],
suppressAnalytics: true,
);
runner = createTestCommandRunner(command);
// Setup repo roots
const String homePath = '/home/user/flutter';
Cache.flutterRoot = homePath;
for (final String dir in <String>['dev', 'examples', 'packages']) {
fileSystem.directory(homePath).childDirectory(dir).createSync(recursive: true);
}
});
testWithoutContext('can output json file', () async {
final MockIosProject ios = MockIosProject();
final MockFlutterProject project = MockFlutterProject(ios);
const String expectedConfig = 'someConfig';
const String expectedTarget = 'someTarget';
const String expectedOutputFile = '/someFile';
ios.outputFileLocation = expectedOutputFile;
await IOSAnalyze(
project: project,
option: IOSAnalyzeOption.outputUniversalLinkSettings,
configuration: expectedConfig,
target: expectedTarget,
logger: logger,
).analyze();
expect(logger.statusText, contains(expectedOutputFile));
expect(ios.outputConfiguration, expectedConfig);
expect(ios.outputTarget, expectedTarget);
});
testWithoutContext('can list build options', () async {
final MockIosProject ios = MockIosProject();
final MockFlutterProject project = MockFlutterProject(ios);
const List<String> targets = <String>['target1', 'target2'];
const List<String> configs = <String>['config1', 'config2'];
ios.expectedProjectInfo = XcodeProjectInfo(targets, configs, const <String>[], logger);
await IOSAnalyze(
project: project,
option: IOSAnalyzeOption.listBuildOptions,
logger: logger,
).analyze();
final Map<String, Object?> jsonOutput = jsonDecode(logger.statusText) as Map<String, Object?>;
expect(jsonOutput['targets'], unorderedEquals(targets));
expect(jsonOutput['configurations'], unorderedEquals(configs));
});
testUsingContext('throws if provide multiple path', () async {
final Directory tempDir = fileSystem.systemTempDirectory.createTempSync('someTemp');
final Directory anotherTempDir = fileSystem.systemTempDirectory.createTempSync('another');
await expectLater(
runner.run(<String>['analyze', '--ios', '--list-build-options', tempDir.path, anotherTempDir.path]),
throwsA(
isA<Exception>().having(
(Exception e) => e.toString(),
'description',
contains('The iOS analyze can process only one directory path'),
),
),
);
});
testUsingContext('throws if not enough parameters', () async {
final Directory tempDir = fileSystem.systemTempDirectory.createTempSync('someTemp');
await expectLater(
runner.run(<String>['analyze', '--ios', '--output-universal-link-settings', tempDir.path]),
throwsA(
isA<Exception>().having(
(Exception e) => e.toString(),
'description',
contains('"--configuration" must be provided'),
),
),
);
});
});
}
class MockFlutterProject extends Fake implements FlutterProject {
MockFlutterProject(this.ios);
@override
final IosProject ios;
}
class MockIosProject extends Fake implements IosProject {
String? outputConfiguration;
String? outputTarget;
late String outputFileLocation;
late XcodeProjectInfo expectedProjectInfo;
@override
Future<String> outputsUniversalLinkSettings({required String configuration, required String target}) async {
outputConfiguration = configuration;
outputTarget = target;
return outputFileLocation;
}
@override
Future<XcodeProjectInfo> projectInfo() async => expectedProjectInfo;
}
| flutter/packages/flutter_tools/test/commands.shard/hermetic/ios_analyze_test.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/commands.shard/hermetic/ios_analyze_test.dart",
"repo_id": "flutter",
"token_count": 1997
} | 800 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:args/command_runner.dart';
import 'package:file/memory.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/build_info.dart';
import 'package:flutter_tools/src/build_system/build_system.dart';
import 'package:flutter_tools/src/bundle.dart';
import 'package:flutter_tools/src/bundle_builder.dart';
import 'package:flutter_tools/src/cache.dart';
import 'package:flutter_tools/src/commands/build_bundle.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:meta/meta.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';
void main() {
Cache.disableLocking();
late Directory tempDir;
late FakeBundleBuilder fakeBundleBuilder;
final FileSystemStyle fileSystemStyle = globals.fs.path.separator == '/' ?
FileSystemStyle.posix : FileSystemStyle.windows;
late FakeAnalytics fakeAnalytics;
MemoryFileSystem fsFactory() {
return MemoryFileSystem.test(style: fileSystemStyle);
}
setUp(() {
tempDir = globals.fs.systemTempDirectory.createTempSync('flutter_tools_packages_test.');
fakeBundleBuilder = FakeBundleBuilder();
fakeAnalytics = getInitializedFakeAnalyticsInstance(
fs: fsFactory(),
fakeFlutterVersion: FakeFlutterVersion(),
);
});
tearDown(() {
tryToDelete(tempDir);
});
Future<BuildBundleCommand> runCommandIn(String projectPath, { List<String>? arguments }) async {
final BuildBundleCommand command = BuildBundleCommand(
logger: BufferLogger.test(),
bundleBuilder: fakeBundleBuilder,
);
final CommandRunner<void> runner = createTestCommandRunner(command);
await runner.run(<String>[
'bundle',
...?arguments,
'--target=$projectPath/lib/main.dart',
'--no-pub',
]);
return command;
}
testUsingContext('bundle getUsage indicate that project is a module', () async {
final String projectPath = await createProject(tempDir,
arguments: <String>['--no-pub', '--template=module']);
final BuildBundleCommand command = await runCommandIn(projectPath);
expect((await command.usageValues).commandBuildBundleIsModule, true);
expect(
fakeAnalytics.sentEvents,
contains(
Event.commandUsageValues(
workflow: 'bundle',
commandHasTerminal: false,
buildBundleTargetPlatform: 'android-arm',
buildBundleIsModule: true,
),
),
);
}, overrides: <Type, Generator>{
Analytics: () => fakeAnalytics,
});
testUsingContext('bundle getUsage indicate that project is not a module', () async {
final String projectPath = await createProject(tempDir,
arguments: <String>['--no-pub', '--template=app']);
final BuildBundleCommand command = await runCommandIn(projectPath);
expect((await command.usageValues).commandBuildBundleIsModule, false);
expect(
fakeAnalytics.sentEvents,
contains(
Event.commandUsageValues(
workflow: 'bundle',
commandHasTerminal: false,
buildBundleTargetPlatform: 'android-arm',
buildBundleIsModule: false,
),
),
);
}, overrides: <Type, Generator>{
Analytics: () => fakeAnalytics,
});
testUsingContext('bundle getUsage indicate the target platform', () async {
final String projectPath = await createProject(tempDir,
arguments: <String>['--no-pub', '--template=app']);
final BuildBundleCommand command = await runCommandIn(projectPath);
expect((await command.usageValues).commandBuildBundleTargetPlatform, 'android-arm');
});
testUsingContext('bundle fails to build for Windows if feature is disabled', () async {
globals.fs.file(globals.fs.path.join('lib', 'main.dart')).createSync(recursive: true);
globals.fs.file('pubspec.yaml').createSync(recursive: true);
globals.fs.file('.packages').createSync(recursive: true);
final CommandRunner<void> runner = createTestCommandRunner(BuildBundleCommand(
logger: BufferLogger.test(),
));
expect(() => runner.run(<String>[
'bundle',
'--no-pub',
'--target-platform=windows-x64',
]), throwsToolExit(message: 'Windows is not a supported target platform.'));
}, overrides: <Type, Generator>{
BuildSystem: () => TestBuildSystem.all(BuildResult(success: true)),
FileSystem: fsFactory,
ProcessManager: () => FakeProcessManager.any(),
FeatureFlags: () => TestFeatureFlags(),
});
testUsingContext('bundle fails to build for Linux if feature is disabled', () async {
globals.fs.file(globals.fs.path.join('lib', 'main.dart')).createSync(recursive: true);
globals.fs.file('pubspec.yaml').createSync();
globals.fs.file('.packages').createSync();
final CommandRunner<void> runner = createTestCommandRunner(BuildBundleCommand(
logger: BufferLogger.test(),
));
expect(() => runner.run(<String>[
'bundle',
'--no-pub',
'--target-platform=linux-x64',
]), throwsToolExit(message: 'Linux is not a supported target platform.'));
}, overrides: <Type, Generator>{
BuildSystem: () => TestBuildSystem.all(BuildResult(success: true)),
FileSystem: fsFactory,
ProcessManager: () => FakeProcessManager.any(),
FeatureFlags: () => TestFeatureFlags(),
});
testUsingContext('bundle fails to build for macOS if feature is disabled', () async {
globals.fs.file(globals.fs.path.join('lib', 'main.dart')).createSync(recursive: true);
globals.fs.file('pubspec.yaml').createSync();
globals.fs.file('.packages').createSync();
final CommandRunner<void> runner = createTestCommandRunner(BuildBundleCommand(
logger: BufferLogger.test(),
));
expect(() => runner.run(<String>[
'bundle',
'--no-pub',
'--target-platform=darwin',
]), throwsToolExit(message: 'macOS is not a supported target platform.'));
}, overrides: <Type, Generator>{
BuildSystem: () => TestBuildSystem.all(BuildResult(success: true)),
FileSystem: fsFactory,
ProcessManager: () => FakeProcessManager.any(),
FeatureFlags: () => TestFeatureFlags(),
});
testUsingContext('bundle --tree-shake-icons fails', () async {
globals.fs.file(globals.fs.path.join('lib', 'main.dart')).createSync(recursive: true);
globals.fs.file('pubspec.yaml').createSync();
globals.fs.file('.packages').createSync();
final CommandRunner<void> runner = createTestCommandRunner(BuildBundleCommand(
logger: BufferLogger.test(),
));
expect(() => runner.run(<String>[
'bundle',
'--no-pub',
'--release',
'--tree-shake-icons',
]), throwsToolExit(message: 'tree-shake-icons'));
}, overrides: <Type, Generator>{
FileSystem: fsFactory,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('bundle can build for Windows if feature is enabled', () async {
globals.fs.file(globals.fs.path.join('lib', 'main.dart')).createSync(recursive: true);
globals.fs.file('pubspec.yaml').createSync();
globals.fs.file('.packages').createSync();
final CommandRunner<void> runner = createTestCommandRunner(BuildBundleCommand(
logger: BufferLogger.test(),
));
await runner.run(<String>[
'bundle',
'--no-pub',
'--target-platform=windows-x64',
]);
}, overrides: <Type, Generator>{
BuildSystem: () => TestBuildSystem.all(BuildResult(success: true)),
FileSystem: fsFactory,
ProcessManager: () => FakeProcessManager.any(),
FeatureFlags: () => TestFeatureFlags(isWindowsEnabled: true),
});
testUsingContext('bundle can build for Linux if feature is enabled', () async {
globals.fs.file(globals.fs.path.join('lib', 'main.dart')).createSync(recursive: true);
globals.fs.file('pubspec.yaml').createSync();
globals.fs.file('.packages').createSync();
final CommandRunner<void> runner = createTestCommandRunner(BuildBundleCommand(
logger: BufferLogger.test(),
));
await runner.run(<String>[
'bundle',
'--no-pub',
'--target-platform=linux-x64',
]);
}, overrides: <Type, Generator>{
BuildSystem: () => TestBuildSystem.all(BuildResult(success: true)),
FileSystem: fsFactory,
ProcessManager: () => FakeProcessManager.any(),
FeatureFlags: () => TestFeatureFlags(isLinuxEnabled: true),
});
testUsingContext('bundle can build for macOS if feature is enabled', () async {
globals.fs.file(globals.fs.path.join('lib', 'main.dart')).createSync(recursive: true);
globals.fs.file('pubspec.yaml').createSync();
globals.fs.file('.packages').createSync();
final CommandRunner<void> runner = createTestCommandRunner(BuildBundleCommand(
logger: BufferLogger.test(),
));
await runner.run(<String>[
'bundle',
'--no-pub',
'--target-platform=darwin',
]);
}, overrides: <Type, Generator>{
BuildSystem: () => TestBuildSystem.all(BuildResult(success: true)),
FileSystem: fsFactory,
ProcessManager: () => FakeProcessManager.any(),
FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true),
});
testUsingContext('passes track widget creation through', () async {
globals.fs.file(globals.fs.path.join('lib', 'main.dart')).createSync(recursive: true);
globals.fs.file('pubspec.yaml').createSync();
globals.fs.file('.packages').createSync();
final CommandRunner<void> runner = createTestCommandRunner(BuildBundleCommand(
logger: BufferLogger.test(),
));
await runner.run(<String>[
'bundle',
'--no-pub',
'--debug',
'--target-platform=android-arm',
'--track-widget-creation',
]);
}, overrides: <Type, Generator>{
BuildSystem: () => TestBuildSystem.all(BuildResult(success: true), (Target target, Environment environment) {
expect(environment.defines, <String, String>{
kBuildMode: 'debug',
kTargetPlatform: 'android-arm',
kTargetFile: globals.fs.path.join('lib', 'main.dart'),
kTrackWidgetCreation: 'true',
kFileSystemScheme: 'org-dartlang-root',
kIconTreeShakerFlag: 'false',
kDeferredComponents: 'false',
kDartObfuscation: 'false',
kNativeAssets: 'false',
});
}),
FileSystem: fsFactory,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('passes dart-define through', () async {
globals.fs.file(globals.fs.path.join('lib', 'main.dart')).createSync(recursive: true);
globals.fs.file('pubspec.yaml').createSync();
globals.fs.file('.packages').createSync();
final CommandRunner<void> runner = createTestCommandRunner(BuildBundleCommand(
logger: BufferLogger.test(),
));
await runner.run(<String>[
'bundle',
'--no-pub',
'--debug',
'--target-platform=android-arm',
'--dart-define=foo=bar',
]);
}, overrides: <Type, Generator>{
BuildSystem: () => TestBuildSystem.all(BuildResult(success: true), (Target target, Environment environment) {
expect(environment.defines, <String, String>{
kBuildMode: 'debug',
kTargetPlatform: 'android-arm',
kTargetFile: globals.fs.path.join('lib', 'main.dart'),
kTrackWidgetCreation: 'true',
kFileSystemScheme: 'org-dartlang-root',
kDartDefines: 'Zm9vPWJhcg==',
kIconTreeShakerFlag: 'false',
kDeferredComponents: 'false',
kDartObfuscation: 'false',
kNativeAssets: 'false',
});
}),
FileSystem: fsFactory,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('passes filesystem-scheme through', () async {
globals.fs.file(globals.fs.path.join('lib', 'main.dart')).createSync(recursive: true);
globals.fs.file('pubspec.yaml').createSync();
globals.fs.file('.packages').createSync();
final CommandRunner<void> runner = createTestCommandRunner(BuildBundleCommand(
logger: BufferLogger.test(),
));
await runner.run(<String>[
'bundle',
'--no-pub',
'--debug',
'--target-platform=android-arm',
'--filesystem-scheme=org-dartlang-root2',
]);
}, overrides: <Type, Generator>{
BuildSystem: () => TestBuildSystem.all(BuildResult(success: true), (Target target, Environment environment) {
expect(environment.defines, <String, String>{
kBuildMode: 'debug',
kTargetPlatform: 'android-arm',
kTargetFile: globals.fs.path.join('lib', 'main.dart'),
kTrackWidgetCreation: 'true',
kFileSystemScheme: 'org-dartlang-root2',
kIconTreeShakerFlag: 'false',
kDeferredComponents: 'false',
kDartObfuscation: 'false',
kNativeAssets: 'false',
});
}),
FileSystem: fsFactory,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('passes filesystem-roots through', () async {
globals.fs.file(globals.fs.path.join('lib', 'main.dart')).createSync(recursive: true);
globals.fs.file('pubspec.yaml').createSync();
globals.fs.file('.packages').createSync();
final CommandRunner<void> runner = createTestCommandRunner(BuildBundleCommand(
logger: BufferLogger.test(),
));
await runner.run(<String>[
'bundle',
'--no-pub',
'--debug',
'--target-platform=android-arm',
'--filesystem-root=test1,test2',
]);
}, overrides: <Type, Generator>{
BuildSystem: () => TestBuildSystem.all(BuildResult(success: true), (Target target, Environment environment) {
expect(environment.defines, <String, String>{
kBuildMode: 'debug',
kTargetPlatform: 'android-arm',
kTargetFile: globals.fs.path.join('lib', 'main.dart'),
kTrackWidgetCreation: 'true',
kFileSystemScheme: 'org-dartlang-root',
kFileSystemRoots: 'test1,test2',
kIconTreeShakerFlag: 'false',
kDeferredComponents: 'false',
kDartObfuscation: 'false',
kNativeAssets: 'false',
});
}),
FileSystem: fsFactory,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('passes extra frontend-options through', () async {
globals.fs.file(globals.fs.path.join('lib', 'main.dart')).createSync(recursive: true);
globals.fs.file('pubspec.yaml').createSync();
globals.fs.file('.packages').createSync();
final CommandRunner<void> runner = createTestCommandRunner(BuildBundleCommand(
logger: BufferLogger.test(),
));
await runner.run(<String>[
'bundle',
'--no-pub',
'--debug',
'--target-platform=android-arm',
'--extra-front-end-options=--testflag,--testflag2',
]);
}, overrides: <Type, Generator>{
BuildSystem: () => TestBuildSystem.all(BuildResult(success: true), (Target target, Environment environment) {
expect(environment.defines, <String, String>{
kBuildMode: 'debug',
kTargetPlatform: 'android-arm',
kTargetFile: globals.fs.path.join('lib', 'main.dart'),
kTrackWidgetCreation: 'true',
kFileSystemScheme: 'org-dartlang-root',
kExtraFrontEndOptions: '--testflag,--testflag2',
kIconTreeShakerFlag: 'false',
kDeferredComponents: 'false',
kDartObfuscation: 'false',
kNativeAssets: 'false',
});
}),
FileSystem: fsFactory,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('passes extra gen_snapshot-options through', () async {
globals.fs.file(globals.fs.path.join('lib', 'main.dart')).createSync(recursive: true);
globals.fs.file('pubspec.yaml').createSync();
globals.fs.file('.packages').createSync();
final CommandRunner<void> runner = createTestCommandRunner(BuildBundleCommand(
logger: BufferLogger.test(),
));
await runner.run(<String>[
'bundle',
'--no-pub',
'--debug',
'--target-platform=android-arm',
'--extra-gen-snapshot-options=--testflag,--testflag2',
]);
}, overrides: <Type, Generator>{
BuildSystem: () => TestBuildSystem.all(BuildResult(success: true), (Target target, Environment environment) {
expect(environment.defines, <String, String>{
kBuildMode: 'debug',
kTargetPlatform: 'android-arm',
kTargetFile: globals.fs.path.join('lib', 'main.dart'),
kTrackWidgetCreation: 'true',
kFileSystemScheme: 'org-dartlang-root',
kExtraGenSnapshotOptions: '--testflag,--testflag2',
kIconTreeShakerFlag: 'false',
kDeferredComponents: 'false',
kDartObfuscation: 'false',
kNativeAssets: 'false',
});
}),
FileSystem: fsFactory,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('passes profile options through', () async {
globals.fs.file(globals.fs.path.join('lib', 'main.dart')).createSync(recursive: true);
globals.fs.file('pubspec.yaml').createSync();
globals.fs.file('.packages').createSync();
final CommandRunner<void> runner = createTestCommandRunner(BuildBundleCommand(
logger: BufferLogger.test(),
));
await runner.run(<String>[
'bundle',
'--no-pub',
'--profile',
'--dart-define=foo=bar',
'--target-platform=android-arm',
'--track-widget-creation',
'--filesystem-scheme=org-dartlang-root',
'--filesystem-root=test1,test2',
'--extra-gen-snapshot-options=--testflag,--testflag2',
'--extra-front-end-options=--testflagFront,--testflagFront2',
]);
}, overrides: <Type, Generator>{
BuildSystem: () => TestBuildSystem.all(BuildResult(success: true), (Target target, Environment environment) {
expect(environment.defines, <String, String>{
kBuildMode: 'profile',
kTargetPlatform: 'android-arm',
kTargetFile: globals.fs.path.join('lib', 'main.dart'),
kDartDefines: 'Zm9vPWJhcg==',
kTrackWidgetCreation: 'true',
kFileSystemScheme: 'org-dartlang-root',
kFileSystemRoots: 'test1,test2',
kExtraGenSnapshotOptions: '--testflag,--testflag2',
kExtraFrontEndOptions: '--testflagFront,--testflagFront2',
kIconTreeShakerFlag: 'false',
kDeferredComponents: 'false',
kDartObfuscation: 'false',
kNativeAssets: 'false',
});
}),
FileSystem: fsFactory,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('passes release options through', () async {
globals.fs.file(globals.fs.path.join('lib', 'main.dart')).createSync(recursive: true);
globals.fs.file('pubspec.yaml').createSync();
globals.fs.file('.packages').createSync();
final CommandRunner<void> runner = createTestCommandRunner(BuildBundleCommand(
logger: BufferLogger.test(),
));
await runner.run(<String>[
'bundle',
'--no-pub',
'--release',
'--dart-define=foo=bar',
'--target-platform=android-arm',
'--track-widget-creation',
'--filesystem-scheme=org-dartlang-root',
'--filesystem-root=test1,test2',
'--extra-gen-snapshot-options=--testflag,--testflag2',
'--extra-front-end-options=--testflagFront,--testflagFront2',
]);
}, overrides: <Type, Generator>{
BuildSystem: () => TestBuildSystem.all(BuildResult(success: true), (Target target, Environment environment) {
expect(environment.defines, <String, String>{
kBuildMode: 'release',
kTargetPlatform: 'android-arm',
kTargetFile: globals.fs.path.join('lib', 'main.dart'),
kDartDefines: 'Zm9vPWJhcg==',
kTrackWidgetCreation: 'true',
kFileSystemScheme: 'org-dartlang-root',
kFileSystemRoots: 'test1,test2',
kExtraGenSnapshotOptions: '--testflag,--testflag2',
kExtraFrontEndOptions: '--testflagFront,--testflagFront2',
kIconTreeShakerFlag: 'false',
kDeferredComponents: 'false',
kDartObfuscation: 'false',
kNativeAssets: 'false',
});
}),
FileSystem: fsFactory,
ProcessManager: () => FakeProcessManager.any(),
});
}
class FakeBundleBuilder extends Fake implements BundleBuilder {
@override
Future<void> build({
required TargetPlatform platform,
required BuildInfo buildInfo,
FlutterProject? project,
String? mainPath,
String manifestPath = defaultManifestPath,
String? applicationKernelFilePath,
String? depfilePath,
String? assetDirPath,
bool buildNativeAssets = true,
@visibleForTesting BuildSystem? buildSystem,
}) async {}
}
| flutter/packages/flutter_tools/test/commands.shard/permeable/build_bundle_test.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/commands.shard/permeable/build_bundle_test.dart",
"repo_id": "flutter",
"token_count": 7979
} | 801 |
// 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 'dart:typed_data';
import 'package:file/memory.dart';
import 'package:flutter_tools/src/android/android_console.dart';
import 'package:flutter_tools/src/android/android_device.dart';
import 'package:flutter_tools/src/android/android_sdk.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/base/io.dart';
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/base/platform.dart';
import 'package:flutter_tools/src/build_info.dart';
import 'package:flutter_tools/src/device.dart';
import 'package:flutter_tools/src/project.dart';
import 'package:test/fake.dart';
import '../../src/common.dart';
import '../../src/fake_process_manager.dart';
void main() {
testWithoutContext('AndroidDevice stores the requested id', () {
final AndroidDevice device = setUpAndroidDevice();
expect(device.id, '1234');
});
testWithoutContext('parseAdbDeviceProperties parses adb shell output', () {
final Map<String, String> properties = parseAdbDeviceProperties(kAdbShellGetprop);
expect(properties, isNotNull);
expect(properties['ro.build.characteristics'], 'emulator');
expect(properties['ro.product.cpu.abi'], 'x86_64');
expect(properties['ro.build.version.sdk'], '23');
});
testWithoutContext('adb exiting with heap corruption is only allowed on windows', () async {
final List<FakeCommand> commands = <FakeCommand>[
const FakeCommand(
command: <String>['adb', '-s', '1234', 'shell', 'getprop'],
stdout: '[ro.hardware]: [goldfish]\n[ro.build.characteristics]: [unused]',
// Heap corruption exit code.
exitCode: -1073740940,
),
];
final AndroidDevice windowsDevice = setUpAndroidDevice(
processManager: FakeProcessManager.list(commands.toList()),
platform: FakePlatform(operatingSystem: 'windows'),
);
final AndroidDevice linuxDevice = setUpAndroidDevice(
processManager: FakeProcessManager.list(commands.toList()),
platform: FakePlatform(),
);
final AndroidDevice macOsDevice = setUpAndroidDevice(
processManager: FakeProcessManager.list(commands.toList()),
platform: FakePlatform(operatingSystem: 'macos')
);
// Parsing succeeds despite the error.
expect(await windowsDevice.isLocalEmulator, true);
// Parsing fails and these default to false.
expect(await linuxDevice.isLocalEmulator, false);
expect(await macOsDevice.isLocalEmulator, false);
});
testWithoutContext('AndroidDevice can detect TargetPlatform from property '
'abi and abiList', () async {
// The format is [ABI, ABI list]: expected target platform.
final Map<List<String>, TargetPlatform> values = <List<String>, TargetPlatform>{
<String>['x86_64', 'unknown']: TargetPlatform.android_x64,
<String>['x86', 'unknown']: TargetPlatform.android_x86,
// The default ABI is arm32
<String>['???', 'unknown']: TargetPlatform.android_arm,
<String>['arm64-v8a', 'arm64-v8a,']: TargetPlatform.android_arm64,
// The Kindle Fire runs 32 bit apps on 64 bit hardware.
<String>['arm64-v8a', 'arm']: TargetPlatform.android_arm,
};
for (final MapEntry<List<String>, TargetPlatform> entry in values.entries) {
final AndroidDevice device = setUpAndroidDevice(
processManager: FakeProcessManager.list(<FakeCommand>[
FakeCommand(
command: const <String>['adb', '-s', '1234', 'shell', 'getprop'],
stdout: '[ro.product.cpu.abi]: [${entry.key.first}]\n'
'[ro.product.cpu.abilist]: [${entry.key.last}]',
),
]),
);
expect(await device.targetPlatform, entry.value);
}
});
testWithoutContext('AndroidDevice supports profile/release mode on arm and x64 targets '
'abi and abiList', () async {
// The format is [ABI, ABI list]: expected release mode support.
final Map<List<String>, bool> values = <List<String>, bool>{
<String>['x86_64', 'unknown']: true,
<String>['x86', 'unknown']: false,
// The default ABI is arm32
<String>['???', 'unknown']: true,
<String>['arm64-v8a', 'arm64-v8a,']: true,
// The Kindle Fire runs 32 bit apps on 64 bit hardware.
<String>['arm64-v8a', 'arm']: true,
};
for (final MapEntry<List<String>, bool> entry in values.entries) {
final AndroidDevice device = setUpAndroidDevice(
processManager: FakeProcessManager.list(<FakeCommand>[
FakeCommand(
command: const <String>['adb', '-s', '1234', 'shell', 'getprop'],
stdout: '[ro.product.cpu.abi]: [${entry.key.first}]\n'
'[ro.product.cpu.abilist]: [${entry.key.last}]'
),
]),
);
expect(await device.supportsRuntimeMode(BuildMode.release), entry.value);
// Debug is always supported.
expect(await device.supportsRuntimeMode(BuildMode.debug), true);
// jitRelease is never supported.
expect(await device.supportsRuntimeMode(BuildMode.jitRelease), false);
}
});
testWithoutContext('AndroidDevice can detect local emulator for known types', () async {
for (final String hardware in kKnownHardware.keys) {
final AndroidDevice device = setUpAndroidDevice(
processManager: FakeProcessManager.list(<FakeCommand>[
FakeCommand(
command: const <String>[
'adb', '-s', '1234', 'shell', 'getprop',
],
stdout: '[ro.hardware]: [$hardware]\n'
'[ro.build.characteristics]: [unused]'
),
])
);
expect(await device.isLocalEmulator, kKnownHardware[hardware] == HardwareType.emulator);
}
});
testWithoutContext('AndroidDevice can detect unknown hardware', () async {
final AndroidDevice device = setUpAndroidDevice(
processManager: FakeProcessManager.list(<FakeCommand>[
const FakeCommand(
command: <String>[
'adb', '-s', '1234', 'shell', 'getprop',
],
stdout: '[ro.hardware]: [unknown]\n'
'[ro.build.characteristics]: [att]'
),
])
);
expect(await device.isLocalEmulator, false);
});
testWithoutContext('AndroidDevice can detect unknown emulator', () async {
final AndroidDevice device = setUpAndroidDevice(
processManager: FakeProcessManager.list(<FakeCommand>[
const FakeCommand(
command: <String>[
'adb', '-s', '1234', 'shell', 'getprop',
],
stdout: '[ro.hardware]: [unknown]\n'
'[ro.build.characteristics]: [att,emulator]'
),
])
);
expect(await device.isLocalEmulator, true);
});
testWithoutContext('isSupportedForProject is true on module project', () async {
final FileSystem fileSystem = MemoryFileSystem.test();
fileSystem.file('pubspec.yaml')
..createSync()
..writeAsStringSync(r'''
name: example
flutter:
module: {}
''');
fileSystem.file('.packages').createSync();
final FlutterProject flutterProject = FlutterProjectFactory(
fileSystem: fileSystem,
logger: BufferLogger.test(),
).fromDirectory(fileSystem.currentDirectory);
final AndroidDevice device = setUpAndroidDevice(fileSystem: fileSystem);
expect(device.isSupportedForProject(flutterProject), true);
});
testWithoutContext('isSupportedForProject is true with editable host app', () async {
final FileSystem fileSystem = MemoryFileSystem.test();
fileSystem.file('pubspec.yaml').createSync();
fileSystem.file('.packages').createSync();
fileSystem.directory('android').createSync();
final FlutterProject flutterProject = FlutterProjectFactory(
fileSystem: fileSystem,
logger: BufferLogger.test(),
).fromDirectory(fileSystem.currentDirectory);
final AndroidDevice device = setUpAndroidDevice(fileSystem: fileSystem);
expect(device.isSupportedForProject(flutterProject), true);
});
testWithoutContext('isSupportedForProject is false with no host app and no module', () async {
final FileSystem fileSystem = MemoryFileSystem.test();
fileSystem.file('pubspec.yaml').createSync();
fileSystem.file('.packages').createSync();
final FlutterProject flutterProject = FlutterProjectFactory(
fileSystem: fileSystem,
logger: BufferLogger.test(),
).fromDirectory(fileSystem.currentDirectory);
final AndroidDevice device = setUpAndroidDevice(fileSystem: fileSystem);
expect(device.isSupportedForProject(flutterProject), false);
});
testWithoutContext('AndroidDevice returns correct ID for responsive emulator', () async {
final AndroidDevice device = setUpAndroidDevice(
processManager: FakeProcessManager.list(<FakeCommand>[
const FakeCommand(
command: <String>['adb', '-s', 'emulator-5555', 'shell', 'getprop'],
stdout: '[ro.hardware]: [goldfish]'
),
]),
id: 'emulator-5555',
androidConsoleSocketFactory: (String host, int port) async =>
FakeWorkingAndroidConsoleSocket('dummyEmulatorId'),
);
expect(await device.emulatorId, equals('dummyEmulatorId'));
});
testWithoutContext('AndroidDevice does not create socket for non-emulator devices', () async {
bool socketWasCreated = false;
// Still use an emulator-looking ID so we can be sure the failure is due
// to the isLocalEmulator field and not because the ID doesn't contain a
// port.
final AndroidDevice device = setUpAndroidDevice(
id: 'emulator-5555',
processManager: FakeProcessManager.list(<FakeCommand>[
const FakeCommand(
command: <String>['adb', '-s', 'emulator-5555', 'shell', 'getprop'],
stdout: '[ro.hardware]: [samsungexynos7420]'
),
]),
androidConsoleSocketFactory: (String host, int port) async {
socketWasCreated = true;
throw Exception('Socket was created for non-emulator');
}
);
expect(await device.emulatorId, isNull);
expect(socketWasCreated, isFalse);
});
testWithoutContext('AndroidDevice does not create socket for emulators with no port', () async {
bool socketWasCreated = false;
final AndroidDevice device = setUpAndroidDevice(
processManager: FakeProcessManager.list(<FakeCommand>[
const FakeCommand(
command: <String>['adb', '-s', '1234', 'shell', 'getprop'],
stdout: '[ro.hardware]: [goldfish]'
),
]),
androidConsoleSocketFactory: (String host, int port) async {
socketWasCreated = true;
throw Exception('Socket was created for emulator without port in ID');
},
);
expect(await device.emulatorId, isNull);
expect(socketWasCreated, isFalse);
});
testWithoutContext('AndroidDevice.emulatorId is null for connection error', () async {
final AndroidDevice device = setUpAndroidDevice(
processManager: FakeProcessManager.list(<FakeCommand>[
const FakeCommand(
command: <String>['adb', '-s', '1234', 'shell', 'getprop'],
stdout: '[ro.hardware]: [goldfish]'
),
]),
androidConsoleSocketFactory: (String host, int port) => throw Exception('Fake socket error'),
);
expect(await device.emulatorId, isNull);
});
testWithoutContext('AndroidDevice.emulatorId is null for unresponsive device', () async {
final AndroidDevice device = setUpAndroidDevice(
processManager: FakeProcessManager.list(<FakeCommand>[
const FakeCommand(
command: <String>['adb', '-s', '1234', 'shell', 'getprop'],
stdout: '[ro.hardware]: [goldfish]'
),
]),
androidConsoleSocketFactory: (String host, int port) async =>
FakeUnresponsiveAndroidConsoleSocket(),
);
expect(await device.emulatorId, isNull);
});
testWithoutContext('AndroidDevice.emulatorId is null on early disconnect', () async {
final AndroidDevice device = setUpAndroidDevice(
processManager: FakeProcessManager.list(<FakeCommand>[
const FakeCommand(
command: <String>['adb', '-s', '1234', 'shell', 'getprop'],
stdout: '[ro.hardware]: [goldfish]'
),
]),
androidConsoleSocketFactory: (String host, int port) async =>
FakeDisconnectingAndroidConsoleSocket()
);
expect(await device.emulatorId, isNull);
});
testWithoutContext('AndroidDevice lastLogcatTimestamp returns null if shell command failed', () async {
final AndroidDevice device = setUpAndroidDevice(
processManager: FakeProcessManager.list(<FakeCommand>[
const FakeCommand(
command: <String>['adb', '-s', '1234', 'shell', '-x', 'logcat', '-v', 'time', '-t', '1'],
exitCode: 1,
),
])
);
expect(await device.lastLogcatTimestamp(), isNull);
});
testWithoutContext('AndroidDevice AdbLogReaders for past+future and future logs are not the same', () async {
final AndroidDevice device = setUpAndroidDevice(
processManager: FakeProcessManager.list(<FakeCommand>[
const FakeCommand(
command: <String>['adb', '-s', '1234', 'shell', 'getprop'],
stdout: '[ro.build.version.sdk]: [23]',
exitCode: 1,
),
const FakeCommand(
command: <String>['adb', '-s', '1234', 'shell', '-x', 'logcat', '-v', 'time', '-s', 'flutter'],
),
const FakeCommand(
command: <String>['adb', '-s', '1234', 'shell', '-x', 'logcat', '-v', 'time'],
),
])
);
final DeviceLogReader pastLogReader = await device.getLogReader(includePastLogs: true);
final DeviceLogReader defaultLogReader = await device.getLogReader();
expect(pastLogReader, isNot(equals(defaultLogReader)));
// Getting again is cached.
expect(pastLogReader, equals(await device.getLogReader(includePastLogs: true)));
expect(defaultLogReader, equals(await device.getLogReader()));
});
testWithoutContext('Can parse adb shell dumpsys info', () {
const String exampleOutput = r'''
Applications Memory Usage (in Kilobytes):
Uptime: 441088659 Realtime: 521464097
** MEMINFO in pid 16141 [io.flutter.demo.gallery] **
Pss Private Private SwapPss Heap Heap Heap
Total Dirty Clean Dirty Size Alloc Free
------ ------ ------ ------ ------ ------ ------
Native Heap 8648 8620 0 16 20480 12403 8076
Dalvik Heap 547 424 40 18 2628 1092 1536
Dalvik Other 464 464 0 0
Stack 496 496 0 0
Ashmem 2 0 0 0
Gfx dev 212 204 0 0
Other dev 48 0 48 0
.so mmap 10770 708 9372 25
.apk mmap 240 0 0 0
.ttf mmap 35 0 32 0
.dex mmap 2205 4 1172 0
.oat mmap 64 0 0 0
.art mmap 4228 3848 24 2
Other mmap 20713 4 20704 0
GL mtrack 2380 2380 0 0
Unknown 43971 43968 0 1
TOTAL 95085 61120 31392 62 23108 13495 9612
App Summary
Pss(KB)
------
Java Heap: 4296
Native Heap: 8620
Code: 11288
Stack: 496
Graphics: 2584
Private Other: 65228
System: 2573
TOTAL: 95085 TOTAL SWAP PSS: 62
Objects
Views: 9 ViewRootImpl: 1
AppContexts: 3 Activities: 1
Assets: 4 AssetManagers: 3
Local Binders: 10 Proxy Binders: 18
Parcel memory: 6 Parcel count: 24
Death Recipients: 0 OpenSSL Sockets: 0
WebViews: 0
SQL
MEMORY_USED: 0
PAGECACHE_OVERFLOW: 0 MALLOC_SIZE: 0
''';
final AndroidMemoryInfo result = parseMeminfoDump(exampleOutput);
// Parses correctly
expect(result.realTime, 521464097);
expect(result.javaHeap, 4296);
expect(result.nativeHeap, 8620);
expect(result.code, 11288);
expect(result.stack, 496);
expect(result.graphics, 2584);
expect(result.privateOther, 65228);
expect(result.system, 2573);
// toJson works correctly
final Map<String, Object> json = result.toJson();
expect(json, containsPair('Realtime', 521464097));
expect(json, containsPair('Java Heap', 4296));
expect(json, containsPair('Native Heap', 8620));
expect(json, containsPair('Code', 11288));
expect(json, containsPair('Stack', 496));
expect(json, containsPair('Graphics', 2584));
expect(json, containsPair('Private Other', 65228));
expect(json, containsPair('System', 2573));
// computed from summation of other fields.
expect(json, containsPair('Total', 95085));
// contains identifier for platform in memory info.
expect(json, containsPair('platform', 'Android'));
});
testWithoutContext('AndroidDevice stopApp does nothing if app is not passed', () async {
final AndroidDevice device = setUpAndroidDevice();
expect(await device.stopApp(null), isFalse);
});
}
AndroidDevice setUpAndroidDevice({
String? id,
AndroidSdk? androidSdk,
FileSystem? fileSystem,
ProcessManager? processManager,
Platform? platform,
AndroidConsoleSocketFactory androidConsoleSocketFactory = kAndroidConsoleSocketFactory,
}) {
androidSdk ??= FakeAndroidSdk();
return AndroidDevice(id ?? '1234',
modelID: 'TestModel',
logger: BufferLogger.test(),
platform: platform ?? FakePlatform(),
androidSdk: androidSdk,
fileSystem: fileSystem ?? MemoryFileSystem.test(),
processManager: processManager ?? FakeProcessManager.any(),
androidConsoleSocketFactory: androidConsoleSocketFactory,
);
}
class FakeAndroidSdk extends Fake implements AndroidSdk {
@override
String get adbPath => 'adb';
}
const String kAdbShellGetprop = '''
[dalvik.vm.dex2oat-Xms]: [64m]
[dalvik.vm.dex2oat-Xmx]: [512m]
[dalvik.vm.heapsize]: [384m]
[dalvik.vm.image-dex2oat-Xms]: [64m]
[dalvik.vm.image-dex2oat-Xmx]: [64m]
[dalvik.vm.isa.x86.variant]: [dalvik.vm.isa.x86.features=default]
[dalvik.vm.isa.x86_64.features]: [default]
[dalvik.vm.isa.x86_64.variant]: [x86_64]
[dalvik.vm.lockprof.threshold]: [500]
[dalvik.vm.stack-trace-file]: [/data/anr/traces.txt]
[debug.atrace.tags.enableflags]: [0]
[debug.force_rtl]: [0]
[gsm.current.phone-type]: [1]
[gsm.network.type]: [Unknown]
[gsm.nitz.time]: [1473102078793]
[gsm.operator.alpha]: []
[gsm.operator.iso-country]: []
[gsm.operator.isroaming]: [false]
[gsm.operator.numeric]: []
[gsm.sim.operator.alpha]: []
[gsm.sim.operator.iso-country]: []
[gsm.sim.operator.numeric]: []
[gsm.sim.state]: [NOT_READY]
[gsm.version.ril-impl]: [android reference-ril 1.0]
[init.svc.adbd]: [running]
[init.svc.bootanim]: [running]
[init.svc.console]: [running]
[init.svc.debuggerd]: [running]
[init.svc.debuggerd64]: [running]
[init.svc.drm]: [running]
[init.svc.fingerprintd]: [running]
[init.svc.gatekeeperd]: [running]
[init.svc.goldfish-logcat]: [stopped]
[init.svc.goldfish-setup]: [stopped]
[init.svc.healthd]: [running]
[init.svc.installd]: [running]
[init.svc.keystore]: [running]
[init.svc.lmkd]: [running]
[init.svc.logd]: [running]
[init.svc.logd-reinit]: [stopped]
[init.svc.media]: [running]
[init.svc.netd]: [running]
[init.svc.perfprofd]: [running]
[init.svc.qemu-props]: [stopped]
[init.svc.ril-daemon]: [running]
[init.svc.servicemanager]: [running]
[init.svc.surfaceflinger]: [running]
[init.svc.ueventd]: [running]
[init.svc.vold]: [running]
[init.svc.zygote]: [running]
[init.svc.zygote_secondary]: [running]
[net.bt.name]: [Android]
[net.change]: [net.qtaguid_enabled]
[net.eth0.dns1]: [10.0.2.3]
[net.eth0.gw]: [10.0.2.2]
[net.gprs.local-ip]: [10.0.2.15]
[net.hostname]: [android-ccd858aa3d3825ee]
[net.qtaguid_enabled]: [1]
[net.tcp.default_init_rwnd]: [60]
[persist.sys.dalvik.vm.lib.2]: [libart.so]
[persist.sys.profiler_ms]: [0]
[persist.sys.timezone]: [America/Los_Angeles]
[persist.sys.usb.config]: [adb]
[qemu.gles]: [1]
[qemu.hw.mainkeys]: [0]
[qemu.sf.fake_camera]: [none]
[qemu.sf.lcd_density]: [420]
[rild.libargs]: [-d /dev/ttyS0]
[rild.libpath]: [/system/lib/libreference-ril.so]
[ro.allow.mock.location]: [0]
[ro.baseband]: [unknown]
[ro.board.platform]: []
[ro.boot.hardware]: [ranchu]
[ro.bootimage.build.date]: [Wed Jul 20 21:03:09 UTC 2016]
[ro.bootimage.build.date.utc]: [1469048589]
[ro.bootimage.build.fingerprint]: [Android/sdk_google_phone_x86_64/generic_x86_64:6.0/MASTER/3079352:userdebug/test-keys]
[ro.bootloader]: [unknown]
[ro.bootmode]: [unknown]
[ro.build.characteristics]: [emulator]
[ro.build.date]: [Wed Jul 20 21:02:14 UTC 2016]
[ro.build.date.utc]: [1469048534]
[ro.build.description]: [sdk_google_phone_x86_64-userdebug 6.0 MASTER 3079352 test-keys]
[ro.build.display.id]: [sdk_google_phone_x86_64-userdebug 6.0 MASTER 3079352 test-keys]
[ro.build.fingerprint]: [Android/sdk_google_phone_x86_64/generic_x86_64:6.0/MASTER/3079352:userdebug/test-keys]
[ro.build.flavor]: [sdk_google_phone_x86_64-userdebug]
[ro.build.host]: [vpba14.mtv.corp.google.com]
[ro.build.id]: [MASTER]
[ro.build.product]: [generic_x86_64]
[ro.build.tags]: [test-keys]
[ro.build.type]: [userdebug]
[ro.build.user]: [android-build]
[ro.build.version.all_codenames]: [REL]
[ro.build.version.base_os]: []
[ro.build.version.codename]: [REL]
[ro.build.version.incremental]: [3079352]
[ro.build.version.preview_sdk]: [0]
[ro.build.version.release]: [6.0]
[ro.build.version.sdk]: [23]
[ro.build.version.security_patch]: [2015-10-01]
[ro.com.google.locationfeatures]: [1]
[ro.config.alarm_alert]: [Alarm_Classic.ogg]
[ro.config.nocheckin]: [yes]
[ro.config.notification_sound]: [OnTheHunt.ogg]
[ro.crypto.state]: [unencrypted]
[ro.dalvik.vm.native.bridge]: [0]
[ro.debuggable]: [1]
[ro.hardware]: [ranchu]
[ro.hardware.audio.primary]: [goldfish]
[ro.hwui.drop_shadow_cache_size]: [6]
[ro.hwui.gradient_cache_size]: [1]
[ro.hwui.layer_cache_size]: [48]
[ro.hwui.path_cache_size]: [32]
[ro.hwui.r_buffer_cache_size]: [8]
[ro.hwui.text_large_cache_height]: [1024]
[ro.hwui.text_large_cache_width]: [2048]
[ro.hwui.text_small_cache_height]: [1024]
[ro.hwui.text_small_cache_width]: [1024]
[ro.hwui.texture_cache_flushrate]: [0.4]
[ro.hwui.texture_cache_size]: [72]
[ro.kernel.android.checkjni]: [1]
[ro.kernel.android.qemud]: [1]
[ro.kernel.androidboot.hardware]: [ranchu]
[ro.kernel.clocksource]: [pit]
[ro.kernel.qemu]: [1]
[ro.kernel.qemu.gles]: [1]
[ro.opengles.version]: [131072]
[ro.product.board]: []
[ro.product.brand]: [Android]
[ro.product.cpu.abi]: [x86_64]
[ro.product.cpu.abilist]: [x86_64,x86]
[ro.product.cpu.abilist32]: [x86]
[ro.product.cpu.abilist64]: [x86_64]
[ro.product.device]: [generic_x86_64]
[ro.product.locale]: [en-US]
[ro.product.manufacturer]: [unknown]
[ro.product.model]: [Android SDK built for x86_64]
[ro.product.name]: [sdk_google_phone_x86_64]
[ro.radio.use-ppp]: [no]
[ro.revision]: [0]
[ro.secure]: [1]
[ro.serialno]: []
[ro.wifi.channels]: []
[ro.zygote]: [zygote64_32]
[selinux.reload_policy]: [1]
[service.bootanim.exit]: [0]
[status.battery.level]: [5]
[status.battery.level_raw]: [50]
[status.battery.level_scale]: [9]
[status.battery.state]: [Slow]
[sys.sysctl.extra_free_kbytes]: [24300]
[sys.usb.config]: [adb]
[sys.usb.state]: [adb]
[vold.has_adoptable]: [1]
[wlan.driver.status]: [unloaded]
[xmpp.auto-presence]: [true]
''';
/// A mock Android Console that presents a connection banner and responds to
/// "avd name" requests with the supplied name.
class FakeWorkingAndroidConsoleSocket extends Fake implements Socket {
FakeWorkingAndroidConsoleSocket(this.avdName) {
_controller.add('Android Console: Welcome!\n');
// Include OK in the same packet here. In the response to "avd name"
// it's sent alone to ensure both are handled.
_controller.add('Android Console: Some intro text\nOK\n');
}
final String avdName;
final StreamController<String> _controller = StreamController<String>();
@override
Stream<E> asyncMap<E>(FutureOr<E> Function(Uint8List event) convert) => _controller.stream as Stream<E>;
@override
void add(List<int> data) {
final String text = ascii.decode(data);
if (text == 'avd name\n') {
_controller.add('$avdName\n');
// Include OK in its own packet here. In welcome banner it's included
// as part of the previous text to ensure both are handled.
_controller.add('OK\n');
} else {
throw Exception('Unexpected command $text');
}
}
@override
void destroy() { }
}
/// An Android console socket that drops all input and returns no output.
class FakeUnresponsiveAndroidConsoleSocket extends Fake implements Socket {
final StreamController<String> _controller = StreamController<String>();
@override
Stream<E> asyncMap<E>(FutureOr<E> Function(Uint8List event) convert) => _controller.stream as Stream<E>;
@override
void add(List<int> data) {}
@override
void destroy() { }
}
/// An Android console socket that drops all input and returns no output.
class FakeDisconnectingAndroidConsoleSocket extends Fake implements Socket {
FakeDisconnectingAndroidConsoleSocket() {
_controller.add('Android Console: Welcome!\n');
// Include OK in the same packet here. In the response to "avd name"
// it's sent alone to ensure both are handled.
_controller.add('Android Console: Some intro text\nOK\n');
}
final StreamController<String> _controller = StreamController<String>();
@override
Stream<E> asyncMap<E>(FutureOr<E> Function(Uint8List event) convert) => _controller.stream as Stream<E>;
@override
void add(List<int> data) {
_controller.close();
}
@override
void destroy() { }
}
| flutter/packages/flutter_tools/test/general.shard/android/android_device_test.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/general.shard/android/android_device_test.dart",
"repo_id": "flutter",
"token_count": 10520
} | 802 |
// 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_studio.dart';
import 'package:flutter_tools/src/android/java.dart';
import 'package:flutter_tools/src/base/config.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/version.dart';
import 'package:test/fake.dart';
import 'package:webdriver/async_io.dart';
import '../../integration.shard/test_utils.dart';
import '../../src/common.dart';
import '../../src/context.dart';
import '../../src/fakes.dart';
void main() {
late Config config;
late Logger logger;
late FileSystem fs;
late Platform platform;
late FakeProcessManager processManager;
setUp(() {
config = Config.test();
logger = BufferLogger.test();
fs = MemoryFileSystem.test();
platform = FakePlatform(environment: <String, String>{
'PATH': '',
});
processManager = FakeProcessManager.empty();
});
group(Java, () {
group('find', () {
testWithoutContext('finds the JDK bundled with Android Studio, if it exists', () {
final AndroidStudio androidStudio = _FakeAndroidStudioWithJdk();
final String androidStudioBundledJdkHome = androidStudio.javaPath!;
final String expectedJavaBinaryPath = fs.path.join(androidStudioBundledJdkHome, 'bin', 'java');
processManager.addCommand(FakeCommand(
command: <String>[
expectedJavaBinaryPath,
'--version',
],
stdout: '''
openjdk 19.0.2 2023-01-17
OpenJDK Runtime Environment Zulu19.32+15-CA (build 19.0.2+7)
OpenJDK 64-Bit Server VM Zulu19.32+15-CA (build 19.0.2+7, mixed mode, sharing)
'''
));
final Java java = Java.find(
config: config,
androidStudio: androidStudio,
logger: logger,
fileSystem: fs,
platform: platform,
processManager: processManager,
)!;
expect(java.javaHome, androidStudioBundledJdkHome);
expect(java.binaryPath, expectedJavaBinaryPath);
expect(java.version!.toString(), 'OpenJDK Runtime Environment Zulu19.32+15-CA (build 19.0.2+7)');
expect(java.version, equals(Version(19, 0, 2)));
});
testWithoutContext('finds JAVA_HOME if it is set and the JDK bundled with Android Studio could not be found', () {
final AndroidStudio androidStudio = _FakeAndroidStudioWithoutJdk();
const String javaHome = '/java/home';
final String expectedJavaBinaryPath = fs.path.join(javaHome, 'bin', 'java');
final Java java = Java.find(
config: config,
androidStudio: androidStudio,
logger: logger,
fileSystem: fs,
platform: FakePlatform(environment: <String, String>{
Java.javaHomeEnvironmentVariable: javaHome,
}),
processManager: processManager,
)!;
expect(java.javaHome, javaHome);
expect(java.binaryPath, expectedJavaBinaryPath);
});
testWithoutContext('returns the java binary found on PATH if no other can be found', () {
final AndroidStudio androidStudio = _FakeAndroidStudioWithoutJdk();
final OperatingSystemUtils os = _FakeOperatingSystemUtilsWithJava(fileSystem);
processManager.addCommand(
const FakeCommand(
command: <String>['which', 'java'],
stdout: '/fake/which/java/path',
),
);
final Java java = Java.find(
config: config,
androidStudio: androidStudio,
logger: logger,
fileSystem: fs,
platform: platform,
processManager: processManager,
)!;
expect(java.javaHome, isNull);
expect(java.binaryPath, os.which('java')!.path);
});
testWithoutContext('returns null if no java could be found', () {
final AndroidStudio androidStudio = _FakeAndroidStudioWithoutJdk();
processManager.addCommand(
const FakeCommand(
command: <String>['which', 'java'],
exitCode: 1,
),
);
final Java? java = Java.find(
config: config,
androidStudio: androidStudio,
logger: logger,
fileSystem: fs,
platform: platform,
processManager: processManager,
);
expect(java, isNull);
});
testWithoutContext('finds and prefers JDK found at config item "jdk-dir" if it is set', () {
const String configuredJdkPath = '/jdk';
config.setValue('jdk-dir', configuredJdkPath);
processManager.addCommand(
const FakeCommand(
command: <String>['which', 'java'],
stdout: '/fake/which/java/path',
),
);
final _FakeAndroidStudioWithJdk androidStudio = _FakeAndroidStudioWithJdk();
final FakePlatform platformWithJavaHome = FakePlatform(
environment: <String, String>{
'JAVA_HOME': '/old/jdk'
},
);
Java? java = Java.find(
config: config,
androidStudio: androidStudio,
logger: logger,
fileSystem: fs,
platform: platformWithJavaHome,
processManager: processManager,
);
expect(java, isNotNull);
expect(java!.javaHome, configuredJdkPath);
expect(java.binaryPath, fs.path.join(configuredJdkPath, 'bin', 'java'));
config.removeValue('jdk-dir');
java = Java.find(
config: config,
androidStudio: androidStudio,
logger: logger,
fileSystem: fs,
platform: platformWithJavaHome,
processManager: processManager,
);
expect(java, isNotNull);
assert(androidStudio.javaPath != configuredJdkPath);
expect(java!.javaHome, androidStudio.javaPath);
expect(java.binaryPath, fs.path.join(androidStudio.javaPath!, 'bin', 'java'));
});
});
group('version', () {
late Java java;
setUp(() {
processManager = FakeProcessManager.empty();
java = Java(
fileSystem: fs,
logger: logger,
os: FakeOperatingSystemUtils(),
platform: platform,
processManager: processManager,
binaryPath: 'javaHome/bin/java',
javaHome: 'javaHome',
);
});
void addJavaVersionCommand(String output) {
processManager.addCommand(
FakeCommand(
command: <String>[java.binaryPath, '--version'],
stdout: output,
),
);
}
testWithoutContext('is null when java binary cannot be run', () async {
addJavaVersionCommand('');
processManager.excludedExecutables.add('java');
expect(java.version, null);
});
testWithoutContext('is null when java --version returns a non-zero exit code', () async {
processManager.addCommand(
FakeCommand(
command: <String>[java.binaryPath, '--version'],
exitCode: 1,
),
);
expect(java.version, null);
});
testWithoutContext('parses jdk 8', () {
addJavaVersionCommand('''
java version "1.8.0_202"
Java(TM) SE Runtime Environment (build 1.8.0_202-b10)
Java HotSpot(TM) 64-Bit Server VM (build 25.202-b10, mixed mode)
''');
final Version version = java.version!;
expect(version.toString(), 'Java(TM) SE Runtime Environment (build 1.8.0_202-b10)');
expect(version, equals(Version(1, 8, 0)));
});
testWithoutContext('parses jdk 11 windows', () {
addJavaVersionCommand('''
java version "11.0.14"
Java(TM) SE Runtime Environment (build 11.0.14+10-b13)
Java HotSpot(TM) 64-Bit Server VM (build 11.0.14+10-b13, mixed mode)
''');
final Version version = java.version!;
expect(version.toString(), 'Java(TM) SE Runtime Environment (build 11.0.14+10-b13)');
expect(version, equals(Version(11, 0, 14)));
});
testWithoutContext('parses jdk 11 mac/linux', () {
addJavaVersionCommand('''
openjdk version "11.0.18" 2023-01-17 LTS
OpenJDK Runtime Environment Zulu11.62+17-CA (build 11.0.18+10-LTS)
OpenJDK 64-Bit Server VM Zulu11.62+17-CA (build 11.0.18+10-LTS, mixed mode)
''');
final Version version = java.version!;
expect(version.toString(), 'OpenJDK Runtime Environment Zulu11.62+17-CA (build 11.0.18+10-LTS)');
expect(version, equals(Version(11, 0, 18)));
});
testWithoutContext('parses jdk 17', () {
addJavaVersionCommand('''
openjdk 17.0.6 2023-01-17
OpenJDK Runtime Environment (build 17.0.6+0-17.0.6b802.4-9586694)
OpenJDK 64-Bit Server VM (build 17.0.6+0-17.0.6b802.4-9586694, mixed mode)
''');
final Version version = java.version!;
expect(version.toString(), 'OpenJDK Runtime Environment (build 17.0.6+0-17.0.6b802.4-9586694)');
expect(version, equals(Version(17, 0, 6)));
});
testWithoutContext('parses jdk 19', () {
addJavaVersionCommand('''
openjdk 19.0.2 2023-01-17
OpenJDK Runtime Environment Homebrew (build 19.0.2)
OpenJDK 64-Bit Server VM Homebrew (build 19.0.2, mixed mode, sharing)
''');
final Version version = java.version!;
expect(version.toString(), 'OpenJDK Runtime Environment Homebrew (build 19.0.2)');
expect(version, equals(Version(19, 0, 2)));
});
// https://chrome-infra-packages.appspot.com/p/flutter/java/openjdk/
testWithoutContext('parses jdk output from ci', () {
addJavaVersionCommand('''
openjdk 11.0.2 2019-01-15
OpenJDK Runtime Environment 18.9 (build 11.0.2+9)
OpenJDK 64-Bit Server VM 18.9 (build 11.0.2+9, mixed mode)
''');
final Version version = java.version!;
expect(version.toString(), 'OpenJDK Runtime Environment 18.9 (build 11.0.2+9)');
expect(version, equals(Version(11, 0, 2)));
});
testWithoutContext('parses jdk two number versions', () {
addJavaVersionCommand('openjdk 19.0 2023-01-17');
final Version version = java.version!;
expect(version.toString(), 'openjdk 19.0 2023-01-17');
expect(version, equals(Version(19, 0, null)));
});
testWithoutContext('parses jdk 21 with patch numbers', () {
addJavaVersionCommand('''
java 21.0.1 2023-09-19 LTS
Java(TM) SE Runtime Environment (build 21+35-LTS-2513)
Java HotSpot(TM) 64-Bit Server VM (build 21+35-LTS-2513, mixed mode, sharing)
''');
final Version? version = java.version;
expect(version, equals(Version(21, 0, 1)));
});
testWithoutContext('parses jdk 21 with no patch numbers', () {
addJavaVersionCommand('''
java 21 2023-09-19 LTS
Java(TM) SE Runtime Environment (build 21+35-LTS-2513)
Java HotSpot(TM) 64-Bit Server VM (build 21+35-LTS-2513, mixed mode, sharing)
''');
final Version? version = java.version;
expect(version, equals(Version(21, 0, 0)));
});
testWithoutContext('parses openjdk 21 with no patch numbers', () {
addJavaVersionCommand('''
openjdk version "21" 2023-09-19
OpenJDK Runtime Environment (build 21+35)
OpenJDK 64-Bit Server VM (build 21+35, mixed mode, sharing)
''');
final Version? version = java.version;
expect(version, equals(Version(21, 0, 0)));
});
});
});
}
class _FakeAndroidStudioWithJdk extends Fake implements AndroidStudio {
@override
String? get javaPath => '/fake/android_studio/java/path/';
}
class _FakeAndroidStudioWithoutJdk extends Fake implements AndroidStudio {
@override
String? get javaPath => null;
}
class _FakeOperatingSystemUtilsWithJava extends FakeOperatingSystemUtils {
_FakeOperatingSystemUtilsWithJava(this._fileSystem);
final FileSystem _fileSystem;
@override
File? which(String execName) {
if (execName == 'java') {
return _fileSystem.file('/fake/which/java/path');
}
throw const InvalidArgumentException(null, null);
}
}
| flutter/packages/flutter_tools/test/general.shard/android/java_test.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/general.shard/android/java_test.dart",
"repo_id": "flutter",
"token_count": 5056
} | 803 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:file/memory.dart';
import 'package:flutter_tools/src/artifacts.dart';
import 'package:flutter_tools/src/base/build.dart';
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/build_info.dart';
import 'package:flutter_tools/src/macos/xcode.dart';
import '../../src/common.dart';
import '../../src/fake_process_manager.dart';
const FakeCommand kWhichSysctlCommand = FakeCommand(
command: <String>[
'which',
'sysctl',
],
);
const FakeCommand kARMCheckCommand = FakeCommand(
command: <String>[
'sysctl',
'hw.optional.arm64',
],
exitCode: 1,
);
const List<String> kDefaultClang = <String>[
'-miphoneos-version-min=12.0',
'-isysroot',
'path/to/sdk',
'-dynamiclib',
'-Xlinker',
'-rpath',
'-Xlinker',
'@executable_path/Frameworks',
'-Xlinker',
'-rpath',
'-Xlinker',
'@loader_path/Frameworks',
'-fapplication-extension',
'-install_name',
'@rpath/App.framework/App',
'-o',
'build/foo/App.framework/App',
'build/foo/snapshot_assembly.o',
];
void main() {
group('SnapshotType', () {
test('does not throw, if target platform is null', () {
expect(() => SnapshotType(null, BuildMode.release), returnsNormally);
});
});
group('GenSnapshot', () {
late GenSnapshot genSnapshot;
late Artifacts artifacts;
late FakeProcessManager processManager;
late BufferLogger logger;
setUp(() async {
artifacts = Artifacts.test();
logger = BufferLogger.test();
processManager = FakeProcessManager.list(< FakeCommand>[]);
genSnapshot = GenSnapshot(
artifacts: artifacts,
logger: logger,
processManager: processManager,
);
});
testWithoutContext('android_x64', () async {
processManager.addCommand(
FakeCommand(
command: <String>[
artifacts.getArtifactPath(Artifact.genSnapshot, platform: TargetPlatform.android_x64, mode: BuildMode.release),
'--additional_arg',
],
),
);
final int result = await genSnapshot.run(
snapshotType: SnapshotType(TargetPlatform.android_x64, BuildMode.release),
additionalArgs: <String>['--additional_arg'],
);
expect(result, 0);
});
testWithoutContext('iOS arm64', () async {
final String genSnapshotPath = artifacts.getArtifactPath(
Artifact.genSnapshot,
platform: TargetPlatform.ios,
mode: BuildMode.release,
);
processManager.addCommand(
FakeCommand(
command: <String>[
'${genSnapshotPath}_arm64',
'--additional_arg',
],
),
);
final int result = await genSnapshot.run(
snapshotType: SnapshotType(TargetPlatform.ios, BuildMode.release),
darwinArch: DarwinArch.arm64,
additionalArgs: <String>['--additional_arg'],
);
expect(result, 0);
});
testWithoutContext('--strip filters error output from gen_snapshot', () async {
processManager.addCommand(FakeCommand(
command: <String>[
artifacts.getArtifactPath(Artifact.genSnapshot, platform: TargetPlatform.android_x64, mode: BuildMode.release),
'--strip',
],
stderr: 'ABC\n${GenSnapshot.kIgnoredWarnings.join('\n')}\nXYZ\n'
));
final int result = await genSnapshot.run(
snapshotType: SnapshotType(TargetPlatform.android_x64, BuildMode.release),
additionalArgs: <String>['--strip'],
);
expect(result, 0);
expect(logger.errorText, contains('ABC'));
for (final String ignoredWarning in GenSnapshot.kIgnoredWarnings) {
expect(logger.errorText, isNot(contains(ignoredWarning)));
}
expect(logger.errorText, contains('XYZ'));
});
});
group('AOTSnapshotter', () {
late MemoryFileSystem fileSystem;
late AOTSnapshotter snapshotter;
late Artifacts artifacts;
late FakeProcessManager processManager;
setUp(() async {
fileSystem = MemoryFileSystem.test();
artifacts = Artifacts.test();
processManager = FakeProcessManager.empty();
snapshotter = AOTSnapshotter(
fileSystem: fileSystem,
logger: BufferLogger.test(),
xcode: Xcode.test(
processManager: processManager,
),
artifacts: artifacts,
processManager: processManager,
);
});
testWithoutContext('does not build iOS with debug build mode', () async {
final String outputPath = fileSystem.path.join('build', 'foo');
expect(await snapshotter.build(
platform: TargetPlatform.ios,
darwinArch: DarwinArch.arm64,
sdkRoot: 'path/to/sdk',
buildMode: BuildMode.debug,
mainPath: 'main.dill',
outputPath: outputPath,
dartObfuscation: false,
), isNot(equals(0)));
});
testWithoutContext('does not build android-arm with debug build mode', () async {
final String outputPath = fileSystem.path.join('build', 'foo');
expect(await snapshotter.build(
platform: TargetPlatform.android_arm,
buildMode: BuildMode.debug,
mainPath: 'main.dill',
outputPath: outputPath,
dartObfuscation: false,
), isNot(0));
});
testWithoutContext('does not build android-arm64 with debug build mode', () async {
final String outputPath = fileSystem.path.join('build', 'foo');
expect(await snapshotter.build(
platform: TargetPlatform.android_arm64,
buildMode: BuildMode.debug,
mainPath: 'main.dill',
outputPath: outputPath,
dartObfuscation: false,
), isNot(0));
});
testWithoutContext('builds iOS snapshot with dwarfStackTraces', () async {
final String outputPath = fileSystem.path.join('build', 'foo');
final String assembly = fileSystem.path.join(outputPath, 'snapshot_assembly.S');
final String debugPath = fileSystem.path.join('foo', 'app.ios-arm64.symbols');
final String genSnapshotPath = artifacts.getArtifactPath(
Artifact.genSnapshot,
platform: TargetPlatform.ios,
mode: BuildMode.profile,
);
processManager.addCommands(<FakeCommand>[
FakeCommand(command: <String>[
'${genSnapshotPath}_arm64',
'--deterministic',
'--snapshot_kind=app-aot-assembly',
'--assembly=$assembly',
'--dwarf-stack-traces',
'--resolve-dwarf-paths',
'--save-debugging-info=$debugPath',
'main.dill',
]),
kWhichSysctlCommand,
kARMCheckCommand,
const FakeCommand(command: <String>[
'xcrun',
'cc',
'-arch',
'arm64',
'-miphoneos-version-min=12.0',
'-isysroot',
'path/to/sdk',
'-c',
'build/foo/snapshot_assembly.S',
'-o',
'build/foo/snapshot_assembly.o',
]),
const FakeCommand(command: <String>[
'xcrun',
'clang',
'-arch',
'arm64',
...kDefaultClang,
]),
const FakeCommand(command: <String>[
'xcrun',
'dsymutil',
'-o',
'build/foo/App.framework.dSYM',
'build/foo/App.framework/App',
]),
const FakeCommand(command: <String>[
'xcrun',
'strip',
'-x',
'build/foo/App.framework/App',
'-o',
'build/foo/App.framework/App',
]),
]);
final int genSnapshotExitCode = await snapshotter.build(
platform: TargetPlatform.ios,
buildMode: BuildMode.profile,
mainPath: 'main.dill',
outputPath: outputPath,
darwinArch: DarwinArch.arm64,
sdkRoot: 'path/to/sdk',
splitDebugInfo: 'foo',
dartObfuscation: false,
);
expect(genSnapshotExitCode, 0);
expect(processManager, hasNoRemainingExpectations);
});
testWithoutContext('builds iOS snapshot with obfuscate', () async {
final String outputPath = fileSystem.path.join('build', 'foo');
final String assembly = fileSystem.path.join(outputPath, 'snapshot_assembly.S');
final String genSnapshotPath = artifacts.getArtifactPath(
Artifact.genSnapshot,
platform: TargetPlatform.ios,
mode: BuildMode.profile,
);
processManager.addCommands(<FakeCommand>[
FakeCommand(command: <String>[
'${genSnapshotPath}_arm64',
'--deterministic',
'--snapshot_kind=app-aot-assembly',
'--assembly=$assembly',
'--obfuscate',
'main.dill',
]),
kWhichSysctlCommand,
kARMCheckCommand,
const FakeCommand(command: <String>[
'xcrun',
'cc',
'-arch',
'arm64',
'-miphoneos-version-min=12.0',
'-isysroot',
'path/to/sdk',
'-c',
'build/foo/snapshot_assembly.S',
'-o',
'build/foo/snapshot_assembly.o',
]),
const FakeCommand(command: <String>[
'xcrun',
'clang',
'-arch',
'arm64',
...kDefaultClang,
]),
const FakeCommand(command: <String>[
'xcrun',
'dsymutil',
'-o',
'build/foo/App.framework.dSYM',
'build/foo/App.framework/App',
]),
const FakeCommand(command: <String>[
'xcrun',
'strip',
'-x',
'build/foo/App.framework/App',
'-o',
'build/foo/App.framework/App',
]),
]);
final int genSnapshotExitCode = await snapshotter.build(
platform: TargetPlatform.ios,
buildMode: BuildMode.profile,
mainPath: 'main.dill',
outputPath: outputPath,
darwinArch: DarwinArch.arm64,
sdkRoot: 'path/to/sdk',
dartObfuscation: true,
);
expect(genSnapshotExitCode, 0);
expect(processManager, hasNoRemainingExpectations);
});
testWithoutContext('builds iOS snapshot', () async {
final String outputPath = fileSystem.path.join('build', 'foo');
final String genSnapshotPath = artifacts.getArtifactPath(
Artifact.genSnapshot,
platform: TargetPlatform.ios,
mode: BuildMode.release,
);
processManager.addCommands(<FakeCommand>[
FakeCommand(command: <String>[
'${genSnapshotPath}_arm64',
'--deterministic',
'--snapshot_kind=app-aot-assembly',
'--assembly=${fileSystem.path.join(outputPath, 'snapshot_assembly.S')}',
'main.dill',
]),
kWhichSysctlCommand,
kARMCheckCommand,
const FakeCommand(command: <String>[
'xcrun',
'cc',
'-arch',
'arm64',
'-miphoneos-version-min=12.0',
'-isysroot',
'path/to/sdk',
'-c',
'build/foo/snapshot_assembly.S',
'-o',
'build/foo/snapshot_assembly.o',
]),
const FakeCommand(command: <String>[
'xcrun',
'clang',
'-arch',
'arm64',
...kDefaultClang,
]),
const FakeCommand(command: <String>[
'xcrun',
'dsymutil',
'-o',
'build/foo/App.framework.dSYM',
'build/foo/App.framework/App',
]),
const FakeCommand(command: <String>[
'xcrun',
'strip',
'-x',
'build/foo/App.framework/App',
'-o',
'build/foo/App.framework/App',
]),
]);
final int genSnapshotExitCode = await snapshotter.build(
platform: TargetPlatform.ios,
buildMode: BuildMode.release,
mainPath: 'main.dill',
outputPath: outputPath,
darwinArch: DarwinArch.arm64,
sdkRoot: 'path/to/sdk',
dartObfuscation: false,
);
expect(genSnapshotExitCode, 0);
expect(processManager, hasNoRemainingExpectations);
});
testWithoutContext('builds shared library for android-arm (32bit)', () async {
final String outputPath = fileSystem.path.join('build', 'foo');
processManager.addCommand(FakeCommand(
command: <String>[
artifacts.getArtifactPath(Artifact.genSnapshot, platform: TargetPlatform.android_arm, mode: BuildMode.release),
'--deterministic',
'--snapshot_kind=app-aot-elf',
'--elf=build/foo/app.so',
'--strip',
'--no-sim-use-hardfp',
'--no-use-integer-division',
'main.dill',
]
));
final int genSnapshotExitCode = await snapshotter.build(
platform: TargetPlatform.android_arm,
buildMode: BuildMode.release,
mainPath: 'main.dill',
outputPath: outputPath,
dartObfuscation: false,
);
expect(genSnapshotExitCode, 0);
expect(processManager, hasNoRemainingExpectations);
});
testWithoutContext('builds shared library for android-arm with dwarf stack traces', () async {
final String outputPath = fileSystem.path.join('build', 'foo');
final String debugPath = fileSystem.path.join('foo', 'app.android-arm.symbols');
processManager.addCommand(FakeCommand(
command: <String>[
artifacts.getArtifactPath(Artifact.genSnapshot, platform: TargetPlatform.android_arm, mode: BuildMode.release),
'--deterministic',
'--snapshot_kind=app-aot-elf',
'--elf=build/foo/app.so',
'--strip',
'--no-sim-use-hardfp',
'--no-use-integer-division',
'--dwarf-stack-traces',
'--resolve-dwarf-paths',
'--save-debugging-info=$debugPath',
'main.dill',
]
));
final int genSnapshotExitCode = await snapshotter.build(
platform: TargetPlatform.android_arm,
buildMode: BuildMode.release,
mainPath: 'main.dill',
outputPath: outputPath,
splitDebugInfo: 'foo',
dartObfuscation: false,
);
expect(genSnapshotExitCode, 0);
expect(processManager, hasNoRemainingExpectations);
});
testWithoutContext('builds shared library for android-arm with obfuscate', () async {
final String outputPath = fileSystem.path.join('build', 'foo');
processManager.addCommand(FakeCommand(
command: <String>[
artifacts.getArtifactPath(Artifact.genSnapshot, platform: TargetPlatform.android_arm, mode: BuildMode.release),
'--deterministic',
'--snapshot_kind=app-aot-elf',
'--elf=build/foo/app.so',
'--strip',
'--no-sim-use-hardfp',
'--no-use-integer-division',
'--obfuscate',
'main.dill',
]
));
final int genSnapshotExitCode = await snapshotter.build(
platform: TargetPlatform.android_arm,
buildMode: BuildMode.release,
mainPath: 'main.dill',
outputPath: outputPath,
dartObfuscation: true,
);
expect(genSnapshotExitCode, 0);
expect(processManager, hasNoRemainingExpectations);
});
testWithoutContext('builds shared library for android-arm without dwarf stack traces due to empty string', () async {
final String outputPath = fileSystem.path.join('build', 'foo');
processManager.addCommand(FakeCommand(
command: <String>[
artifacts.getArtifactPath(Artifact.genSnapshot, platform: TargetPlatform.android_arm, mode: BuildMode.release),
'--deterministic',
'--snapshot_kind=app-aot-elf',
'--elf=build/foo/app.so',
'--strip',
'--no-sim-use-hardfp',
'--no-use-integer-division',
'main.dill',
]
));
final int genSnapshotExitCode = await snapshotter.build(
platform: TargetPlatform.android_arm,
buildMode: BuildMode.release,
mainPath: 'main.dill',
outputPath: outputPath,
splitDebugInfo: '',
dartObfuscation: false,
);
expect(genSnapshotExitCode, 0);
expect(processManager, hasNoRemainingExpectations);
});
testWithoutContext('builds shared library for android-arm64', () async {
final String outputPath = fileSystem.path.join('build', 'foo');
processManager.addCommand(FakeCommand(
command: <String>[
artifacts.getArtifactPath(Artifact.genSnapshot, platform: TargetPlatform.android_arm64, mode: BuildMode.release),
'--deterministic',
'--snapshot_kind=app-aot-elf',
'--elf=build/foo/app.so',
'--strip',
'main.dill',
]
));
final int genSnapshotExitCode = await snapshotter.build(
platform: TargetPlatform.android_arm64,
buildMode: BuildMode.release,
mainPath: 'main.dill',
outputPath: outputPath,
dartObfuscation: false,
);
expect(genSnapshotExitCode, 0);
expect(processManager, hasNoRemainingExpectations);
});
testWithoutContext('--no-strip in extraGenSnapshotOptions suppresses --strip', () async {
final String outputPath = fileSystem.path.join('build', 'foo');
processManager.addCommand(FakeCommand(
command: <String>[
artifacts.getArtifactPath(Artifact.genSnapshot, platform: TargetPlatform.android_arm64, mode: BuildMode.release),
'--deterministic',
'--snapshot_kind=app-aot-elf',
'--elf=build/foo/app.so',
'main.dill',
]
));
final int genSnapshotExitCode = await snapshotter.build(
platform: TargetPlatform.android_arm64,
buildMode: BuildMode.release,
mainPath: 'main.dill',
outputPath: outputPath,
dartObfuscation: false,
extraGenSnapshotOptions: const <String>['--no-strip'],
);
expect(genSnapshotExitCode, 0);
expect(processManager, hasNoRemainingExpectations);
});
});
}
| flutter/packages/flutter_tools/test/general.shard/base/build_test.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/general.shard/base/build_test.dart",
"repo_id": "flutter",
"token_count": 8130
} | 804 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:io' as io;
import 'package:flutter_tools/src/base/io.dart';
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/base/process.dart';
import 'package:flutter_tools/src/base/signals.dart';
import 'package:test/fake.dart';
import '../../src/common.dart';
import '../../src/context.dart';
void main() {
group('Signals', () {
late Signals signals;
late FakeProcessSignal fakeSignal;
late ProcessSignal signalUnderTest;
late FakeShutdownHooks shutdownHooks;
setUp(() {
shutdownHooks = FakeShutdownHooks();
signals = Signals.test(shutdownHooks: shutdownHooks);
fakeSignal = FakeProcessSignal();
signalUnderTest = ProcessSignal(fakeSignal);
});
testWithoutContext('signal handler runs', () async {
final Completer<void> completer = Completer<void>();
signals.addHandler(signalUnderTest, (ProcessSignal s) {
expect(s, signalUnderTest);
completer.complete();
});
fakeSignal.controller.add(fakeSignal);
await completer.future;
});
testWithoutContext('signal handlers run in order', () async {
final Completer<void> completer = Completer<void>();
bool first = false;
signals.addHandler(signalUnderTest, (ProcessSignal s) {
expect(s, signalUnderTest);
first = true;
});
signals.addHandler(signalUnderTest, (ProcessSignal s) {
expect(s, signalUnderTest);
expect(first, isTrue);
completer.complete();
});
fakeSignal.controller.add(fakeSignal);
await completer.future;
});
testWithoutContext('signal handlers do not cause concurrent modification errors when removing handlers in a signal callback', () async {
final Completer<void> completer = Completer<void>();
late Object token;
Future<void> handle(ProcessSignal s) async {
expect(s, signalUnderTest);
expect(await signals.removeHandler(signalUnderTest, token), true);
completer.complete();
}
token = signals.addHandler(signalUnderTest, handle);
fakeSignal.controller.add(fakeSignal);
await completer.future;
});
testWithoutContext('signal handler error goes on error stream', () async {
final Exception exn = Exception('Error');
signals.addHandler(signalUnderTest, (ProcessSignal s) async {
throw exn;
});
final Completer<void> completer = Completer<void>();
final List<Object> errList = <Object>[];
final StreamSubscription<Object> errSub = signals.errors.listen(
(Object err) {
errList.add(err);
completer.complete();
},
);
fakeSignal.controller.add(fakeSignal);
await completer.future;
await errSub.cancel();
expect(errList, contains(exn));
});
testWithoutContext('removed signal handler does not run', () async {
final Object token = signals.addHandler(
signalUnderTest,
(ProcessSignal s) async {
fail('Signal handler should have been removed.');
},
);
await signals.removeHandler(signalUnderTest, token);
final List<Object> errList = <Object>[];
final StreamSubscription<Object> errSub = signals.errors.listen(
(Object err) {
errList.add(err);
},
);
fakeSignal.controller.add(fakeSignal);
await errSub.cancel();
expect(errList, isEmpty);
});
testWithoutContext('non-removed signal handler still runs', () async {
final Completer<void> completer = Completer<void>();
signals.addHandler(signalUnderTest, (ProcessSignal s) {
expect(s, signalUnderTest);
completer.complete();
});
final Object token = signals.addHandler(
signalUnderTest,
(ProcessSignal s) async {
fail('Signal handler should have been removed.');
},
);
await signals.removeHandler(signalUnderTest, token);
final List<Object> errList = <Object>[];
final StreamSubscription<Object> errSub = signals.errors.listen(
(Object err) {
errList.add(err);
},
);
fakeSignal.controller.add(fakeSignal);
await completer.future;
await errSub.cancel();
expect(errList, isEmpty);
});
testWithoutContext('only handlers for the correct signal run', () async {
final FakeProcessSignal mockSignal2 = FakeProcessSignal();
final ProcessSignal otherSignal = ProcessSignal(mockSignal2);
final Completer<void> completer = Completer<void>();
signals.addHandler(signalUnderTest, (ProcessSignal s) {
expect(s, signalUnderTest);
completer.complete();
});
signals.addHandler(otherSignal, (ProcessSignal s) async {
fail('Wrong signal!.');
});
final List<Object> errList = <Object>[];
final StreamSubscription<Object> errSub = signals.errors.listen(
(Object err) {
errList.add(err);
},
);
fakeSignal.controller.add(fakeSignal);
await completer.future;
await errSub.cancel();
expect(errList, isEmpty);
});
testUsingContext('all handlers for exiting signals are run before exit', () async {
final Signals signals = Signals.test(
exitSignals: <ProcessSignal>[signalUnderTest],
shutdownHooks: shutdownHooks,
);
final Completer<void> completer = Completer<void>();
bool first = false;
bool second = false;
setExitFunctionForTests((int exitCode) {
// Both handlers have run before exit is called.
expect(first, isTrue);
expect(second, isTrue);
expect(exitCode, 0);
restoreExitFunction();
completer.complete();
});
signals.addHandler(signalUnderTest, (ProcessSignal s) {
expect(s, signalUnderTest);
expect(first, isFalse);
expect(second, isFalse);
first = true;
});
signals.addHandler(signalUnderTest, (ProcessSignal s) {
expect(s, signalUnderTest);
expect(first, isTrue);
expect(second, isFalse);
second = true;
});
fakeSignal.controller.add(fakeSignal);
await completer.future;
expect(shutdownHooks.ranShutdownHooks, isTrue);
});
testUsingContext('ShutdownHooks run before exiting', () async {
final Signals signals = Signals.test(
exitSignals: <ProcessSignal>[signalUnderTest],
shutdownHooks: shutdownHooks,
);
final Completer<void> completer = Completer<void>();
setExitFunctionForTests((int exitCode) {
expect(exitCode, 0);
restoreExitFunction();
completer.complete();
});
signals.addHandler(signalUnderTest, (ProcessSignal s) {});
fakeSignal.controller.add(fakeSignal);
await completer.future;
expect(shutdownHooks.ranShutdownHooks, isTrue);
});
});
}
class FakeProcessSignal extends Fake implements io.ProcessSignal {
final StreamController<io.ProcessSignal> controller = StreamController<io.ProcessSignal>();
@override
Stream<io.ProcessSignal> watch() => controller.stream;
}
class FakeShutdownHooks extends Fake implements ShutdownHooks {
bool ranShutdownHooks = false;
@override
Future<void> runShutdownHooks(Logger logger) async {
ranShutdownHooks = true;
}
}
| flutter/packages/flutter_tools/test/general.shard/base/signals_test.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/general.shard/base/signals_test.dart",
"repo_id": "flutter",
"token_count": 2945
} | 805 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:file/memory.dart';
import 'package:flutter_tools/src/artifacts.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/base/platform.dart';
import 'package:flutter_tools/src/build_info.dart';
import 'package:flutter_tools/src/build_system/build_system.dart';
import 'package:flutter_tools/src/build_system/exceptions.dart';
import 'package:flutter_tools/src/build_system/targets/common.dart';
import 'package:flutter_tools/src/build_system/targets/ios.dart';
import 'package:flutter_tools/src/compile.dart';
import '../../../src/common.dart';
import '../../../src/context.dart';
import '../../../src/fake_process_manager.dart';
const String kBoundaryKey = '4d2d9609-c662-4571-afde-31410f96caa6';
const String kElfAot = '--snapshot_kind=app-aot-elf';
const String kAssemblyAot = '--snapshot_kind=app-aot-assembly';
final Platform macPlatform = FakePlatform(operatingSystem: 'macos', environment: <String, String>{});
void main() {
late FakeProcessManager processManager;
late Environment androidEnvironment;
late Environment iosEnvironment;
late Artifacts artifacts;
late FileSystem fileSystem;
late Logger logger;
setUp(() {
processManager = FakeProcessManager.empty();
logger = BufferLogger.test();
artifacts = Artifacts.test();
fileSystem = MemoryFileSystem.test();
androidEnvironment = Environment.test(
fileSystem.currentDirectory,
defines: <String, String>{
kBuildMode: BuildMode.profile.cliName,
kTargetPlatform: getNameForTargetPlatform(TargetPlatform.android_arm),
},
inputs: <String, String>{},
artifacts: artifacts,
processManager: processManager,
fileSystem: fileSystem,
logger: logger,
);
androidEnvironment.buildDir.createSync(recursive: true);
iosEnvironment = Environment.test(
fileSystem.currentDirectory,
defines: <String, String>{
kBuildMode: BuildMode.profile.cliName,
kTargetPlatform: getNameForTargetPlatform(TargetPlatform.ios),
},
inputs: <String, String>{},
artifacts: artifacts,
processManager: processManager,
fileSystem: fileSystem,
logger: logger,
);
iosEnvironment.buildDir.createSync(recursive: true);
});
testWithoutContext('KernelSnapshot throws error if missing build mode', () async {
androidEnvironment.defines.remove(kBuildMode);
expect(
const KernelSnapshot().build(androidEnvironment),
throwsA(isA<MissingDefineException>()));
});
const String emptyNativeAssets = '''
format-version:
- 1
- 0
- 0
native-assets: {}
''';
testWithoutContext('KernelSnapshot handles null result from kernel compilation', () async {
fileSystem.file('.dart_tool/package_config.json')
..createSync(recursive: true)
..writeAsStringSync('{"configVersion": 2, "packages":[]}');
androidEnvironment.buildDir.childFile('native_assets.yaml')
..createSync(recursive: true)
..writeAsStringSync(emptyNativeAssets);
final String build = androidEnvironment.buildDir.path;
final String flutterPatchedSdkPath = artifacts.getArtifactPath(
Artifact.flutterPatchedSdkPath,
platform: TargetPlatform.android_arm,
mode: BuildMode.profile,
);
processManager.addCommands(<FakeCommand>[
FakeCommand(command: <String>[
artifacts.getArtifactPath(Artifact.engineDartAotRuntime),
'--disable-dart-dev',
artifacts.getArtifactPath(Artifact.frontendServerSnapshotForEngineDartSdk),
'--sdk-root',
'$flutterPatchedSdkPath/',
'--target=flutter',
'--no-print-incremental-dependencies',
...buildModeOptions(BuildMode.profile, <String>[]),
'--track-widget-creation',
'--aot',
'--tfa',
'--target-os',
'android',
'--packages',
'/.dart_tool/package_config.json',
'--output-dill',
'$build/app.dill',
'--depfile',
'$build/kernel_snapshot.d',
'--native-assets',
'$build/native_assets.yaml',
'--verbosity=error',
'file:///lib/main.dart',
], exitCode: 1),
]);
await expectLater(() => const KernelSnapshot().build(androidEnvironment), throwsException);
expect(processManager, hasNoRemainingExpectations);
});
testWithoutContext('KernelSnapshot does use track widget creation on profile builds', () async {
fileSystem.file('.dart_tool/package_config.json')
..createSync(recursive: true)
..writeAsStringSync('{"configVersion": 2, "packages":[]}');
androidEnvironment.buildDir.childFile('native_assets.yaml')
..createSync(recursive: true)
..writeAsStringSync(emptyNativeAssets);
final String build = androidEnvironment.buildDir.path;
final String flutterPatchedSdkPath = artifacts.getArtifactPath(
Artifact.flutterPatchedSdkPath,
platform: TargetPlatform.android_arm,
mode: BuildMode.profile,
);
processManager.addCommands(<FakeCommand>[
FakeCommand(command: <String>[
artifacts.getArtifactPath(Artifact.engineDartAotRuntime),
'--disable-dart-dev',
artifacts.getArtifactPath(Artifact.frontendServerSnapshotForEngineDartSdk),
'--sdk-root',
'$flutterPatchedSdkPath/',
'--target=flutter',
'--no-print-incremental-dependencies',
...buildModeOptions(BuildMode.profile, <String>[]),
'--track-widget-creation',
'--aot',
'--tfa',
'--target-os',
'android',
'--packages',
'/.dart_tool/package_config.json',
'--output-dill',
'$build/app.dill',
'--depfile',
'$build/kernel_snapshot.d',
'--native-assets',
'$build/native_assets.yaml',
'--verbosity=error',
'file:///lib/main.dart',
], stdout: 'result $kBoundaryKey\n$kBoundaryKey\n$kBoundaryKey $build/app.dill 0\n'),
]);
await const KernelSnapshot().build(androidEnvironment);
expect(processManager, hasNoRemainingExpectations);
});
testWithoutContext('KernelSnapshot correctly handles an empty string in ExtraFrontEndOptions', () async {
fileSystem.file('.dart_tool/package_config.json')
..createSync(recursive: true)
..writeAsStringSync('{"configVersion": 2, "packages":[]}');
androidEnvironment.buildDir.childFile('native_assets.yaml')
..createSync(recursive: true)
..writeAsStringSync(emptyNativeAssets);
final String build = androidEnvironment.buildDir.path;
final String flutterPatchedSdkPath = artifacts.getArtifactPath(
Artifact.flutterPatchedSdkPath,
platform: TargetPlatform.android_arm,
mode: BuildMode.profile,
);
processManager.addCommands(<FakeCommand>[
FakeCommand(command: <String>[
artifacts.getArtifactPath(Artifact.engineDartAotRuntime),
'--disable-dart-dev',
artifacts.getArtifactPath(Artifact.frontendServerSnapshotForEngineDartSdk),
'--sdk-root',
'$flutterPatchedSdkPath/',
'--target=flutter',
'--no-print-incremental-dependencies',
...buildModeOptions(BuildMode.profile, <String>[]),
'--track-widget-creation',
'--aot',
'--tfa',
'--target-os',
'android',
'--packages',
'/.dart_tool/package_config.json',
'--output-dill',
'$build/app.dill',
'--depfile',
'$build/kernel_snapshot.d',
'--native-assets',
'$build/native_assets.yaml',
'--verbosity=error',
'file:///lib/main.dart',
], stdout: 'result $kBoundaryKey\n$kBoundaryKey\n$kBoundaryKey $build/app.dill 0\n'),
]);
await const KernelSnapshot()
.build(androidEnvironment..defines[kExtraFrontEndOptions] = '');
expect(processManager, hasNoRemainingExpectations);
});
testWithoutContext('KernelSnapshot correctly forwards FrontendServerStarterPath', () async {
fileSystem.file('.dart_tool/package_config.json')
..createSync(recursive: true)
..writeAsStringSync('{"configVersion": 2, "packages":[]}');
androidEnvironment.buildDir.childFile('native_assets.yaml')
..createSync(recursive: true)
..writeAsStringSync(emptyNativeAssets);
final String build = androidEnvironment.buildDir.path;
final String flutterPatchedSdkPath = artifacts.getArtifactPath(
Artifact.flutterPatchedSdkPath,
platform: TargetPlatform.android_arm,
mode: BuildMode.profile,
);
processManager.addCommands(<FakeCommand>[
FakeCommand(command: <String>[
artifacts.getArtifactPath(Artifact.engineDartBinary),
'--disable-dart-dev',
'path/to/frontend_server_starter.dart',
'--sdk-root',
'$flutterPatchedSdkPath/',
'--target=flutter',
'--no-print-incremental-dependencies',
...buildModeOptions(BuildMode.profile, <String>[]),
'--track-widget-creation',
'--aot',
'--tfa',
'--target-os',
'android',
'--packages',
'/.dart_tool/package_config.json',
'--output-dill',
'$build/app.dill',
'--depfile',
'$build/kernel_snapshot.d',
'--native-assets',
'$build/native_assets.yaml',
'--verbosity=error',
'file:///lib/main.dart',
], stdout: 'result $kBoundaryKey\n$kBoundaryKey\n$kBoundaryKey $build/app.dill 0\n'),
]);
await const KernelSnapshot()
.build(androidEnvironment..defines[kFrontendServerStarterPath] = 'path/to/frontend_server_starter.dart');
expect(processManager, hasNoRemainingExpectations);
});
testWithoutContext('KernelSnapshot correctly forwards ExtraFrontEndOptions', () async {
fileSystem.file('.dart_tool/package_config.json')
..createSync(recursive: true)
..writeAsStringSync('{"configVersion": 2, "packages":[]}');
androidEnvironment.buildDir.childFile('native_assets.yaml')
..createSync(recursive: true)
..writeAsStringSync(emptyNativeAssets);
final String build = androidEnvironment.buildDir.path;
final String flutterPatchedSdkPath = artifacts.getArtifactPath(
Artifact.flutterPatchedSdkPath,
platform: TargetPlatform.android_arm,
mode: BuildMode.profile,
);
processManager.addCommands(<FakeCommand>[
FakeCommand(command: <String>[
artifacts.getArtifactPath(Artifact.engineDartAotRuntime),
'--disable-dart-dev',
artifacts.getArtifactPath(Artifact.frontendServerSnapshotForEngineDartSdk),
'--sdk-root',
'$flutterPatchedSdkPath/',
'--target=flutter',
'--no-print-incremental-dependencies',
...buildModeOptions(BuildMode.profile, <String>[]),
'--track-widget-creation',
'--aot',
'--tfa',
'--target-os',
'android',
'--packages',
'/.dart_tool/package_config.json',
'--output-dill',
'$build/app.dill',
'--depfile',
'$build/kernel_snapshot.d',
'--native-assets',
'$build/native_assets.yaml',
'--verbosity=error',
'foo',
'bar',
'file:///lib/main.dart',
], stdout: 'result $kBoundaryKey\n$kBoundaryKey\n$kBoundaryKey $build/app.dill 0\n'),
]);
await const KernelSnapshot()
.build(androidEnvironment..defines[kExtraFrontEndOptions] = 'foo,bar');
expect(processManager, hasNoRemainingExpectations);
});
testWithoutContext('KernelSnapshot can disable track-widget-creation on debug builds', () async {
fileSystem.file('.dart_tool/package_config.json')
..createSync(recursive: true)
..writeAsStringSync('{"configVersion": 2, "packages":[]}');
androidEnvironment.buildDir.childFile('native_assets.yaml')
..createSync(recursive: true)
..writeAsStringSync(emptyNativeAssets);
final String build = androidEnvironment.buildDir.path;
final String flutterPatchedSdkPath = artifacts.getArtifactPath(
Artifact.flutterPatchedSdkPath,
platform: TargetPlatform.android_arm,
mode: BuildMode.debug,
);
processManager.addCommands(<FakeCommand>[
FakeCommand(command: <String>[
artifacts.getArtifactPath(Artifact.engineDartAotRuntime),
'--disable-dart-dev',
artifacts.getArtifactPath(Artifact.frontendServerSnapshotForEngineDartSdk),
'--sdk-root',
'$flutterPatchedSdkPath/',
'--target=flutter',
'--no-print-incremental-dependencies',
...buildModeOptions(BuildMode.debug, <String>[]),
'--no-link-platform',
'--packages',
'/.dart_tool/package_config.json',
'--output-dill',
'$build/app.dill',
'--depfile',
'$build/kernel_snapshot.d',
'--incremental',
'--initialize-from-dill',
'$build/app.dill',
'--native-assets',
'$build/native_assets.yaml',
'--verbosity=error',
'file:///lib/main.dart',
], stdout: 'result $kBoundaryKey\n$kBoundaryKey\n$kBoundaryKey $build/app.dill 0\n'),
]);
await const KernelSnapshot().build(androidEnvironment
..defines[kBuildMode] = BuildMode.debug.cliName
..defines[kTrackWidgetCreation] = 'false');
expect(processManager, hasNoRemainingExpectations);
});
testWithoutContext('KernelSnapshot forces platform linking on debug for darwin target platforms', () async {
fileSystem.file('.dart_tool/package_config.json')
..createSync(recursive: true)
..writeAsStringSync('{"configVersion": 2, "packages":[]}');
androidEnvironment.buildDir.childFile('native_assets.yaml')
..createSync(recursive: true)
..writeAsStringSync(emptyNativeAssets);
final String build = androidEnvironment.buildDir.path;
final String flutterPatchedSdkPath = artifacts.getArtifactPath(
Artifact.flutterPatchedSdkPath,
platform: TargetPlatform.darwin,
mode: BuildMode.debug,
);
processManager.addCommands(<FakeCommand>[
FakeCommand(command: <String>[
artifacts.getArtifactPath(Artifact.engineDartAotRuntime),
'--disable-dart-dev',
artifacts.getArtifactPath(Artifact.frontendServerSnapshotForEngineDartSdk),
'--sdk-root',
'$flutterPatchedSdkPath/',
'--target=flutter',
'--no-print-incremental-dependencies',
...buildModeOptions(BuildMode.debug, <String>[]),
'--packages',
'/.dart_tool/package_config.json',
'--output-dill',
'$build/app.dill',
'--depfile',
'$build/kernel_snapshot.d',
'--incremental',
'--initialize-from-dill',
'$build/app.dill',
'--native-assets',
'$build/native_assets.yaml',
'--verbosity=error',
'file:///lib/main.dart',
], stdout: 'result $kBoundaryKey\n$kBoundaryKey\n$kBoundaryKey $build/app.dill 0\n'),
]);
await const KernelSnapshot().build(androidEnvironment
..defines[kTargetPlatform] = getNameForTargetPlatform(TargetPlatform.darwin)
..defines[kBuildMode] = BuildMode.debug.cliName
..defines[kTrackWidgetCreation] = 'false'
);
expect(processManager, hasNoRemainingExpectations);
});
testWithoutContext('KernelSnapshot does use track widget creation on debug builds', () async {
fileSystem.file('.dart_tool/package_config.json')
..createSync(recursive: true)
..writeAsStringSync('{"configVersion": 2, "packages":[]}');
final Environment testEnvironment = Environment.test(
fileSystem.currentDirectory,
defines: <String, String>{
kBuildMode: BuildMode.debug.cliName,
kTargetPlatform: getNameForTargetPlatform(TargetPlatform.android_arm),
},
processManager: processManager,
artifacts: artifacts,
fileSystem: fileSystem,
logger: logger,
);
testEnvironment.buildDir.childFile('native_assets.yaml')
..createSync(recursive: true)
..writeAsStringSync(emptyNativeAssets);
final String build = testEnvironment.buildDir.path;
final String flutterPatchedSdkPath = artifacts.getArtifactPath(
Artifact.flutterPatchedSdkPath,
platform: TargetPlatform.android_arm,
mode: BuildMode.debug,
);
processManager.addCommands(<FakeCommand>[
FakeCommand(command: <String>[
artifacts.getArtifactPath(Artifact.engineDartAotRuntime),
'--disable-dart-dev',
artifacts.getArtifactPath(Artifact.frontendServerSnapshotForEngineDartSdk),
'--sdk-root',
'$flutterPatchedSdkPath/',
'--target=flutter',
'--no-print-incremental-dependencies',
...buildModeOptions(BuildMode.debug, <String>[]),
'--track-widget-creation',
'--no-link-platform',
'--packages',
'/.dart_tool/package_config.json',
'--output-dill',
'$build/app.dill',
'--depfile',
'$build/kernel_snapshot.d',
'--incremental',
'--initialize-from-dill',
'$build/app.dill',
'--native-assets',
'$build/native_assets.yaml',
'--verbosity=error',
'file:///lib/main.dart',
], stdout: 'result $kBoundaryKey\n$kBoundaryKey\n$kBoundaryKey /build/653e11a8e6908714056a57cd6b4f602a/app.dill 0\n'),
]);
await const KernelSnapshot().build(testEnvironment);
expect(processManager, hasNoRemainingExpectations);
});
testUsingContext('AotElfProfile Produces correct output directory', () async {
final String build = androidEnvironment.buildDir.path;
processManager.addCommands(<FakeCommand>[
FakeCommand(command: <String>[
artifacts.getArtifactPath(
Artifact.genSnapshot,
platform: TargetPlatform.android_arm,
mode: BuildMode.profile,
),
'--deterministic',
kElfAot,
'--elf=$build/app.so',
'--strip',
'--no-sim-use-hardfp',
'--no-use-integer-division',
'$build/app.dill',
]),
]);
androidEnvironment.buildDir.childFile('app.dill').createSync(recursive: true);
await const AotElfProfile(TargetPlatform.android_arm).build(androidEnvironment);
expect(processManager, hasNoRemainingExpectations);
});
testUsingContext('AotElfRelease configures gen_snapshot with code size directory', () async {
androidEnvironment.defines[kCodeSizeDirectory] = 'code_size_1';
final String build = androidEnvironment.buildDir.path;
processManager.addCommands(<FakeCommand>[
FakeCommand(command: <String>[
artifacts.getArtifactPath(
Artifact.genSnapshot,
platform: TargetPlatform.android_arm,
mode: BuildMode.profile,
),
'--deterministic',
'--write-v8-snapshot-profile-to=code_size_1/snapshot.android-arm.json',
'--trace-precompiler-to=code_size_1/trace.android-arm.json',
kElfAot,
'--elf=$build/app.so',
'--strip',
'--no-sim-use-hardfp',
'--no-use-integer-division',
'$build/app.dill',
]),
]);
androidEnvironment.buildDir.childFile('app.dill').createSync(recursive: true);
await const AotElfRelease(TargetPlatform.android_arm).build(androidEnvironment);
expect(processManager, hasNoRemainingExpectations);
});
testUsingContext('AotElfProfile throws error if missing build mode', () async {
androidEnvironment.defines.remove(kBuildMode);
expect(const AotElfProfile(TargetPlatform.android_arm).build(androidEnvironment),
throwsA(isA<MissingDefineException>()));
});
testUsingContext('AotElfProfile throws error if missing target platform', () async {
androidEnvironment.defines.remove(kTargetPlatform);
expect(const AotElfProfile(TargetPlatform.android_arm).build(androidEnvironment),
throwsA(isA<MissingDefineException>()));
});
testUsingContext('AotAssemblyProfile throws error if missing build mode', () async {
iosEnvironment.defines.remove(kBuildMode);
expect(const AotAssemblyProfile().build(iosEnvironment),
throwsA(isA<MissingDefineException>()));
}, overrides: <Type, Generator>{
Platform: () => macPlatform,
FileSystem: () => fileSystem,
ProcessManager: () => processManager,
});
testUsingContext('AotAssemblyProfile throws error if missing target platform', () async {
iosEnvironment.defines.remove(kTargetPlatform);
expect(const AotAssemblyProfile().build(iosEnvironment),
throwsA(isA<MissingDefineException>()));
}, overrides: <Type, Generator>{
Platform: () => macPlatform,
FileSystem: () => fileSystem,
ProcessManager: () => processManager,
});
testUsingContext('AotAssemblyProfile throws error if built for non-iOS platform', () async {
expect(const AotAssemblyProfile().build(androidEnvironment), throwsException);
}, overrides: <Type, Generator>{
Platform: () => macPlatform,
FileSystem: () => fileSystem,
ProcessManager: () => processManager,
});
testUsingContext('AotAssemblyRelease configures gen_snapshot with code size directory', () async {
iosEnvironment.defines[kCodeSizeDirectory] = 'code_size_1';
iosEnvironment.defines[kIosArchs] = 'arm64';
iosEnvironment.defines[kSdkRoot] = 'path/to/iPhoneOS.sdk';
final String build = iosEnvironment.buildDir.path;
processManager.addCommands(<FakeCommand>[
FakeCommand(command: <String>[
// This path is not known by the cache due to the iOS gen_snapshot split.
'Artifact.genSnapshot.TargetPlatform.ios.profile_arm64',
'--deterministic',
'--write-v8-snapshot-profile-to=code_size_1/snapshot.arm64.json',
'--trace-precompiler-to=code_size_1/trace.arm64.json',
kAssemblyAot,
'--assembly=$build/arm64/snapshot_assembly.S',
'$build/app.dill',
]),
FakeCommand(command: <String>[
'xcrun',
'cc',
'-arch',
'arm64',
'-miphoneos-version-min=12.0',
'-isysroot',
'path/to/iPhoneOS.sdk',
'-c',
'$build/arm64/snapshot_assembly.S',
'-o',
'$build/arm64/snapshot_assembly.o',
]),
FakeCommand(command: <String>[
'xcrun',
'clang',
'-arch',
'arm64',
'-miphoneos-version-min=12.0',
'-isysroot',
'path/to/iPhoneOS.sdk',
'-dynamiclib',
'-Xlinker',
'-rpath',
'-Xlinker',
'@executable_path/Frameworks',
'-Xlinker',
'-rpath',
'-Xlinker',
'@loader_path/Frameworks',
'-fapplication-extension',
'-install_name',
'@rpath/App.framework/App',
'-o',
'$build/arm64/App.framework/App',
'$build/arm64/snapshot_assembly.o',
]),
FakeCommand(command: <String>[
'xcrun',
'dsymutil',
'-o',
'$build/arm64/App.framework.dSYM',
'$build/arm64/App.framework/App',
]),
FakeCommand(command: <String>[
'xcrun',
'strip',
'-x',
'$build/arm64/App.framework/App',
'-o',
'$build/arm64/App.framework/App',
]),
FakeCommand(command: <String>[
'lipo',
'$build/arm64/App.framework/App',
'-create',
'-output',
'$build/App.framework/App',
]),
]);
await const AotAssemblyProfile().build(iosEnvironment);
expect(processManager, hasNoRemainingExpectations);
}, overrides: <Type, Generator>{
Platform: () => macPlatform,
FileSystem: () => fileSystem,
ProcessManager: () => processManager,
});
testUsingContext('kExtraGenSnapshotOptions passes values to gen_snapshot', () async {
androidEnvironment.defines[kExtraGenSnapshotOptions] = 'foo,bar,baz=2';
androidEnvironment.defines[kBuildMode] = BuildMode.profile.cliName;
final String build = androidEnvironment.buildDir.path;
processManager.addCommands(<FakeCommand>[
FakeCommand(command: <String>[
artifacts.getArtifactPath(
Artifact.genSnapshot,
platform: TargetPlatform.android_arm,
mode: BuildMode.profile,
),
'--deterministic',
'foo',
'bar',
'baz=2',
kElfAot,
'--elf=$build/app.so',
'--strip',
'--no-sim-use-hardfp',
'--no-use-integer-division',
'$build/app.dill',
]),
]);
await const AotElfRelease(TargetPlatform.android_arm).build(androidEnvironment);
expect(processManager, hasNoRemainingExpectations);
});
}
| flutter/packages/flutter_tools/test/general.shard/build_system/targets/common_test.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/general.shard/build_system/targets/common_test.dart",
"repo_id": "flutter",
"token_count": 10088
} | 806 |
// 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:file_testing/file_testing.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/cmake.dart';
import 'package:flutter_tools/src/project.dart';
import '../src/common.dart';
const String _kTestFlutterRoot = '/flutter';
const String _kTestWindowsFlutterRoot = r'C:\flutter';
void main() {
late FileSystem fileSystem;
late BufferLogger logger;
setUp(() {
fileSystem = MemoryFileSystem.test();
logger = BufferLogger.test();
});
testWithoutContext('parses executable name from cmake file', () async {
final FlutterProject project = FlutterProject.fromDirectoryTest(fileSystem.currentDirectory);
final CmakeBasedProject cmakeProject = _FakeProject.fromFlutter(project);
cmakeProject.cmakeFile
..createSync(recursive: true)
..writeAsStringSync('set(BINARY_NAME "hello")');
final String? name = getCmakeExecutableName(cmakeProject);
expect(name, 'hello');
});
testWithoutContext('defaults executable name to null if cmake config does not exist', () async {
final FlutterProject project = FlutterProject.fromDirectoryTest(fileSystem.currentDirectory);
final CmakeBasedProject cmakeProject = _FakeProject.fromFlutter(project);
final String? name = getCmakeExecutableName(cmakeProject);
expect(name, isNull);
});
testWithoutContext('generates config', () async {
final FlutterProject project = FlutterProject.fromDirectoryTest(fileSystem.currentDirectory);
final CmakeBasedProject cmakeProject = _FakeProject.fromFlutter(project);
const BuildInfo buildInfo = BuildInfo(BuildMode.release, null, treeShakeIcons: false);
final Map<String, String> environment = <String, String>{};
writeGeneratedCmakeConfig(
_kTestFlutterRoot,
cmakeProject,
buildInfo,
environment,
logger,
);
final File cmakeConfig = cmakeProject.generatedCmakeConfigFile;
expect(cmakeConfig, exists);
final List<String> configLines = cmakeConfig.readAsLinesSync();
expect(configLines, containsAll(<String>[
r'# Generated code do not commit.',
r'file(TO_CMAKE_PATH "/flutter" FLUTTER_ROOT)',
r'file(TO_CMAKE_PATH "/" PROJECT_DIR)',
r'set(FLUTTER_VERSION "1.0.0" PARENT_SCOPE)',
r'set(FLUTTER_VERSION_MAJOR 1 PARENT_SCOPE)',
r'set(FLUTTER_VERSION_MINOR 0 PARENT_SCOPE)',
r'set(FLUTTER_VERSION_PATCH 0 PARENT_SCOPE)',
r'set(FLUTTER_VERSION_BUILD 0 PARENT_SCOPE)',
r'# Environment variables to pass to tool_backend.sh',
r'list(APPEND FLUTTER_TOOL_ENVIRONMENT',
r' "FLUTTER_ROOT=/flutter"',
r' "PROJECT_DIR=/"',
r')',
]));
});
testWithoutContext('config escapes backslashes', () async {
fileSystem = MemoryFileSystem.test(style: FileSystemStyle.windows);
final FlutterProject project = FlutterProject.fromDirectoryTest(fileSystem.currentDirectory);
final CmakeBasedProject cmakeProject = _FakeProject.fromFlutter(project);
const BuildInfo buildInfo = BuildInfo(BuildMode.release, null, treeShakeIcons: false);
final Map<String, String> environment = <String, String>{
'TEST': r'hello\world',
};
writeGeneratedCmakeConfig(
_kTestWindowsFlutterRoot,
cmakeProject,
buildInfo,
environment,
logger,
);
final File cmakeConfig = cmakeProject.generatedCmakeConfigFile;
expect(cmakeConfig, exists);
final List<String> configLines = cmakeConfig.readAsLinesSync();
expect(configLines, containsAll(<String>[
r'# Generated code do not commit.',
r'file(TO_CMAKE_PATH "C:\\flutter" FLUTTER_ROOT)',
r'file(TO_CMAKE_PATH "C:\\" PROJECT_DIR)',
r'set(FLUTTER_VERSION "1.0.0" PARENT_SCOPE)',
r'set(FLUTTER_VERSION_MAJOR 1 PARENT_SCOPE)',
r'set(FLUTTER_VERSION_MINOR 0 PARENT_SCOPE)',
r'set(FLUTTER_VERSION_PATCH 0 PARENT_SCOPE)',
r'set(FLUTTER_VERSION_BUILD 0 PARENT_SCOPE)',
r'# Environment variables to pass to tool_backend.sh',
r'list(APPEND FLUTTER_TOOL_ENVIRONMENT',
r' "FLUTTER_ROOT=C:\\flutter"',
r' "PROJECT_DIR=C:\\"',
r' "TEST=hello\\world"',
r')',
]));
});
testWithoutContext('generated config uses pubspec version', () async {
fileSystem.file('pubspec.yaml')
..createSync()
..writeAsStringSync('version: 1.2.3+4');
final FlutterProject project = FlutterProject.fromDirectoryTest(fileSystem.currentDirectory);
final CmakeBasedProject cmakeProject = _FakeProject.fromFlutter(project);
const BuildInfo buildInfo = BuildInfo(BuildMode.release, null, treeShakeIcons: false);
final Map<String, String> environment = <String, String>{};
writeGeneratedCmakeConfig(
_kTestFlutterRoot,
cmakeProject,
buildInfo,
environment,
logger,
);
final File cmakeConfig = cmakeProject.generatedCmakeConfigFile;
expect(cmakeConfig, exists);
final List<String> configLines = cmakeConfig.readAsLinesSync();
expect(configLines, containsAll(<String>[
'set(FLUTTER_VERSION "1.2.3+4" PARENT_SCOPE)',
'set(FLUTTER_VERSION_MAJOR 1 PARENT_SCOPE)',
'set(FLUTTER_VERSION_MINOR 2 PARENT_SCOPE)',
'set(FLUTTER_VERSION_PATCH 3 PARENT_SCOPE)',
'set(FLUTTER_VERSION_BUILD 4 PARENT_SCOPE)',
]));
});
testWithoutContext('generated config uses build name', () async {
final FlutterProject project = FlutterProject.fromDirectoryTest(fileSystem.currentDirectory);
final CmakeBasedProject cmakeProject = _FakeProject.fromFlutter(project);
const BuildInfo buildInfo = BuildInfo(
BuildMode.release,
null,
buildName: '1.2.3',
treeShakeIcons: false,
);
final Map<String, String> environment = <String, String>{};
writeGeneratedCmakeConfig(
_kTestFlutterRoot,
cmakeProject,
buildInfo,
environment,
logger,
);
final File cmakeConfig = cmakeProject.generatedCmakeConfigFile;
expect(cmakeConfig, exists);
final List<String> configLines = cmakeConfig.readAsLinesSync();
expect(configLines, containsAll(<String>[
'set(FLUTTER_VERSION "1.2.3" PARENT_SCOPE)',
'set(FLUTTER_VERSION_MAJOR 1 PARENT_SCOPE)',
'set(FLUTTER_VERSION_MINOR 2 PARENT_SCOPE)',
'set(FLUTTER_VERSION_PATCH 3 PARENT_SCOPE)',
'set(FLUTTER_VERSION_BUILD 0 PARENT_SCOPE)',
]));
});
testWithoutContext('generated config uses build number', () async {
final FlutterProject project = FlutterProject.fromDirectoryTest(fileSystem.currentDirectory);
final CmakeBasedProject cmakeProject = _FakeProject.fromFlutter(project);
const BuildInfo buildInfo = BuildInfo(
BuildMode.release,
null,
buildNumber: '4',
treeShakeIcons: false,
);
final Map<String, String> environment = <String, String>{};
writeGeneratedCmakeConfig(
_kTestFlutterRoot,
cmakeProject,
buildInfo,
environment,
logger,
);
final File cmakeConfig = cmakeProject.generatedCmakeConfigFile;
expect(cmakeConfig, exists);
final List<String> configLines = cmakeConfig.readAsLinesSync();
expect(configLines, containsAll(<String>[
'set(FLUTTER_VERSION "1.0.0+4" 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 4 PARENT_SCOPE)',
]));
});
testWithoutContext('generated config uses build name and build number', () async {
final FlutterProject project = FlutterProject.fromDirectoryTest(fileSystem.currentDirectory);
final CmakeBasedProject cmakeProject = _FakeProject.fromFlutter(project);
const BuildInfo buildInfo = BuildInfo(
BuildMode.release,
null,
buildName: '1.2.3',
buildNumber: '4',
treeShakeIcons: false,
);
final Map<String, String> environment = <String, String>{};
writeGeneratedCmakeConfig(
_kTestFlutterRoot,
cmakeProject,
buildInfo,
environment,
logger,
);
final File cmakeConfig = cmakeProject.generatedCmakeConfigFile;
expect(cmakeConfig, exists);
final List<String> configLines = cmakeConfig.readAsLinesSync();
expect(configLines, containsAll(<String>[
'set(FLUTTER_VERSION "1.2.3+4" PARENT_SCOPE)',
'set(FLUTTER_VERSION_MAJOR 1 PARENT_SCOPE)',
'set(FLUTTER_VERSION_MINOR 2 PARENT_SCOPE)',
'set(FLUTTER_VERSION_PATCH 3 PARENT_SCOPE)',
'set(FLUTTER_VERSION_BUILD 4 PARENT_SCOPE)',
]));
});
testWithoutContext('generated config uses build name over pubspec version', () async {
fileSystem.file('pubspec.yaml')
..createSync()
..writeAsStringSync('version: 9.9.9+9');
final FlutterProject project = FlutterProject.fromDirectoryTest(fileSystem.currentDirectory);
final CmakeBasedProject cmakeProject = _FakeProject.fromFlutter(project);
const BuildInfo buildInfo = BuildInfo(
BuildMode.release,
null,
buildName: '1.2.3',
treeShakeIcons: false,
);
final Map<String, String> environment = <String, String>{};
writeGeneratedCmakeConfig(
_kTestFlutterRoot,
cmakeProject,
buildInfo,
environment,
logger,
);
final File cmakeConfig = cmakeProject.generatedCmakeConfigFile;
expect(cmakeConfig, exists);
final List<String> configLines = cmakeConfig.readAsLinesSync();
expect(configLines, containsAll(<String>[
'set(FLUTTER_VERSION "1.2.3" PARENT_SCOPE)',
'set(FLUTTER_VERSION_MAJOR 1 PARENT_SCOPE)',
'set(FLUTTER_VERSION_MINOR 2 PARENT_SCOPE)',
'set(FLUTTER_VERSION_PATCH 3 PARENT_SCOPE)',
'set(FLUTTER_VERSION_BUILD 0 PARENT_SCOPE)',
]));
});
testWithoutContext('generated config uses build number over pubspec version', () async {
fileSystem.file('pubspec.yaml')
..createSync()
..writeAsStringSync('version: 1.2.3+4');
final FlutterProject project = FlutterProject.fromDirectoryTest(fileSystem.currentDirectory);
final CmakeBasedProject cmakeProject = _FakeProject.fromFlutter(project);
const BuildInfo buildInfo = BuildInfo(
BuildMode.release,
null,
buildNumber: '5',
treeShakeIcons: false,
);
final Map<String, String> environment = <String, String>{};
writeGeneratedCmakeConfig(
_kTestFlutterRoot,
cmakeProject,
buildInfo,
environment,
logger,
);
final File cmakeConfig = cmakeProject.generatedCmakeConfigFile;
expect(cmakeConfig, exists);
final List<String> configLines = cmakeConfig.readAsLinesSync();
expect(configLines, containsAll(<String>[
'set(FLUTTER_VERSION "1.2.3+5" PARENT_SCOPE)',
'set(FLUTTER_VERSION_MAJOR 1 PARENT_SCOPE)',
'set(FLUTTER_VERSION_MINOR 2 PARENT_SCOPE)',
'set(FLUTTER_VERSION_PATCH 3 PARENT_SCOPE)',
'set(FLUTTER_VERSION_BUILD 5 PARENT_SCOPE)',
]));
});
testWithoutContext('generated config uses build name and build number over pubspec version', () async {
fileSystem.file('pubspec.yaml')
..createSync()
..writeAsStringSync('version: 9.9.9+9');
final FlutterProject project = FlutterProject.fromDirectoryTest(fileSystem.currentDirectory);
final CmakeBasedProject cmakeProject = _FakeProject.fromFlutter(project);
const BuildInfo buildInfo = BuildInfo(
BuildMode.release,
null,
buildName: '1.2.3',
buildNumber: '4',
treeShakeIcons: false,
);
final Map<String, String> environment = <String, String>{};
writeGeneratedCmakeConfig(
_kTestFlutterRoot,
cmakeProject,
buildInfo,
environment,
logger,
);
final File cmakeConfig = cmakeProject.generatedCmakeConfigFile;
expect(cmakeConfig, exists);
final List<String> configLines = cmakeConfig.readAsLinesSync();
expect(configLines, containsAll(<String>[
'set(FLUTTER_VERSION "1.2.3+4" PARENT_SCOPE)',
'set(FLUTTER_VERSION_MAJOR 1 PARENT_SCOPE)',
'set(FLUTTER_VERSION_MINOR 2 PARENT_SCOPE)',
'set(FLUTTER_VERSION_PATCH 3 PARENT_SCOPE)',
'set(FLUTTER_VERSION_BUILD 4 PARENT_SCOPE)',
]));
});
testWithoutContext('generated config ignores invalid build name', () async {
final FlutterProject project = FlutterProject.fromDirectoryTest(fileSystem.currentDirectory);
final CmakeBasedProject cmakeProject = _FakeProject.fromFlutter(project);
const BuildInfo buildInfo = BuildInfo(
BuildMode.release,
null,
buildName: 'hello.world',
treeShakeIcons: false,
);
final Map<String, String> environment = <String, String>{};
writeGeneratedCmakeConfig(
_kTestFlutterRoot,
cmakeProject,
buildInfo,
environment,
logger,
);
final File cmakeConfig = cmakeProject.generatedCmakeConfigFile;
expect(cmakeConfig, exists);
final List<String> configLines = cmakeConfig.readAsLinesSync();
expect(configLines, containsAll(<String>[
'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)',
]));
expect(logger.warningText, contains('Warning: could not parse version hello.world, defaulting to 1.0.0.'));
});
testWithoutContext('generated config ignores invalid build number', () async {
final FlutterProject project = FlutterProject.fromDirectoryTest(fileSystem.currentDirectory);
final CmakeBasedProject cmakeProject = _FakeProject.fromFlutter(project);
const BuildInfo buildInfo = BuildInfo(
BuildMode.release,
null,
buildName: '1.2.3',
buildNumber: 'foo_bar',
treeShakeIcons: false,
);
final Map<String, String> environment = <String, String>{};
writeGeneratedCmakeConfig(
_kTestFlutterRoot,
cmakeProject,
buildInfo,
environment,
logger,
);
final File cmakeConfig = cmakeProject.generatedCmakeConfigFile;
expect(cmakeConfig, exists);
final List<String> configLines = cmakeConfig.readAsLinesSync();
expect(configLines, containsAll(<String>[
'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)',
]));
expect(logger.warningText, contains('Warning: could not parse version 1.2.3+foo_bar, defaulting to 1.0.0.'));
});
testWithoutContext('generated config handles non-numeric build number', () async {
final FlutterProject project = FlutterProject.fromDirectoryTest(fileSystem.currentDirectory);
final CmakeBasedProject cmakeProject = _FakeProject.fromFlutter(project);
const BuildInfo buildInfo = BuildInfo(
BuildMode.release,
null,
buildName: '1.2.3',
buildNumber: 'hello',
treeShakeIcons: false,
);
final Map<String, String> environment = <String, String>{};
writeGeneratedCmakeConfig(
_kTestFlutterRoot,
cmakeProject,
buildInfo,
environment,
logger,
);
expect(logger.warningText, isEmpty);
final File cmakeConfig = cmakeProject.generatedCmakeConfigFile;
expect(cmakeConfig, exists);
final List<String> configLines = cmakeConfig.readAsLinesSync();
expect(configLines, containsAll(<String>[
'set(FLUTTER_VERSION "1.2.3+hello" PARENT_SCOPE)',
'set(FLUTTER_VERSION_MAJOR 1 PARENT_SCOPE)',
'set(FLUTTER_VERSION_MINOR 2 PARENT_SCOPE)',
'set(FLUTTER_VERSION_PATCH 3 PARENT_SCOPE)',
'set(FLUTTER_VERSION_BUILD 0 PARENT_SCOPE)',
]));
});
testWithoutContext('generated config handles complex build number', () async {
final FlutterProject project = FlutterProject.fromDirectoryTest(fileSystem.currentDirectory);
final CmakeBasedProject cmakeProject = _FakeProject.fromFlutter(project);
const BuildInfo buildInfo = BuildInfo(
BuildMode.release,
null,
buildName: '1.2.3',
buildNumber: '4.5',
treeShakeIcons: false,
);
final Map<String, String> environment = <String, String>{};
writeGeneratedCmakeConfig(
_kTestFlutterRoot,
cmakeProject,
buildInfo,
environment,
logger,
);
expect(logger.warningText, isEmpty);
final File cmakeConfig = cmakeProject.generatedCmakeConfigFile;
expect(cmakeConfig, exists);
final List<String> configLines = cmakeConfig.readAsLinesSync();
expect(configLines, containsAll(<String>[
'set(FLUTTER_VERSION "1.2.3+4.5" PARENT_SCOPE)',
'set(FLUTTER_VERSION_MAJOR 1 PARENT_SCOPE)',
'set(FLUTTER_VERSION_MINOR 2 PARENT_SCOPE)',
'set(FLUTTER_VERSION_PATCH 3 PARENT_SCOPE)',
'set(FLUTTER_VERSION_BUILD 0 PARENT_SCOPE)',
]));
});
testWithoutContext('generated config warns on Windows project with non-numeric build number', () async {
final FlutterProject project = FlutterProject.fromDirectoryTest(fileSystem.currentDirectory);
final CmakeBasedProject cmakeProject = WindowsProject.fromFlutter(project);
const BuildInfo buildInfo = BuildInfo(
BuildMode.release,
null,
buildName: '1.2.3',
buildNumber: 'hello',
treeShakeIcons: false,
);
final Map<String, String> environment = <String, String>{};
writeGeneratedCmakeConfig(
_kTestFlutterRoot,
cmakeProject,
buildInfo,
environment,
logger,
);
expect(logger.warningText, contains(
'Warning: build identifier hello in version 1.2.3+hello is not numeric and '
'cannot be converted into a Windows build version number. Defaulting to 0.\n'
'This may cause issues with Windows installers.'
));
final File cmakeConfig = cmakeProject.generatedCmakeConfigFile;
expect(cmakeConfig, exists);
final List<String> configLines = cmakeConfig.readAsLinesSync();
expect(configLines, containsAll(<String>[
'set(FLUTTER_VERSION "1.2.3+hello" PARENT_SCOPE)',
'set(FLUTTER_VERSION_MAJOR 1 PARENT_SCOPE)',
'set(FLUTTER_VERSION_MINOR 2 PARENT_SCOPE)',
'set(FLUTTER_VERSION_PATCH 3 PARENT_SCOPE)',
'set(FLUTTER_VERSION_BUILD 0 PARENT_SCOPE)',
]));
});
testWithoutContext('generated config warns on Windows project with complex build number', () async {
final FlutterProject project = FlutterProject.fromDirectoryTest(fileSystem.currentDirectory);
final CmakeBasedProject cmakeProject = WindowsProject.fromFlutter(project);
const BuildInfo buildInfo = BuildInfo(
BuildMode.release,
null,
buildName: '1.2.3',
buildNumber: '4.5',
treeShakeIcons: false,
);
final Map<String, String> environment = <String, String>{};
writeGeneratedCmakeConfig(
_kTestFlutterRoot,
cmakeProject,
buildInfo,
environment,
logger,
);
expect(logger.warningText, contains(
'Warning: build identifier 4.5 in version 1.2.3+4.5 is not numeric and '
'cannot be converted into a Windows build version number. Defaulting to 0.\n'
'This may cause issues with Windows installers.'
));
final File cmakeConfig = cmakeProject.generatedCmakeConfigFile;
expect(cmakeConfig, exists);
final List<String> configLines = cmakeConfig.readAsLinesSync();
expect(configLines, containsAll(<String>[
'set(FLUTTER_VERSION "1.2.3+4.5" PARENT_SCOPE)',
'set(FLUTTER_VERSION_MAJOR 1 PARENT_SCOPE)',
'set(FLUTTER_VERSION_MINOR 2 PARENT_SCOPE)',
'set(FLUTTER_VERSION_PATCH 3 PARENT_SCOPE)',
'set(FLUTTER_VERSION_BUILD 0 PARENT_SCOPE)',
]));
});
}
class _FakeProject implements CmakeBasedProject {
_FakeProject.fromFlutter(this._parent);
final FlutterProject _parent;
@override
bool existsSync() => _editableDirectory.existsSync();
@override
File get cmakeFile => _editableDirectory.childFile('CMakeLists.txt');
@override
File get managedCmakeFile => _managedDirectory.childFile('CMakeLists.txt');
@override
File get generatedCmakeConfigFile => _ephemeralDirectory.childFile('generated_config.cmake');
@override
File get generatedPluginCmakeFile => _managedDirectory.childFile('generated_plugins.cmake');
@override
Directory get pluginSymlinkDirectory => _ephemeralDirectory.childDirectory('.plugin_symlinks');
@override
FlutterProject get parent => _parent;
Directory get _editableDirectory => parent.directory.childDirectory('test');
Directory get _managedDirectory => _editableDirectory.childDirectory('flutter');
Directory get _ephemeralDirectory => _managedDirectory.childDirectory('ephemeral');
}
| flutter/packages/flutter_tools/test/general.shard/cmake_test.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/general.shard/cmake_test.dart",
"repo_id": "flutter",
"token_count": 8030
} | 807 |
// 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/file.dart';
import 'package:file/memory.dart';
import 'package:file_testing/file_testing.dart';
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/build_info.dart';
import 'package:flutter_tools/src/build_system/build_system.dart';
import 'package:flutter_tools/src/bundle.dart';
import 'package:flutter_tools/src/bundle_builder.dart';
import 'package:flutter_tools/src/convert.dart';
import 'package:flutter_tools/src/custom_devices/custom_device.dart';
import 'package:flutter_tools/src/custom_devices/custom_device_config.dart';
import 'package:flutter_tools/src/custom_devices/custom_devices_config.dart';
import 'package:flutter_tools/src/device.dart';
import 'package:flutter_tools/src/globals.dart' as globals;
import 'package:flutter_tools/src/linux/application_package.dart';
import 'package:flutter_tools/src/project.dart';
import 'package:meta/meta.dart';
import 'package:test/fake.dart';
import '../../src/common.dart';
import '../../src/context.dart';
import '../../src/fakes.dart';
void _writeCustomDevicesConfigFile(Directory dir, List<CustomDeviceConfig> configs) {
dir.createSync();
final File file = dir.childFile('.flutter_custom_devices.json');
file.writeAsStringSync(jsonEncode(
<String, dynamic>{
'custom-devices': configs.map<dynamic>((CustomDeviceConfig c) => c.toJson()).toList(),
}
));
}
FlutterProject _setUpFlutterProject(Directory directory) {
final FlutterProjectFactory flutterProjectFactory = FlutterProjectFactory(
fileSystem: directory.fileSystem,
logger: BufferLogger.test(),
);
return flutterProjectFactory.fromDirectory(directory);
}
void main() {
testWithoutContext('replacing string interpolation occurrences in custom device commands', () async {
expect(
interpolateCommand(
<String>['scp', r'${localPath}', r'/tmp/${appName}', 'pi@raspberrypi'],
<String, String>{
'localPath': 'build/flutter_assets',
'appName': 'hello_world',
},
),
<String>[
'scp', 'build/flutter_assets', '/tmp/hello_world', 'pi@raspberrypi',
]
);
expect(
interpolateCommand(
<String>[r'${test1}', r' ${test2}', r'${test3}'],
<String, String>{
'test1': '_test1',
'test2': '_test2',
},
),
<String>[
'_test1', ' _test2', r'',
]
);
expect(
interpolateCommand(
<String>[r'${test1}', r' ${test2}', r'${test3}'],
<String, String>{
'test1': '_test1',
'test2': '_test2',
},
additionalReplacementValues: <String, String>{
'test2': '_nottest2',
'test3': '_test3',
}
),
<String>[
'_test1', ' _test2', r'_test3',
]
);
});
final CustomDeviceConfig testConfig = CustomDeviceConfig(
id: 'testid',
label: 'testlabel',
sdkNameAndVersion: 'testsdknameandversion',
enabled: true,
pingCommand: const <String>['testping'],
pingSuccessRegex: RegExp('testpingsuccess'),
postBuildCommand: const <String>['testpostbuild'],
installCommand: const <String>['testinstall'],
uninstallCommand: const <String>['testuninstall'],
runDebugCommand: const <String>['testrundebug'],
forwardPortCommand: const <String>['testforwardport'],
forwardPortSuccessRegex: RegExp('testforwardportsuccess'),
screenshotCommand: const <String>['testscreenshot'],
);
const String testConfigPingSuccessOutput = 'testpingsuccess\n';
const String testConfigForwardPortSuccessOutput = 'testforwardportsuccess\n';
final CustomDeviceConfig disabledTestConfig = testConfig.copyWith(enabled: false);
final CustomDeviceConfig testConfigNonForwarding = testConfig.copyWith(
explicitForwardPortCommand: true,
explicitForwardPortSuccessRegex: true,
);
testUsingContext('CustomDevice defaults',
() async {
final CustomDevice device = CustomDevice(
config: testConfig,
processManager: FakeProcessManager.any(),
logger: BufferLogger.test()
);
final PrebuiltLinuxApp linuxApp = PrebuiltLinuxApp(executable: 'foo');
expect(device.id, 'testid');
expect(device.name, 'testlabel');
expect(device.platformType, PlatformType.custom);
expect(await device.sdkNameAndVersion, 'testsdknameandversion');
expect(await device.targetPlatform, TargetPlatform.linux_arm64);
expect(await device.installApp(linuxApp), true);
expect(await device.uninstallApp(linuxApp), true);
expect(await device.isLatestBuildInstalled(linuxApp), false);
expect(await device.isAppInstalled(linuxApp), false);
expect(await device.stopApp(linuxApp), false);
expect(await device.stopApp(null), false);
expect(device.category, Category.mobile);
expect(device.supportsRuntimeMode(BuildMode.debug), true);
expect(device.supportsRuntimeMode(BuildMode.profile), false);
expect(device.supportsRuntimeMode(BuildMode.release), false);
expect(device.supportsRuntimeMode(BuildMode.jitRelease), false);
},
overrides: <Type, dynamic Function()>{
FileSystem: () => MemoryFileSystem.test(),
ProcessManager: () => FakeProcessManager.any(),
}
);
testWithoutContext('CustomDevice: no devices listed if only disabled devices configured', () async {
final MemoryFileSystem fs = MemoryFileSystem.test();
final Directory dir = fs.directory('custom_devices_config_dir');
_writeCustomDevicesConfigFile(dir, <CustomDeviceConfig>[disabledTestConfig]);
expect(await CustomDevices(
featureFlags: TestFeatureFlags(areCustomDevicesEnabled: true),
logger: BufferLogger.test(),
processManager: FakeProcessManager.any(),
config: CustomDevicesConfig.test(
fileSystem: fs,
directory: dir,
logger: BufferLogger.test()
)
).devices(), <Device>[]);
});
testWithoutContext('CustomDevice: no devices listed if custom devices feature flag disabled', () async {
final MemoryFileSystem fs = MemoryFileSystem.test();
final Directory dir = fs.directory('custom_devices_config_dir');
_writeCustomDevicesConfigFile(dir, <CustomDeviceConfig>[testConfig]);
expect(await CustomDevices(
featureFlags: TestFeatureFlags(),
logger: BufferLogger.test(),
processManager: FakeProcessManager.any(),
config: CustomDevicesConfig.test(
fileSystem: fs,
directory: dir,
logger: BufferLogger.test()
)
).devices(), <Device>[]);
});
testWithoutContext('CustomDevices.devices', () async {
final MemoryFileSystem fs = MemoryFileSystem.test();
final Directory dir = fs.directory('custom_devices_config_dir');
_writeCustomDevicesConfigFile(dir, <CustomDeviceConfig>[testConfig]);
expect(
await CustomDevices(
featureFlags: TestFeatureFlags(areCustomDevicesEnabled: true),
logger: BufferLogger.test(),
processManager: FakeProcessManager.list(<FakeCommand>[
FakeCommand(
command: testConfig.pingCommand,
stdout: testConfigPingSuccessOutput
),
]),
config: CustomDevicesConfig.test(
fileSystem: fs,
directory: dir,
logger: BufferLogger.test()
)
).devices(),
hasLength(1)
);
});
testWithoutContext('CustomDevices.discoverDevices successfully discovers devices and executes ping command', () async {
final MemoryFileSystem fs = MemoryFileSystem.test();
final Directory dir = fs.directory('custom_devices_config_dir');
_writeCustomDevicesConfigFile(dir, <CustomDeviceConfig>[testConfig]);
bool pingCommandWasExecuted = false;
final CustomDevices discovery = CustomDevices(
featureFlags: TestFeatureFlags(areCustomDevicesEnabled: true),
logger: BufferLogger.test(),
processManager: FakeProcessManager.list(<FakeCommand>[
FakeCommand(
command: testConfig.pingCommand,
onRun: (_) => pingCommandWasExecuted = true,
stdout: testConfigPingSuccessOutput
),
]),
config: CustomDevicesConfig.test(
fileSystem: fs,
directory: dir,
logger: BufferLogger.test(),
),
);
final List<Device> discoveredDevices = await discovery.discoverDevices();
expect(discoveredDevices, hasLength(1));
expect(pingCommandWasExecuted, true);
});
testWithoutContext("CustomDevices.discoverDevices doesn't report device when ping command fails", () async {
final MemoryFileSystem fs = MemoryFileSystem.test();
final Directory dir = fs.directory('custom_devices_config_dir');
_writeCustomDevicesConfigFile(dir, <CustomDeviceConfig>[testConfig]);
final CustomDevices discovery = CustomDevices(
featureFlags: TestFeatureFlags(areCustomDevicesEnabled: true),
logger: BufferLogger.test(),
processManager: FakeProcessManager.list(<FakeCommand>[
FakeCommand(
command: testConfig.pingCommand,
stdout: testConfigPingSuccessOutput,
exitCode: 1
),
]),
config: CustomDevicesConfig.test(
fileSystem: fs,
directory: dir,
logger: BufferLogger.test(),
),
);
expect(await discovery.discoverDevices(), hasLength(0));
});
testWithoutContext("CustomDevices.discoverDevices doesn't report device when ping command output doesn't match ping success regex", () async {
final MemoryFileSystem fs = MemoryFileSystem.test();
final Directory dir = fs.directory('custom_devices_config_dir');
_writeCustomDevicesConfigFile(dir, <CustomDeviceConfig>[testConfig]);
final CustomDevices discovery = CustomDevices(
featureFlags: TestFeatureFlags(areCustomDevicesEnabled: true),
logger: BufferLogger.test(),
processManager: FakeProcessManager.list(<FakeCommand>[
FakeCommand(
command: testConfig.pingCommand,
),
]),
config: CustomDevicesConfig.test(
fileSystem: fs,
directory: dir,
logger: BufferLogger.test(),
),
);
expect(await discovery.discoverDevices(), hasLength(0));
});
testWithoutContext('CustomDevice.isSupportedForProject is true with editable host app', () async {
final MemoryFileSystem fileSystem = MemoryFileSystem.test();
fileSystem.file('pubspec.yaml').createSync();
fileSystem.file('.packages').createSync();
final FlutterProject flutterProject = _setUpFlutterProject(fileSystem.currentDirectory);
expect(CustomDevice(
config: testConfig,
logger: BufferLogger.test(),
processManager: FakeProcessManager.any(),
).isSupportedForProject(flutterProject), true);
});
testUsingContext(
'CustomDevice.install invokes uninstall and install command',
() async {
bool bothCommandsWereExecuted = false;
final CustomDevice device = CustomDevice(
config: testConfig,
logger: BufferLogger.test(),
processManager: FakeProcessManager.list(<FakeCommand>[
FakeCommand(command: testConfig.uninstallCommand),
FakeCommand(command: testConfig.installCommand, onRun: (_) => bothCommandsWereExecuted = true),
])
);
expect(await device.installApp(PrebuiltLinuxApp(executable: 'exe')), true);
expect(bothCommandsWereExecuted, true);
},
overrides: <Type, dynamic Function()>{
FileSystem: () => MemoryFileSystem.test(),
ProcessManager: () => FakeProcessManager.any(),
}
);
testWithoutContext('CustomDevicePortForwarder will run and terminate forwardPort command', () async {
final Completer<void> forwardPortCommandCompleter = Completer<void>();
final CustomDevicePortForwarder forwarder = CustomDevicePortForwarder(
deviceName: 'testdevicename',
forwardPortCommand: testConfig.forwardPortCommand!,
forwardPortSuccessRegex: testConfig.forwardPortSuccessRegex!,
logger: BufferLogger.test(),
processManager: FakeProcessManager.list(<FakeCommand>[
FakeCommand(
command: testConfig.forwardPortCommand!,
stdout: testConfigForwardPortSuccessOutput,
completer: forwardPortCommandCompleter,
),
])
);
// this should start the command
expect(await forwarder.forward(12345), 12345);
expect(forwardPortCommandCompleter.isCompleted, false);
// this should terminate it
await forwarder.dispose();
// the termination should have completed our completer
expect(forwardPortCommandCompleter.isCompleted, true);
});
testWithoutContext('CustomDevice forwards VM Service port correctly when port forwarding is configured', () async {
final Completer<void> runDebugCompleter = Completer<void>();
final Completer<void> forwardPortCompleter = Completer<void>();
final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[
FakeCommand(
command: testConfig.runDebugCommand,
completer: runDebugCompleter,
stdout: 'The Dart VM service is listening on http://127.0.0.1:12345/abcd/\n',
),
FakeCommand(
command: testConfig.forwardPortCommand!,
completer: forwardPortCompleter,
stdout: testConfigForwardPortSuccessOutput,
),
]);
final CustomDeviceAppSession appSession = CustomDeviceAppSession(
name: 'testname',
device: CustomDevice(
config: testConfig,
logger: BufferLogger.test(),
processManager: processManager
),
appPackage: PrebuiltLinuxApp(executable: 'testexecutable'),
logger: BufferLogger.test(),
processManager: processManager,
);
final LaunchResult launchResult = await appSession.start(debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug));
expect(launchResult.started, true);
expect(launchResult.vmServiceUri, Uri.parse('http://127.0.0.1:12345/abcd/'));
expect(runDebugCompleter.isCompleted, false);
expect(forwardPortCompleter.isCompleted, false);
expect(await appSession.stop(), true);
expect(runDebugCompleter.isCompleted, true);
expect(forwardPortCompleter.isCompleted, true);
});
testWithoutContext('CustomDeviceAppSession forwards VM Service port correctly when port forwarding is not configured', () async {
final Completer<void> runDebugCompleter = Completer<void>();
final FakeProcessManager processManager = FakeProcessManager.list(
<FakeCommand>[
FakeCommand(
command: testConfigNonForwarding.runDebugCommand,
completer: runDebugCompleter,
stdout: 'The Dart VM service is listening on http://192.168.178.123:12345/abcd/\n'
),
]
);
final CustomDeviceAppSession appSession = CustomDeviceAppSession(
name: 'testname',
device: CustomDevice(
config: testConfigNonForwarding,
logger: BufferLogger.test(),
processManager: processManager
),
appPackage: PrebuiltLinuxApp(executable: 'testexecutable'),
logger: BufferLogger.test(),
processManager: processManager
);
final LaunchResult launchResult = await appSession.start(debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug));
expect(launchResult.started, true);
expect(launchResult.vmServiceUri, Uri.parse('http://192.168.178.123:12345/abcd/'));
expect(runDebugCompleter.isCompleted, false);
expect(await appSession.stop(), true);
expect(runDebugCompleter.isCompleted, true);
});
testUsingContext(
'custom device end-to-end test',
() async {
final Completer<void> runDebugCompleter = Completer<void>();
final Completer<void> forwardPortCompleter = Completer<void>();
final FakeProcessManager processManager = FakeProcessManager.list(
<FakeCommand>[
FakeCommand(
command: testConfig.pingCommand,
stdout: testConfigPingSuccessOutput
),
FakeCommand(command: testConfig.postBuildCommand!),
FakeCommand(command: testConfig.uninstallCommand),
FakeCommand(command: testConfig.installCommand),
FakeCommand(
command: testConfig.runDebugCommand,
completer: runDebugCompleter,
stdout: 'The Dart VM service is listening on http://127.0.0.1:12345/abcd/\n',
),
FakeCommand(
command: testConfig.forwardPortCommand!,
completer: forwardPortCompleter,
stdout: testConfigForwardPortSuccessOutput,
),
]
);
// Reuse our filesystem from context instead of mixing two filesystem instances
// together
final FileSystem fs = globals.fs;
// CustomDevice.startApp doesn't care whether we pass a prebuilt app or
// buildable app as long as we pass prebuiltApplication as false
final PrebuiltLinuxApp app = PrebuiltLinuxApp(executable: 'testexecutable');
final Directory configFileDir = fs.directory('custom_devices_config_dir');
_writeCustomDevicesConfigFile(configFileDir, <CustomDeviceConfig>[testConfig]);
// finally start actually testing things
final CustomDevices customDevices = CustomDevices(
featureFlags: TestFeatureFlags(areCustomDevicesEnabled: true),
processManager: processManager,
logger: BufferLogger.test(),
config: CustomDevicesConfig.test(
fileSystem: fs,
directory: configFileDir,
logger: BufferLogger.test()
)
);
final List<Device> devices = await customDevices.discoverDevices();
expect(devices.length, 1);
expect(devices.single, isA<CustomDevice>());
final CustomDevice device = devices.single as CustomDevice;
expect(device.id, testConfig.id);
expect(device.name, testConfig.label);
expect(await device.sdkNameAndVersion, testConfig.sdkNameAndVersion);
final LaunchResult result = await device.startApp(
app,
debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug),
bundleBuilder: FakeBundleBuilder()
);
expect(result.started, true);
expect(result.hasVmService, true);
expect(result.vmServiceUri, Uri.tryParse('http://127.0.0.1:12345/abcd/'));
expect(runDebugCompleter.isCompleted, false);
expect(forwardPortCompleter.isCompleted, false);
expect(await device.stopApp(app), true);
expect(runDebugCompleter.isCompleted, true);
expect(forwardPortCompleter.isCompleted, true);
},
overrides: <Type, Generator>{
FileSystem: () => MemoryFileSystem.test(),
ProcessManager: () => FakeProcessManager.any(),
}
);
testWithoutContext('CustomDevice screenshotting', () async {
bool screenshotCommandWasExecuted = false;
final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[
FakeCommand(
command: testConfig.screenshotCommand!,
onRun: (_) => screenshotCommandWasExecuted = true,
),
]);
final MemoryFileSystem fs = MemoryFileSystem.test();
final File screenshotFile = fs.file('screenshot.png');
final CustomDevice device = CustomDevice(
config: testConfig,
logger: BufferLogger.test(),
processManager: processManager
);
expect(device.supportsScreenshot, true);
await device.takeScreenshot(screenshotFile);
expect(screenshotCommandWasExecuted, true);
expect(screenshotFile, exists);
});
testWithoutContext('CustomDevice without screenshotting support', () async {
bool screenshotCommandWasExecuted = false;
final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[
FakeCommand(
command: testConfig.screenshotCommand!,
onRun: (_) => screenshotCommandWasExecuted = true,
),
]);
final MemoryFileSystem fs = MemoryFileSystem.test();
final File screenshotFile = fs.file('screenshot.png');
final CustomDevice device = CustomDevice(
config: testConfig.copyWith(
explicitScreenshotCommand: true
),
logger: BufferLogger.test(),
processManager: processManager
);
expect(device.supportsScreenshot, false);
expect(
() => device.takeScreenshot(screenshotFile),
throwsA(const TypeMatcher<UnsupportedError>()),
);
expect(screenshotCommandWasExecuted, false);
expect(screenshotFile.existsSync(), false);
});
testWithoutContext('CustomDevice returns correct target platform', () async {
final CustomDevice device = CustomDevice(
config: testConfig.copyWith(
platform: TargetPlatform.linux_x64
),
logger: BufferLogger.test(),
processManager: FakeProcessManager.empty()
);
expect(await device.targetPlatform, TargetPlatform.linux_x64);
});
testWithoutContext('CustomDeviceLogReader cancels subscriptions before closing logLines stream', () async {
final CustomDeviceLogReader logReader = CustomDeviceLogReader('testname');
final Iterable<List<int>> lines = Iterable<List<int>>.generate(5, (int _) => utf8.encode('test'));
logReader.listenToProcessOutput(
FakeProcess(
exitCode: Future<int>.value(0),
stdout: Stream<List<int>>.fromIterable(lines),
stderr: Stream<List<int>>.fromIterable(lines),
),
);
final List<MyFakeStreamSubscription<String>> subscriptions = <MyFakeStreamSubscription<String>>[];
bool logLinesStreamDone = false;
logReader.logLines.listen((_) {}, onDone: () {
expect(subscriptions, everyElement((MyFakeStreamSubscription<String> s) => s.canceled));
logLinesStreamDone = true;
});
logReader.subscriptions.replaceRange(
0,
logReader.subscriptions.length,
logReader.subscriptions.map(
(StreamSubscription<String> e) => MyFakeStreamSubscription<String>(e)
),
);
subscriptions.addAll(logReader.subscriptions.cast());
await logReader.dispose();
expect(logLinesStreamDone, true);
});
}
class MyFakeStreamSubscription<T> extends Fake implements StreamSubscription<T> {
MyFakeStreamSubscription(this.parent);
StreamSubscription<T> parent;
bool canceled = false;
@override
Future<void> cancel() {
canceled = true;
return parent.cancel();
}
}
class FakeBundleBuilder extends Fake implements BundleBuilder {
@override
Future<void> build({
TargetPlatform? platform,
BuildInfo? buildInfo,
FlutterProject? project,
String? mainPath,
String manifestPath = defaultManifestPath,
String? applicationKernelFilePath,
String? depfilePath,
String? assetDirPath,
Uri? nativeAssets,
bool buildNativeAssets = true,
@visibleForTesting BuildSystem? buildSystem
}) async {}
}
| flutter/packages/flutter_tools/test/general.shard/custom_devices/custom_device_test.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/general.shard/custom_devices/custom_device_test.dart",
"repo_id": "flutter",
"token_count": 8221
} | 808 |
// 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/file.dart';
import 'package:file/memory.dart';
import 'package:flutter_tools/src/application_package.dart';
import 'package:flutter_tools/src/base/dds.dart';
import 'package:flutter_tools/src/base/io.dart' as io;
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/base/process.dart';
import 'package:flutter_tools/src/build_info.dart';
import 'package:flutter_tools/src/convert.dart';
import 'package:flutter_tools/src/device.dart';
import 'package:flutter_tools/src/drive/drive_service.dart';
import 'package:flutter_tools/src/project.dart';
import 'package:flutter_tools/src/resident_runner.dart';
import 'package:flutter_tools/src/version.dart';
import 'package:flutter_tools/src/vmservice.dart';
import 'package:package_config/package_config_types.dart';
import 'package:test/fake.dart';
import 'package:vm_service/vm_service.dart' as vm_service;
import '../../src/common.dart';
import '../../src/context.dart';
import '../../src/fake_vm_services.dart';
import '../../src/fakes.dart';
final vm_service.Isolate fakeUnpausedIsolate = vm_service.Isolate(
id: '1',
pauseEvent: vm_service.Event(
kind: vm_service.EventKind.kResume,
timestamp: 0
),
breakpoints: <vm_service.Breakpoint>[],
libraries: <vm_service.LibraryRef>[
vm_service.LibraryRef(
id: '1',
uri: 'file:///hello_world/main.dart',
name: '',
),
],
livePorts: 0,
name: 'test',
number: '1',
pauseOnExit: false,
runnable: true,
startTime: 0,
isSystemIsolate: false,
isolateFlags: <vm_service.IsolateFlag>[],
);
final vm_service.VM fakeVM = vm_service.VM(
isolates: <vm_service.IsolateRef>[fakeUnpausedIsolate],
pid: 1,
hostCPU: '',
isolateGroups: <vm_service.IsolateGroupRef>[],
targetCPU: '',
startTime: 0,
name: 'dart',
architectureBits: 64,
operatingSystem: '',
version: '',
systemIsolateGroups: <vm_service.IsolateGroupRef>[],
systemIsolates: <vm_service.IsolateRef>[],
);
final FlutterView fakeFlutterView = FlutterView(
id: 'a',
uiIsolate: fakeUnpausedIsolate,
);
final FakeVmServiceRequest listViews = FakeVmServiceRequest(
method: kListViewsMethod,
jsonResponse: <String, Object>{
'views': <Object>[
fakeFlutterView.toJson(),
],
},
);
final FakeVmServiceRequest getVM = FakeVmServiceRequest(
method: 'getVM',
args: <String, Object>{},
jsonResponse: fakeVM.toJson(),
);
void main() {
testWithoutContext('Exits if device fails to start', () {
final DriverService driverService = setUpDriverService();
final Device device = FakeDevice(LaunchResult.failed());
expect(
() => driverService.start(BuildInfo.profile, device, DebuggingOptions.enabled(BuildInfo.profile), true),
throwsToolExit(message: 'Application failed to start. Will not run test. Quitting.'),
);
});
testWithoutContext('Retries application launch if it fails the first time', () async {
final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(requests: <FakeVmServiceRequest>[
getVM,
]);
final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[
const FakeCommand(
command: <String>['dart', '--enable-experiment=non-nullable', 'foo.test', '-rexpanded'],
exitCode: 23,
environment: <String, String>{
'FOO': 'BAR',
'VM_SERVICE_URL': 'http://127.0.0.1:1234/', // dds forwarded URI
},
),
]);
final DriverService driverService = setUpDriverService(processManager: processManager, vmService: fakeVmServiceHost.vmService);
final Device device = FakeDevice(LaunchResult.succeeded(
vmServiceUri: Uri.parse('http://127.0.0.1:63426/1UasC_ihpXY=/'),
))..failOnce = true;
await expectLater(
() async => driverService.start(BuildInfo.profile, device, DebuggingOptions.enabled(BuildInfo.profile), true),
returnsNormally,
);
});
testWithoutContext('Connects to device VM Service and runs test application', () async {
final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(requests: <FakeVmServiceRequest>[
getVM,
]);
final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[
const FakeCommand(
command: <String>['dart', '--enable-experiment=non-nullable', 'foo.test', '-rexpanded'],
exitCode: 23,
environment: <String, String>{
'FOO': 'BAR',
'VM_SERVICE_URL': 'http://127.0.0.1:1234/', // dds forwarded URI
},
),
]);
final DriverService driverService = setUpDriverService(processManager: processManager, vmService: fakeVmServiceHost.vmService);
final Device device = FakeDevice(LaunchResult.succeeded(
vmServiceUri: Uri.parse('http://127.0.0.1:63426/1UasC_ihpXY=/'),
));
await driverService.start(BuildInfo.profile, device, DebuggingOptions.enabled(BuildInfo.profile), true);
final int testResult = await driverService.startTest(
'foo.test',
<String>['--enable-experiment=non-nullable'],
<String, String>{'FOO': 'BAR'},
PackageConfig(<Package>[Package('test', Uri.base)]),
);
expect(testResult, 23);
});
testWithoutContext('Connects to device VM Service and runs test application with devtools memory profile', () async {
final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(requests: <FakeVmServiceRequest>[
getVM,
]);
final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[
const FakeCommand(
command: <String>['dart', '--enable-experiment=non-nullable', 'foo.test', '-rexpanded'],
exitCode: 23,
environment: <String, String>{
'FOO': 'BAR',
'VM_SERVICE_URL': 'http://127.0.0.1:1234/', // dds forwarded URI
},
),
]);
final FakeDevtoolsLauncher launcher = FakeDevtoolsLauncher();
final DriverService driverService = setUpDriverService(processManager: processManager, vmService: fakeVmServiceHost.vmService, devtoolsLauncher: launcher);
final Device device = FakeDevice(LaunchResult.succeeded(
vmServiceUri: Uri.parse('http://127.0.0.1:63426/1UasC_ihpXY=/'),
));
await driverService.start(BuildInfo.profile, device, DebuggingOptions.enabled(BuildInfo.profile), true);
final int testResult = await driverService.startTest(
'foo.test',
<String>['--enable-experiment=non-nullable'],
<String, String>{'FOO': 'BAR'},
PackageConfig(<Package>[Package('test', Uri.base)]),
profileMemory: 'devtools_memory.json',
);
expect(launcher.closed, true);
expect(testResult, 23);
});
testWithoutContext('Uses dart to execute the test if there is no package:test dependency', () async {
final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(requests: <FakeVmServiceRequest>[
getVM,
]);
final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[
const FakeCommand(
command: <String>['dart', '--enable-experiment=non-nullable', 'foo.test', '-rexpanded'],
exitCode: 23,
environment: <String, String>{
'FOO': 'BAR',
'VM_SERVICE_URL': 'http://127.0.0.1:1234/', // dds forwarded URI
},
),
]);
final DriverService driverService = setUpDriverService(processManager: processManager, vmService: fakeVmServiceHost.vmService);
final Device device = FakeDevice(LaunchResult.succeeded(
vmServiceUri: Uri.parse('http://127.0.0.1:63426/1UasC_ihpXY=/'),
));
await driverService.start(BuildInfo.profile, device, DebuggingOptions.enabled(BuildInfo.profile), true);
final int testResult = await driverService.startTest(
'foo.test',
<String>['--enable-experiment=non-nullable'],
<String, String>{'FOO': 'BAR'},
PackageConfig.empty,
);
expect(testResult, 23);
});
testWithoutContext('Connects to device VM Service and runs test application without dds', () async {
final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(requests: <FakeVmServiceRequest>[
getVM,
]);
final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[
const FakeCommand(
command: <String>['dart', 'foo.test', '-rexpanded'],
exitCode: 11,
environment: <String, String>{
'VM_SERVICE_URL': 'http://127.0.0.1:63426/1UasC_ihpXY=/',
},
),
]);
final DriverService driverService = setUpDriverService(processManager: processManager, vmService: fakeVmServiceHost.vmService);
final Device device = FakeDevice(LaunchResult.succeeded(
vmServiceUri: Uri.parse('http://127.0.0.1:63426/1UasC_ihpXY=/'),
));
final FakeDartDevelopmentService dds = device.dds as FakeDartDevelopmentService;
expect(dds.started, false);
await driverService.start(BuildInfo.profile, device, DebuggingOptions.enabled(BuildInfo.profile, enableDds: false), true);
expect(dds.started, false);
final int testResult = await driverService.startTest(
'foo.test',
<String>[],
<String, String>{},
PackageConfig(<Package>[Package('test', Uri.base)]),
);
expect(testResult, 11);
expect(dds.started, false);
});
testWithoutContext('Safely stops and uninstalls application', () async {
final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(requests: <FakeVmServiceRequest>[
getVM,
]);
final FakeProcessManager processManager = FakeProcessManager.empty();
final DriverService driverService = setUpDriverService(processManager: processManager, vmService: fakeVmServiceHost.vmService);
final FakeDevice device = FakeDevice(LaunchResult.succeeded(
vmServiceUri: Uri.parse('http://127.0.0.1:63426/1UasC_ihpXY=/'),
));
await driverService.start(BuildInfo.profile, device, DebuggingOptions.enabled(BuildInfo.profile), true);
await driverService.stop();
expect(device.didStopApp, true);
expect(device.didUninstallApp, true);
expect(device.didDispose, true);
});
// FlutterVersion requires context.
testUsingContext('Writes SkSL to file when provided with out file', () async {
final MemoryFileSystem fileSystem = MemoryFileSystem.test();
final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(requests: <FakeVmServiceRequest>[
getVM,
listViews,
const FakeVmServiceRequest(
method: '_flutter.getSkSLs',
args: <String, Object>{
'viewId': 'a',
},
jsonResponse: <String, Object>{
'SkSLs': <String, Object>{
'A': 'B',
},
},
),
]);
final FakeProcessManager processManager = FakeProcessManager.empty();
final DriverService driverService = setUpDriverService(processManager: processManager, vmService: fakeVmServiceHost.vmService);
final FakeDevice device = FakeDevice(LaunchResult.succeeded(
vmServiceUri: Uri.parse('http://127.0.0.1:63426/1UasC_ihpXY=/'),
));
await driverService.start(BuildInfo.profile, device, DebuggingOptions.enabled(BuildInfo.profile), true);
await driverService.stop(writeSkslOnExit: fileSystem.file('out.json'));
expect(device.didStopApp, true);
expect(device.didUninstallApp, true);
expect(json.decode(fileSystem.file('out.json').readAsStringSync()), <String, Object>{
'platform': 'android',
'name': 'test',
'engineRevision': 'abcdefghijklmnopqrstuvwxyz',
'data': <String, Object>{'A': 'B'},
});
}, overrides: <Type, Generator>{
FlutterVersion: () => FakeFlutterVersion(),
});
testWithoutContext('Can connect to existing application and stop it during cleanup', () async {
final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(requests: <FakeVmServiceRequest>[
getVM,
getVM,
const FakeVmServiceRequest(
method: 'ext.flutter.exit',
args: <String, Object>{
'isolateId': '1',
},
),
]);
final FakeProcessManager processManager = FakeProcessManager.empty();
final DriverService driverService = setUpDriverService(processManager: processManager, vmService: fakeVmServiceHost.vmService);
final FakeDevice device = FakeDevice(LaunchResult.failed());
await driverService.reuseApplication(
Uri.parse('http://127.0.0.1:63426/1UasC_ihpXY=/'),
device,
DebuggingOptions.enabled(BuildInfo.debug),
false,
);
await driverService.stop();
});
testWithoutContext('Can connect to existing application using ws URI', () async {
final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(requests: <FakeVmServiceRequest>[
getVM,
getVM,
const FakeVmServiceRequest(
method: 'ext.flutter.exit',
args: <String, Object>{
'isolateId': '1',
},
),
]);
final FakeProcessManager processManager = FakeProcessManager.empty();
final DriverService driverService = setUpDriverService(processManager: processManager, vmService: fakeVmServiceHost.vmService);
final FakeDevice device = FakeDevice(LaunchResult.failed());
await driverService.reuseApplication(
Uri.parse('ws://127.0.0.1:63426/1UasC_ihpXY=/ws/'),
device,
DebuggingOptions.enabled(BuildInfo.debug),
false,
);
await driverService.stop();
});
testWithoutContext('Can connect to existing application using ws URI (no trailing slash)', () async {
final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(requests: <FakeVmServiceRequest>[
getVM,
getVM,
const FakeVmServiceRequest(
method: 'ext.flutter.exit',
args: <String, Object>{
'isolateId': '1',
},
),
]);
final FakeProcessManager processManager = FakeProcessManager.empty();
final DriverService driverService = setUpDriverService(processManager: processManager, vmService: fakeVmServiceHost.vmService);
final FakeDevice device = FakeDevice(LaunchResult.failed());
await driverService.reuseApplication(
Uri.parse('ws://127.0.0.1:63426/1UasC_ihpXY=/ws'),
device,
DebuggingOptions.enabled(BuildInfo.debug),
false,
);
await driverService.stop();
});
testWithoutContext('Can connect to existing application using ws URI (no trailing slash, ws in auth code)', () async {
final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(requests: <FakeVmServiceRequest>[
getVM,
getVM,
const FakeVmServiceRequest(
method: 'ext.flutter.exit',
args: <String, Object>{
'isolateId': '1',
},
),
]);
final FakeProcessManager processManager = FakeProcessManager.empty();
final DriverService driverService = setUpDriverService(processManager: processManager, vmService: fakeVmServiceHost.vmService);
final FakeDevice device = FakeDevice(LaunchResult.failed());
await driverService.reuseApplication(
Uri.parse('ws://127.0.0.1:63426/wsasC_ihpXY=/ws'),
device,
DebuggingOptions.enabled(BuildInfo.debug),
false,
);
await driverService.stop();
});
testWithoutContext('Does not call flutterExit on device types that do not support it', () async {
final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(requests: <FakeVmServiceRequest>[
getVM,
]);
final FakeProcessManager processManager = FakeProcessManager.empty();
final DriverService driverService = setUpDriverService(processManager: processManager, vmService: fakeVmServiceHost.vmService);
final FakeDevice device = FakeDevice(LaunchResult.failed(), supportsFlutterExit: false);
await driverService.reuseApplication(
Uri.parse('http://127.0.0.1:63426/1UasC_ihpXY=/'),
device,
DebuggingOptions.enabled(BuildInfo.debug),
false,
);
await driverService.stop();
});
}
FlutterDriverService setUpDriverService({
Logger? logger,
ProcessManager? processManager,
FlutterVmService? vmService,
DevtoolsLauncher? devtoolsLauncher,
}) {
logger ??= BufferLogger.test();
return FlutterDriverService(
applicationPackageFactory: FakeApplicationPackageFactory(FakeApplicationPackage()),
logger: logger,
processUtils: ProcessUtils(
logger: logger,
processManager: processManager ?? FakeProcessManager.any(),
),
dartSdkPath: 'dart',
devtoolsLauncher: devtoolsLauncher ?? FakeDevtoolsLauncher(),
vmServiceConnector: (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 {
if (httpUri.scheme != 'http') {
fail('Expected an HTTP scheme, found $httpUri');
}
if (httpUri.path.endsWith('/ws')) {
fail('Expected HTTP uri to not contain `/ws`, found $httpUri');
}
return vmService!;
}
);
}
class FakeApplicationPackageFactory extends Fake implements ApplicationPackageFactory {
FakeApplicationPackageFactory(this.applicationPackage);
ApplicationPackage applicationPackage;
@override
Future<ApplicationPackage> getPackageForPlatform(
TargetPlatform platform, {
BuildInfo? buildInfo,
File? applicationBinary,
}) async => applicationPackage;
}
class FakeApplicationPackage extends Fake implements ApplicationPackage { }
class FakeDevice extends Fake implements Device {
FakeDevice(this.result, {this.supportsFlutterExit = true});
LaunchResult result;
bool didStopApp = false;
bool didUninstallApp = false;
bool didDispose = false;
bool failOnce = false;
@override
final PlatformType platformType = PlatformType.web;
@override
String get name => 'test';
@override
final bool supportsFlutterExit;
@override
final DartDevelopmentService dds = FakeDartDevelopmentService();
@override
Future<TargetPlatform> get targetPlatform async => TargetPlatform.android_arm;
@override
Future<DeviceLogReader> getLogReader({
ApplicationPackage? app,
bool includePastLogs = false,
}) async => NoOpDeviceLogReader('test');
@override
Future<LaunchResult> startApp(
ApplicationPackage? package, {
String? mainPath,
String? route,
required DebuggingOptions debuggingOptions,
Map<String, Object?> platformArgs = const <String, Object?>{},
bool prebuiltApplication = false,
bool ipv6 = false,
String? userIdentifier,
}) async {
if (failOnce) {
failOnce = false;
return LaunchResult.failed();
}
return result;
}
@override
Future<bool> stopApp(ApplicationPackage? app, {String? userIdentifier}) async {
didStopApp = true;
return true;
}
@override
Future<bool> uninstallApp(ApplicationPackage app, {String? userIdentifier}) async {
didUninstallApp = true;
return true;
}
@override
Future<void> dispose() async {
didDispose = true;
}
}
class FakeDartDevelopmentService extends Fake implements DartDevelopmentService {
bool started = false;
bool disposed = false;
@override
final Uri uri = Uri.parse('http://127.0.0.1:1234/');
@override
Future<void> startDartDevelopmentService(
Uri vmServiceUri, {
required Logger logger,
int? hostPort,
bool? ipv6,
bool? disableServiceAuthCodes,
bool cacheStartupProfile = false,
}) async {
started = true;
}
@override
Future<void> shutdown() async {
disposed = true;
}
}
class FakeDevtoolsLauncher extends Fake implements DevtoolsLauncher {
bool closed = false;
final Completer<void> _processStarted = Completer<void>();
@override
Future<void> launch(Uri vmServiceUri, {List<String>? additionalArguments}) {
_processStarted.complete();
return Completer<void>().future;
}
@override
Future<void> get processStart => _processStarted.future;
@override
Future<void> close() async {
closed = true;
}
}
| flutter/packages/flutter_tools/test/general.shard/drive/drive_service_test.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/general.shard/drive/drive_service_test.dart",
"repo_id": "flutter",
"token_count": 7314
} | 809 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:file/memory.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/fuchsia/fuchsia_pm.dart';
import 'package:flutter_tools/src/fuchsia/fuchsia_sdk.dart';
import 'package:test/fake.dart';
import '../../src/common.dart';
import '../../src/context.dart';
import '../../src/fake_process_manager.dart';
void main() {
group('FuchsiaPM', () {
late File pm;
late FakeProcessManager fakeProcessManager;
late FakeFuchsiaArtifacts fakeFuchsiaArtifacts;
setUp(() {
pm = MemoryFileSystem.test().file('pm');
fakeFuchsiaArtifacts = FakeFuchsiaArtifacts(pm);
fakeProcessManager = FakeProcessManager.empty();
});
testUsingContext('serve - IPv4 address', () async {
fakeProcessManager.addCommand(const FakeCommand(command: <String>[
'pm',
'serve',
'-repo',
'<repo>',
'-l',
'127.0.0.1:43819',
'-c',
'2',
]));
await FuchsiaPM().serve('<repo>', '127.0.0.1', 43819);
expect(fakeProcessManager, hasNoRemainingExpectations);
}, overrides: <Type, Generator>{
FuchsiaArtifacts: () => fakeFuchsiaArtifacts,
ProcessManager: () => fakeProcessManager,
});
testUsingContext('serve - IPv6 address', () async {
fakeProcessManager.addCommand(const FakeCommand(command: <String>[
'pm',
'serve',
'-repo',
'<repo>',
'-l',
'[fe80::ec4:7aff:fecc:ea8f%eno2]:43819',
'-c',
'2',
]));
await FuchsiaPM().serve('<repo>', 'fe80::ec4:7aff:fecc:ea8f%eno2', 43819);
expect(fakeProcessManager, hasNoRemainingExpectations);
}, overrides: <Type, Generator>{
FuchsiaArtifacts: () => fakeFuchsiaArtifacts,
ProcessManager: () => fakeProcessManager,
});
});
}
class FakeFuchsiaArtifacts extends Fake implements FuchsiaArtifacts {
FakeFuchsiaArtifacts(this.pm);
@override
final File pm;
}
| flutter/packages/flutter_tools/test/general.shard/fuchsia/fuchsia_pm_test.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/general.shard/fuchsia/fuchsia_pm_test.dart",
"repo_id": "flutter",
"token_count": 897
} | 810 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:file/memory.dart';
import 'package:flutter_tools/src/artifacts.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/base/platform.dart';
import 'package:flutter_tools/src/build_info.dart';
import 'package:flutter_tools/src/cache.dart';
import 'package:flutter_tools/src/device.dart';
import 'package:flutter_tools/src/ios/core_devices.dart';
import 'package:flutter_tools/src/ios/devices.dart';
import 'package:flutter_tools/src/ios/ios_deploy.dart';
import 'package:flutter_tools/src/ios/iproxy.dart';
import 'package:flutter_tools/src/ios/mac.dart';
import 'package:flutter_tools/src/ios/xcode_debug.dart';
import 'package:flutter_tools/src/project.dart';
import 'package:test/fake.dart';
import '../../src/common.dart';
import '../../src/context.dart';
// FlutterProject still depends on context.
void main() {
late FileSystem fileSystem;
// This setup is required to inject the context.
setUp(() {
fileSystem = MemoryFileSystem.test();
});
testUsingContext('IOSDevice.isSupportedForProject is true on module project', () async {
fileSystem.file('pubspec.yaml')
..createSync()
..writeAsStringSync(r'''
name: example
flutter:
module: {}
''');
fileSystem.file('.packages').writeAsStringSync('\n');
final FlutterProject flutterProject =
FlutterProject.fromDirectory(fileSystem.currentDirectory);
final IOSDevice device = setUpIOSDevice(fileSystem);
expect(device.isSupportedForProject(flutterProject), true);
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('IOSDevice.isSupportedForProject is true with editable host app', () async {
final FileSystem fileSystem = MemoryFileSystem.test();
fileSystem.file('pubspec.yaml').createSync();
fileSystem.file('.packages').writeAsStringSync('\n');
fileSystem.directory('ios').createSync();
final FlutterProject flutterProject =
FlutterProject.fromDirectory(fileSystem.currentDirectory);
final IOSDevice device = setUpIOSDevice(fileSystem);
expect(device.isSupportedForProject(flutterProject), true);
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('IOSDevice.isSupportedForProject is false with no host app and no module', () async {
final FileSystem fileSystem = MemoryFileSystem.test();
fileSystem.file('pubspec.yaml').createSync();
fileSystem.file('.packages').writeAsStringSync('\n');
final FlutterProject flutterProject =
FlutterProject.fromDirectory(fileSystem.currentDirectory);
final IOSDevice device = setUpIOSDevice(fileSystem);
expect(device.isSupportedForProject(flutterProject), false);
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
}
IOSDevice setUpIOSDevice(FileSystem fileSystem) {
final Platform platform = FakePlatform(operatingSystem: 'macos');
final Logger logger = BufferLogger.test();
final ProcessManager processManager = FakeProcessManager.any();
return IOSDevice(
'test',
fileSystem: fileSystem,
logger: logger,
iosDeploy: IOSDeploy(
platform: platform,
logger: logger,
processManager: processManager,
artifacts: Artifacts.test(),
cache: Cache.test(processManager: processManager),
),
iMobileDevice: IMobileDevice.test(processManager: processManager),
coreDeviceControl: FakeIOSCoreDeviceControl(),
xcodeDebug: FakeXcodeDebug(),
platform: platform,
name: 'iPhone 1',
sdkVersion: '13.3',
cpuArchitecture: DarwinArch.arm64,
iProxy: IProxy.test(logger: logger, processManager: processManager),
connectionInterface: DeviceConnectionInterface.attached,
isConnected: true,
isPaired: true,
devModeEnabled: true,
isCoreDevice: false,
);
}
class FakeXcodeDebug extends Fake implements XcodeDebug {}
class FakeIOSCoreDeviceControl extends Fake implements IOSCoreDeviceControl {}
| flutter/packages/flutter_tools/test/general.shard/ios/ios_device_project_test.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/general.shard/ios/ios_device_project_test.dart",
"repo_id": "flutter",
"token_count": 1412
} | 811 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.