text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:two_dimensional_scrollables/two_dimensional_scrollables.dart'; const TableSpan span = TableSpan(extent: FixedTableSpanExtent(100)); void main() { test('TableVicinity converts ChildVicinity', () { const TableVicinity vicinity = TableVicinity(column: 5, row: 10); expect(vicinity.xIndex, 5); expect(vicinity.yIndex, 10); expect(vicinity.row, 10); expect(vicinity.column, 5); expect(vicinity.toString(), '(row: 10, column: 5)'); }); test('TableVicinity.zero', () { const TableVicinity vicinity = TableVicinity.zero; expect(vicinity.xIndex, 0); expect(vicinity.yIndex, 0); expect(vicinity.row, 0); expect(vicinity.column, 0); expect(vicinity.toString(), '(row: 0, column: 0)'); }); test('TableVicinity.copyWith', () { TableVicinity vicinity = TableVicinity.zero; vicinity = vicinity.copyWith(column: 10); expect(vicinity.xIndex, 10); expect(vicinity.yIndex, 0); expect(vicinity.row, 0); expect(vicinity.column, 10); expect(vicinity.toString(), '(row: 0, column: 10)'); vicinity = vicinity.copyWith(row: 20); expect(vicinity.xIndex, 10); expect(vicinity.yIndex, 20); expect(vicinity.row, 20); expect(vicinity.column, 10); expect(vicinity.toString(), '(row: 20, column: 10)'); }); group('Merged cells', () { group('Valid merge assertions', () { test('TableViewCell asserts nonsensical merge configurations', () { TableViewCell? cell; const Widget child = SizedBox.shrink(); expect( () { cell = TableViewCell(rowMergeStart: 0, child: child); }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains( 'Row merge start and span must both be set, or both unset.', ), ), ), ); expect( () { cell = TableViewCell(rowMergeSpan: 0, child: child); }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains( 'Row merge start and span must both be set, or both unset.', ), ), ), ); expect( () { cell = TableViewCell( rowMergeStart: -1, rowMergeSpan: 2, child: child, ); }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains('rowMergeStart == null || rowMergeStart >= 0'), ), ), ); expect( () { cell = TableViewCell( rowMergeStart: 0, rowMergeSpan: 0, child: child, ); }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains('rowMergeSpan == null || rowMergeSpan > 0'), ), ), ); expect( () { cell = TableViewCell(columnMergeStart: 0, child: child); }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains( 'Column merge start and span must both be set, or both unset.', ), ), ), ); expect( () { cell = TableViewCell(columnMergeSpan: 0, child: child); }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains( 'Column merge start and span must both be set, or both unset.', ), ), ), ); expect( () { cell = TableViewCell( columnMergeStart: -1, columnMergeSpan: 2, child: child, ); }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains('columnMergeStart == null || columnMergeStart >= 0'), ), ), ); expect( () { cell = TableViewCell( columnMergeStart: 0, columnMergeSpan: 0, child: child, ); }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains('columnMergeSpan == null || columnMergeSpan > 0'), ), ), ); expect(cell, isNull); }); testWidgets('Merge start cannot exceed current index', (WidgetTester tester) async { // Merge span start is greater than given index, ex: column 10 has merge // start at 20. final List<Object> exceptions = <Object>[]; final FlutterExceptionHandler? oldHandler = FlutterError.onError; FlutterError.onError = (FlutterErrorDetails details) { exceptions.add(details.exception); }; // Row // +---------+ // | X err | // | | // +---------+ // | merge | // | | // + + // | | // | | // +---------+ // This cell should only be built for (0, 1) and (0, 2), not (0,0). TableViewCell cell = const TableViewCell( rowMergeStart: 1, rowMergeSpan: 2, child: SizedBox.shrink(), ); await tester.pumpWidget(TableView.builder( cellBuilder: (_, __) => cell, columnBuilder: (_) => span, rowBuilder: (_) => span, columnCount: 1, rowCount: 3, )); FlutterError.onError = oldHandler; expect(exceptions.length, 2); expect( exceptions.first.toString(), contains('spanMergeStart <= currentSpan'), ); await tester.pumpWidget(Container()); exceptions.clear(); FlutterError.onError = (FlutterErrorDetails details) { exceptions.add(details.exception); }; // Column // +---------+---------+---------+ // | X err | merged | // | | | // +---------+---------+---------+ // This cell should only be returned for (1, 0) and (2, 0), not (0,0). cell = const TableViewCell( columnMergeStart: 1, columnMergeSpan: 2, child: SizedBox.shrink(), ); await tester.pumpWidget(TableView.builder( cellBuilder: (_, __) => cell, columnBuilder: (_) => span, rowBuilder: (_) => span, columnCount: 3, rowCount: 1, )); FlutterError.onError = oldHandler; expect(exceptions.length, 2); expect( exceptions.first.toString(), contains('spanMergeStart <= currentSpan'), ); }); testWidgets('Merge cannot exceed table contents', (WidgetTester tester) async { // Merge exceeds table content, ex: at column 10, cell spans 4 columns, // but table only has 12 columns. final List<Object> exceptions = <Object>[]; final FlutterExceptionHandler? oldHandler = FlutterError.onError; FlutterError.onError = (FlutterErrorDetails details) { exceptions.add(details.exception); }; // Row TableViewCell cell = const TableViewCell( rowMergeStart: 0, rowMergeSpan: 10, // Exceeds the number of rows child: SizedBox.shrink(), ); await tester.pumpWidget(TableView.builder( cellBuilder: (_, __) => cell, columnBuilder: (_) => span, rowBuilder: (_) => span, columnCount: 1, rowCount: 3, )); FlutterError.onError = oldHandler; expect(exceptions.length, 2); expect( exceptions.first.toString(), contains('spanMergeEnd < spanCount'), ); await tester.pumpWidget(Container()); exceptions.clear(); FlutterError.onError = (FlutterErrorDetails details) { exceptions.add(details.exception); }; // Column cell = const TableViewCell( columnMergeStart: 0, columnMergeSpan: 10, // Exceeds the number of columns child: SizedBox.shrink(), ); await tester.pumpWidget(TableView.builder( cellBuilder: (_, __) => cell, columnBuilder: (_) => span, rowBuilder: (_) => span, columnCount: 3, rowCount: 1, )); FlutterError.onError = oldHandler; expect(exceptions.length, 2); expect( exceptions.first.toString(), contains('spanMergeEnd < spanCount'), ); }); testWidgets('Merge cannot contain pinned and unpinned cells', (WidgetTester tester) async { // Merge spans pinned and unpinned cells, ex: column 0 is pinned, 0-2 // expected merge. final List<Object> exceptions = <Object>[]; final FlutterExceptionHandler? oldHandler = FlutterError.onError; FlutterError.onError = (FlutterErrorDetails details) { exceptions.add(details.exception); }; // Row TableViewCell cell = const TableViewCell( rowMergeStart: 0, rowMergeSpan: 3, child: SizedBox.shrink(), ); await tester.pumpWidget(TableView.builder( cellBuilder: (_, __) => cell, columnBuilder: (_) => span, rowBuilder: (_) => span, columnCount: 1, rowCount: 3, pinnedRowCount: 1, )); FlutterError.onError = oldHandler; expect(exceptions.length, 2); expect( exceptions.first.toString(), contains('spanMergeEnd < pinnedSpanCount'), ); await tester.pumpWidget(Container()); exceptions.clear(); FlutterError.onError = (FlutterErrorDetails details) { exceptions.add(details.exception); }; // Column cell = const TableViewCell( columnMergeStart: 0, columnMergeSpan: 3, child: SizedBox.shrink(), ); await tester.pumpWidget(TableView.builder( cellBuilder: (_, __) => cell, columnBuilder: (_) => span, rowBuilder: (_) => span, columnCount: 3, rowCount: 1, pinnedColumnCount: 1, )); FlutterError.onError = oldHandler; expect(exceptions.length, 2); expect( exceptions.first.toString(), contains('spanMergeEnd < pinnedSpanCount'), ); }); }); group('layout', () { // For TableView.mainAxis vertical (default) and // For TableView.mainAxis horizontal // - natural scroll directions // - vertical reversed // - horizontal reversed // - both reversed late ScrollController verticalController; late ScrollController horizontalController; // Verifies the right constraints for merged cells, and that extra calls // to build are not made for merged cells. late Map<TableVicinity, BoxConstraints> layoutConstraints; // Cluster of merged cells (M) surrounded by regular cells (...). // +---------+--------+--------+ // | M(0,0) | M(0, 1) | .... // | | | // + +--------+--------+ // | | M(1,1) | .... // | | | // +---------+ + // | (2,0) | | .... // | | | // +---------+--------+--------+ // ... ... ... final Map<TableVicinity, (int, int)> mergedColumns = <TableVicinity, (int, int)>{ const TableVicinity(row: 0, column: 1): (1, 2), // M(0, 1) const TableVicinity(row: 0, column: 2): (1, 2), // M(0, 1) const TableVicinity(row: 1, column: 1): (1, 2), // M(1, 1) const TableVicinity(row: 1, column: 2): (1, 2), // M(1, 1) const TableVicinity(row: 2, column: 1): (1, 2), // M(1, 1) const TableVicinity(row: 2, column: 2): (1, 2), // M(1, 1) }; final Map<TableVicinity, (int, int)> mergedRows = <TableVicinity, (int, int)>{ TableVicinity.zero: (0, 2), // M(0, 0) TableVicinity.zero.copyWith(row: 1): (0, 2), // M(0,0) const TableVicinity(row: 1, column: 1): (1, 2), // M(1, 1) const TableVicinity(row: 1, column: 2): (1, 2), // M(1, 1) const TableVicinity(row: 2, column: 1): (1, 2), // M(1, 1) const TableVicinity(row: 2, column: 2): (1, 2), // M(1, 1) }; TableViewCell cellBuilder(BuildContext context, TableVicinity vicinity) { if (mergedColumns.keys.contains(vicinity) || mergedRows.keys.contains(vicinity)) { return TableViewCell( rowMergeStart: mergedRows[vicinity]?.$1, rowMergeSpan: mergedRows[vicinity]?.$2, columnMergeStart: mergedColumns[vicinity]?.$1, columnMergeSpan: mergedColumns[vicinity]?.$2, child: LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { layoutConstraints[vicinity] = constraints; return Text( 'M(${mergedRows[vicinity]?.$1 ?? vicinity.row},' '${mergedColumns[vicinity]?.$1 ?? vicinity.column})', ); }, ), ); } return TableViewCell( child: Text('M(${vicinity.row},${vicinity.column})'), ); } setUp(() { verticalController = ScrollController(); horizontalController = ScrollController(); layoutConstraints = <TableVicinity, BoxConstraints>{}; }); tearDown(() { verticalController.dispose(); horizontalController.dispose(); }); testWidgets('vertical main axis and natural scroll directions', (WidgetTester tester) async { await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: TableView.builder( verticalDetails: ScrollableDetails.vertical( controller: verticalController, ), horizontalDetails: ScrollableDetails.horizontal( controller: horizontalController, ), cellBuilder: cellBuilder, columnBuilder: (_) => span, rowBuilder: (_) => span, columnCount: 10, rowCount: 10, ), )); await tester.pumpAndSettle(); expect(find.text('M(0,0)'), findsOneWidget); expect(find.text('M(0,1)'), findsOneWidget); expect(find.text('M(0,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 0, column: 2)], isNull, ); expect(find.text('M(1,0)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 1, column: 0)], isNull, ); expect(find.text('M(1,1)'), findsOneWidget); expect(find.text('M(1,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 1, column: 2)], isNull, ); expect(find.text('M(2,0)'), findsOneWidget); expect(find.text('M(2,1)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 2, column: 1)], isNull, ); expect(find.text('M(2,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 2, column: 2)], isNull, ); expect(tester.getTopLeft(find.text('M(0,0)')), Offset.zero); expect(tester.getSize(find.text('M(0,0)')), const Size(100.0, 200.0)); expect( layoutConstraints[TableVicinity.zero], BoxConstraints.tight(const Size(100.0, 200.0)), ); expect( tester.getTopLeft(find.text('M(0,1)')), const Offset(100.0, 0.0), ); expect(tester.getSize(find.text('M(0,1)')), const Size(200.0, 100.0)); expect( layoutConstraints[const TableVicinity(row: 0, column: 1)], BoxConstraints.tight(const Size(200.0, 100.0)), ); expect( tester.getTopLeft(find.text('M(1,1)')), const Offset(100.0, 100.0), ); expect(tester.getSize(find.text('M(1,1)')), const Size(200.0, 200.0)); expect( layoutConstraints[const TableVicinity(row: 1, column: 1)], BoxConstraints.tight(const Size(200.0, 200.0)), ); expect( tester.getTopLeft(find.text('M(2,0)')), const Offset(0.0, 200.0), ); expect(tester.getSize(find.text('M(2,0)')), const Size(100.0, 100.0)); // Let's scroll a bit and check the layout verticalController.jumpTo(25.0); horizontalController.jumpTo(30.0); await tester.pumpAndSettle(); expect(find.text('M(0,0)'), findsOneWidget); expect(find.text('M(0,1)'), findsOneWidget); expect(find.text('M(0,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 0, column: 2)], isNull, ); expect(find.text('M(1,0)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 1, column: 0)], isNull, ); expect(find.text('M(1,1)'), findsOneWidget); expect(find.text('M(1,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 1, column: 2)], isNull, ); expect(find.text('M(2,0)'), findsOneWidget); expect(find.text('M(2,1)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 2, column: 1)], isNull, ); expect(find.text('M(2,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 2, column: 2)], isNull, ); expect( tester.getTopLeft(find.text('M(0,0)')), const Offset(-30.0, -25.0)); expect(tester.getSize(find.text('M(0,0)')), const Size(100.0, 200.0)); expect( layoutConstraints[TableVicinity.zero], BoxConstraints.tight(const Size(100.0, 200.0)), ); expect( tester.getTopLeft(find.text('M(0,1)')), const Offset(70.0, -25.0), ); expect(tester.getSize(find.text('M(0,1)')), const Size(200.0, 100.0)); expect( layoutConstraints[const TableVicinity(row: 0, column: 1)], BoxConstraints.tight(const Size(200.0, 100.0)), ); expect( tester.getTopLeft(find.text('M(1,1)')), const Offset(70.0, 75.0), ); expect(tester.getSize(find.text('M(1,1)')), const Size(200.0, 200.0)); expect( layoutConstraints[const TableVicinity(row: 1, column: 1)], BoxConstraints.tight(const Size(200.0, 200.0)), ); expect( tester.getTopLeft(find.text('M(2,0)')), const Offset(-30.0, 175.0), ); expect(tester.getSize(find.text('M(2,0)')), const Size(100.0, 100.0)); }); testWidgets('vertical main axis, reversed vertical', (WidgetTester tester) async { await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: TableView.builder( verticalDetails: ScrollableDetails.vertical( controller: verticalController, reverse: true, ), horizontalDetails: ScrollableDetails.horizontal( controller: horizontalController, ), cellBuilder: cellBuilder, columnBuilder: (_) => span, rowBuilder: (_) => span, columnCount: 10, rowCount: 10, ), )); await tester.pumpAndSettle(); expect(find.text('M(0,0)'), findsOneWidget); expect(find.text('M(0,1)'), findsOneWidget); expect(find.text('M(0,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 0, column: 2)], isNull, ); expect(find.text('M(1,0)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 1, column: 0)], isNull, ); expect(find.text('M(1,1)'), findsOneWidget); expect(find.text('M(1,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 1, column: 2)], isNull, ); expect(find.text('M(2,0)'), findsOneWidget); expect(find.text('M(2,1)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 2, column: 1)], isNull, ); expect(find.text('M(2,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 2, column: 2)], isNull, ); expect( tester.getTopLeft(find.text('M(0,0)')), const Offset(0.0, 400.0), ); expect(tester.getSize(find.text('M(0,0)')), const Size(100.0, 200.0)); expect( layoutConstraints[TableVicinity.zero], BoxConstraints.tight(const Size(100.0, 200.0)), ); expect( tester.getTopLeft(find.text('M(0,1)')), const Offset(100.0, 500.0), ); expect(tester.getSize(find.text('M(0,1)')), const Size(200.0, 100.0)); expect( layoutConstraints[const TableVicinity(row: 0, column: 1)], BoxConstraints.tight(const Size(200.0, 100.0)), ); expect( tester.getTopLeft(find.text('M(1,1)')), const Offset(100.0, 300.0), ); expect(tester.getSize(find.text('M(1,1)')), const Size(200.0, 200.0)); expect( layoutConstraints[const TableVicinity(row: 1, column: 1)], BoxConstraints.tight(const Size(200.0, 200.0)), ); expect( tester.getTopLeft(find.text('M(2,0)')), const Offset(0.0, 300.0), ); expect(tester.getSize(find.text('M(2,0)')), const Size(100.0, 100.0)); // Let's scroll a bit and check the layout verticalController.jumpTo(25.0); horizontalController.jumpTo(30.0); await tester.pumpAndSettle(); expect(find.text('M(0,0)'), findsOneWidget); expect(find.text('M(0,1)'), findsOneWidget); expect(find.text('M(0,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 0, column: 2)], isNull, ); expect(find.text('M(1,0)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 1, column: 0)], isNull, ); expect(find.text('M(1,1)'), findsOneWidget); expect(find.text('M(1,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 1, column: 2)], isNull, ); expect(find.text('M(2,0)'), findsOneWidget); expect(find.text('M(2,1)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 2, column: 1)], isNull, ); expect(find.text('M(2,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 2, column: 2)], isNull, ); expect( tester.getTopLeft(find.text('M(0,0)')), const Offset(-30.0, 425.0), ); expect(tester.getSize(find.text('M(0,0)')), const Size(100.0, 200.0)); expect( layoutConstraints[TableVicinity.zero], BoxConstraints.tight(const Size(100.0, 200.0)), ); expect( tester.getTopLeft(find.text('M(0,1)')), const Offset(70.0, 525.0), ); expect(tester.getSize(find.text('M(0,1)')), const Size(200.0, 100.0)); expect( layoutConstraints[const TableVicinity(row: 0, column: 1)], BoxConstraints.tight(const Size(200.0, 100.0)), ); expect( tester.getTopLeft(find.text('M(1,1)')), const Offset(70.0, 325.0), ); expect(tester.getSize(find.text('M(1,1)')), const Size(200.0, 200.0)); expect( layoutConstraints[const TableVicinity(row: 1, column: 1)], BoxConstraints.tight(const Size(200.0, 200.0)), ); expect( tester.getTopLeft(find.text('M(2,0)')), const Offset(-30.0, 325.0), ); expect(tester.getSize(find.text('M(2,0)')), const Size(100.0, 100.0)); }); testWidgets('vertical main axis, reversed horizontal', (WidgetTester tester) async { await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: TableView.builder( verticalDetails: ScrollableDetails.vertical( controller: verticalController, ), horizontalDetails: ScrollableDetails.horizontal( controller: horizontalController, reverse: true, ), cellBuilder: cellBuilder, columnBuilder: (_) => span, rowBuilder: (_) => span, columnCount: 10, rowCount: 10, ), )); await tester.pumpAndSettle(); expect(find.text('M(0,0)'), findsOneWidget); expect(find.text('M(0,1)'), findsOneWidget); expect(find.text('M(0,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 0, column: 2)], isNull, ); expect(find.text('M(1,0)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 1, column: 0)], isNull, ); expect(find.text('M(1,1)'), findsOneWidget); expect(find.text('M(1,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 1, column: 2)], isNull, ); expect(find.text('M(2,0)'), findsOneWidget); expect(find.text('M(2,1)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 2, column: 1)], isNull, ); expect(find.text('M(2,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 2, column: 2)], isNull, ); expect( tester.getTopLeft(find.text('M(0,0)')), const Offset(700.0, 0.0), ); expect(tester.getSize(find.text('M(0,0)')), const Size(100.0, 200.0)); expect( layoutConstraints[TableVicinity.zero], BoxConstraints.tight(const Size(100.0, 200.0)), ); expect( tester.getTopLeft(find.text('M(0,1)')), const Offset(500.0, 0.0), ); expect(tester.getSize(find.text('M(0,1)')), const Size(200.0, 100.0)); expect( layoutConstraints[const TableVicinity(row: 0, column: 1)], BoxConstraints.tight(const Size(200.0, 100.0)), ); expect( tester.getTopLeft(find.text('M(1,1)')), const Offset(500.0, 100.0), ); expect(tester.getSize(find.text('M(1,1)')), const Size(200.0, 200.0)); expect( layoutConstraints[const TableVicinity(row: 1, column: 1)], BoxConstraints.tight(const Size(200.0, 200.0)), ); expect( tester.getTopLeft(find.text('M(2,0)')), const Offset(700.0, 200.0), ); expect(tester.getSize(find.text('M(2,0)')), const Size(100.0, 100.0)); // Let's scroll a bit and check the layout verticalController.jumpTo(25.0); horizontalController.jumpTo(30.0); await tester.pumpAndSettle(); expect(find.text('M(0,0)'), findsOneWidget); expect(find.text('M(0,1)'), findsOneWidget); expect(find.text('M(0,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 0, column: 2)], isNull, ); expect(find.text('M(1,0)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 1, column: 0)], isNull, ); expect(find.text('M(1,1)'), findsOneWidget); expect(find.text('M(1,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 1, column: 2)], isNull, ); expect(find.text('M(2,0)'), findsOneWidget); expect(find.text('M(2,1)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 2, column: 1)], isNull, ); expect(find.text('M(2,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 2, column: 2)], isNull, ); expect( tester.getTopLeft(find.text('M(0,0)')), const Offset(730.0, -25.0), ); expect( tester.getSize(find.text('M(0,0)')), const Size(100.0, 200.0), ); expect( layoutConstraints[TableVicinity.zero], BoxConstraints.tight(const Size(100.0, 200.0)), ); expect( tester.getTopLeft(find.text('M(0,1)')), const Offset(530.0, -25.0), ); expect( tester.getSize(find.text('M(0,1)')), const Size(200.0, 100.0), ); expect( layoutConstraints[const TableVicinity(row: 0, column: 1)], BoxConstraints.tight(const Size(200.0, 100.0)), ); expect( tester.getTopLeft(find.text('M(1,1)')), const Offset(530.0, 75.0), ); expect( tester.getSize(find.text('M(1,1)')), const Size(200.0, 200.0), ); expect( layoutConstraints[const TableVicinity(row: 1, column: 1)], BoxConstraints.tight(const Size(200.0, 200.0)), ); expect( tester.getTopLeft(find.text('M(2,0)')), const Offset(730.0, 175.0), ); expect(tester.getSize(find.text('M(2,0)')), const Size(100.0, 100.0)); }); testWidgets('vertical main axis, both axes reversed', (WidgetTester tester) async { await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: TableView.builder( verticalDetails: ScrollableDetails.vertical( controller: verticalController, reverse: true, ), horizontalDetails: ScrollableDetails.horizontal( controller: horizontalController, reverse: true, ), cellBuilder: cellBuilder, columnBuilder: (_) => span, rowBuilder: (_) => span, columnCount: 10, rowCount: 10, ), )); await tester.pumpAndSettle(); expect(find.text('M(0,0)'), findsOneWidget); expect(find.text('M(0,1)'), findsOneWidget); expect(find.text('M(0,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 0, column: 2)], isNull, ); expect(find.text('M(1,0)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 1, column: 0)], isNull, ); expect(find.text('M(1,1)'), findsOneWidget); expect(find.text('M(1,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 1, column: 2)], isNull, ); expect(find.text('M(2,0)'), findsOneWidget); expect(find.text('M(2,1)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 2, column: 1)], isNull, ); expect(find.text('M(2,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 2, column: 2)], isNull, ); expect( tester.getTopLeft(find.text('M(0,0)')), const Offset(700.0, 400.0), ); expect( tester.getSize(find.text('M(0,0)')), const Size(100.0, 200.0), ); expect( layoutConstraints[TableVicinity.zero], BoxConstraints.tight(const Size(100.0, 200.0)), ); expect( tester.getTopLeft(find.text('M(0,1)')), const Offset(500.0, 500.0), ); expect( tester.getSize(find.text('M(0,1)')), const Size(200.0, 100.0), ); expect( layoutConstraints[const TableVicinity(row: 0, column: 1)], BoxConstraints.tight(const Size(200.0, 100.0)), ); expect( tester.getTopLeft(find.text('M(1,1)')), const Offset(500.0, 300.0), ); expect( tester.getSize(find.text('M(1,1)')), const Size(200.0, 200.0), ); expect( layoutConstraints[const TableVicinity(row: 1, column: 1)], BoxConstraints.tight(const Size(200.0, 200.0)), ); expect( tester.getTopLeft(find.text('M(2,0)')), const Offset(700.0, 300.0), ); expect( tester.getSize(find.text('M(2,0)')), const Size(100.0, 100.0), ); // Let's scroll a bit and check the layout verticalController.jumpTo(25.0); horizontalController.jumpTo(30.0); await tester.pumpAndSettle(); expect(find.text('M(0,0)'), findsOneWidget); expect(find.text('M(0,1)'), findsOneWidget); expect(find.text('M(0,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 0, column: 2)], isNull, ); expect(find.text('M(1,0)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 1, column: 0)], isNull, ); expect(find.text('M(1,1)'), findsOneWidget); expect(find.text('M(1,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 1, column: 2)], isNull, ); expect(find.text('M(2,0)'), findsOneWidget); expect(find.text('M(2,1)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 2, column: 1)], isNull, ); expect(find.text('M(2,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 2, column: 2)], isNull, ); expect( tester.getTopLeft(find.text('M(0,0)')), const Offset(730.0, 425.0), ); expect( tester.getSize(find.text('M(0,0)')), const Size(100.0, 200.0), ); expect( layoutConstraints[TableVicinity.zero], BoxConstraints.tight(const Size(100.0, 200.0)), ); expect( tester.getTopLeft(find.text('M(0,1)')), const Offset(530.0, 525.0), ); expect( tester.getSize(find.text('M(0,1)')), const Size(200.0, 100.0), ); expect( layoutConstraints[const TableVicinity(row: 0, column: 1)], BoxConstraints.tight(const Size(200.0, 100.0)), ); expect( tester.getTopLeft(find.text('M(1,1)')), const Offset(530.0, 325.0), ); expect( tester.getSize(find.text('M(1,1)')), const Size(200.0, 200.0), ); expect( layoutConstraints[const TableVicinity(row: 1, column: 1)], BoxConstraints.tight(const Size(200.0, 200.0)), ); expect( tester.getTopLeft(find.text('M(2,0)')), const Offset(730.0, 325.0), ); expect( tester.getSize(find.text('M(2,0)')), const Size(100.0, 100.0), ); }); testWidgets('horizontal main axis and natural scroll directions', (WidgetTester tester) async { await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: TableView.builder( mainAxis: Axis.horizontal, verticalDetails: ScrollableDetails.vertical( controller: verticalController, ), horizontalDetails: ScrollableDetails.horizontal( controller: horizontalController, ), cellBuilder: cellBuilder, columnBuilder: (_) => span, rowBuilder: (_) => span, columnCount: 10, rowCount: 10, ), )); await tester.pumpAndSettle(); expect(find.text('M(0,0)'), findsOneWidget); expect(find.text('M(0,1)'), findsOneWidget); expect(find.text('M(0,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 0, column: 2)], isNull, ); expect(find.text('M(1,0)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 1, column: 0)], isNull, ); expect(find.text('M(1,1)'), findsOneWidget); expect(find.text('M(1,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 1, column: 2)], isNull, ); expect(find.text('M(2,0)'), findsOneWidget); expect(find.text('M(2,1)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 2, column: 1)], isNull, ); expect(find.text('M(2,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 2, column: 2)], isNull, ); expect(tester.getTopLeft(find.text('M(0,0)')), Offset.zero); expect(tester.getSize(find.text('M(0,0)')), const Size(100.0, 200.0)); expect( layoutConstraints[TableVicinity.zero], BoxConstraints.tight(const Size(100.0, 200.0)), ); expect( tester.getTopLeft(find.text('M(0,1)')), const Offset(100.0, 0.0), ); expect(tester.getSize(find.text('M(0,1)')), const Size(200.0, 100.0)); expect( layoutConstraints[const TableVicinity(row: 0, column: 1)], BoxConstraints.tight(const Size(200.0, 100.0)), ); expect( tester.getTopLeft(find.text('M(1,1)')), const Offset(100.0, 100.0), ); expect(tester.getSize(find.text('M(1,1)')), const Size(200.0, 200.0)); expect( layoutConstraints[const TableVicinity(row: 1, column: 1)], BoxConstraints.tight(const Size(200.0, 200.0)), ); expect( tester.getTopLeft(find.text('M(2,0)')), const Offset(0.0, 200.0), ); expect(tester.getSize(find.text('M(2,0)')), const Size(100.0, 100.0)); // Let's scroll a bit and check the layout verticalController.jumpTo(25.0); horizontalController.jumpTo(30.0); await tester.pumpAndSettle(); expect(find.text('M(0,0)'), findsOneWidget); expect(find.text('M(0,1)'), findsOneWidget); expect(find.text('M(0,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 0, column: 2)], isNull, ); expect(find.text('M(1,0)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 1, column: 0)], isNull, ); expect(find.text('M(1,1)'), findsOneWidget); expect(find.text('M(1,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 1, column: 2)], isNull, ); expect(find.text('M(2,0)'), findsOneWidget); expect(find.text('M(2,1)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 2, column: 1)], isNull, ); expect(find.text('M(2,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 2, column: 2)], isNull, ); expect( tester.getTopLeft(find.text('M(0,0)')), const Offset(-30.0, -25.0)); expect(tester.getSize(find.text('M(0,0)')), const Size(100.0, 200.0)); expect( layoutConstraints[TableVicinity.zero], BoxConstraints.tight(const Size(100.0, 200.0)), ); expect( tester.getTopLeft(find.text('M(0,1)')), const Offset(70.0, -25.0), ); expect(tester.getSize(find.text('M(0,1)')), const Size(200.0, 100.0)); expect( layoutConstraints[const TableVicinity(row: 0, column: 1)], BoxConstraints.tight(const Size(200.0, 100.0)), ); expect( tester.getTopLeft(find.text('M(1,1)')), const Offset(70.0, 75.0), ); expect(tester.getSize(find.text('M(1,1)')), const Size(200.0, 200.0)); expect( layoutConstraints[const TableVicinity(row: 1, column: 1)], BoxConstraints.tight(const Size(200.0, 200.0)), ); expect( tester.getTopLeft(find.text('M(2,0)')), const Offset(-30.0, 175.0), ); expect(tester.getSize(find.text('M(2,0)')), const Size(100.0, 100.0)); }); testWidgets('horizontal main axis, reversed vertical', (WidgetTester tester) async { await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: TableView.builder( mainAxis: Axis.horizontal, verticalDetails: ScrollableDetails.vertical( controller: verticalController, reverse: true, ), horizontalDetails: ScrollableDetails.horizontal( controller: horizontalController, ), cellBuilder: cellBuilder, columnBuilder: (_) => span, rowBuilder: (_) => span, columnCount: 10, rowCount: 10, ), )); await tester.pumpAndSettle(); expect(find.text('M(0,0)'), findsOneWidget); expect(find.text('M(0,1)'), findsOneWidget); expect(find.text('M(0,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 0, column: 2)], isNull, ); expect(find.text('M(1,0)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 1, column: 0)], isNull, ); expect(find.text('M(1,1)'), findsOneWidget); expect(find.text('M(1,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 1, column: 2)], isNull, ); expect(find.text('M(2,0)'), findsOneWidget); expect(find.text('M(2,1)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 2, column: 1)], isNull, ); expect(find.text('M(2,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 2, column: 2)], isNull, ); expect( tester.getTopLeft(find.text('M(0,0)')), const Offset(0.0, 400.0), ); expect(tester.getSize(find.text('M(0,0)')), const Size(100.0, 200.0)); expect( layoutConstraints[TableVicinity.zero], BoxConstraints.tight(const Size(100.0, 200.0)), ); expect( tester.getTopLeft(find.text('M(0,1)')), const Offset(100.0, 500.0), ); expect(tester.getSize(find.text('M(0,1)')), const Size(200.0, 100.0)); expect( layoutConstraints[const TableVicinity(row: 0, column: 1)], BoxConstraints.tight(const Size(200.0, 100.0)), ); expect( tester.getTopLeft(find.text('M(1,1)')), const Offset(100.0, 300.0), ); expect(tester.getSize(find.text('M(1,1)')), const Size(200.0, 200.0)); expect( layoutConstraints[const TableVicinity(row: 1, column: 1)], BoxConstraints.tight(const Size(200.0, 200.0)), ); expect( tester.getTopLeft(find.text('M(2,0)')), const Offset(0.0, 300.0), ); expect(tester.getSize(find.text('M(2,0)')), const Size(100.0, 100.0)); // Let's scroll a bit and check the layout verticalController.jumpTo(25.0); horizontalController.jumpTo(30.0); await tester.pumpAndSettle(); expect(find.text('M(0,0)'), findsOneWidget); expect(find.text('M(0,1)'), findsOneWidget); expect(find.text('M(0,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 0, column: 2)], isNull, ); expect(find.text('M(1,0)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 1, column: 0)], isNull, ); expect(find.text('M(1,1)'), findsOneWidget); expect(find.text('M(1,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 1, column: 2)], isNull, ); expect(find.text('M(2,0)'), findsOneWidget); expect(find.text('M(2,1)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 2, column: 1)], isNull, ); expect(find.text('M(2,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 2, column: 2)], isNull, ); expect( tester.getTopLeft(find.text('M(0,0)')), const Offset(-30.0, 425.0)); expect(tester.getSize(find.text('M(0,0)')), const Size(100.0, 200.0)); expect( layoutConstraints[TableVicinity.zero], BoxConstraints.tight(const Size(100.0, 200.0)), ); expect( tester.getTopLeft(find.text('M(0,1)')), const Offset(70.0, 525.0), ); expect(tester.getSize(find.text('M(0,1)')), const Size(200.0, 100.0)); expect( layoutConstraints[const TableVicinity(row: 0, column: 1)], BoxConstraints.tight(const Size(200.0, 100.0)), ); expect( tester.getTopLeft(find.text('M(1,1)')), const Offset(70.0, 325.0), ); expect(tester.getSize(find.text('M(1,1)')), const Size(200.0, 200.0)); expect( layoutConstraints[const TableVicinity(row: 1, column: 1)], BoxConstraints.tight(const Size(200.0, 200.0)), ); expect( tester.getTopLeft(find.text('M(2,0)')), const Offset(-30.0, 325.0), ); expect(tester.getSize(find.text('M(2,0)')), const Size(100.0, 100.0)); }); testWidgets('horizontal main axis, reversed horizontal', (WidgetTester tester) async { await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: TableView.builder( mainAxis: Axis.horizontal, verticalDetails: ScrollableDetails.vertical( controller: verticalController, ), horizontalDetails: ScrollableDetails.horizontal( controller: horizontalController, reverse: true, ), cellBuilder: cellBuilder, columnBuilder: (_) => span, rowBuilder: (_) => span, columnCount: 10, rowCount: 10, ), )); await tester.pumpAndSettle(); expect(find.text('M(0,0)'), findsOneWidget); expect(find.text('M(0,1)'), findsOneWidget); expect(find.text('M(0,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 0, column: 2)], isNull, ); expect(find.text('M(1,0)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 1, column: 0)], isNull, ); expect(find.text('M(1,1)'), findsOneWidget); expect(find.text('M(1,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 1, column: 2)], isNull, ); expect(find.text('M(2,0)'), findsOneWidget); expect(find.text('M(2,1)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 2, column: 1)], isNull, ); expect(find.text('M(2,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 2, column: 2)], isNull, ); expect( tester.getTopLeft(find.text('M(0,0)')), const Offset(700.0, 0.0), ); expect(tester.getSize(find.text('M(0,0)')), const Size(100.0, 200.0)); expect( layoutConstraints[TableVicinity.zero], BoxConstraints.tight(const Size(100.0, 200.0)), ); expect( tester.getTopLeft(find.text('M(0,1)')), const Offset(500.0, 0.0), ); expect(tester.getSize(find.text('M(0,1)')), const Size(200.0, 100.0)); expect( layoutConstraints[const TableVicinity(row: 0, column: 1)], BoxConstraints.tight(const Size(200.0, 100.0)), ); expect( tester.getTopLeft(find.text('M(1,1)')), const Offset(500.0, 100.0), ); expect(tester.getSize(find.text('M(1,1)')), const Size(200.0, 200.0)); expect( layoutConstraints[const TableVicinity(row: 1, column: 1)], BoxConstraints.tight(const Size(200.0, 200.0)), ); expect( tester.getTopLeft(find.text('M(2,0)')), const Offset(700.0, 200.0), ); expect(tester.getSize(find.text('M(2,0)')), const Size(100.0, 100.0)); // Let's scroll a bit and check the layout verticalController.jumpTo(25.0); horizontalController.jumpTo(30.0); await tester.pumpAndSettle(); expect(find.text('M(0,0)'), findsOneWidget); expect(find.text('M(0,1)'), findsOneWidget); expect(find.text('M(0,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 0, column: 2)], isNull, ); expect(find.text('M(1,0)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 1, column: 0)], isNull, ); expect(find.text('M(1,1)'), findsOneWidget); expect(find.text('M(1,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 1, column: 2)], isNull, ); expect(find.text('M(2,0)'), findsOneWidget); expect(find.text('M(2,1)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 2, column: 1)], isNull, ); expect(find.text('M(2,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 2, column: 2)], isNull, ); expect( tester.getTopLeft(find.text('M(0,0)')), const Offset(730.0, -25.0), ); expect( tester.getSize(find.text('M(0,0)')), const Size(100.0, 200.0), ); expect( layoutConstraints[TableVicinity.zero], BoxConstraints.tight(const Size(100.0, 200.0)), ); expect( tester.getTopLeft(find.text('M(0,1)')), const Offset(530.0, -25.0), ); expect( tester.getSize(find.text('M(0,1)')), const Size(200.0, 100.0), ); expect( layoutConstraints[const TableVicinity(row: 0, column: 1)], BoxConstraints.tight(const Size(200.0, 100.0)), ); expect( tester.getTopLeft(find.text('M(1,1)')), const Offset(530.0, 75.0), ); expect( tester.getSize(find.text('M(1,1)')), const Size(200.0, 200.0), ); expect( layoutConstraints[const TableVicinity(row: 1, column: 1)], BoxConstraints.tight(const Size(200.0, 200.0)), ); expect( tester.getTopLeft(find.text('M(2,0)')), const Offset(730.0, 175.0), ); expect(tester.getSize(find.text('M(2,0)')), const Size(100.0, 100.0)); }); testWidgets('horizontal main axis, both axes reversed', (WidgetTester tester) async { await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: TableView.builder( mainAxis: Axis.horizontal, verticalDetails: ScrollableDetails.vertical( controller: verticalController, reverse: true, ), horizontalDetails: ScrollableDetails.horizontal( controller: horizontalController, reverse: true, ), cellBuilder: cellBuilder, columnBuilder: (_) => span, rowBuilder: (_) => span, columnCount: 10, rowCount: 10, ), )); await tester.pumpAndSettle(); expect(find.text('M(0,0)'), findsOneWidget); expect(find.text('M(0,1)'), findsOneWidget); expect(find.text('M(0,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 0, column: 2)], isNull, ); expect(find.text('M(1,0)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 1, column: 0)], isNull, ); expect(find.text('M(1,1)'), findsOneWidget); expect(find.text('M(1,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 1, column: 2)], isNull, ); expect(find.text('M(2,0)'), findsOneWidget); expect(find.text('M(2,1)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 2, column: 1)], isNull, ); expect(find.text('M(2,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 2, column: 2)], isNull, ); expect( tester.getTopLeft(find.text('M(0,0)')), const Offset(700.0, 400.0), ); expect( tester.getSize(find.text('M(0,0)')), const Size(100.0, 200.0), ); expect( layoutConstraints[TableVicinity.zero], BoxConstraints.tight(const Size(100.0, 200.0)), ); expect( tester.getTopLeft(find.text('M(0,1)')), const Offset(500.0, 500.0), ); expect( tester.getSize(find.text('M(0,1)')), const Size(200.0, 100.0), ); expect( layoutConstraints[const TableVicinity(row: 0, column: 1)], BoxConstraints.tight(const Size(200.0, 100.0)), ); expect( tester.getTopLeft(find.text('M(1,1)')), const Offset(500.0, 300.0), ); expect( tester.getSize(find.text('M(1,1)')), const Size(200.0, 200.0), ); expect( layoutConstraints[const TableVicinity(row: 1, column: 1)], BoxConstraints.tight(const Size(200.0, 200.0)), ); expect( tester.getTopLeft(find.text('M(2,0)')), const Offset(700.0, 300.0), ); expect( tester.getSize(find.text('M(2,0)')), const Size(100.0, 100.0), ); // Let's scroll a bit and check the layout verticalController.jumpTo(25.0); horizontalController.jumpTo(30.0); await tester.pumpAndSettle(); expect(find.text('M(0,0)'), findsOneWidget); expect(find.text('M(0,1)'), findsOneWidget); expect(find.text('M(0,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 0, column: 2)], isNull, ); expect(find.text('M(1,0)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 1, column: 0)], isNull, ); expect(find.text('M(1,1)'), findsOneWidget); expect(find.text('M(1,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 1, column: 2)], isNull, ); expect(find.text('M(2,0)'), findsOneWidget); expect(find.text('M(2,1)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 2, column: 1)], isNull, ); expect(find.text('M(2,2)'), findsNothing); // Merged expect( layoutConstraints[const TableVicinity(row: 2, column: 2)], isNull, ); expect( tester.getTopLeft(find.text('M(0,0)')), const Offset(730.0, 425.0), ); expect( tester.getSize(find.text('M(0,0)')), const Size(100.0, 200.0), ); expect( layoutConstraints[TableVicinity.zero], BoxConstraints.tight(const Size(100.0, 200.0)), ); expect( tester.getTopLeft(find.text('M(0,1)')), const Offset(530.0, 525.0), ); expect( tester.getSize(find.text('M(0,1)')), const Size(200.0, 100.0), ); expect( layoutConstraints[const TableVicinity(row: 0, column: 1)], BoxConstraints.tight(const Size(200.0, 100.0)), ); expect( tester.getTopLeft(find.text('M(1,1)')), const Offset(530.0, 325.0), ); expect( tester.getSize(find.text('M(1,1)')), const Size(200.0, 200.0), ); expect( layoutConstraints[const TableVicinity(row: 1, column: 1)], BoxConstraints.tight(const Size(200.0, 200.0)), ); expect( tester.getTopLeft(find.text('M(2,0)')), const Offset(730.0, 325.0), ); expect( tester.getSize(find.text('M(2,0)')), const Size(100.0, 100.0), ); }); }); }); }
packages/packages/two_dimensional_scrollables/test/table_view/table_cell_test.dart/0
{ "file_path": "packages/packages/two_dimensional_scrollables/test/table_view/table_cell_test.dart", "repo_id": "packages", "token_count": 30604 }
1,012
buildFlags: _pluginToolsConfigGlobalKey: - "--no-tree-shake-icons" - "--dart-define=buildmode=testing"
packages/packages/url_launcher/url_launcher_android/example/.pluginToolsConfig.yaml/0
{ "file_path": "packages/packages/url_launcher/url_launcher_android/example/.pluginToolsConfig.yaml", "repo_id": "packages", "token_count": 45 }
1,013
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:io'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); testWidgets('canLaunch', (WidgetTester _) async { final UrlLauncherPlatform launcher = UrlLauncherPlatform.instance; expect(await launcher.canLaunch('randomstring'), false); // Generally all devices should have some default browser. expect(await launcher.canLaunch('http://flutter.dev'), true); // sms:, tel:, and mailto: links may not be openable on every device, so // aren't tested here. }); testWidgets('launch and close', (WidgetTester _) async { final UrlLauncherPlatform launcher = UrlLauncherPlatform.instance; // Setup fake http server. final HttpServer server = await HttpServer.bind(InternetAddress.anyIPv4, 0); unawaited(server.forEach((HttpRequest request) { if (request.uri.path == '/hello.txt') { request.response.writeln('Hello, world.'); } else { fail('unexpected request: ${request.method} ${request.uri}'); } request.response.close(); })); // Https to avoid cleartext warning on android. final String prefixUrl = 'https://${server.address.address}:${server.port}'; final String primaryUrl = '$prefixUrl/hello.txt'; // Launch a url then close. expect( await launcher.launch(primaryUrl, useSafariVC: true, useWebView: true, enableJavaScript: false, enableDomStorage: false, universalLinksOnly: false, headers: <String, String>{}), true); await launcher.closeWebView(); // Delay required to catch android side crashes in onDestroy. // // If this test flakes with an android crash during this delay the test // should be considered failing because this integration test can have a // false positive pass if the test closes before an onDestroy crash. // See https://github.com/flutter/flutter/issues/126460 for more info. await Future<void>.delayed(const Duration(seconds: 5)); }); }
packages/packages/url_launcher/url_launcher_android/example/integration_test/url_launcher_test.dart/0
{ "file_path": "packages/packages/url_launcher/url_launcher_android/example/integration_test/url_launcher_test.dart", "repo_id": "packages", "token_count": 818 }
1,014
name: url_launcher_ios description: iOS implementation of the url_launcher plugin. repository: https://github.com/flutter/packages/tree/main/packages/url_launcher/url_launcher_ios issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+url_launcher%22 version: 6.2.5 environment: sdk: ^3.2.3 flutter: ">=3.16.6" flutter: plugin: implements: url_launcher platforms: ios: pluginClass: URLLauncherPlugin dartPluginClass: UrlLauncherIOS dependencies: flutter: sdk: flutter url_launcher_platform_interface: ^2.2.0 dev_dependencies: build_runner: ^2.3.3 flutter_test: sdk: flutter mockito: 5.4.4 pigeon: ^11.0.1 plugin_platform_interface: ^2.1.7 test: ^1.16.3 topics: - links - os-integration - url-launcher - urls
packages/packages/url_launcher/url_launcher_ios/pubspec.yaml/0
{ "file_path": "packages/packages/url_launcher/url_launcher_ios/pubspec.yaml", "repo_id": "packages", "token_count": 354 }
1,015
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import FlutterMacOS import XCTest @testable import url_launcher_macos /// A stub to simulate the system Url handler. class StubWorkspace: SystemURLHandler { var isSuccessful = true func open(_ url: URL) -> Bool { return isSuccessful } func urlForApplication(toOpen: URL) -> URL? { return toOpen } } class RunnerTests: XCTestCase { func testCanLaunchSuccessReturnsTrue() throws { let plugin = UrlLauncherPlugin() let result = try plugin.canLaunch(url: "https://flutter.dev") XCTAssertNil(result.error) XCTAssertTrue(result.value) } func testCanLaunchNoAppIsAbleToOpenUrlReturnsFalse() throws { let plugin = UrlLauncherPlugin() let result = try plugin.canLaunch(url: "example://flutter.dev") XCTAssertNil(result.error) XCTAssertFalse(result.value) } func testCanLaunchInvalidUrlReturnsError() throws { let plugin = UrlLauncherPlugin() let result = try plugin.canLaunch(url: "invalid url") XCTAssertEqual(result.error, .invalidUrl) } func testLaunchSuccessReturnsTrue() throws { let workspace = StubWorkspace() let plugin = UrlLauncherPlugin(workspace) let result = try plugin.launch(url: "https://flutter.dev") XCTAssertNil(result.error) XCTAssertTrue(result.value) } func testLaunchNoAppIsAbleToOpenUrlReturnsFalse() throws { let workspace = StubWorkspace() workspace.isSuccessful = false let plugin = UrlLauncherPlugin(workspace) let result = try plugin.launch(url: "schemethatdoesnotexist://flutter.dev") XCTAssertNil(result.error) XCTAssertFalse(result.value) } func testLaunchInvalidUrlReturnsError() throws { let plugin = UrlLauncherPlugin() let result = try plugin.launch(url: "invalid url") XCTAssertEqual(result.error, .invalidUrl) } }
packages/packages/url_launcher/url_launcher_macos/example/macos/RunnerTests/RunnerTests.swift/0
{ "file_path": "packages/packages/url_launcher/url_launcher_macos/example/macos/RunnerTests/RunnerTests.swift", "repo_id": "packages", "token_count": 674 }
1,016
rootProject.name = 'video_player_android'
packages/packages/video_player/video_player_android/android/settings.gradle/0
{ "file_path": "packages/packages/video_player/video_player_android/android/settings.gradle", "repo_id": "packages", "token_count": 13 }
1,017
# # To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = 'video_player_avfoundation' s.version = '0.0.1' s.summary = 'Flutter Video Player' s.description = <<-DESC A Flutter plugin for playing back video on a Widget surface. Downloaded by pub (not CocoaPods). DESC s.homepage = 'https://github.com/flutter/packages' s.license = { :type => 'BSD', :file => '../LICENSE' } s.author = { 'Flutter Dev Team' => '[email protected]' } s.source = { :http => 'https://github.com/flutter/packages/tree/main/packages/video_player/video_player_avfoundation' } s.documentation_url = 'https://pub.dev/packages/video_player' s.source_files = 'Classes/*' s.ios.source_files = 'Classes/ios/*' s.osx.source_files = 'Classes/macos/*' s.public_header_files = 'Classes/**/*.h' s.ios.dependency 'Flutter' s.osx.dependency 'FlutterMacOS' s.ios.deployment_target = '12.0' s.osx.deployment_target = '10.14' s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' } s.resource_bundles = {'video_player_avfoundation_privacy' => ['Resources/PrivacyInfo.xcprivacy']} end
packages/packages/video_player/video_player_avfoundation/darwin/video_player_avfoundation.podspec/0
{ "file_path": "packages/packages/video_player/video_player_avfoundation/darwin/video_player_avfoundation.podspec", "repo_id": "packages", "token_count": 540 }
1,018
name: video_player_avfoundation description: iOS and macOS implementation of the video_player plugin. repository: https://github.com/flutter/packages/tree/main/packages/video_player/video_player_avfoundation issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+video_player%22 version: 2.5.6 environment: sdk: ^3.2.3 flutter: ">=3.16.6" flutter: plugin: implements: video_player platforms: ios: dartPluginClass: AVFoundationVideoPlayer pluginClass: FVPVideoPlayerPlugin sharedDarwinSource: true macos: dartPluginClass: AVFoundationVideoPlayer pluginClass: FVPVideoPlayerPlugin sharedDarwinSource: true dependencies: flutter: sdk: flutter video_player_platform_interface: ">=6.1.0 <7.0.0" dev_dependencies: flutter_test: sdk: flutter pigeon: ^13.0.0 topics: - video - video-player
packages/packages/video_player/video_player_avfoundation/pubspec.yaml/0
{ "file_path": "packages/packages/video_player/video_player_avfoundation/pubspec.yaml", "repo_id": "packages", "token_count": 370 }
1,019
name: web_benchmarks description: A benchmark harness for performance-testing Flutter apps in Chrome. repository: https://github.com/flutter/packages/tree/main/packages/web_benchmarks issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+web_benchmarks%22 version: 1.2.1 environment: sdk: ^3.3.0 flutter: ">=3.19.0" dependencies: collection: ^1.18.0 flutter: sdk: flutter flutter_test: sdk: flutter logging: ^1.0.2 meta: ^1.7.0 path: ^1.8.0 process: ">=4.2.4 <6.0.0" shelf: ^1.2.0 shelf_static: ^1.1.0 test: ^1.19.5 web: ^0.5.0 webkit_inspection_protocol: ^1.0.0 topics: - benchmarking - performance
packages/packages/web_benchmarks/pubspec.yaml/0
{ "file_path": "packages/packages/web_benchmarks/pubspec.yaml", "repo_id": "packages", "token_count": 304 }
1,020
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'about_page.dart'; import 'home_page.dart'; import 'icon_page.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, visualDensity: VisualDensity.adaptivePlatformDensity, ), initialRoute: 'home', routes: <String, WidgetBuilder>{ 'home': (_) => const HomePage(title: 'Flutter Demo Home Page'), 'about': (_) => const AboutPage(), 'icon_generator': (_) => const IconGeneratorPage(), }, ); } }
packages/packages/web_benchmarks/testing/test_app/lib/main.dart/0
{ "file_path": "packages/packages/web_benchmarks/testing/test_app/lib/main.dart", "repo_id": "packages", "token_count": 329 }
1,021
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.webviewflutter; import android.webkit.DownloadListener; import androidx.annotation.NonNull; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.DownloadListenerFlutterApi; /** * Flutter Api implementation for {@link DownloadListener}. * * <p>Passes arguments of callbacks methods from a {@link DownloadListener} to Dart. */ public class DownloadListenerFlutterApiImpl extends DownloadListenerFlutterApi { private final InstanceManager instanceManager; /** * Creates a Flutter api that sends messages to Dart. * * @param binaryMessenger handles sending messages to Dart * @param instanceManager maintains instances stored to communicate with Dart objects */ public DownloadListenerFlutterApiImpl( @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { super(binaryMessenger); this.instanceManager = instanceManager; } /** Passes arguments from {@link DownloadListener#onDownloadStart} to Dart. */ public void onDownloadStart( @NonNull DownloadListener downloadListener, @NonNull String url, @NonNull String userAgent, @NonNull String contentDisposition, @NonNull String mimetype, long contentLength, @NonNull Reply<Void> callback) { onDownloadStart( getIdentifierForListener(downloadListener), url, userAgent, contentDisposition, mimetype, contentLength, callback); } private long getIdentifierForListener(DownloadListener listener) { final Long identifier = instanceManager.getIdentifierForStrongReference(listener); if (identifier == null) { throw new IllegalStateException("Could not find identifier for DownloadListener."); } return identifier; } }
packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/DownloadListenerFlutterApiImpl.java/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/DownloadListenerFlutterApiImpl.java", "repo_id": "packages", "token_count": 614 }
1,022
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.webviewflutter; import android.webkit.PermissionRequest; import androidx.annotation.NonNull; import androidx.annotation.VisibleForTesting; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.PermissionRequestFlutterApi; import java.util.Arrays; /** * Flutter API implementation for `PermissionRequest`. * * <p>This class may handle adding native instances that are attached to a Dart instance or passing * arguments of callbacks methods to a Dart instance. */ public class PermissionRequestFlutterApiImpl { // To ease adding additional methods, this value is added prematurely. @SuppressWarnings({"unused", "FieldCanBeLocal"}) private final BinaryMessenger binaryMessenger; private final InstanceManager instanceManager; private PermissionRequestFlutterApi api; /** * Constructs a {@link PermissionRequestFlutterApiImpl}. * * @param binaryMessenger used to communicate with Dart over asynchronous messages * @param instanceManager maintains instances stored to communicate with attached Dart objects */ public PermissionRequestFlutterApiImpl( @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { this.binaryMessenger = binaryMessenger; this.instanceManager = instanceManager; api = new PermissionRequestFlutterApi(binaryMessenger); } /** * Stores the `PermissionRequest` instance and notifies Dart to create and store a new * `PermissionRequest` instance that is attached to this one. If `instance` has already been * added, this method does nothing. */ public void create( @NonNull PermissionRequest instance, @NonNull String[] resources, @NonNull PermissionRequestFlutterApi.Reply<Void> callback) { if (!instanceManager.containsInstance(instance)) { api.create( instanceManager.addHostCreatedInstance(instance), Arrays.asList(resources), callback); } } /** * Sets the Flutter API used to send messages to Dart. * * <p>This is only visible for testing. */ @VisibleForTesting void setApi(@NonNull PermissionRequestFlutterApi api) { this.api = api; } }
packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/PermissionRequestFlutterApiImpl.java/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/PermissionRequestFlutterApiImpl.java", "repo_id": "packages", "token_count": 695 }
1,023
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:html' as html; import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import 'package:webview_flutter_web_example/legacy/web_view.dart'; void main() async { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); const String primaryPage = 'first.txt'; const String secondaryPage = 'second.txt'; final HttpServer server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); unawaited(server.forEach((HttpRequest request) { if (request.uri.path == '/$primaryPage') { request.response.writeln('Hello, world.'); } if (request.uri.path == '/$secondaryPage') { request.response.writeln('Another page.'); } else { fail('unexpected request: ${request.method} ${request.uri}'); } request.response.close(); })); final String prefixUrl = 'http://localhost:${server.port}'; final String primaryUrl = '$prefixUrl/$primaryPage'; final String secondaryUrl = '$prefixUrl/$secondaryPage'; testWidgets('initialUrl', (WidgetTester tester) async { final Completer<WebViewController> controllerCompleter = Completer<WebViewController>(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WebView( key: GlobalKey(), initialUrl: primaryUrl, onWebViewCreated: (WebViewController controller) { controllerCompleter.complete(controller); }, ), ), ); await controllerCompleter.future; // Assert an iframe has been rendered to the DOM with the correct src attribute. final html.IFrameElement? element = html.document.querySelector('iframe') as html.IFrameElement?; expect(element, isNotNull); expect(element!.src, primaryUrl); }); testWidgets('loadUrl', (WidgetTester tester) async { final Completer<WebViewController> controllerCompleter = Completer<WebViewController>(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WebView( key: GlobalKey(), initialUrl: primaryUrl, onWebViewCreated: (WebViewController controller) { controllerCompleter.complete(controller); }, ), ), ); final WebViewController controller = await controllerCompleter.future; await controller.loadUrl(secondaryUrl); // Assert an iframe has been rendered to the DOM with the correct src attribute. final html.IFrameElement? element = html.document.querySelector('iframe') as html.IFrameElement?; expect(element, isNotNull); expect(element!.src, secondaryUrl); }); }
packages/packages/webview_flutter/webview_flutter_web/example/integration_test/legacy/webview_flutter_test.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_web/example/integration_test/legacy/webview_flutter_test.dart", "repo_id": "packages", "token_count": 1075 }
1,024
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter_web_plugins/flutter_web_plugins.dart'; import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart'; import 'web_webview_controller.dart'; /// An implementation of [WebViewPlatform] using Flutter for Web API. class WebWebViewPlatform extends WebViewPlatform { @override PlatformWebViewController createPlatformWebViewController( PlatformWebViewControllerCreationParams params, ) { return WebWebViewController(params); } @override PlatformWebViewWidget createPlatformWebViewWidget( PlatformWebViewWidgetCreationParams params, ) { return WebWebViewWidget(params); } /// Gets called when the plugin is registered. static void registerWith(Registrar registrar) { WebViewPlatform.instance = WebWebViewPlatform(); } }
packages/packages/webview_flutter/webview_flutter_web/lib/src/web_webview_platform.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_web/lib/src/web_webview_platform.dart", "repo_id": "packages", "token_count": 280 }
1,025
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "FWFScrollViewHostApi.h" #import "FWFScrollViewDelegateHostApi.h" #import "FWFWebViewHostApi.h" @interface FWFScrollViewHostApiImpl () // BinaryMessenger must be weak to prevent a circular reference with the host API it // references. @property(nonatomic, weak) id<FlutterBinaryMessenger> binaryMessenger; // InstanceManager must be weak to prevent a circular reference with the object it stores. @property(nonatomic, weak) FWFInstanceManager *instanceManager; @end @implementation FWFScrollViewHostApiImpl - (instancetype)initWithInstanceManager:(FWFInstanceManager *)instanceManager { self = [self init]; if (self) { _instanceManager = instanceManager; } return self; } - (UIScrollView *)scrollViewForIdentifier:(NSInteger)identifier { return (UIScrollView *)[self.instanceManager instanceForIdentifier:identifier]; } - (void)createFromWebViewWithIdentifier:(NSInteger)identifier webViewIdentifier:(NSInteger)webViewIdentifier error:(FlutterError *_Nullable __autoreleasing *_Nonnull)error { WKWebView *webView = (WKWebView *)[self.instanceManager instanceForIdentifier:webViewIdentifier]; [self.instanceManager addDartCreatedInstance:webView.scrollView withIdentifier:identifier]; } - (NSArray<NSNumber *> *) contentOffsetForScrollViewWithIdentifier:(NSInteger)identifier error:(FlutterError *_Nullable *_Nonnull)error { CGPoint point = [[self scrollViewForIdentifier:identifier] contentOffset]; return @[ @(point.x), @(point.y) ]; } - (void)scrollByForScrollViewWithIdentifier:(NSInteger)identifier x:(double)x y:(double)y error:(FlutterError *_Nullable *_Nonnull)error { UIScrollView *scrollView = [self scrollViewForIdentifier:identifier]; CGPoint contentOffset = scrollView.contentOffset; [scrollView setContentOffset:CGPointMake(contentOffset.x + x, contentOffset.y + y)]; } - (void)setContentOffsetForScrollViewWithIdentifier:(NSInteger)identifier toX:(double)x y:(double)y error:(FlutterError *_Nullable *_Nonnull)error { [[self scrollViewForIdentifier:identifier] setContentOffset:CGPointMake(x, y)]; } - (void)setDelegateForScrollViewWithIdentifier:(NSInteger)identifier uiScrollViewDelegateIdentifier:(nullable NSNumber *)uiScrollViewDelegateIdentifier error:(FlutterError *_Nullable *_Nonnull)error { [[self scrollViewForIdentifier:identifier] setDelegate:uiScrollViewDelegateIdentifier ? (FWFScrollViewDelegate *)[self.instanceManager instanceForIdentifier:uiScrollViewDelegateIdentifier.longValue] : nil]; } @end
packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFScrollViewHostApi.m/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFScrollViewHostApi.m", "repo_id": "packages", "token_count": 1298 }
1,026
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "FWFWebViewConfigurationHostApi.h" #import "FWFDataConverters.h" #import "FWFWebViewConfigurationHostApi.h" @interface FWFWebViewConfigurationFlutterApiImpl () // InstanceManager must be weak to prevent a circular reference with the object it stores. @property(nonatomic, weak) FWFInstanceManager *instanceManager; @end @implementation FWFWebViewConfigurationFlutterApiImpl - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger instanceManager:(FWFInstanceManager *)instanceManager { self = [self initWithBinaryMessenger:binaryMessenger]; if (self) { _instanceManager = instanceManager; } return self; } - (void)createWithConfiguration:(WKWebViewConfiguration *)configuration completion:(void (^)(FlutterError *_Nullable))completion { long identifier = [self.instanceManager addHostCreatedInstance:configuration]; [self createWithIdentifier:identifier completion:completion]; } @end @implementation FWFWebViewConfiguration - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger instanceManager:(FWFInstanceManager *)instanceManager { self = [self init]; if (self) { _objectApi = [[FWFObjectFlutterApiImpl alloc] initWithBinaryMessenger:binaryMessenger instanceManager:instanceManager]; } return self; } - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey, id> *)change context:(void *)context { [self.objectApi observeValueForObject:self keyPath:keyPath object:object change:change completion:^(FlutterError *error) { NSAssert(!error, @"%@", error); }]; } @end @interface FWFWebViewConfigurationHostApiImpl () // BinaryMessenger must be weak to prevent a circular reference with the host API it // references. @property(nonatomic, weak) id<FlutterBinaryMessenger> binaryMessenger; // InstanceManager must be weak to prevent a circular reference with the object it stores. @property(nonatomic, weak) FWFInstanceManager *instanceManager; @end @implementation FWFWebViewConfigurationHostApiImpl - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger instanceManager:(FWFInstanceManager *)instanceManager { self = [self init]; if (self) { _binaryMessenger = binaryMessenger; _instanceManager = instanceManager; } return self; } - (WKWebViewConfiguration *)webViewConfigurationForIdentifier:(NSInteger)identifier { return (WKWebViewConfiguration *)[self.instanceManager instanceForIdentifier:identifier]; } - (void)createWithIdentifier:(NSInteger)identifier error:(FlutterError *_Nullable *_Nonnull)error { FWFWebViewConfiguration *webViewConfiguration = [[FWFWebViewConfiguration alloc] initWithBinaryMessenger:self.binaryMessenger instanceManager:self.instanceManager]; [self.instanceManager addDartCreatedInstance:webViewConfiguration withIdentifier:identifier]; } - (void)createFromWebViewWithIdentifier:(NSInteger)identifier webViewIdentifier:(NSInteger)webViewIdentifier error:(FlutterError *_Nullable __autoreleasing *_Nonnull)error { WKWebView *webView = (WKWebView *)[self.instanceManager instanceForIdentifier:webViewIdentifier]; [self.instanceManager addDartCreatedInstance:webView.configuration withIdentifier:identifier]; } - (void)setAllowsInlineMediaPlaybackForConfigurationWithIdentifier:(NSInteger)identifier isAllowed:(BOOL)allow error: (FlutterError *_Nullable *_Nonnull) error { [[self webViewConfigurationForIdentifier:identifier] setAllowsInlineMediaPlayback:allow]; } - (void)setLimitsNavigationsToAppBoundDomainsForConfigurationWithIdentifier:(NSInteger)identifier isLimited:(BOOL)limit error:(FlutterError *_Nullable *_Nonnull)error { if (@available(iOS 14, *)) { [[self webViewConfigurationForIdentifier:identifier] setLimitsNavigationsToAppBoundDomains:limit]; } else { *error = [FlutterError errorWithCode:@"FWFUnsupportedVersionError" message:@"setLimitsNavigationsToAppBoundDomains is only supported on versions 14+." details:nil]; } } - (void) setMediaTypesRequiresUserActionForConfigurationWithIdentifier:(NSInteger)identifier forTypes: (nonnull NSArray< FWFWKAudiovisualMediaTypeEnumData *> *)types error: (FlutterError *_Nullable *_Nonnull) error { NSAssert(types.count, @"Types must not be empty."); WKWebViewConfiguration *configuration = (WKWebViewConfiguration *)[self webViewConfigurationForIdentifier:identifier]; WKAudiovisualMediaTypes typesInt = 0; for (FWFWKAudiovisualMediaTypeEnumData *data in types) { typesInt |= FWFNativeWKAudiovisualMediaTypeFromEnumData(data); } [configuration setMediaTypesRequiringUserActionForPlayback:typesInt]; } @end
packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFWebViewConfigurationHostApi.m/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFWebViewConfigurationHostApi.m", "repo_id": "packages", "token_count": 2892 }
1,027
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io' as io; import 'package:args/command_runner.dart'; import 'package:file/file.dart'; import 'package:file/local.dart'; import 'analyze_command.dart'; import 'build_examples_command.dart'; import 'common/core.dart'; import 'create_all_packages_app_command.dart'; import 'custom_test_command.dart'; import 'dart_test_command.dart'; import 'dependabot_check_command.dart'; import 'drive_examples_command.dart'; import 'federation_safety_check_command.dart'; import 'fetch_deps_command.dart'; import 'firebase_test_lab_command.dart'; import 'fix_command.dart'; import 'format_command.dart'; import 'gradle_check_command.dart'; import 'license_check_command.dart'; import 'lint_android_command.dart'; import 'list_command.dart'; import 'make_deps_path_based_command.dart'; import 'native_test_command.dart'; import 'podspec_check_command.dart'; import 'publish_check_command.dart'; import 'publish_command.dart'; import 'pubspec_check_command.dart'; import 'readme_check_command.dart'; import 'remove_dev_dependencies_command.dart'; import 'repo_package_info_check_command.dart'; import 'update_dependency_command.dart'; import 'update_excerpts_command.dart'; import 'update_min_sdk_command.dart'; import 'update_release_info_command.dart'; import 'version_check_command.dart'; import 'xcode_analyze_command.dart'; void main(List<String> args) { const FileSystem fileSystem = LocalFileSystem(); final Directory scriptDir = fileSystem.file(io.Platform.script.toFilePath()).parent; // Support running either via directly invoking main.dart, or the wrapper in // bin/. final Directory toolsDir = scriptDir.basename == 'bin' ? scriptDir.parent : scriptDir.parent.parent; final Directory root = toolsDir.parent.parent; final Directory packagesDir = root.childDirectory('packages'); if (!packagesDir.existsSync()) { print('Error: Cannot find a "packages" sub-directory'); io.exit(1); } final CommandRunner<void> commandRunner = CommandRunner<void>( 'dart pub global run flutter_plugin_tools', 'Productivity utils for hosting multiple plugins within one repository.') ..addCommand(AnalyzeCommand(packagesDir)) ..addCommand(BuildExamplesCommand(packagesDir)) ..addCommand(CreateAllPackagesAppCommand(packagesDir)) ..addCommand(CustomTestCommand(packagesDir)) ..addCommand(DependabotCheckCommand(packagesDir)) ..addCommand(DriveExamplesCommand(packagesDir)) ..addCommand(FederationSafetyCheckCommand(packagesDir)) ..addCommand(FetchDepsCommand(packagesDir)) ..addCommand(FirebaseTestLabCommand(packagesDir)) ..addCommand(FixCommand(packagesDir)) ..addCommand(FormatCommand(packagesDir)) ..addCommand(GradleCheckCommand(packagesDir)) ..addCommand(LicenseCheckCommand(packagesDir)) ..addCommand(LintAndroidCommand(packagesDir)) ..addCommand(PodspecCheckCommand(packagesDir)) ..addCommand(ListCommand(packagesDir)) ..addCommand(NativeTestCommand(packagesDir)) ..addCommand(MakeDepsPathBasedCommand(packagesDir)) ..addCommand(PublishCheckCommand(packagesDir)) ..addCommand(PublishCommand(packagesDir)) ..addCommand(PubspecCheckCommand(packagesDir)) ..addCommand(ReadmeCheckCommand(packagesDir)) ..addCommand(RemoveDevDependenciesCommand(packagesDir)) ..addCommand(RepoPackageInfoCheckCommand(packagesDir)) ..addCommand(DartTestCommand(packagesDir)) ..addCommand(UpdateDependencyCommand(packagesDir)) ..addCommand(UpdateExcerptsCommand(packagesDir)) ..addCommand(UpdateMinSdkCommand(packagesDir)) ..addCommand(UpdateReleaseInfoCommand(packagesDir)) ..addCommand(VersionCheckCommand(packagesDir)) ..addCommand(XcodeAnalyzeCommand(packagesDir)); commandRunner.run(args).catchError((Object e) { final ToolExit toolExit = e as ToolExit; int exitCode = toolExit.exitCode; // This should never happen; this check is here to guarantee that a ToolExit // never accidentally has code 0 thus causing CI to pass. if (exitCode == 0) { assert(false); exitCode = 255; } io.exit(exitCode); }, test: (Object e) => e is ToolExit); }
packages/script/tool/lib/src/main.dart/0
{ "file_path": "packages/script/tool/lib/src/main.dart", "repo_id": "packages", "token_count": 1397 }
1,028
name: flutter_plugin_tools description: Productivity and CI utils for flutter/packages repository: https://github.com/flutter/packages/tree/main/script/tool version: 1.0.0 publish_to: none dependencies: args: ^2.1.0 async: ^2.6.1 collection: ^1.15.0 colorize: ^3.0.0 file: ^6.1.0 # Pin git to 2.0.x until dart >=2.18 is legacy git: '>=2.0.0 <2.1.0' http: '>=0.13.3 <2.0.0' http_multi_server: ^3.0.1 meta: ^1.3.0 path: ^1.8.0 platform: ^3.0.0 pub_semver: ^2.0.0 pubspec_parse: ^1.0.0 quiver: ^3.0.1 test: ^1.17.3 uuid: ^3.0.4 yaml: ^3.1.0 yaml_edit: ^2.0.2 dev_dependencies: build_runner: ^2.0.3 matcher: ^0.12.10 mockito: '>=5.3.2 <=5.5.0' environment: sdk: '>=3.0.0 <4.0.0'
packages/script/tool/pubspec.yaml/0
{ "file_path": "packages/script/tool/pubspec.yaml", "repo_id": "packages", "token_count": 374 }
1,029
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io' as io; import 'package:args/command_runner.dart'; import 'package:file/file.dart'; import 'package:file/memory.dart'; import 'package:flutter_plugin_tools/src/common/core.dart'; import 'package:flutter_plugin_tools/src/create_all_packages_app_command.dart'; import 'package:platform/platform.dart'; import 'package:pubspec_parse/pubspec_parse.dart'; import 'package:test/test.dart'; import 'mocks.dart'; import 'util.dart'; void main() { late CommandRunner<void> runner; late CreateAllPackagesAppCommand command; late Platform mockPlatform; late FileSystem fileSystem; late Directory testRoot; late Directory packagesDir; late RecordingProcessRunner processRunner; setUp(() { mockPlatform = MockPlatform(isMacOS: true); fileSystem = MemoryFileSystem(); testRoot = fileSystem.systemTempDirectory.createTempSync(); packagesDir = testRoot.childDirectory('packages'); processRunner = RecordingProcessRunner(); command = CreateAllPackagesAppCommand( packagesDir, processRunner: processRunner, platform: mockPlatform, ); runner = CommandRunner<void>( 'create_all_test', 'Test for $CreateAllPackagesAppCommand'); runner.addCommand(command); }); /// Simulates enough of `flutter create`s output to allow the modifications /// made by the command to work. void writeFakeFlutterCreateOutput( Directory outputDirectory, { String dartSdkConstraint = '>=3.0.0 <4.0.0', String? appBuildGradleDependencies, bool androidOnly = false, }) { final RepositoryPackage package = RepositoryPackage( outputDirectory.childDirectory(allPackagesProjectName)); // Android final String dependencies = appBuildGradleDependencies ?? r''' dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" } '''; package .platformDirectory(FlutterPlatform.android) .childDirectory('app') .childFile('build.gradle') ..createSync(recursive: true) ..writeAsStringSync(''' android { namespace 'dev.flutter.packages.foo.example' compileSdk flutter.compileSdkVersion sourceSets { main.java.srcDirs += 'src/main/kotlin' } defaultConfig { applicationId "dev.flutter.packages.foo.example" minSdkVersion flutter.minSdkVersion targetSdkVersion 32 } } $dependencies '''); if (androidOnly) { return; } // Non-platform-specific package.pubspecFile ..createSync(recursive: true) ..writeAsStringSync(''' name: $allPackagesProjectName description: Flutter app containing all 1st party plugins. publish_to: none version: 1.0.0 environment: sdk: '$dartSdkConstraint' dependencies: flutter: sdk: flutter dev_dependencies: flutter_test: sdk: flutter ### '''); // macOS final Directory macOS = package.platformDirectory(FlutterPlatform.macos); macOS.childDirectory('Runner.xcodeproj').childFile('project.pbxproj') ..createSync(recursive: true) ..writeAsStringSync(''' 97C147041CF9000F007C117D /* Release */ = { isa = XCBuildConfiguration; buildSettings = { GCC_WARN_UNUSED_VARIABLE = YES; MACOSX_DEPLOYMENT_TARGET = 10.14; }; name = Release; }; '''); macOS.childFile('Podfile') ..createSync(recursive: true) ..writeAsStringSync(''' # platform :osx, '10.14' ENV['COCOAPODS_DISABLE_STATS'] = 'true' project 'Runner', { 'Debug' => :debug, 'Profile' => :release, 'Release' => :release, } '''); } group('non-macOS host', () { setUp(() { mockPlatform = MockPlatform(isLinux: true); command = CreateAllPackagesAppCommand( packagesDir, processRunner: processRunner, platform: mockPlatform, ); runner = CommandRunner<void>( 'create_all_test', 'Test for $CreateAllPackagesAppCommand'); runner.addCommand(command); }); test('calls "flutter create"', () async { writeFakeFlutterCreateOutput(testRoot); createFakePlugin('plugina', packagesDir); await runCapturingPrint(runner, <String>['create-all-packages-app']); expect( processRunner.recordedCalls, contains(ProcessCall( getFlutterCommand(mockPlatform), <String>[ 'create', '--template=app', '--project-name=$allPackagesProjectName', testRoot.childDirectory(allPackagesProjectName).path, ], null))); }); test('pubspec includes all plugins', () async { writeFakeFlutterCreateOutput(testRoot); createFakePlugin('plugina', packagesDir); createFakePlugin('pluginb', packagesDir); createFakePlugin('pluginc', packagesDir); await runCapturingPrint(runner, <String>['create-all-packages-app']); final List<String> pubspec = command.app.pubspecFile.readAsLinesSync(); expect( pubspec, containsAll(<Matcher>[ contains(RegExp('path: .*/packages/plugina')), contains(RegExp('path: .*/packages/pluginb')), contains(RegExp('path: .*/packages/pluginc')), ])); }); test('pubspec has overrides for all plugins', () async { writeFakeFlutterCreateOutput(testRoot); createFakePlugin('plugina', packagesDir); createFakePlugin('pluginb', packagesDir); createFakePlugin('pluginc', packagesDir); await runCapturingPrint(runner, <String>['create-all-packages-app']); final List<String> pubspec = command.app.pubspecFile.readAsLinesSync(); expect( pubspec, containsAllInOrder(<Matcher>[ contains('dependency_overrides:'), contains(RegExp('path: .*/packages/plugina')), contains(RegExp('path: .*/packages/pluginb')), contains(RegExp('path: .*/packages/pluginc')), ])); }); test( 'pubspec special-cases camera_android to remove it from deps but not overrides', () async { writeFakeFlutterCreateOutput(testRoot); final Directory cameraDir = packagesDir.childDirectory('camera'); createFakePlugin('camera', cameraDir); createFakePlugin('camera_android', cameraDir); createFakePlugin('camera_android_camerax', cameraDir); await runCapturingPrint(runner, <String>['create-all-packages-app']); final Pubspec pubspec = command.app.parsePubspec(); final Dependency? cameraDependency = pubspec.dependencies['camera']; final Dependency? cameraAndroidDependency = pubspec.dependencies['camera_android']; final Dependency? cameraCameraXDependency = pubspec.dependencies['camera_android_camerax']; expect(cameraDependency, isA<PathDependency>()); expect((cameraDependency! as PathDependency).path, endsWith('/packages/camera/camera')); expect(cameraCameraXDependency, isA<PathDependency>()); expect((cameraCameraXDependency! as PathDependency).path, endsWith('/packages/camera/camera_android_camerax')); expect(cameraAndroidDependency, null); final Dependency? cameraAndroidOverride = pubspec.dependencyOverrides['camera_android']; expect(cameraAndroidOverride, isA<PathDependency>()); expect((cameraAndroidOverride! as PathDependency).path, endsWith('/packages/camera/camera_android')); }); test('legacy files are copied when requested', () async { writeFakeFlutterCreateOutput(testRoot); createFakePlugin('plugina', packagesDir); // Make a fake legacy source with all the necessary files, replacing one // of them. final Directory legacyDir = testRoot.childDirectory('legacy'); final RepositoryPackage legacySource = RepositoryPackage(legacyDir.childDirectory(allPackagesProjectName)); writeFakeFlutterCreateOutput(legacyDir, androidOnly: true); const String legacyAppBuildGradleContents = 'Fake legacy content'; final File legacyGradleFile = legacySource .platformDirectory(FlutterPlatform.android) .childFile('build.gradle'); legacyGradleFile.writeAsStringSync(legacyAppBuildGradleContents); await runCapturingPrint(runner, <String>[ 'create-all-packages-app', '--legacy-source=${legacySource.path}', ]); final File buildGradle = command.app .platformDirectory(FlutterPlatform.android) .childFile('build.gradle'); expect(buildGradle.readAsStringSync(), legacyAppBuildGradleContents); }); test('legacy directory replaces, rather than overlaying', () async { writeFakeFlutterCreateOutput(testRoot); createFakePlugin('plugina', packagesDir); final File extraFile = RepositoryPackage(testRoot.childDirectory(allPackagesProjectName)) .platformDirectory(FlutterPlatform.android) .childFile('extra_file'); extraFile.createSync(recursive: true); // Make a fake legacy source with all the necessary files, but not // including the extra file. final Directory legacyDir = testRoot.childDirectory('legacy'); final RepositoryPackage legacySource = RepositoryPackage(legacyDir.childDirectory(allPackagesProjectName)); writeFakeFlutterCreateOutput(legacyDir, androidOnly: true); await runCapturingPrint(runner, <String>[ 'create-all-packages-app', '--legacy-source=${legacySource.path}', ]); expect(extraFile.existsSync(), false); }); test('legacy files are modified as needed by the tool', () async { writeFakeFlutterCreateOutput(testRoot); createFakePlugin('plugina', packagesDir); // Make a fake legacy source with all the necessary files, replacing one // of them. final Directory legacyDir = testRoot.childDirectory('legacy'); final RepositoryPackage legacySource = RepositoryPackage(legacyDir.childDirectory(allPackagesProjectName)); writeFakeFlutterCreateOutput(legacyDir, androidOnly: true); const String legacyAppBuildGradleContents = ''' # This is the legacy file android { compileSdk flutter.compileSdkVersion defaultConfig { minSdkVersion flutter.minSdkVersion } } '''; final File legacyGradleFile = legacySource .platformDirectory(FlutterPlatform.android) .childDirectory('app') .childFile('build.gradle'); legacyGradleFile.writeAsStringSync(legacyAppBuildGradleContents); await runCapturingPrint(runner, <String>[ 'create-all-packages-app', '--legacy-source=${legacySource.path}', ]); final List<String> buildGradle = command.app .platformDirectory(FlutterPlatform.android) .childDirectory('app') .childFile('build.gradle') .readAsLinesSync(); expect( buildGradle, containsAll(<Matcher>[ contains('This is the legacy file'), contains('minSdkVersion 21'), contains('compileSdk 34'), ])); }); test('pubspec preserves existing Dart SDK version', () async { const String existingSdkConstraint = '>=1.0.0 <99.0.0'; writeFakeFlutterCreateOutput(testRoot, dartSdkConstraint: existingSdkConstraint); createFakePlugin('plugina', packagesDir); await runCapturingPrint(runner, <String>['create-all-packages-app']); final Pubspec generatedPubspec = command.app.parsePubspec(); const String dartSdkKey = 'sdk'; expect(generatedPubspec.environment?[dartSdkKey].toString(), existingSdkConstraint); }); test('Android app gradle is modified as expected', () async { writeFakeFlutterCreateOutput(testRoot); createFakePlugin('plugina', packagesDir); await runCapturingPrint(runner, <String>['create-all-packages-app']); final List<String> buildGradle = command.app .platformDirectory(FlutterPlatform.android) .childDirectory('app') .childFile('build.gradle') .readAsLinesSync(); expect( buildGradle, containsAll(<Matcher>[ contains('minSdkVersion 21'), contains('compileSdk 34'), contains('multiDexEnabled true'), contains('androidx.lifecycle:lifecycle-runtime'), ])); }); // The template's app/build.gradle does not always have a dependencies // section; ensure that the dependency is added if there is not one. test('Android lifecyle dependency is added with no dependencies', () async { writeFakeFlutterCreateOutput(testRoot, appBuildGradleDependencies: ''); createFakePlugin('plugina', packagesDir); await runCapturingPrint(runner, <String>['create-all-packages-app']); final List<String> buildGradle = command.app .platformDirectory(FlutterPlatform.android) .childDirectory('app') .childFile('build.gradle') .readAsLinesSync(); expect( buildGradle, containsAllInOrder(<Matcher>[ equals('dependencies {'), contains('androidx.lifecycle:lifecycle-runtime'), equals('}'), ])); }); // Some versions of the template's app/build.gradle has an empty // dependencies section; ensure that the dependency is added in that case. test('Android lifecyle dependency is added with empty dependencies', () async { writeFakeFlutterCreateOutput(testRoot, appBuildGradleDependencies: 'dependencies {}'); createFakePlugin('plugina', packagesDir); await runCapturingPrint(runner, <String>['create-all-packages-app']); final List<String> buildGradle = command.app .platformDirectory(FlutterPlatform.android) .childDirectory('app') .childFile('build.gradle') .readAsLinesSync(); expect( buildGradle, containsAllInOrder(<Matcher>[ equals('dependencies {'), contains('androidx.lifecycle:lifecycle-runtime'), equals('}'), ])); }); test('macOS deployment target is modified in pbxproj', () async { writeFakeFlutterCreateOutput(testRoot); createFakePlugin('plugina', packagesDir); await runCapturingPrint(runner, <String>['create-all-packages-app']); final List<String> pbxproj = command.app .platformDirectory(FlutterPlatform.macos) .childDirectory('Runner.xcodeproj') .childFile('project.pbxproj') .readAsLinesSync(); expect( pbxproj, everyElement((String line) => !line.contains('MACOSX_DEPLOYMENT_TARGET') || line.contains('10.15'))); }); test('calls flutter pub get', () async { writeFakeFlutterCreateOutput(testRoot); createFakePlugin('plugina', packagesDir); await runCapturingPrint(runner, <String>['create-all-packages-app']); expect( processRunner.recordedCalls, contains(ProcessCall( getFlutterCommand(mockPlatform), const <String>['pub', 'get'], testRoot.childDirectory(allPackagesProjectName).path))); }); test('fails if flutter create fails', () async { writeFakeFlutterCreateOutput(testRoot); createFakePlugin('plugina', packagesDir); processRunner .mockProcessesForExecutable[getFlutterCommand(mockPlatform)] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(exitCode: 1), <String>['create']) ]; Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['create-all-packages-app'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('Failed to `flutter create`'), ])); }); test('fails if flutter pub get fails', () async { writeFakeFlutterCreateOutput(testRoot); createFakePlugin('plugina', packagesDir); processRunner .mockProcessesForExecutable[getFlutterCommand(mockPlatform)] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(), <String>['create']), FakeProcessInfo(MockProcess(exitCode: 1), <String>['pub', 'get']) ]; Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['create-all-packages-app'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains( "Failed to generate native build files via 'flutter pub get'"), ])); }, // See comment about Windows in create_all_packages_app_command.dart skip: io.Platform.isWindows); test('handles --output-dir', () async { final Directory customOutputDir = fileSystem.systemTempDirectory.createTempSync(); writeFakeFlutterCreateOutput(customOutputDir); createFakePlugin('plugina', packagesDir); await runCapturingPrint(runner, <String>[ 'create-all-packages-app', '--output-dir=${customOutputDir.path}' ]); expect(command.app.path, customOutputDir.childDirectory(allPackagesProjectName).path); }); test('logs exclusions', () async { writeFakeFlutterCreateOutput(testRoot); createFakePlugin('plugina', packagesDir); createFakePlugin('pluginb', packagesDir); createFakePlugin('pluginc', packagesDir); final List<String> output = await runCapturingPrint(runner, <String>['create-all-packages-app', '--exclude=pluginb,pluginc']); expect( output, containsAllInOrder(<String>[ 'Exluding the following plugins from the combined build:', ' pluginb', ' pluginc', ])); }); }); group('macOS host', () { setUp(() { command = CreateAllPackagesAppCommand( packagesDir, processRunner: processRunner, platform: MockPlatform(isMacOS: true), ); runner = CommandRunner<void>( 'create_all_test', 'Test for $CreateAllPackagesAppCommand'); runner.addCommand(command); }); test('macOS deployment target is modified in Podfile', () async { writeFakeFlutterCreateOutput(testRoot); createFakePlugin('plugina', packagesDir); final File podfileFile = RepositoryPackage( command.packagesDir.parent.childDirectory(allPackagesProjectName)) .platformDirectory(FlutterPlatform.macos) .childFile('Podfile'); podfileFile.createSync(recursive: true); podfileFile.writeAsStringSync(""" platform :osx, '10.11' # some other line """); await runCapturingPrint(runner, <String>['create-all-packages-app']); final List<String> podfile = command.app .platformDirectory(FlutterPlatform.macos) .childFile('Podfile') .readAsLinesSync(); expect( podfile, everyElement((String line) => !line.contains('platform :osx') || line.contains("'10.15'"))); }, // Podfile is only generated (and thus only edited) on macOS. skip: !io.Platform.isMacOS); }); }
packages/script/tool/test/create_all_packages_app_command_test.dart/0
{ "file_path": "packages/script/tool/test/create_all_packages_app_command_test.dart", "repo_id": "packages", "token_count": 7731 }
1,030
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'dart:ffi'; import 'package:args/command_runner.dart'; import 'package:file/file.dart'; import 'package:file/memory.dart'; import 'package:flutter_plugin_tools/src/common/cmake.dart'; import 'package:flutter_plugin_tools/src/common/core.dart'; import 'package:flutter_plugin_tools/src/common/file_utils.dart'; import 'package:flutter_plugin_tools/src/common/plugin_utils.dart'; import 'package:flutter_plugin_tools/src/native_test_command.dart'; import 'package:path/path.dart' as p; import 'package:platform/platform.dart'; import 'package:test/test.dart'; import 'mocks.dart'; import 'util.dart'; const String _androidIntegrationTestFilter = '-Pandroid.testInstrumentationRunnerArguments.' 'notAnnotation=io.flutter.plugins.DartIntegrationTest'; final Map<String, dynamic> _kDeviceListMap = <String, dynamic>{ 'runtimes': <Map<String, dynamic>>[ <String, dynamic>{ 'bundlePath': '/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 13.4.simruntime', 'buildversion': '17L255', 'runtimeRoot': '/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 13.4.simruntime/Contents/Resources/RuntimeRoot', 'identifier': 'com.apple.CoreSimulator.SimRuntime.iOS-13-4', 'version': '13.4', 'isAvailable': true, 'name': 'iOS 13.4' }, ], 'devices': <String, dynamic>{ 'com.apple.CoreSimulator.SimRuntime.iOS-13-4': <Map<String, dynamic>>[ <String, dynamic>{ 'dataPath': '/Users/xxx/Library/Developer/CoreSimulator/Devices/1E76A0FD-38AC-4537-A989-EA639D7D012A/data', 'logPath': '/Users/xxx/Library/Logs/CoreSimulator/1E76A0FD-38AC-4537-A989-EA639D7D012A', 'udid': '1E76A0FD-38AC-4537-A989-EA639D7D012A', 'isAvailable': true, 'deviceTypeIdentifier': 'com.apple.CoreSimulator.SimDeviceType.iPhone-8-Plus', 'state': 'Shutdown', 'name': 'iPhone 8 Plus' } ] } }; const String _fakeCmakeCommand = 'path/to/cmake'; const String _archDirX64 = 'x64'; const String _archDirArm64 = 'arm64'; void _createFakeCMakeCache( RepositoryPackage plugin, Platform platform, String? archDir) { final CMakeProject project = CMakeProject(getExampleDir(plugin), platform: platform, buildMode: 'Release', arch: archDir); final File cache = project.buildDirectory.childFile('CMakeCache.txt'); cache.createSync(recursive: true); cache.writeAsStringSync('CMAKE_COMMAND:INTERNAL=$_fakeCmakeCommand'); } // TODO(stuartmorgan): Rework these tests to use a mock Xcode instead of // doing all the process mocking and validation. void main() { const String kDestination = '--ios-destination'; group('test native_test_command on Posix', () { late FileSystem fileSystem; late MockPlatform mockPlatform; late Directory packagesDir; late CommandRunner<void> runner; late RecordingProcessRunner processRunner; setUp(() { fileSystem = MemoryFileSystem(); // iOS and macOS tests expect macOS, Linux tests expect Linux; nothing // needs to distinguish between Linux and macOS, so set both to true to // allow them to share a setup group. mockPlatform = MockPlatform(isMacOS: true, isLinux: true); packagesDir = createPackagesDirectory(fileSystem: fileSystem); processRunner = RecordingProcessRunner(); final NativeTestCommand command = NativeTestCommand(packagesDir, processRunner: processRunner, platform: mockPlatform); runner = CommandRunner<void>( 'native_test_command', 'Test for native_test_command'); runner.addCommand(command); }); // Returns a FakeProcessInfo to provide for "xcrun xcodebuild -list" for a // project that contains [targets]. FakeProcessInfo getMockXcodebuildListProcess(List<String> targets) { final Map<String, dynamic> projects = <String, dynamic>{ 'project': <String, dynamic>{ 'targets': targets, } }; return FakeProcessInfo(MockProcess(stdout: jsonEncode(projects)), <String>['xcodebuild', '-list']); } // Returns the ProcessCall to expect for checking the targets present in // the [package]'s [platform]/Runner.xcodeproj. ProcessCall getTargetCheckCall(Directory package, String platform) { return ProcessCall( 'xcrun', <String>[ 'xcodebuild', '-list', '-json', '-project', package .childDirectory(platform) .childDirectory('Runner.xcodeproj') .path, ], null); } // Returns the ProcessCall to expect for running the tests in the // workspace [platform]/Runner.xcworkspace, with the given extra flags. ProcessCall getRunTestCall( Directory package, String platform, { String? destination, List<String> extraFlags = const <String>[], }) { return ProcessCall( 'xcrun', <String>[ 'xcodebuild', 'test', '-workspace', '$platform/Runner.xcworkspace', '-scheme', 'Runner', '-configuration', 'Debug', if (destination != null) ...<String>['-destination', destination], ...extraFlags, 'GCC_TREAT_WARNINGS_AS_ERRORS=YES', ], package.path); } // Returns the ProcessCall to expect for build the Linux unit tests for the // given plugin. ProcessCall getLinuxBuildCall(RepositoryPackage plugin) { return ProcessCall( 'cmake', <String>[ '--build', getExampleDir(plugin) .childDirectory('build') .childDirectory('linux') .childDirectory('x64') .childDirectory('release') .path, '--target', 'unit_tests' ], null); } test('fails if no platforms are provided', () async { Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['native-test'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('At least one platform flag must be provided.'), ]), ); }); test('fails if all test types are disabled', () async { Error? commandError; final List<String> output = await runCapturingPrint(runner, <String>[ 'native-test', '--macos', '--no-unit', '--no-integration', ], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('At least one test type must be enabled.'), ]), ); }); test('reports skips with no tests', () async { final RepositoryPackage plugin = createFakePlugin('plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformMacOS: const PlatformDetails(PlatformSupport.inline), }); final Directory pluginExampleDirectory = getExampleDir(plugin); processRunner.mockProcessesForExecutable['xcrun'] = <FakeProcessInfo>[ getMockXcodebuildListProcess(<String>['RunnerTests', 'RunnerUITests']), // Exit code 66 from testing indicates no tests. FakeProcessInfo( MockProcess(exitCode: 66), <String>['xcodebuild', 'test']), ]; final List<String> output = await runCapturingPrint( runner, <String>['native-test', '--macos', '--no-unit']); expect( output, containsAllInOrder(<Matcher>[ contains('No tests found.'), contains('Skipped 1 package(s)'), ])); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ getTargetCheckCall(pluginExampleDirectory, 'macos'), getRunTestCall(pluginExampleDirectory, 'macos', extraFlags: <String>['-only-testing:RunnerUITests']), ])); }); group('iOS', () { test('skip if iOS is not supported', () async { createFakePlugin('plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformMacOS: const PlatformDetails(PlatformSupport.inline), }); final List<String> output = await runCapturingPrint(runner, <String>['native-test', '--ios', kDestination, 'foo_destination']); expect( output, containsAllInOrder(<Matcher>[ contains('No implementation for iOS.'), contains('SKIPPING: Nothing to test for target platform(s).'), ])); expect(processRunner.recordedCalls, orderedEquals(<ProcessCall>[])); }); test('skip if iOS is implemented in a federated package', () async { createFakePlugin('plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformIOS: const PlatformDetails(PlatformSupport.federated) }); final List<String> output = await runCapturingPrint(runner, <String>['native-test', '--ios', kDestination, 'foo_destination']); expect( output, containsAllInOrder(<Matcher>[ contains('No implementation for iOS.'), contains('SKIPPING: Nothing to test for target platform(s).'), ])); expect(processRunner.recordedCalls, orderedEquals(<ProcessCall>[])); }); test('running with correct destination', () async { final RepositoryPackage plugin = createFakePlugin('plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformIOS: const PlatformDetails(PlatformSupport.inline) }); final Directory pluginExampleDirectory = getExampleDir(plugin); processRunner.mockProcessesForExecutable['xcrun'] = <FakeProcessInfo>[ getMockXcodebuildListProcess( <String>['RunnerTests', 'RunnerUITests']), ]; final List<String> output = await runCapturingPrint(runner, <String>[ 'native-test', '--ios', kDestination, 'foo_destination', ]); expect( output, containsAllInOrder(<Matcher>[ contains('Running for plugin'), contains('Successfully ran iOS xctest for plugin/example') ])); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ getTargetCheckCall(pluginExampleDirectory, 'ios'), getRunTestCall(pluginExampleDirectory, 'ios', destination: 'foo_destination'), ])); }); test('Not specifying --ios-destination assigns an available simulator', () async { final RepositoryPackage plugin = createFakePlugin('plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformIOS: const PlatformDetails(PlatformSupport.inline) }); final Directory pluginExampleDirectory = getExampleDir(plugin); processRunner.mockProcessesForExecutable['xcrun'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(stdout: jsonEncode(_kDeviceListMap)), <String>['simctl', 'list']), getMockXcodebuildListProcess( <String>['RunnerTests', 'RunnerUITests']), ]; await runCapturingPrint(runner, <String>['native-test', '--ios']); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ const ProcessCall( 'xcrun', <String>[ 'simctl', 'list', 'devices', 'runtimes', 'available', '--json', ], null), getTargetCheckCall(pluginExampleDirectory, 'ios'), getRunTestCall(pluginExampleDirectory, 'ios', destination: 'id=1E76A0FD-38AC-4537-A989-EA639D7D012A'), ])); }); }); group('macOS', () { test('skip if macOS is not supported', () async { createFakePlugin('plugin', packagesDir); final List<String> output = await runCapturingPrint(runner, <String>['native-test', '--macos']); expect( output, containsAllInOrder(<Matcher>[ contains('No implementation for macOS.'), contains('SKIPPING: Nothing to test for target platform(s).'), ])); expect(processRunner.recordedCalls, orderedEquals(<ProcessCall>[])); }); test('skip if macOS is implemented in a federated package', () async { createFakePlugin('plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformMacOS: const PlatformDetails(PlatformSupport.federated), }); final List<String> output = await runCapturingPrint(runner, <String>['native-test', '--macos']); expect( output, containsAllInOrder(<Matcher>[ contains('No implementation for macOS.'), contains('SKIPPING: Nothing to test for target platform(s).'), ])); expect(processRunner.recordedCalls, orderedEquals(<ProcessCall>[])); }); test('runs for macOS plugin', () async { final RepositoryPackage plugin = createFakePlugin('plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformMacOS: const PlatformDetails(PlatformSupport.inline), }); final Directory pluginExampleDirectory = getExampleDir(plugin); processRunner.mockProcessesForExecutable['xcrun'] = <FakeProcessInfo>[ getMockXcodebuildListProcess( <String>['RunnerTests', 'RunnerUITests']), ]; final List<String> output = await runCapturingPrint(runner, <String>[ 'native-test', '--macos', ]); expect( output, contains( contains('Successfully ran macOS xctest for plugin/example'))); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ getTargetCheckCall(pluginExampleDirectory, 'macos'), getRunTestCall(pluginExampleDirectory, 'macos'), ])); }); }); group('Android', () { test('runs Java unit tests in Android implementation folder', () async { final RepositoryPackage plugin = createFakePlugin( 'plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.inline) }, extraFiles: <String>[ 'example/android/gradlew', 'android/src/test/example_test.java', ], ); await runCapturingPrint(runner, <String>['native-test', '--android']); final Directory androidFolder = plugin .getExamples() .first .platformDirectory(FlutterPlatform.android); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( androidFolder.childFile('gradlew').path, const <String>[ 'app:testDebugUnitTest', 'plugin:testDebugUnitTest', ], androidFolder.path, ), ]), ); }); test('runs Java unit tests in example folder', () async { final RepositoryPackage plugin = createFakePlugin( 'plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.inline) }, extraFiles: <String>[ 'example/android/gradlew', 'example/android/app/src/test/example_test.java', ], ); await runCapturingPrint(runner, <String>['native-test', '--android']); final Directory androidFolder = plugin .getExamples() .first .platformDirectory(FlutterPlatform.android); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( androidFolder.childFile('gradlew').path, const <String>[ 'app:testDebugUnitTest', 'plugin:testDebugUnitTest', ], androidFolder.path, ), ]), ); }); test('only runs plugin-level unit tests once', () async { final RepositoryPackage plugin = createFakePlugin( 'plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.inline) }, examples: <String>['example1', 'example2'], extraFiles: <String>[ 'example/example1/android/gradlew', 'example/example1/android/app/src/test/example_test.java', 'example/example2/android/gradlew', 'example/example2/android/app/src/test/example_test.java', ], ); await runCapturingPrint(runner, <String>['native-test', '--android']); final List<RepositoryPackage> examples = plugin.getExamples().toList(); final Directory androidFolder1 = examples[0].platformDirectory(FlutterPlatform.android); final Directory androidFolder2 = examples[1].platformDirectory(FlutterPlatform.android); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( androidFolder1.childFile('gradlew').path, const <String>[ 'app:testDebugUnitTest', 'plugin:testDebugUnitTest', ], androidFolder1.path, ), ProcessCall( androidFolder2.childFile('gradlew').path, const <String>[ 'app:testDebugUnitTest', ], androidFolder2.path, ), ]), ); }); test('runs Java integration tests', () async { final RepositoryPackage plugin = createFakePlugin( 'plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.inline) }, extraFiles: <String>[ 'example/android/gradlew', 'example/android/app/src/androidTest/IntegrationTest.java', ], ); await runCapturingPrint( runner, <String>['native-test', '--android', '--no-unit']); final Directory androidFolder = plugin .getExamples() .first .platformDirectory(FlutterPlatform.android); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( androidFolder.childFile('gradlew').path, const <String>[ 'app:connectedAndroidTest', _androidIntegrationTestFilter, ], androidFolder.path, ), ]), ); }); test( 'ignores Java integration test files using (or defining) DartIntegrationTest', () async { const String dartTestDriverRelativePath = 'android/app/src/androidTest/java/io/flutter/plugins/plugin/FlutterActivityTest.java'; final RepositoryPackage plugin = createFakePlugin( 'plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.inline) }, extraFiles: <String>[ 'example/android/gradlew', 'example/android/app/src/androidTest/java/io/flutter/plugins/DartIntegrationTest.java', 'example/android/app/src/androidTest/java/io/flutter/plugins/DartIntegrationTest.kt', 'example/$dartTestDriverRelativePath', ], ); final File dartTestDriverFile = childFileWithSubcomponents( plugin.getExamples().first.directory, p.posix.split(dartTestDriverRelativePath)); dartTestDriverFile.writeAsStringSync(''' import io.flutter.plugins.DartIntegrationTest; import org.junit.runner.RunWith; @DartIntegrationTest @RunWith(FlutterTestRunner.class) public class FlutterActivityTest { } '''); await runCapturingPrint( runner, <String>['native-test', '--android', '--no-unit']); // Nothing should run since those files are all // integration_test-specific. expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[]), ); }); test( 'fails for Java integration tests Using FlutterTestRunner without @DartIntegrationTest', () async { const String dartTestDriverRelativePath = 'android/app/src/androidTest/java/io/flutter/plugins/plugin/FlutterActivityTest.java'; final RepositoryPackage plugin = createFakePlugin( 'plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.inline) }, extraFiles: <String>[ 'example/android/gradlew', 'example/$dartTestDriverRelativePath', ], ); final File dartTestDriverFile = childFileWithSubcomponents( plugin.getExamples().first.directory, p.posix.split(dartTestDriverRelativePath)); dartTestDriverFile.writeAsStringSync(''' import io.flutter.plugins.DartIntegrationTest; import org.junit.runner.RunWith; @RunWith(FlutterTestRunner.class) public class FlutterActivityTest { } '''); Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['native-test', '--android', '--no-unit'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, contains( contains(misconfiguredJavaIntegrationTestErrorExplanation))); expect( output, contains(contains( 'example/android/app/src/androidTest/java/io/flutter/plugins/plugin/FlutterActivityTest.java'))); }); test('runs all tests when present', () async { final RepositoryPackage plugin = createFakePlugin( 'plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.inline) }, extraFiles: <String>[ 'android/src/test/example_test.java', 'example/android/gradlew', 'example/android/app/src/androidTest/IntegrationTest.java', ], ); await runCapturingPrint(runner, <String>['native-test', '--android']); final Directory androidFolder = plugin .getExamples() .first .platformDirectory(FlutterPlatform.android); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( androidFolder.childFile('gradlew').path, const <String>[ 'app:testDebugUnitTest', 'plugin:testDebugUnitTest', ], androidFolder.path, ), ProcessCall( androidFolder.childFile('gradlew').path, const <String>[ 'app:connectedAndroidTest', _androidIntegrationTestFilter, ], androidFolder.path, ), ]), ); }); test('honors --no-unit', () async { final RepositoryPackage plugin = createFakePlugin( 'plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.inline) }, extraFiles: <String>[ 'android/src/test/example_test.java', 'example/android/gradlew', 'example/android/app/src/androidTest/IntegrationTest.java', ], ); await runCapturingPrint( runner, <String>['native-test', '--android', '--no-unit']); final Directory androidFolder = plugin .getExamples() .first .platformDirectory(FlutterPlatform.android); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( androidFolder.childFile('gradlew').path, const <String>[ 'app:connectedAndroidTest', _androidIntegrationTestFilter, ], androidFolder.path, ), ]), ); }); test('honors --no-integration', () async { final RepositoryPackage plugin = createFakePlugin( 'plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.inline) }, extraFiles: <String>[ 'android/src/test/example_test.java', 'example/android/gradlew', 'example/android/app/src/androidTest/IntegrationTest.java', ], ); await runCapturingPrint( runner, <String>['native-test', '--android', '--no-integration']); final Directory androidFolder = plugin .getExamples() .first .platformDirectory(FlutterPlatform.android); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( androidFolder.childFile('gradlew').path, const <String>[ 'app:testDebugUnitTest', 'plugin:testDebugUnitTest', ], androidFolder.path, ), ]), ); }); test('runs a config-only build when the app needs to be built', () async { final RepositoryPackage package = createFakePlugin( 'plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.inline) }, extraFiles: <String>[ 'example/android/app/src/test/example_test.java', ], ); final RepositoryPackage example = package.getExamples().first; final Directory androidFolder = example.platformDirectory(FlutterPlatform.android); await runCapturingPrint(runner, <String>['native-test', '--android']); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( getFlutterCommand(mockPlatform), const <String>['build', 'apk', '--config-only'], example.path, ), ProcessCall( androidFolder.childFile('gradlew').path, const <String>[ 'app:testDebugUnitTest', 'plugin:testDebugUnitTest', ], androidFolder.path, ), ]), ); }); test('fails when the gradlew generation fails', () async { createFakePlugin( 'plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.inline) }, extraFiles: <String>[ 'example/android/app/src/test/example_test.java', ], ); processRunner .mockProcessesForExecutable[getFlutterCommand(mockPlatform)] = <FakeProcessInfo>[FakeProcessInfo(MockProcess(exitCode: 1))]; Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['native-test', '--android'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('Unable to configure Gradle project'), ]), ); }); test('logs missing test types', () async { // No unit tests. createFakePlugin( 'plugin1', packagesDir, platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.inline) }, extraFiles: <String>[ 'example/android/gradlew', 'example/android/app/src/androidTest/IntegrationTest.java', ], ); // No integration tests. createFakePlugin( 'plugin2', packagesDir, platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.inline) }, extraFiles: <String>[ 'android/src/test/example_test.java', 'example/android/gradlew', ], ); final List<String> output = await runCapturingPrint( runner, <String>['native-test', '--android'], errorHandler: (Error e) { // Having no unit tests is fatal, but that's not the point of this // test so just ignore the failure. }); expect( output, containsAllInOrder(<Matcher>[ contains('No Android unit tests found for plugin1/example'), contains('Running integration tests...'), contains( 'No Android integration tests found for plugin2/example'), contains('Running unit tests...'), ])); }); test('fails when a unit test fails', () async { final RepositoryPackage plugin = createFakePlugin( 'plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.inline) }, extraFiles: <String>[ 'example/android/gradlew', 'example/android/app/src/test/example_test.java', ], ); final String gradlewPath = plugin .getExamples() .first .platformDirectory(FlutterPlatform.android) .childFile('gradlew') .path; processRunner.mockProcessesForExecutable[gradlewPath] = <FakeProcessInfo>[FakeProcessInfo(MockProcess(exitCode: 1))]; Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['native-test', '--android'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('plugin/example unit tests failed.'), contains('The following packages had errors:'), contains('plugin') ]), ); }); test('fails when an integration test fails', () async { final RepositoryPackage plugin = createFakePlugin( 'plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.inline) }, extraFiles: <String>[ 'example/android/gradlew', 'example/android/app/src/test/example_test.java', 'example/android/app/src/androidTest/IntegrationTest.java', ], ); final String gradlewPath = plugin .getExamples() .first .platformDirectory(FlutterPlatform.android) .childFile('gradlew') .path; processRunner.mockProcessesForExecutable[gradlewPath] = <FakeProcessInfo>[ FakeProcessInfo( MockProcess(), <String>['app:testDebugUnitTest']), // unit passes FakeProcessInfo(MockProcess(exitCode: 1), <String>['app:connectedAndroidTest']), // integration fails ]; Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['native-test', '--android'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('plugin/example integration tests failed.'), contains('The following packages had errors:'), contains('plugin') ]), ); }); test('fails if there are no unit tests', () async { createFakePlugin( 'plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.inline) }, extraFiles: <String>[ 'example/android/gradlew', 'example/android/app/src/androidTest/IntegrationTest.java', ], ); Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['native-test', '--android'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('No Android unit tests found for plugin/example'), contains( 'No unit tests ran. Plugins are required to have unit tests.'), contains('The following packages had errors:'), contains('plugin:\n' ' No unit tests ran (use --exclude if this is intentional).') ]), ); }); test('skips if Android is not supported', () async { createFakePlugin( 'plugin', packagesDir, ); final List<String> output = await runCapturingPrint( runner, <String>['native-test', '--android']); expect( output, containsAllInOrder(<Matcher>[ contains('No implementation for Android.'), contains('SKIPPING: Nothing to test for target platform(s).'), ]), ); }); test('skips when running no tests in integration-only mode', () async { createFakePlugin( 'plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.inline) }, ); final List<String> output = await runCapturingPrint( runner, <String>['native-test', '--android', '--no-unit']); expect( output, containsAllInOrder(<Matcher>[ contains('No Android integration tests found for plugin/example'), contains('SKIPPING: No tests found.'), ]), ); }); }); group('Linux', () { test('builds and runs unit tests', () async { const String testBinaryRelativePath = 'build/linux/x64/release/bar/plugin_test'; final RepositoryPackage plugin = createFakePlugin('plugin', packagesDir, extraFiles: <String>[ 'example/$testBinaryRelativePath' ], platformSupport: <String, PlatformDetails>{ platformLinux: const PlatformDetails(PlatformSupport.inline), }); _createFakeCMakeCache(plugin, mockPlatform, _archDirX64); final File testBinary = childFileWithSubcomponents(plugin.directory, <String>['example', ...testBinaryRelativePath.split('/')]); final List<String> output = await runCapturingPrint(runner, <String>[ 'native-test', '--linux', '--no-integration', ]); expect( output, containsAllInOrder(<Matcher>[ contains('Running plugin_test...'), contains('No issues found!'), ]), ); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ getLinuxBuildCall(plugin), ProcessCall(testBinary.path, const <String>[], null), ])); }); test('only runs release unit tests', () async { const String debugTestBinaryRelativePath = 'build/linux/x64/debug/bar/plugin_test'; const String releaseTestBinaryRelativePath = 'build/linux/x64/release/bar/plugin_test'; final RepositoryPackage plugin = createFakePlugin('plugin', packagesDir, extraFiles: <String>[ 'example/$debugTestBinaryRelativePath', 'example/$releaseTestBinaryRelativePath' ], platformSupport: <String, PlatformDetails>{ platformLinux: const PlatformDetails(PlatformSupport.inline), }); _createFakeCMakeCache(plugin, mockPlatform, _archDirX64); final File releaseTestBinary = childFileWithSubcomponents( plugin.directory, <String>['example', ...releaseTestBinaryRelativePath.split('/')]); final List<String> output = await runCapturingPrint(runner, <String>[ 'native-test', '--linux', '--no-integration', ]); expect( output, containsAllInOrder(<Matcher>[ contains('Running plugin_test...'), contains('No issues found!'), ]), ); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ getLinuxBuildCall(plugin), ProcessCall(releaseTestBinary.path, const <String>[], null), ])); }); test('fails if CMake has not been configured', () async { createFakePlugin('plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformLinux: const PlatformDetails(PlatformSupport.inline), }); Error? commandError; final List<String> output = await runCapturingPrint(runner, <String>[ 'native-test', '--linux', '--no-integration', ], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('plugin:\n' ' Examples must be built before testing.') ]), ); expect(processRunner.recordedCalls, orderedEquals(<ProcessCall>[])); }); test('fails if there are no unit tests', () async { final RepositoryPackage plugin = createFakePlugin('plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformLinux: const PlatformDetails(PlatformSupport.inline), }); _createFakeCMakeCache(plugin, mockPlatform, _archDirX64); Error? commandError; final List<String> output = await runCapturingPrint(runner, <String>[ 'native-test', '--linux', '--no-integration', ], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('No test binaries found.'), ]), ); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ getLinuxBuildCall(plugin), ])); }); test('fails if a unit test fails', () async { const String testBinaryRelativePath = 'build/linux/x64/release/bar/plugin_test'; final RepositoryPackage plugin = createFakePlugin('plugin', packagesDir, extraFiles: <String>[ 'example/$testBinaryRelativePath' ], platformSupport: <String, PlatformDetails>{ platformLinux: const PlatformDetails(PlatformSupport.inline), }); _createFakeCMakeCache(plugin, mockPlatform, _archDirX64); final File testBinary = childFileWithSubcomponents(plugin.directory, <String>['example', ...testBinaryRelativePath.split('/')]); processRunner.mockProcessesForExecutable[testBinary.path] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(exitCode: 1)), ]; Error? commandError; final List<String> output = await runCapturingPrint(runner, <String>[ 'native-test', '--linux', '--no-integration', ], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('Running plugin_test...'), ]), ); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ getLinuxBuildCall(plugin), ProcessCall(testBinary.path, const <String>[], null), ])); }); }); // Tests behaviors of implementation that is shared between iOS and macOS. group('iOS/macOS', () { test('fails if xcrun fails', () async { createFakePlugin('plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformMacOS: const PlatformDetails(PlatformSupport.inline), }); processRunner.mockProcessesForExecutable['xcrun'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(exitCode: 1)) ]; Error? commandError; final List<String> output = await runCapturingPrint(runner, <String>['native-test', '--macos'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('The following packages had errors:'), contains(' plugin'), ]), ); }); test('honors unit-only', () async { final RepositoryPackage plugin = createFakePlugin('plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformMacOS: const PlatformDetails(PlatformSupport.inline), }); final Directory pluginExampleDirectory = getExampleDir(plugin); processRunner.mockProcessesForExecutable['xcrun'] = <FakeProcessInfo>[ getMockXcodebuildListProcess( <String>['RunnerTests', 'RunnerUITests']), ]; final List<String> output = await runCapturingPrint(runner, <String>[ 'native-test', '--macos', '--no-integration', ]); expect( output, contains( contains('Successfully ran macOS xctest for plugin/example'))); // --no-integration should translate to '-only-testing:RunnerTests'. expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ getTargetCheckCall(pluginExampleDirectory, 'macos'), getRunTestCall(pluginExampleDirectory, 'macos', extraFlags: <String>['-only-testing:RunnerTests']), ])); }); test('honors integration-only', () async { final RepositoryPackage plugin1 = createFakePlugin( 'plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformMacOS: const PlatformDetails(PlatformSupport.inline), }); final Directory pluginExampleDirectory = getExampleDir(plugin1); processRunner.mockProcessesForExecutable['xcrun'] = <FakeProcessInfo>[ getMockXcodebuildListProcess( <String>['RunnerTests', 'RunnerUITests']), ]; final List<String> output = await runCapturingPrint(runner, <String>[ 'native-test', '--macos', '--no-unit', ]); expect( output, contains( contains('Successfully ran macOS xctest for plugin/example'))); // --no-unit should translate to '-only-testing:RunnerUITests'. expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ getTargetCheckCall(pluginExampleDirectory, 'macos'), getRunTestCall(pluginExampleDirectory, 'macos', extraFlags: <String>['-only-testing:RunnerUITests']), ])); }); test('skips when the requested target is not present', () async { final RepositoryPackage plugin1 = createFakePlugin( 'plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformMacOS: const PlatformDetails(PlatformSupport.inline), }); final Directory pluginExampleDirectory = getExampleDir(plugin1); // Simulate a project with unit tests but no integration tests... processRunner.mockProcessesForExecutable['xcrun'] = <FakeProcessInfo>[ getMockXcodebuildListProcess(<String>['RunnerTests']), ]; // ... then try to run only integration tests. final List<String> output = await runCapturingPrint(runner, <String>[ 'native-test', '--macos', '--no-unit', ]); expect( output, containsAllInOrder(<Matcher>[ contains( 'No "RunnerUITests" target in plugin/example; skipping.'), ])); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ getTargetCheckCall(pluginExampleDirectory, 'macos'), ])); }); test('fails if there are no unit tests', () async { final RepositoryPackage plugin1 = createFakePlugin( 'plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformMacOS: const PlatformDetails(PlatformSupport.inline), }); final Directory pluginExampleDirectory = getExampleDir(plugin1); processRunner.mockProcessesForExecutable['xcrun'] = <FakeProcessInfo>[ getMockXcodebuildListProcess(<String>['RunnerUITests']), ]; Error? commandError; final List<String> output = await runCapturingPrint(runner, <String>['native-test', '--macos'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('No "RunnerTests" target in plugin/example; skipping.'), contains( 'No unit tests ran. Plugins are required to have unit tests.'), contains('The following packages had errors:'), contains('plugin:\n' ' No unit tests ran (use --exclude if this is intentional).'), ])); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ getTargetCheckCall(pluginExampleDirectory, 'macos'), ])); }); test('fails if unable to check for requested target', () async { final RepositoryPackage plugin1 = createFakePlugin( 'plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformMacOS: const PlatformDetails(PlatformSupport.inline), }); final Directory pluginExampleDirectory = getExampleDir(plugin1); processRunner.mockProcessesForExecutable['xcrun'] = <FakeProcessInfo>[ FakeProcessInfo( MockProcess(exitCode: 1), <String>['xcodebuild', '-list']), ]; Error? commandError; final List<String> output = await runCapturingPrint(runner, <String>[ 'native-test', '--macos', '--no-integration', ], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('Unable to check targets for plugin/example.'), ]), ); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ getTargetCheckCall(pluginExampleDirectory, 'macos'), ])); }); }); group('multiplatform', () { test('runs all platfroms when supported', () async { final RepositoryPackage plugin = createFakePlugin( 'plugin', packagesDir, extraFiles: <String>[ 'example/android/gradlew', 'android/src/test/example_test.java', ], platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.inline), platformIOS: const PlatformDetails(PlatformSupport.inline), platformMacOS: const PlatformDetails(PlatformSupport.inline), }, ); final Directory pluginExampleDirectory = getExampleDir(plugin); final Directory androidFolder = pluginExampleDirectory.childDirectory('android'); processRunner.mockProcessesForExecutable['xcrun'] = <FakeProcessInfo>[ getMockXcodebuildListProcess( <String>['RunnerTests', 'RunnerUITests']), // iOS list FakeProcessInfo( MockProcess(), <String>['xcodebuild', 'test']), // iOS run getMockXcodebuildListProcess( <String>['RunnerTests', 'RunnerUITests']), // macOS list FakeProcessInfo( MockProcess(), <String>['xcodebuild', 'test']), // macOS run ]; final List<String> output = await runCapturingPrint(runner, <String>[ 'native-test', '--android', '--ios', '--macos', kDestination, 'foo_destination', ]); expect( output, containsAll(<Matcher>[ contains('Running Android tests for plugin/example'), contains('Successfully ran iOS xctest for plugin/example'), contains('Successfully ran macOS xctest for plugin/example'), ])); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( androidFolder.childFile('gradlew').path, const <String>[ 'app:testDebugUnitTest', 'plugin:testDebugUnitTest', ], androidFolder.path), getTargetCheckCall(pluginExampleDirectory, 'ios'), getRunTestCall(pluginExampleDirectory, 'ios', destination: 'foo_destination'), getTargetCheckCall(pluginExampleDirectory, 'macos'), getRunTestCall(pluginExampleDirectory, 'macos'), ])); }); test('runs only macOS for a macOS plugin', () async { final RepositoryPackage plugin = createFakePlugin('plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformMacOS: const PlatformDetails(PlatformSupport.inline), }); final Directory pluginExampleDirectory = getExampleDir(plugin); processRunner.mockProcessesForExecutable['xcrun'] = <FakeProcessInfo>[ getMockXcodebuildListProcess( <String>['RunnerTests', 'RunnerUITests']), ]; final List<String> output = await runCapturingPrint(runner, <String>[ 'native-test', '--ios', '--macos', kDestination, 'foo_destination', ]); expect( output, containsAllInOrder(<Matcher>[ contains('No implementation for iOS.'), contains('Successfully ran macOS xctest for plugin/example'), ])); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ getTargetCheckCall(pluginExampleDirectory, 'macos'), getRunTestCall(pluginExampleDirectory, 'macos'), ])); }); test('runs only iOS for a iOS plugin', () async { final RepositoryPackage plugin = createFakePlugin('plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformIOS: const PlatformDetails(PlatformSupport.inline) }); final Directory pluginExampleDirectory = getExampleDir(plugin); processRunner.mockProcessesForExecutable['xcrun'] = <FakeProcessInfo>[ getMockXcodebuildListProcess( <String>['RunnerTests', 'RunnerUITests']), ]; final List<String> output = await runCapturingPrint(runner, <String>[ 'native-test', '--ios', '--macos', kDestination, 'foo_destination', ]); expect( output, containsAllInOrder(<Matcher>[ contains('No implementation for macOS.'), contains('Successfully ran iOS xctest for plugin/example') ])); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ getTargetCheckCall(pluginExampleDirectory, 'ios'), getRunTestCall(pluginExampleDirectory, 'ios', destination: 'foo_destination'), ])); }); test('skips when nothing is supported', () async { createFakePlugin('plugin', packagesDir); final List<String> output = await runCapturingPrint(runner, <String>[ 'native-test', '--android', '--ios', '--macos', '--windows', kDestination, 'foo_destination', ]); expect( output, containsAllInOrder(<Matcher>[ contains('No implementation for Android.'), contains('No implementation for iOS.'), contains('No implementation for macOS.'), contains('SKIPPING: Nothing to test for target platform(s).'), ])); expect(processRunner.recordedCalls, orderedEquals(<ProcessCall>[])); }); test('skips Dart-only plugins', () async { createFakePlugin( 'plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformMacOS: const PlatformDetails(PlatformSupport.inline, hasDartCode: true, hasNativeCode: false), platformWindows: const PlatformDetails(PlatformSupport.inline, hasDartCode: true, hasNativeCode: false), }, ); final List<String> output = await runCapturingPrint(runner, <String>[ 'native-test', '--macos', '--windows', kDestination, 'foo_destination', ]); expect( output, containsAllInOrder(<Matcher>[ contains('No native code for macOS.'), contains('No native code for Windows.'), contains('SKIPPING: Nothing to test for target platform(s).'), ])); expect(processRunner.recordedCalls, orderedEquals(<ProcessCall>[])); }); test('failing one platform does not stop the tests', () async { final RepositoryPackage plugin = createFakePlugin( 'plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.inline), platformIOS: const PlatformDetails(PlatformSupport.inline), }, extraFiles: <String>[ 'example/android/gradlew', 'example/android/app/src/test/example_test.java', ], ); processRunner.mockProcessesForExecutable['xcrun'] = <FakeProcessInfo>[ getMockXcodebuildListProcess( <String>['RunnerTests', 'RunnerUITests']), ]; // Simulate failing Android, but not iOS. final String gradlewPath = plugin .getExamples() .first .platformDirectory(FlutterPlatform.android) .childFile('gradlew') .path; processRunner.mockProcessesForExecutable[gradlewPath] = <FakeProcessInfo>[FakeProcessInfo(MockProcess(exitCode: 1))]; Error? commandError; final List<String> output = await runCapturingPrint(runner, <String>[ 'native-test', '--android', '--ios', '--ios-destination', 'foo_destination', ], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('Running tests for Android...'), contains('plugin/example unit tests failed.'), contains('Running tests for iOS...'), contains('Successfully ran iOS xctest for plugin/example'), contains('The following packages had errors:'), contains('plugin:\n' ' Android') ]), ); }); test('failing multiple platforms reports multiple failures', () async { final RepositoryPackage plugin = createFakePlugin( 'plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.inline), platformIOS: const PlatformDetails(PlatformSupport.inline), }, extraFiles: <String>[ 'example/android/gradlew', 'example/android/app/src/test/example_test.java', ], ); // Simulate failing Android. final String gradlewPath = plugin .getExamples() .first .platformDirectory(FlutterPlatform.android) .childFile('gradlew') .path; processRunner.mockProcessesForExecutable[gradlewPath] = <FakeProcessInfo>[FakeProcessInfo(MockProcess(exitCode: 1))]; // Simulate failing iOS. processRunner.mockProcessesForExecutable['xcrun'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(exitCode: 1)) ]; Error? commandError; final List<String> output = await runCapturingPrint(runner, <String>[ 'native-test', '--android', '--ios', '--ios-destination', 'foo_destination', ], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('Running tests for Android...'), contains('Running tests for iOS...'), contains('The following packages had errors:'), contains('plugin:\n' ' Android\n' ' iOS') ]), ); }); }); }); group('test native_test_command on Windows', () { late FileSystem fileSystem; late MockPlatform mockPlatform; late Directory packagesDir; late CommandRunner<void> runner; late RecordingProcessRunner processRunner; setUp(() { fileSystem = MemoryFileSystem(style: FileSystemStyle.windows); mockPlatform = MockPlatform(isWindows: true); packagesDir = createPackagesDirectory(fileSystem: fileSystem); processRunner = RecordingProcessRunner(); }); // Returns the ProcessCall to expect for build the Windows unit tests for // the given plugin. ProcessCall getWindowsBuildCall(RepositoryPackage plugin, String? arch) { Directory projectDir = getExampleDir(plugin) .childDirectory('build') .childDirectory('windows'); if (arch != null) { projectDir = projectDir.childDirectory(arch); } return ProcessCall( _fakeCmakeCommand, <String>[ '--build', projectDir.path, '--target', 'unit_tests', '--config', 'Debug' ], null); } group('Windows x64', () { setUp(() { final NativeTestCommand command = NativeTestCommand(packagesDir, processRunner: processRunner, platform: mockPlatform, abi: Abi.windowsX64); runner = CommandRunner<void>( 'native_test_command', 'Test for native_test_command'); runner.addCommand(command); }); test('runs unit tests', () async { const String x64TestBinaryRelativePath = 'build/windows/x64/Debug/bar/plugin_test.exe'; const String arm64TestBinaryRelativePath = 'build/windows/arm64/Debug/bar/plugin_test.exe'; final RepositoryPackage plugin = createFakePlugin('plugin', packagesDir, extraFiles: <String>[ 'example/$x64TestBinaryRelativePath', 'example/$arm64TestBinaryRelativePath', ], platformSupport: <String, PlatformDetails>{ platformWindows: const PlatformDetails(PlatformSupport.inline), }); _createFakeCMakeCache(plugin, mockPlatform, _archDirX64); final File testBinary = childFileWithSubcomponents(plugin.directory, <String>['example', ...x64TestBinaryRelativePath.split('/')]); final List<String> output = await runCapturingPrint(runner, <String>[ 'native-test', '--windows', '--no-integration', ]); expect( output, containsAllInOrder(<Matcher>[ contains('Running plugin_test.exe...'), contains('No issues found!'), ]), ); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ getWindowsBuildCall(plugin, _archDirX64), ProcessCall(testBinary.path, const <String>[], null), ])); }); test('runs unit tests with legacy build output', () async { const String testBinaryRelativePath = 'build/windows/Debug/bar/plugin_test.exe'; final RepositoryPackage plugin = createFakePlugin('plugin', packagesDir, extraFiles: <String>[ 'example/$testBinaryRelativePath' ], platformSupport: <String, PlatformDetails>{ platformWindows: const PlatformDetails(PlatformSupport.inline), }); _createFakeCMakeCache(plugin, mockPlatform, null); final File testBinary = childFileWithSubcomponents(plugin.directory, <String>['example', ...testBinaryRelativePath.split('/')]); final List<String> output = await runCapturingPrint(runner, <String>[ 'native-test', '--windows', '--no-integration', ]); expect( output, containsAllInOrder(<Matcher>[ contains('Running plugin_test.exe...'), contains('No issues found!'), ]), ); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ getWindowsBuildCall(plugin, null), ProcessCall(testBinary.path, const <String>[], null), ])); }); test('only runs debug unit tests', () async { const String debugTestBinaryRelativePath = 'build/windows/x64/Debug/bar/plugin_test.exe'; const String releaseTestBinaryRelativePath = 'build/windows/x64/Release/bar/plugin_test.exe'; final RepositoryPackage plugin = createFakePlugin('plugin', packagesDir, extraFiles: <String>[ 'example/$debugTestBinaryRelativePath', 'example/$releaseTestBinaryRelativePath' ], platformSupport: <String, PlatformDetails>{ platformWindows: const PlatformDetails(PlatformSupport.inline), }); _createFakeCMakeCache(plugin, mockPlatform, _archDirX64); final File debugTestBinary = childFileWithSubcomponents( plugin.directory, <String>['example', ...debugTestBinaryRelativePath.split('/')]); final List<String> output = await runCapturingPrint(runner, <String>[ 'native-test', '--windows', '--no-integration', ]); expect( output, containsAllInOrder(<Matcher>[ contains('Running plugin_test.exe...'), contains('No issues found!'), ]), ); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ getWindowsBuildCall(plugin, _archDirX64), ProcessCall(debugTestBinary.path, const <String>[], null), ])); }); test('only runs debug unit tests with legacy build output', () async { const String debugTestBinaryRelativePath = 'build/windows/Debug/bar/plugin_test.exe'; const String releaseTestBinaryRelativePath = 'build/windows/Release/bar/plugin_test.exe'; final RepositoryPackage plugin = createFakePlugin('plugin', packagesDir, extraFiles: <String>[ 'example/$debugTestBinaryRelativePath', 'example/$releaseTestBinaryRelativePath' ], platformSupport: <String, PlatformDetails>{ platformWindows: const PlatformDetails(PlatformSupport.inline), }); _createFakeCMakeCache(plugin, mockPlatform, null); final File debugTestBinary = childFileWithSubcomponents( plugin.directory, <String>['example', ...debugTestBinaryRelativePath.split('/')]); final List<String> output = await runCapturingPrint(runner, <String>[ 'native-test', '--windows', '--no-integration', ]); expect( output, containsAllInOrder(<Matcher>[ contains('Running plugin_test.exe...'), contains('No issues found!'), ]), ); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ getWindowsBuildCall(plugin, null), ProcessCall(debugTestBinary.path, const <String>[], null), ])); }); test('fails if CMake has not been configured', () async { createFakePlugin('plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformWindows: const PlatformDetails(PlatformSupport.inline), }); Error? commandError; final List<String> output = await runCapturingPrint(runner, <String>[ 'native-test', '--windows', '--no-integration', ], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('plugin:\n' ' Examples must be built before testing.') ]), ); expect(processRunner.recordedCalls, orderedEquals(<ProcessCall>[])); }); test('fails if there are no unit tests', () async { final RepositoryPackage plugin = createFakePlugin('plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformWindows: const PlatformDetails(PlatformSupport.inline), }); _createFakeCMakeCache(plugin, mockPlatform, _archDirX64); Error? commandError; final List<String> output = await runCapturingPrint(runner, <String>[ 'native-test', '--windows', '--no-integration', ], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('No test binaries found.'), ]), ); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ getWindowsBuildCall(plugin, _archDirX64), ])); }); test('fails if a unit test fails', () async { const String testBinaryRelativePath = 'build/windows/x64/Debug/bar/plugin_test.exe'; final RepositoryPackage plugin = createFakePlugin('plugin', packagesDir, extraFiles: <String>[ 'example/$testBinaryRelativePath' ], platformSupport: <String, PlatformDetails>{ platformWindows: const PlatformDetails(PlatformSupport.inline), }); _createFakeCMakeCache(plugin, mockPlatform, _archDirX64); final File testBinary = childFileWithSubcomponents(plugin.directory, <String>['example', ...testBinaryRelativePath.split('/')]); processRunner.mockProcessesForExecutable[testBinary.path] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(exitCode: 1)), ]; Error? commandError; final List<String> output = await runCapturingPrint(runner, <String>[ 'native-test', '--windows', '--no-integration', ], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('Running plugin_test.exe...'), ]), ); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ getWindowsBuildCall(plugin, _archDirX64), ProcessCall(testBinary.path, const <String>[], null), ])); }); }); group('Windows arm64', () { setUp(() { final NativeTestCommand command = NativeTestCommand(packagesDir, processRunner: processRunner, platform: mockPlatform, abi: Abi.windowsArm64); runner = CommandRunner<void>( 'native_test_command', 'Test for native_test_command'); runner.addCommand(command); }); test('runs unit tests', () async { const String x64TestBinaryRelativePath = 'build/windows/x64/Debug/bar/plugin_test.exe'; const String arm64TestBinaryRelativePath = 'build/windows/arm64/Debug/bar/plugin_test.exe'; final RepositoryPackage plugin = createFakePlugin('plugin', packagesDir, extraFiles: <String>[ 'example/$x64TestBinaryRelativePath', 'example/$arm64TestBinaryRelativePath', ], platformSupport: <String, PlatformDetails>{ platformWindows: const PlatformDetails(PlatformSupport.inline), }); _createFakeCMakeCache(plugin, mockPlatform, _archDirArm64); final File testBinary = childFileWithSubcomponents(plugin.directory, <String>['example', ...arm64TestBinaryRelativePath.split('/')]); final List<String> output = await runCapturingPrint(runner, <String>[ 'native-test', '--windows', '--no-integration', ]); expect( output, containsAllInOrder(<Matcher>[ contains('Running plugin_test.exe...'), contains('No issues found!'), ]), ); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ getWindowsBuildCall(plugin, _archDirArm64), ProcessCall(testBinary.path, const <String>[], null), ])); }); test('falls back to x64 unit tests if arm64 is not built', () async { const String x64TestBinaryRelativePath = 'build/windows/x64/Debug/bar/plugin_test.exe'; final RepositoryPackage plugin = createFakePlugin('plugin', packagesDir, extraFiles: <String>[ 'example/$x64TestBinaryRelativePath', ], platformSupport: <String, PlatformDetails>{ platformWindows: const PlatformDetails(PlatformSupport.inline), }); _createFakeCMakeCache(plugin, mockPlatform, _archDirX64); final File testBinary = childFileWithSubcomponents(plugin.directory, <String>['example', ...x64TestBinaryRelativePath.split('/')]); final List<String> output = await runCapturingPrint(runner, <String>[ 'native-test', '--windows', '--no-integration', ]); expect( output, containsAllInOrder(<Matcher>[ contains('Running plugin_test.exe...'), contains('No issues found!'), ]), ); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ getWindowsBuildCall(plugin, _archDirX64), ProcessCall(testBinary.path, const <String>[], null), ])); }); test('only runs debug unit tests', () async { const String debugTestBinaryRelativePath = 'build/windows/arm64/Debug/bar/plugin_test.exe'; const String releaseTestBinaryRelativePath = 'build/windows/arm64/Release/bar/plugin_test.exe'; final RepositoryPackage plugin = createFakePlugin('plugin', packagesDir, extraFiles: <String>[ 'example/$debugTestBinaryRelativePath', 'example/$releaseTestBinaryRelativePath' ], platformSupport: <String, PlatformDetails>{ platformWindows: const PlatformDetails(PlatformSupport.inline), }); _createFakeCMakeCache(plugin, mockPlatform, _archDirArm64); final File debugTestBinary = childFileWithSubcomponents( plugin.directory, <String>['example', ...debugTestBinaryRelativePath.split('/')]); final List<String> output = await runCapturingPrint(runner, <String>[ 'native-test', '--windows', '--no-integration', ]); expect( output, containsAllInOrder(<Matcher>[ contains('Running plugin_test.exe...'), contains('No issues found!'), ]), ); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ getWindowsBuildCall(plugin, _archDirArm64), ProcessCall(debugTestBinary.path, const <String>[], null), ])); }); }); }); }
packages/script/tool/test/native_test_command_test.dart/0
{ "file_path": "packages/script/tool/test/native_test_command_test.dart", "repo_id": "packages", "token_count": 33812 }
1,031
## NEXT * Updates minimum supported SDK version to Flutter 3.13/Dart 3.1. ## 1.0.7 * Adds example.md file to display usage. * Updates minimum supported SDK version to Flutter 3.10/Dart 3.0. ## 1.0.6 * Adds pub topics to package metadata. * Adds pub topics to package metadata. * Updates minimum supported SDK version to Flutter 3.7/Dart 2.19. * Aligns Dart and Flutter SDK constraints. ## 1.0.5 * Updates README to reference correct URL. ## 1.0.4 * Updates README to link to API docs. ## 1.0.3 * Source moved to flutter/packages. ## 1.0.2 * Vertically center align the glyphs in the .ttf. ## 1.0.1+2 * Update README images ## 1.0.1+1 * Add README note that version 1.0.0 should be used until nnbd is on stable. ## 1.0.1 * Add Dart SDK constraint to make it compatible with null safety. ## 1.0.0 * Move to 1.0.0 and remove SDK version constraint since the font's codepoints are now fully compatible and missing glyphs are backfilled. ## 1.0.0-dev.4 * dev.3's codepoints were off by 1. The previous "car" glyph was added but was not manually mapped to its previous codepoint. ## 1.0.0-dev.3 * Serve icons map on GitHub Pages * Auto width everything since not all SVGs have the same canvas. * Add back missing icons from 0.1.3 not part of the new iOS icon repertoire to preserve backward compatibility. * Duplicate codepoints for merged icons so they're addressable from different CupertinoIcons that have now merged. ## 1.0.0-dev.2 * Add back 2 thicker chevrons for back/forward navigation. ## 1.0.0-dev.1 * Updated font content to the iOS 13 system icons repertoire for use on Flutter SDK versions 1.22+. ## 0.1.3 * Updated 'chevron left' and 'chevron right' icons to match San Francisco font. ## 0.1.2 * Fix linter warning for missing lib/ folder. * Constrain to Dart 2. ## 0.1.1 * Initial release.
packages/third_party/packages/cupertino_icons/CHANGELOG.md/0
{ "file_path": "packages/third_party/packages/cupertino_icons/CHANGELOG.md", "repo_id": "packages", "token_count": 598 }
1,032
import * as admin from 'firebase-admin'; import * as functions from 'firebase-functions'; import * as path from 'path'; import * as querystring from 'querystring'; import mustache from 'mustache'; import { UPLOAD_PATH, ALLOWED_HOSTS } from '../config'; import footerTmpl from './templates/footer'; import notFoundTmpl from './templates/notfound'; import shareTmpl from './templates/share'; import stylesTmpl from './templates/styles'; import gaTmpl from './templates/ga'; const VALID_IMAGE_EXT = [ '.png', '.jpeg', '.jpg' ]; const BaseHTMLContext: Record<string, string | Record<string, string>> = { appUrl: '', shareUrl: '', shareImageUrl: '', assetUrls: { favicon: bucketPathForFile('public/favicon.png'), bg: bucketPathForFile('public/background.jpg'), bgMobile: bucketPathForFile('public/background-mobile.jpg'), notFoundPhoto: bucketPathForFile('public/404-photo.png'), fixedPhotosLeft: bucketPathForFile('public/table-photos-left.png'), fixedPhotosRight: bucketPathForFile('public/table-photos-right.png'), }, meta: { title: 'Google I/O Photo Booth', desc: ( 'Take a photo in the I/O Photo Booth with your favorite Google Developer Mascots! ' + 'Built with Flutter & Firebase for Google I/O 2021.' ), }, footer: footerTmpl, ga: gaTmpl, styles: '', }; /** * Returns bucket path * @param {string} filename * @return {string} */ function bucketPathForFile(filename: string): string { return ( 'https://firebasestorage.googleapis.com/v0' + `/b/${admin.storage().bucket().name}` + `/o/${querystring.escape(filename)}?alt=media` ); } /** * Return a local file HTML template built with context * @param {string} tmpl - html template string * @param {Object} context - html context dict * @return {string} HTML template string */ function renderTemplate( tmpl: string, context: Record<string, string | Record<string, string>> ): string { context.styles = mustache.render(stylesTmpl, context); return mustache.render(tmpl, context); } /** * Render the 404 html page * @param {string} imageFileName - filename of storage image * @param {string} baseUrl - http base fully qualified URL * @return {string} HTML string */ function renderNotFoundPage(imageFileName: string, baseUrl: string): string { const context = Object.assign({}, BaseHTMLContext, { appUrl: baseUrl, shareUrl: `${baseUrl}/share/${imageFileName}`, shareImageUrl: bucketPathForFile(`${UPLOAD_PATH}/${imageFileName}`), }); return renderTemplate(notFoundTmpl, context); } /** * Populate and return the share page HTML for given path * @param {string} imageFileName - filename of storage image * @param {string} baseUrl - http base fully qualified URL * @return {string} HTML string */ function renderSharePage(imageFileName: string, baseUrl: string): string { const context = Object.assign({}, BaseHTMLContext, { appUrl: baseUrl, shareUrl: `${baseUrl}/share/${imageFileName}`, shareImageUrl: bucketPathForFile(`${UPLOAD_PATH}/${imageFileName}`), }); return renderTemplate(shareTmpl, context); } /** * Get share response * @param {Object} req - request object * @return {Object} share response */ export async function getShareResponse( req: functions.https.Request ): Promise<{ status: number; send: string }> { try { const host = req.get('host') ?? ''; const baseUrl = `${req.protocol}://${host}`; const { ext, base: imageFileName } = path.parse(req.path); if (!ALLOWED_HOSTS.includes(host) || !VALID_IMAGE_EXT.includes(ext)) { functions.logger.log('Bad host or image ext', { host, baseUrl, ext, imageFileName }); return { status: 404, send: renderNotFoundPage(imageFileName, baseUrl), }; } const imageBlobPath = `${UPLOAD_PATH}/${imageFileName}`; const imageExists = await admin.storage().bucket().file(imageBlobPath).exists(); if (Array.isArray(imageExists) && imageExists[0]) { return { status: 200, send: renderSharePage(imageFileName, baseUrl), }; } functions.logger.log('Image does not exist', { imageBlobPath }); // NOTE 200 status so that default share meta tags work, // where twitter does not show meta tags on a 404 status return { status: 200, send: renderNotFoundPage(imageFileName, baseUrl), }; } catch (error) { functions.logger.error(error); return { status: 500, send: 'Something went wrong', }; } } /** * Public sharing function */ export const shareImage = functions.https.onRequest(async (req, res) => { const { status, send } = await getShareResponse(req); res.set('Access-Control-Allow-Origin', '*'); res.status(status).send(send); });
photobooth/functions/src/share/index.ts/0
{ "file_path": "photobooth/functions/src/share/index.ts", "repo_id": "photobooth", "token_count": 1630 }
1,033
import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:io_photobooth/external_links/external_links.dart'; import 'package:io_photobooth/l10n/l10n.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; class FooterLink extends StatelessWidget { const FooterLink({ required this.text, required this.link, super.key, }); final String text; final String link; @override Widget build(BuildContext context) { return Clickable( onPressed: () => openLink(link), child: Text(text), ); } } class FooterMadeWithLink extends StatelessWidget { const FooterMadeWithLink({ super.key, }); @override Widget build(BuildContext context) { final l10n = context.l10n; final theme = Theme.of(context); final defaultTextStyle = DefaultTextStyle.of(context); return RichText( textAlign: TextAlign.center, text: TextSpan( text: l10n.footerMadeWithText, style: theme.textTheme.bodyLarge?.copyWith( fontWeight: PhotoboothFontWeight.regular, color: defaultTextStyle.style.color, ), children: <TextSpan>[ TextSpan( text: l10n.footerMadeWithFlutterLinkText, recognizer: TapGestureRecognizer()..onTap = launchFlutterDevLink, style: const TextStyle( decoration: TextDecoration.underline, ), ), const TextSpan( text: ' & ', ), TextSpan( text: l10n.footerMadeWithFirebaseLinkText, recognizer: TapGestureRecognizer()..onTap = launchFirebaseLink, style: const TextStyle( decoration: TextDecoration.underline, ), ), ], ), ); } } class FooterGoogleIOLink extends StatelessWidget { const FooterGoogleIOLink({ super.key, }); @override Widget build(BuildContext context) { final l10n = context.l10n; return FooterLink( link: googleIOExternalLink, text: l10n.footerGoogleIOLinkText, ); } } class FooterCodelabLink extends StatelessWidget { const FooterCodelabLink({ super.key, }); @override Widget build(BuildContext context) { final l10n = context.l10n; return FooterLink( link: 'https://firebase.google.com/codelabs/firebase-get-to-know-flutter#0', text: l10n.footerCodelabLinkText, ); } } class FooterHowItsMadeLink extends StatelessWidget { const FooterHowItsMadeLink({ super.key, }); @override Widget build(BuildContext context) { final l10n = context.l10n; return FooterLink( link: 'https://medium.com/flutter/how-its-made-i-o-photo-booth-3b8355d35883', text: l10n.footerHowItsMadeLinkText, ); } } class FooterTermsOfServiceLink extends StatelessWidget { const FooterTermsOfServiceLink({ super.key, }); @override Widget build(BuildContext context) { final l10n = context.l10n; return FooterLink( link: 'https://policies.google.com/terms', text: l10n.footerTermsOfServiceLinkText, ); } } class FooterPrivacyPolicyLink extends StatelessWidget { const FooterPrivacyPolicyLink({ super.key, }); @override Widget build(BuildContext context) { final l10n = context.l10n; return FooterLink( link: 'https://policies.google.com/privacy', text: l10n.footerPrivacyPolicyLinkText, ); } }
photobooth/lib/footer/widgets/footer_link.dart/0
{ "file_path": "photobooth/lib/footer/widgets/footer_link.dart", "repo_id": "photobooth", "token_count": 1474 }
1,034
void removeLoadingIndicator() { // Mobile doesn't need the splash screen to be removed explicitly. }
photobooth/lib/landing/loading_indicator_io.dart/0
{ "file_path": "photobooth/lib/landing/loading_indicator_io.dart", "repo_id": "photobooth", "token_count": 25 }
1,035
import 'package:flutter/material.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; class AnimatedDino extends AnimatedSprite { const AnimatedDino({super.key}) : super( loadingIndicatorColor: PhotoboothColors.orange, sprites: const Sprites( asset: 'dino_spritesheet.png', size: Size(648, 757), frames: 25, stepTime: 2 / 25, ), ); }
photobooth/lib/photobooth/widgets/animated_characters/animated_dino.dart/0
{ "file_path": "photobooth/lib/photobooth/widgets/animated_characters/animated_dino.dart", "repo_id": "photobooth", "token_count": 205 }
1,036
import 'dart:typed_data'; import 'package:flutter/material.dart'; import 'package:io_photobooth/l10n/l10n.dart'; import 'package:io_photobooth/share/share.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; class ShareBottomSheet extends StatelessWidget { const ShareBottomSheet({ required this.image, super.key, }); final Uint8List image; @override Widget build(BuildContext context) { final theme = Theme.of(context); final l10n = context.l10n; return Container( margin: const EdgeInsets.only(top: 30), decoration: const BoxDecoration( color: PhotoboothColors.white, borderRadius: BorderRadius.vertical(top: Radius.circular(12)), ), child: Stack( children: [ SingleChildScrollView( child: Padding( padding: const EdgeInsets.symmetric( horizontal: 24, vertical: 32, ), child: Column( mainAxisSize: MainAxisSize.min, children: [ const SizedBox(height: 60), SharePreviewPhoto(image: image), const SizedBox(height: 60), SelectableText( l10n.shareDialogHeading, key: const Key('shareBottomSheet_heading'), style: theme.textTheme.displayLarge?.copyWith(fontSize: 32), textAlign: TextAlign.center, ), const SizedBox(height: 24), SelectableText( l10n.shareDialogSubheading, key: const Key('shareBottomSheet_subheading'), style: theme.textTheme.displaySmall?.copyWith(fontSize: 18), textAlign: TextAlign.center, ), const SizedBox(height: 42), const Column( children: [ TwitterButton(), SizedBox(height: 18), FacebookButton(), ], ), const SizedBox(height: 42), const SocialMediaShareClarificationNote(), ], ), ), ), Positioned( right: 24, top: 24, child: IconButton( icon: const Icon( Icons.clear, color: PhotoboothColors.black54, ), onPressed: () => Navigator.of(context).pop(), ), ), ], ), ); } }
photobooth/lib/share/view/share_bottom_sheet.dart/0
{ "file_path": "photobooth/lib/share/view/share_bottom_sheet.dart", "repo_id": "photobooth", "token_count": 1441 }
1,037
import 'dart:ui'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:io_photobooth/l10n/l10n.dart'; import 'package:io_photobooth/share/share.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; /// Overlay displayed on top of the [SharePage] when [ShareBloc] is /// in the in progress state. class ShareProgressOverlay extends StatelessWidget { const ShareProgressOverlay({ super.key, }); @override Widget build(BuildContext context) { return BlocBuilder<ShareBloc, ShareState>( builder: (context, state) => state.uploadStatus.isLoading || (state.compositeStatus.isLoading && state.isUploadRequested) ? const _ShareProgressOverlay( key: Key('shareProgressOverlay_loading'), ) : const SizedBox(key: Key('shareProgressOverlay_nothing')), ); } } class _ShareProgressOverlay extends StatelessWidget { const _ShareProgressOverlay({super.key}); @override Widget build(BuildContext context) { return ColoredBox( color: PhotoboothColors.black.withOpacity(0.8), child: BackdropFilter( filter: ImageFilter.blur(sigmaX: 6, sigmaY: 6), child: Center( child: ResponsiveLayoutBuilder( small: (_, __) => const _MobileShareProgressOverlay( key: Key('shareProgressOverlay_mobile'), ), large: (_, __) => const _DesktopShareProgressOverlay( key: Key('shareProgressOverlay_desktop'), ), ), ), ), ); } } class _DesktopShareProgressOverlay extends StatelessWidget { const _DesktopShareProgressOverlay({super.key}); @override Widget build(BuildContext context) { final l10n = context.l10n; final theme = Theme.of(context); return Column( mainAxisAlignment: MainAxisAlignment.center, children: [ const CircularProgressIndicator( color: PhotoboothColors.orange, ), const SizedBox(height: 28), Padding( padding: const EdgeInsets.symmetric(horizontal: 258), child: Text( l10n.sharePageProgressOverlayHeading, style: theme.textTheme.displayLarge?.copyWith( color: PhotoboothColors.white, ), textAlign: TextAlign.center, ), ), const SizedBox(height: 14), Text( l10n.sharePageProgressOverlaySubheading, style: theme.textTheme.displaySmall?.copyWith( color: PhotoboothColors.white, ), textAlign: TextAlign.center, ), ], ); } } class _MobileShareProgressOverlay extends StatelessWidget { const _MobileShareProgressOverlay({super.key}); @override Widget build(BuildContext context) { final l10n = context.l10n; final theme = Theme.of(context); return Column( mainAxisAlignment: MainAxisAlignment.center, children: [ const AppCircularProgressIndicator(), const SizedBox(height: 24), Padding( padding: const EdgeInsets.symmetric(horizontal: 32), child: Text( l10n.sharePageProgressOverlayHeading, style: theme.textTheme.displayLarge?.copyWith( color: PhotoboothColors.white, fontSize: 32, ), textAlign: TextAlign.center, ), ), const SizedBox(height: 15), Text( l10n.sharePageProgressOverlaySubheading, style: theme.textTheme.displaySmall?.copyWith( color: PhotoboothColors.white, fontSize: 18, ), textAlign: TextAlign.center, ), ], ); } }
photobooth/lib/share/widgets/share_progress_overlay.dart/0
{ "file_path": "photobooth/lib/share/widgets/share_progress_overlay.dart", "repo_id": "photobooth", "token_count": 1662 }
1,038
import 'package:flutter/material.dart'; import 'package:io_photobooth/l10n/l10n.dart'; import 'package:io_photobooth/stickers/stickers.dart'; class ClearStickersDialog extends StatelessWidget { const ClearStickersDialog({ super.key, }); @override Widget build(BuildContext context) { final theme = Theme.of(context); final l10n = context.l10n; return SingleChildScrollView( child: Padding( padding: const EdgeInsets.symmetric( horizontal: 30, vertical: 80, ), child: Column( mainAxisSize: MainAxisSize.min, children: [ Text( l10n.clearStickersDialogHeading, key: const Key('clearStickersDialog_heading'), style: theme.textTheme.displayLarge, textAlign: TextAlign.center, ), const SizedBox(height: 24), Text( l10n.clearStickersDialogSubheading, key: const Key('clearStickersDialog_subheading'), style: theme.textTheme.displaySmall, textAlign: TextAlign.center, ), const SizedBox(height: 48), const Wrap( alignment: WrapAlignment.center, spacing: 30, runSpacing: 15, children: [ ClearStickersCancelButton(), ClearStickersConfirmButton(), ], ), ], ), ), ); } }
photobooth/lib/stickers/widgets/clear_stickers/clear_stickers_dialog.dart/0
{ "file_path": "photobooth/lib/stickers/widgets/clear_stickers/clear_stickers_dialog.dart", "repo_id": "photobooth", "token_count": 752 }
1,039
include: package:very_good_analysis/analysis_options.yaml
photobooth/packages/authentication_repository/analysis_options.yaml/0
{ "file_path": "photobooth/packages/authentication_repository/analysis_options.yaml", "repo_id": "photobooth", "token_count": 16 }
1,040
include: package:very_good_analysis/analysis_options.yaml analyzer: errors: undefined_prefixed_name: ignore linter: rules: public_member_api_docs: false
photobooth/packages/camera/camera_web/analysis_options.yaml/0
{ "file_path": "photobooth/packages/camera/camera_web/analysis_options.yaml", "repo_id": "photobooth", "token_count": 58 }
1,041
@TestOn('!chrome') library; import 'package:flutter_test/flutter_test.dart'; import 'package:image_compositor/image_compositor.dart'; void main() { group('ImageCompositor', () { test('is unsupported in other platforms', () { final compositor = ImageCompositor(); expect( () => compositor.composite( data: '', width: 1, height: 1, layers: [], aspectRatio: 1, ), throwsUnsupportedError, ); }); }); }
photobooth/packages/image_compositor/test/io_image_compositor_test.dart/0
{ "file_path": "photobooth/packages/image_compositor/test/io_image_compositor_test.dart", "repo_id": "photobooth", "token_count": 232 }
1,042
/// Namespace for Default Photobooth Breakpoints abstract class PhotoboothBreakpoints { /// Max width for a small layout. static const double small = 760; /// Max width for a medium layout. static const double medium = 1644; /// Max width for a large layout. static const double large = 1920; }
photobooth/packages/photobooth_ui/lib/src/layout/breakpoints.dart/0
{ "file_path": "photobooth/packages/photobooth_ui/lib/src/layout/breakpoints.dart", "repo_id": "photobooth", "token_count": 81 }
1,043
import 'package:flutter/material.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; /// {@template app_circular_progress_indicator} /// Circular progress indicator /// {@endtemplate} class AppCircularProgressIndicator extends StatelessWidget { /// {@macro app_circular_progress_indicator} const AppCircularProgressIndicator({ super.key, this.color = PhotoboothColors.orange, this.backgroundColor = PhotoboothColors.white, this.strokeWidth = 4.0, }); /// [Color] of the progress indicator final Color color; /// [Color] for the background final Color? backgroundColor; /// Optional stroke width of the progress indicator final double strokeWidth; @override Widget build(BuildContext context) { return CircularProgressIndicator( color: color, backgroundColor: backgroundColor, strokeWidth: strokeWidth, ); } }
photobooth/packages/photobooth_ui/lib/src/widgets/app_circular_progress_indicator.dart/0
{ "file_path": "photobooth/packages/photobooth_ui/lib/src/widgets/app_circular_progress_indicator.dart", "repo_id": "photobooth", "token_count": 280 }
1,044
import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; import 'package:platform_helper/platform_helper.dart'; import '../helpers/helpers.dart'; class MockPlatformHelper extends Mock implements PlatformHelper {} void main() { late PlatformHelper platformHelper; group('showAppModal', () { setUp(() { platformHelper = MockPlatformHelper(); }); testWidgets('renders without platform helper injected', (tester) async { await tester.pumpWidget( MaterialApp( home: Builder( builder: (context) => TextButton( onPressed: () => showAppModal<void>( context: context, portraitChild: const Text('portrait'), landscapeChild: const Text('landscape'), ), child: const Text('open app modal'), ), ), ), ); await tester.tap(find.text('open app modal')); await tester.pumpAndSettle(); expect(tester.takeException(), isNull); }); testWidgets('shows portraitChild on mobile', (tester) async { when(() => platformHelper.isMobile).thenReturn(true); await tester.pumpWidget( MaterialApp( home: Builder( builder: (context) => TextButton( onPressed: () => showAppModal<void>( context: context, platformHelper: platformHelper, portraitChild: const Text('portrait'), landscapeChild: const Text('landscape'), ), child: const Text('open app modal'), ), ), ), ); await tester.tap(find.text('open app modal')); await tester.pumpAndSettle(); expect(find.text('portrait'), findsOneWidget); }); testWidgets('shows portraitChild sheet on portrait', (tester) async { when(() => platformHelper.isMobile).thenReturn(false); tester.setPortraitDisplaySize(); await tester.pumpWidget( MaterialApp( home: Builder( builder: (context) => TextButton( onPressed: () => showAppModal<void>( context: context, platformHelper: platformHelper, portraitChild: const Text('portrait'), landscapeChild: const Text('landscape'), ), child: const Text('open app modal'), ), ), ), ); await tester.tap(find.text('open app modal')); await tester.pumpAndSettle(); expect(find.text('portrait'), findsOneWidget); }); testWidgets('shows landscapeChild when landscape and no mobile', (tester) async { when(() => platformHelper.isMobile).thenReturn(false); tester.setLandscapeDisplaySize(); await tester.pumpWidget( MaterialApp( home: Builder( builder: (context) => TextButton( onPressed: () => showAppModal<void>( context: context, platformHelper: platformHelper, portraitChild: const Text('portrait'), landscapeChild: const Text('landscape'), ), child: const Text('open app modal'), ), ), ), ); await tester.tap(find.text('open app modal')); await tester.pumpAndSettle(); expect(find.text('landscape'), findsOneWidget); }); }); }
photobooth/packages/photobooth_ui/test/src/helpers/modal_helper_test.dart/0
{ "file_path": "photobooth/packages/photobooth_ui/test/src/helpers/modal_helper_test.dart", "repo_id": "photobooth", "token_count": 1614 }
1,045
// ignore_for_file: prefer_const_constructors import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; import 'package:platform_helper/platform_helper.dart'; class MockPlatformHelper extends Mock implements PlatformHelper {} void main() { TestWidgetsFlutterBinding.ensureInitialized(); final childKey = UniqueKey(); const size = Size(300, 300); final child = SizedBox(key: childKey, width: 100, height: 100); late PlatformHelper platformHelper; group('DraggableResizable', () { setUp(() { platformHelper = MockPlatformHelper(); when(() => platformHelper.isMobile).thenReturn(true); }); testWidgets('renders child by (default)', (tester) async { await tester.pumpWidget( MaterialApp(home: DraggableResizable(size: size, child: child)), ); expect(find.byKey(childKey), findsOneWidget); }); group('desktop', () { setUp(() { when(() => platformHelper.isMobile).thenReturn(false); }); testWidgets('renders child as draggable point', (tester) async { await tester.pumpWidget( MaterialApp( home: DraggableResizable( platformHelper: platformHelper, size: size, child: child, ), ), ); expect( find.byKey(Key('draggableResizable_child_draggablePoint')), findsOneWidget, ); }); testWidgets('child is draggable', (tester) async { final onUpdateCalls = <DragUpdate>[]; await tester.pumpWidget( MaterialApp( home: DraggableResizable( platformHelper: platformHelper, onUpdate: onUpdateCalls.add, size: size, child: child, ), ), ); final firstLocation = tester.getCenter( find.byKey(Key('draggableResizable_child_draggablePoint')), ); await tester.dragFrom(firstLocation, const Offset(200, 300)); await tester.pump(kThemeAnimationDuration); final destination = tester.getCenter( find.byKey(Key('draggableResizable_child_draggablePoint')), ); expect(firstLocation == destination, isFalse); expect(onUpdateCalls, isNotEmpty); }); testWidgets( 'top left corner as draggable point renders ' 'when canTransform is true', (tester) async { await tester.pumpWidget( MaterialApp( home: DraggableResizable( platformHelper: platformHelper, canTransform: true, size: size, child: child, ), ), ); expect( find.byKey(Key('draggableResizable_topLeft_resizePoint')), findsOneWidget, ); }); testWidgets( 'top left corner as draggable point does not render ' 'when canTransform is false', (tester) async { await tester.pumpWidget( MaterialApp( home: DraggableResizable( platformHelper: platformHelper, size: size, child: child, ), ), ); expect( find.byKey(Key('draggableResizable_topLeft_resizePoint')), findsNothing, ); }); testWidgets('top left corner point can resize child', (tester) async { final onUpdateCalls = <DragUpdate>[]; await tester.pumpWidget( MaterialApp( home: Stack( children: [ DraggableResizable( platformHelper: platformHelper, onUpdate: onUpdateCalls.add, canTransform: true, size: size, child: child, ), ], ), ), ); final resizePointFinder = find.byKey( Key('draggableResizable_topLeft_resizePoint'), ); final childFinder = find.byKey( const Key('draggableResizable_child_container'), ); final originalSize = tester.getSize(childFinder); final firstLocation = tester.getCenter(resizePointFinder); await tester.flingFrom( firstLocation, Offset(firstLocation.dx - 1, firstLocation.dy - 1), 3, ); await tester.pump(kThemeAnimationDuration); final newSize = tester.getSize(childFinder); expect(originalSize == newSize, isFalse); expect(onUpdateCalls, isNotEmpty); }); testWidgets( 'top right corner as draggable point renders ' 'when canTransform is true', (tester) async { await tester.pumpWidget( MaterialApp( home: Stack( children: [ DraggableResizable( platformHelper: platformHelper, canTransform: true, size: size, child: child, ), ], ), ), ); expect( find.byKey(Key('draggableResizable_topRight_resizePoint')), findsOneWidget, ); }); testWidgets( 'top right corner as draggable point does not render ' 'when canTransform is false', (tester) async { await tester.pumpWidget( MaterialApp( home: Stack( children: [ DraggableResizable( platformHelper: platformHelper, size: size, child: child, ), ], ), ), ); expect( find.byKey(Key('draggableResizable_topRight_resizePoint')), findsNothing, ); }); testWidgets('top right corner point can resize child', (tester) async { final onUpdateCalls = <DragUpdate>[]; await tester.pumpWidget( MaterialApp( home: Stack( children: [ DraggableResizable( platformHelper: platformHelper, onUpdate: onUpdateCalls.add, canTransform: true, size: size, child: child, ), ], ), ), ); final resizePointFinder = find.byKey( Key('draggableResizable_topRight_resizePoint'), ); final childFinder = find.byKey( const Key('draggableResizable_child_container'), ); final originalSize = tester.getSize(childFinder); final firstLocation = tester.getCenter(resizePointFinder); await tester.flingFrom( firstLocation, Offset(firstLocation.dx + 10, firstLocation.dy + 10), 3, ); await tester.pump(kThemeAnimationDuration); final newSize = tester.getSize(childFinder); expect(originalSize == newSize, isFalse); expect(onUpdateCalls, isNotEmpty); }); testWidgets( 'bottom right corner as draggable point renders ' 'when canTransform is true', (tester) async { await tester.pumpWidget( MaterialApp( home: Stack( children: [ DraggableResizable( platformHelper: platformHelper, canTransform: true, size: size, child: child, ), ], ), ), ); expect( find.byKey(Key('draggableResizable_bottomRight_resizePoint')), findsOneWidget, ); }); testWidgets( 'bottom right corner as draggable point does not render ' 'when canTransform is false', (tester) async { await tester.pumpWidget( MaterialApp( home: Stack( children: [ DraggableResizable( platformHelper: platformHelper, size: size, child: child, ), ], ), ), ); expect( find.byKey(Key('draggableResizable_bottomRight_resizePoint')), findsNothing, ); }); testWidgets('bottom right corner point can resize child', (tester) async { final onUpdateCalls = <DragUpdate>[]; await tester.pumpWidget( MaterialApp( home: Stack( children: [ DraggableResizable( platformHelper: platformHelper, onUpdate: onUpdateCalls.add, canTransform: true, size: size, child: child, ), ], ), ), ); final resizePointFinder = find.byKey( Key('draggableResizable_bottomRight_resizePoint'), ); final childFinder = find.byKey( const Key('draggableResizable_child_container'), ); final originalSize = tester.getSize(childFinder); final firstLocation = tester.getCenter(resizePointFinder); await tester.flingFrom( firstLocation, Offset(firstLocation.dx + 10, firstLocation.dy + 10), 3, ); await tester.pump(kThemeAnimationDuration); final newSize = tester.getSize(childFinder); expect(originalSize == newSize, isFalse); expect(onUpdateCalls, isNotEmpty); }); testWidgets( 'bottom left corner as draggable point renders ' 'when canTransform is true', (tester) async { await tester.pumpWidget( MaterialApp( home: Stack( children: [ DraggableResizable( platformHelper: platformHelper, canTransform: true, size: size, child: child, ), ], ), ), ); expect( find.byKey(Key('draggableResizable_bottomLeft_resizePoint')), findsOneWidget, ); }); testWidgets( 'bottom left corner as draggable point does not render ' 'when canTransform is false', (tester) async { await tester.pumpWidget( MaterialApp( home: Stack( children: [ DraggableResizable( platformHelper: platformHelper, size: size, child: child, ), ], ), ), ); expect( find.byKey(Key('draggableResizable_bottomLeft_resizePoint')), findsNothing, ); }); testWidgets('bottom left corner point can resize child', (tester) async { final onUpdateCalls = <DragUpdate>[]; await tester.pumpWidget( MaterialApp( home: Stack( children: [ DraggableResizable( platformHelper: platformHelper, onUpdate: onUpdateCalls.add, canTransform: true, size: size, child: child, ), ], ), ), ); final resizePointFinder = find.byKey( Key('draggableResizable_bottomLeft_resizePoint'), ); final childFinder = find.byKey( const Key('draggableResizable_child_container'), ); final originalSize = tester.getSize(childFinder); final firstLocation = tester.getCenter(resizePointFinder); await tester.flingFrom( firstLocation, Offset(firstLocation.dx + 10, firstLocation.dy + 10), 3, ); await tester.pump(kThemeAnimationDuration); final newSize = tester.getSize(childFinder); expect(originalSize == newSize, isFalse); expect(onUpdateCalls, isNotEmpty); }); testWidgets('delete button does not render when canTransform is false', (tester) async { await tester.pumpWidget( MaterialApp( home: DraggableResizable( platformHelper: platformHelper, onDelete: () {}, size: size, child: child, ), ), ); expect( find.byKey(Key('draggableResizable_delete_floatingActionIcon')), findsNothing, ); }); testWidgets( 'delete button does not render when ' 'there is delete callback', (tester) async { await tester.pumpWidget( MaterialApp( home: DraggableResizable( platformHelper: platformHelper, size: size, child: child, ), ), ); expect( find.byKey(Key('draggableResizable_delete_floatingActionIcon')), findsNothing, ); }); testWidgets( 'delete button renders when canTransform is true and ' 'has delete callback', (tester) async { await tester.pumpWidget( MaterialApp( home: DraggableResizable( platformHelper: platformHelper, canTransform: true, onDelete: () {}, size: size, child: child, ), ), ); expect( find.byKey(Key('draggableResizable_delete_floatingActionIcon')), findsOneWidget, ); }); testWidgets('rotate anchor rotates asset', (tester) async { await tester.pumpWidget( MaterialApp( home: DraggableResizable( platformHelper: platformHelper, canTransform: true, size: size, child: child, ), ), ); final gestureDetector = tester.widget<GestureDetector>( find.byKey(Key('draggableResizable_rotate_gestureDetector')), ); gestureDetector.onScaleStart!( ScaleStartDetails(localFocalPoint: Offset(0, 0)), ); gestureDetector.onScaleUpdate!( ScaleUpdateDetails(localFocalPoint: Offset(1, 1)), ); gestureDetector.onScaleEnd!(ScaleEndDetails()); await tester.pumpAndSettle(); final childFinder = find.byKey( Key('draggableResizable_child_draggablePoint'), ); final transformFinder = find.ancestor( of: childFinder, matching: find.byType(Transform), ); final transformWidget = tester.widget<Transform>(transformFinder); expect( transformWidget.transform, isNot(equals(Matrix4.diagonal3Values(1, 1, 1))), ); }); testWidgets('tapping on rotate icon does nothing', (tester) async { await tester.pumpWidget( MaterialApp( home: DraggableResizable( platformHelper: platformHelper, canTransform: true, size: size, child: child, ), ), ); await tester.tap( find.byKey(Key('draggableResizable_rotate_floatingActionIcon')), ); await tester.pumpAndSettle(); expect(tester.takeException(), isNull); }); }); group('mobile', () { setUp(() { when(() => platformHelper.isMobile).thenReturn(true); }); testWidgets('is draggable', (tester) async { final onUpdateCalls = <DragUpdate>[]; await tester.pumpWidget( MaterialApp( home: Stack( children: [ DraggableResizable( onUpdate: onUpdateCalls.add, canTransform: true, platformHelper: platformHelper, size: size, child: child, ), ], ), ), ); final childFinder = find.byKey( Key('draggableResizable_child_draggablePoint'), ); final origin = tester.getCenter(childFinder); final offset = Offset(30, 30); await tester.drag(childFinder, offset); await tester.pumpAndSettle(); final destination = tester.getCenter(childFinder); expect(origin == destination, isFalse); expect(onUpdateCalls, isNotEmpty); }); testWidgets('is resizable', (tester) async { final onUpdateCalls = <DragUpdate>[]; await tester.pumpWidget( MaterialApp( home: Stack( children: [ DraggableResizable( onUpdate: onUpdateCalls.add, canTransform: true, platformHelper: platformHelper, size: size, child: child, ), ], ), ), ); final childFinder = find.byKey( Key('draggableResizable_child_draggablePoint'), ); final gestureDetectorFinder = find.descendant( of: childFinder, matching: find.byType(GestureDetector), ); final gestureDetector = tester.widget<GestureDetector>(gestureDetectorFinder); gestureDetector.onScaleStart!(ScaleStartDetails(pointerCount: 2)); gestureDetector.onScaleUpdate!( ScaleUpdateDetails(scale: 2, pointerCount: 2), ); await tester.pumpAndSettle(); expect(onUpdateCalls, isNotEmpty); }); testWidgets('is rotatable', (tester) async { final onUpdateCalls = <DragUpdate>[]; await tester.pumpWidget( MaterialApp( home: Stack( children: [ DraggableResizable( onUpdate: onUpdateCalls.add, canTransform: true, platformHelper: platformHelper, size: size, child: child, ), ], ), ), ); final childFinder = find.byKey( Key('draggableResizable_child_draggablePoint'), ); final gestureDetectorFinder = find.descendant( of: childFinder, matching: find.byType(GestureDetector), ); final gestureDetector = tester.widget<GestureDetector>(gestureDetectorFinder); gestureDetector.onScaleStart!(ScaleStartDetails(pointerCount: 2)); gestureDetector.onScaleUpdate!( ScaleUpdateDetails(rotation: 2, pointerCount: 2), ); await tester.pumpAndSettle(); final transformFinder = find.ancestor( of: childFinder, matching: find.byType(Transform), ); final transformWidget = tester.widget<Transform>(transformFinder); expect( transformWidget.transform, isNot(equals(Matrix4.diagonal3Values(1, 1, 1))), ); expect(onUpdateCalls, isNotEmpty); }); testWidgets('rotation is continuous', (tester) async { final onUpdateCalls = <DragUpdate>[]; await tester.pumpWidget( MaterialApp( home: Stack( children: [ DraggableResizable( onUpdate: onUpdateCalls.add, canTransform: true, platformHelper: platformHelper, size: size, child: child, ), ], ), ), ); final childFinder = find.byKey( Key('draggableResizable_child_draggablePoint'), ); final gestureDetectorFinder = find.descendant( of: childFinder, matching: find.byType(GestureDetector), ); final gestureDetector = tester.widget<GestureDetector>(gestureDetectorFinder); gestureDetector.onScaleStart!(ScaleStartDetails(pointerCount: 2)); gestureDetector.onScaleUpdate!( ScaleUpdateDetails(rotation: 2, pointerCount: 2), ); await tester.pumpAndSettle(); final transformFinder = find.ancestor( of: childFinder, matching: find.byType(Transform), ); final transformA = tester.widget<Transform>(transformFinder).transform; gestureDetector.onScaleStart!(ScaleStartDetails(pointerCount: 2)); gestureDetector.onScaleUpdate!( ScaleUpdateDetails(rotation: 2, pointerCount: 2), ); await tester.pumpAndSettle(); final transformB = tester.widget<Transform>(transformFinder).transform; expect(transformA, isNot(equals(transformB))); }); }); }); }
photobooth/packages/photobooth_ui/test/src/widgets/draggable_resizable_test.dart/0
{ "file_path": "photobooth/packages/photobooth_ui/test/src/widgets/draggable_resizable_test.dart", "repo_id": "photobooth", "token_count": 10622 }
1,046
/// IO Implementation of [PlatformHelper] class PlatformHelper { /// Returns whether the current platform is running on a mobile device. bool get isMobile => true; }
photobooth/packages/platform_helper/lib/src/mobile.dart/0
{ "file_path": "photobooth/packages/platform_helper/lib/src/mobile.dart", "repo_id": "photobooth", "token_count": 40 }
1,047
import 'package:bloc_test/bloc_test.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:io_photobooth/l10n/l10n.dart'; import 'package:io_photobooth/photobooth/photobooth.dart'; import 'package:io_photobooth/share/share.dart'; import 'package:mocktail/mocktail.dart'; import 'package:mocktail_image_network/mocktail_image_network.dart'; import 'package:photos_repository/photos_repository.dart'; class MockPhotoboothBloc extends MockBloc<PhotoboothEvent, PhotoboothState> implements PhotoboothBloc {} class FakePhotoboothEvent extends Fake implements PhotoboothEvent {} class FakePhotoboothState extends Fake implements PhotoboothState {} class MockShareBloc extends MockBloc<ShareEvent, ShareState> implements ShareBloc {} class FakeShareEvent extends Fake implements ShareEvent {} class FakeShareState extends Fake implements ShareState {} class MockPhotosRepository extends Mock implements PhotosRepository {} extension PumpApp on WidgetTester { Future<void> pumpApp( Widget widget, { PhotosRepository? photosRepository, PhotoboothBloc? photoboothBloc, ShareBloc? shareBloc, }) async { registerFallbackValue(FakePhotoboothEvent()); registerFallbackValue(FakePhotoboothState()); registerFallbackValue(FakeShareEvent()); registerFallbackValue(FakeShareState()); return mockNetworkImages(() async { return pumpWidget( RepositoryProvider.value( value: photosRepository ?? MockPhotosRepository(), child: MultiBlocProvider( providers: [ BlocProvider.value(value: photoboothBloc ?? MockPhotoboothBloc()), BlocProvider.value(value: shareBloc ?? MockShareBloc()), ], child: MaterialApp( localizationsDelegates: const [ AppLocalizations.delegate, GlobalMaterialLocalizations.delegate, ], supportedLocales: AppLocalizations.supportedLocales, home: widget, ), ), ), ); }); } }
photobooth/test/helpers/pump_app.dart/0
{ "file_path": "photobooth/test/helpers/pump_app.dart", "repo_id": "photobooth", "token_count": 838 }
1,048
// ignore_for_file: prefer_const_constructors import 'package:bloc_test/bloc_test.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:io_photobooth/assets.g.dart'; import 'package:io_photobooth/photobooth/photobooth.dart'; import 'package:io_photobooth/stickers/stickers.dart'; import 'package:mocktail/mocktail.dart'; import '../../../helpers/helpers.dart'; class FakeStickersEvent extends Fake implements StickersEvent {} class FakeStickersState extends Fake implements StickersState {} class MockStickersBloc extends MockBloc<StickersEvent, StickersState> implements StickersBloc {} class FakePhotoboothEvent extends Fake implements PhotoboothEvent {} class FakePhotoboothState extends Fake implements PhotoboothState {} class MockPhotoboothBloc extends MockBloc<PhotoboothEvent, PhotoboothState> implements PhotoboothBloc {} void main() { TestWidgetsFlutterBinding.ensureInitialized(); setUpAll(() { registerFallbackValue(FakeStickersEvent()); registerFallbackValue(FakeStickersState()); registerFallbackValue(FakePhotoboothEvent()); registerFallbackValue(FakePhotoboothState()); }); group('StickersDrawerLayer', () { late PhotoboothBloc photoboothBloc; late StickersBloc stickersBloc; setUp(() { photoboothBloc = MockPhotoboothBloc(); stickersBloc = MockStickersBloc(); }); group('DesktopStickersDrawer', () { testWidgets( 'does not render DesktopStickersDrawer when ' 'drawer is inactive', (tester) async { when(() => stickersBloc.state).thenReturn( StickersState(), ); await tester.pumpApp( BlocProvider.value( value: stickersBloc, child: Scaffold( body: Stack(children: const [StickersDrawerLayer()]), ), ), photoboothBloc: photoboothBloc, ); expect(find.byType(DesktopStickersDrawer), findsNothing); }); testWidgets( 'renders DesktopStickersDrawer when ' 'width greater than mobile breakpoint and it is drawer active', (tester) async { when(() => stickersBloc.state).thenReturn( StickersState(isDrawerActive: true), ); tester.setLandscapeDisplaySize(); await tester.pumpApp( BlocProvider.value( value: stickersBloc, child: Scaffold( body: Stack(children: const [StickersDrawerLayer()]), ), ), photoboothBloc: photoboothBloc, ); expect(find.byType(DesktopStickersDrawer), findsOneWidget); }); testWidgets( 'does not render DesktopStickersDrawer when ' 'width smaller than mobile and it is drawer active', (tester) async { when(() => stickersBloc.state).thenReturn( StickersState(isDrawerActive: true), ); tester.setSmallDisplaySize(); await tester.pumpApp( BlocProvider.value( value: stickersBloc, child: Scaffold( body: Stack(children: const [StickersDrawerLayer()]), ), ), photoboothBloc: photoboothBloc, ); expect(find.byType(DesktopStickersDrawer), findsNothing); }); testWidgets('adds StickerSelected when StickerChoice tapped', (tester) async { final sticker = Assets.props.first; when(() => stickersBloc.state).thenReturn( StickersState(isDrawerActive: true), ); tester.setLandscapeDisplaySize(); when(() => photoboothBloc.state).thenReturn( PhotoboothState(stickers: [PhotoAsset(id: '0', asset: sticker)]), ); await tester.pumpApp( BlocProvider.value( value: stickersBloc, child: Scaffold( body: Stack(children: const [StickersDrawerLayer()]), ), ), photoboothBloc: photoboothBloc, ); final stickerChoice = tester.widgetList<StickerChoice>(find.byType(StickerChoice)).first; stickerChoice.onPressed(); await tester.pump(); verify( () => photoboothBloc.add(PhotoStickerTapped(sticker: sticker)), ).called(1); verify(() => stickersBloc.add(StickersDrawerToggled())).called(1); }); testWidgets('adds StickersDrawerTabTapped when tab is selected', (tester) async { final sticker = Assets.props.first; when(() => stickersBloc.state).thenReturn( StickersState(isDrawerActive: true), ); tester.setLandscapeDisplaySize(); when(() => photoboothBloc.state).thenReturn( PhotoboothState(stickers: [PhotoAsset(id: '0', asset: sticker)]), ); await tester.pumpApp( BlocProvider.value( value: stickersBloc, child: Scaffold( body: Stack(children: const [StickersDrawerLayer()]), ), ), photoboothBloc: photoboothBloc, ); await tester.tap(find.byKey(Key('stickersTabs_eyewearTab'))); verify( () => stickersBloc.add(StickersDrawerTabTapped(index: 2)), ).called(1); }); testWidgets('can be closed', (tester) async { var onCloseTappedCallCount = 0; await tester.pumpApp( Scaffold( body: DesktopStickersDrawer( initialIndex: 0, onTabChanged: (_) {}, onStickerSelected: (_) {}, onCloseTapped: () => onCloseTappedCallCount++, bucket: PageStorageBucket(), ), ), ); await tester .ensureVisible(find.byKey(Key('stickersDrawer_close_iconButton'))); await tester.tap(find.byKey(Key('stickersDrawer_close_iconButton'))); await tester.pump(); expect(onCloseTappedCallCount, equals(1)); }); }); group('MobileStickersDrawer', () { testWidgets( 'opens MobileStickersDrawer when ' 'is active and width smaller than mobile breakpoint', (tester) async { whenListen( stickersBloc, Stream.fromIterable([StickersState(isDrawerActive: true)]), initialState: StickersState(), ); tester.setSmallDisplaySize(); await tester.pumpApp( BlocProvider.value(value: stickersBloc, child: StickersDrawerLayer()), photoboothBloc: photoboothBloc, ); await tester.pump(); expect(find.byType(MobileStickersDrawer), findsOneWidget); tester.widget<IconButton>(find.byType(IconButton)).onPressed!(); await tester.pumpAndSettle(); }); testWidgets( 'does not open MobileStickersDrawer when ' 'width greater than mobile breakpoint', (tester) async { whenListen( stickersBloc, Stream.fromIterable([StickersState(isDrawerActive: true)]), initialState: StickersState(), ); tester.setLandscapeDisplaySize(); await tester.pumpApp( BlocProvider.value( value: stickersBloc, child: Scaffold( body: Stack(children: const [StickersDrawerLayer()]), ), ), photoboothBloc: photoboothBloc, ); await tester.pump(); expect(find.byType(MobileStickersDrawer), findsNothing); tester.widget<IconButton>(find.byType(IconButton)).onPressed!(); await tester.pump(); }); testWidgets('can select stickers on MobileStickersDrawer', (tester) async { final sticker = Assets.props.first; whenListen( stickersBloc, Stream.fromIterable([StickersState(isDrawerActive: true)]), initialState: StickersState(), ); tester.setSmallDisplaySize(); await tester.pumpApp( BlocProvider.value(value: stickersBloc, child: StickersDrawerLayer()), photoboothBloc: photoboothBloc, ); await tester.pump(); expect(find.byType(MobileStickersDrawer), findsOneWidget); final stickerChoice = tester.widgetList<StickerChoice>(find.byType(StickerChoice)).first; stickerChoice.onPressed(); await tester.pumpAndSettle(); verify( () => photoboothBloc.add(PhotoStickerTapped(sticker: sticker)), ).called(1); expect(find.byType(MobileStickersDrawer), findsNothing); }); testWidgets('can change tabs on MobileStickersDrawer', (tester) async { whenListen( stickersBloc, Stream.fromIterable([StickersState(isDrawerActive: true)]), initialState: StickersState(), ); tester.setSmallDisplaySize(); await tester.pumpApp( BlocProvider.value( value: stickersBloc, child: Scaffold(body: StickersDrawerLayer()), ), photoboothBloc: photoboothBloc, ); await tester.pump(); expect(find.byType(MobileStickersDrawer), findsOneWidget); final tabBar = tester.widget<TabBar>(find.byType(TabBar)); tabBar.onTap!(4); verify( () => stickersBloc.add(StickersDrawerTabTapped(index: 4)), ).called(1); final closeButtonFinder = find.byKey( Key('stickersDrawer_close_iconButton'), ); tester.widget<IconButton>(closeButtonFinder).onPressed!(); await tester.pumpAndSettle(); }); testWidgets('can close MobileStickersDrawer', (tester) async { whenListen( stickersBloc, Stream.fromIterable([StickersState(isDrawerActive: true)]), initialState: StickersState(), ); tester.setSmallDisplaySize(); await tester.pumpApp( BlocProvider.value( value: stickersBloc, child: StickersDrawerLayer(), ), photoboothBloc: photoboothBloc, ); await tester.pump(); expect(find.byType(MobileStickersDrawer), findsOneWidget); final closeButtonFinder = find.byKey( Key('stickersDrawer_close_iconButton'), ); tester.widget<IconButton>(closeButtonFinder).onPressed!(); await tester.pumpAndSettle(); expect(find.byType(MobileStickersDrawer), findsNothing); verify(() => stickersBloc.add(StickersDrawerToggled())).called(1); }); }); }); }
photobooth/test/stickers/widgets/stickers_drawer_layer/stickers_drawer_layer_test.dart/0
{ "file_path": "photobooth/test/stickers/widgets/stickers_drawer_layer/stickers_drawer_layer_test.dart", "repo_id": "photobooth", "token_count": 4798 }
1,049
import 'package:flame/components.dart'; import 'package:flame_bloc/flame_bloc.dart'; import 'package:pinball/select_character/select_character.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; import 'package:platform_helper/platform_helper.dart'; /// Updates the [ArcadeBackground] and launch [Ball] to reflect character /// selections. class CharacterSelectionBehavior extends Component with FlameBlocListenable<CharacterThemeCubit, CharacterThemeState>, HasGameRef { @override void onNewState(CharacterThemeState state) { if (!readProvider<PlatformHelper>().isMobile) { gameRef .descendants() .whereType<ArcadeBackground>() .single .bloc .onCharacterSelected(state.characterTheme); } gameRef .descendants() .whereType<Ball>() .single .bloc .onCharacterSelected(state.characterTheme); } }
pinball/lib/game/behaviors/character_selection_behavior.dart/0
{ "file_path": "pinball/lib/game/behaviors/character_selection_behavior.dart", "repo_id": "pinball", "token_count": 380 }
1,050
import 'dart:async'; import 'package:flame/components.dart'; import 'package:flutter/material.dart'; import 'package:leaderboard_repository/leaderboard_repository.dart'; import 'package:pinball/game/components/backbox/bloc/backbox_bloc.dart'; import 'package:pinball/game/components/backbox/displays/displays.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball/l10n/l10n.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; import 'package:pinball_theme/pinball_theme.dart' hide Assets; import 'package:pinball_ui/pinball_ui.dart'; import 'package:platform_helper/platform_helper.dart'; import 'package:share_repository/share_repository.dart'; /// {@template backbox} /// The [Backbox] of the pinball machine. /// {@endtemplate} class Backbox extends PositionComponent with ZIndex, HasGameRef { /// {@macro backbox} Backbox({ required LeaderboardRepository leaderboardRepository, required ShareRepository shareRepository, required List<LeaderboardEntryData>? entries, }) : _bloc = BackboxBloc( leaderboardRepository: leaderboardRepository, initialEntries: entries, ), _shareRepository = shareRepository; /// {@macro backbox} @visibleForTesting Backbox.test({ required BackboxBloc bloc, required ShareRepository shareRepository, }) : _bloc = bloc, _shareRepository = shareRepository; final ShareRepository _shareRepository; late final Component _display; final BackboxBloc _bloc; late StreamSubscription<BackboxState> _subscription; @override Future<void> onLoad() async { position = Vector2(0, -87); anchor = Anchor.bottomCenter; zIndex = ZIndexes.backbox; await add(_BackboxSpriteComponent()); await add(_display = Component()); _build(_bloc.state); _subscription = _bloc.stream.listen((state) { _display.children.removeWhere((_) => true); _build(state); }); } @override void onRemove() { super.onRemove(); _subscription.cancel(); } void _build(BackboxState state) { if (state is LoadingState) { _display.add(LoadingDisplay()); } else if (state is LeaderboardSuccessState) { _display.add(LeaderboardDisplay(entries: state.entries)); } else if (state is LeaderboardFailureState) { _display.add(LeaderboardFailureDisplay()); } else if (state is InitialsFormState) { if (readProvider<PlatformHelper>().isMobile) { gameRef.overlays.add(PinballGame.mobileControlsOverlay); } _display.add( InitialsInputDisplay( score: state.score, characterIconPath: state.character.leaderboardIcon.keyName, onSubmit: (initials) { _bloc.add( PlayerInitialsSubmitted( score: state.score, initials: initials, character: state.character, ), ); }, ), ); } else if (state is InitialsSuccessState) { gameRef.overlays.remove(PinballGame.mobileControlsOverlay); _display.add( GameOverInfoDisplay( onShare: () { _bloc.add(ShareScoreRequested(score: state.score)); }, ), ); } else if (state is ShareState) { _display.add( ShareDisplay( onShare: (platform) { final message = readProvider<AppLocalizations>() .iGotScoreAtPinball(state.score.formatScore()); final url = _shareRepository.shareText( value: message, platform: platform, ); openLink(url); }, ), ); } else if (state is InitialsFailureState) { _display.add( InitialsSubmissionFailureDisplay( onDismissed: () { _bloc.add( PlayerInitialsRequested( score: state.score, character: state.character, ), ); }, ), ); } } /// Puts [InitialsInputDisplay] on the [Backbox]. void requestInitials({ required int score, required CharacterTheme character, }) { _bloc.add( PlayerInitialsRequested( score: score, character: character, ), ); } } class _BackboxSpriteComponent extends SpriteComponent with HasGameRef { _BackboxSpriteComponent() : super(anchor: Anchor.bottomCenter); @override Future<void> onLoad() async { await super.onLoad(); final sprite = Sprite( gameRef.images.fromCache( Assets.images.backbox.marquee.keyName, ), ); this.sprite = sprite; size = sprite.originalSize / 20; } }
pinball/lib/game/components/backbox/backbox.dart/0
{ "file_path": "pinball/lib/game/components/backbox/backbox.dart", "repo_id": "pinball", "token_count": 1980 }
1,051
import 'package:flame/components.dart'; import 'package:flame_bloc/flame_bloc.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; /// Adds a [GameBonus.dinoChomp] when a [Ball] is chomped by the [ChromeDino]. class ChromeDinoBonusBehavior extends Component with ParentIsA<DinoDesert>, FlameBlocReader<GameBloc, GameState> { @override void onMount() { super.onMount(); final chromeDino = parent.firstChild<ChromeDino>()!; chromeDino.bloc.stream.listen((state) { final listenWhen = state.status == ChromeDinoStatus.chomping; if (!listenWhen) return; bloc.add(const BonusActivated(GameBonus.dinoChomp)); }); } }
pinball/lib/game/components/dino_desert/behaviors/chrome_dino_bonus_behavior.dart/0
{ "file_path": "pinball/lib/game/components/dino_desert/behaviors/chrome_dino_bonus_behavior.dart", "repo_id": "pinball", "token_count": 284 }
1,052
export 'multipliers_behavior.dart';
pinball/lib/game/components/multipliers/behaviors/behaviors.dart/0
{ "file_path": "pinball/lib/game/components/multipliers/behaviors/behaviors.dart", "repo_id": "pinball", "token_count": 11 }
1,053
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball/l10n/l10n.dart'; import 'package:pinball/start_game/start_game.dart'; import 'package:pinball_ui/pinball_ui.dart'; /// {@template replay_button_overlay} /// [Widget] that renders the button responsible for restarting the game. /// {@endtemplate} class ReplayButtonOverlay extends StatelessWidget { /// {@macro replay_button_overlay} const ReplayButtonOverlay({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final l10n = context.l10n; return PinballButton( text: l10n.replay, onTap: () { context.read<GameBloc>().add(const GameStarted()); context.read<StartGameBloc>().add(const ReplayTapped()); }, ); } }
pinball/lib/game/view/widgets/replay_button_overlay.dart/0
{ "file_path": "pinball/lib/game/view/widgets/replay_button_overlay.dart", "repo_id": "pinball", "token_count": 315 }
1,054
part of 'character_theme_cubit.dart'; class CharacterThemeState extends Equatable { const CharacterThemeState(this.characterTheme); const CharacterThemeState.initial() : characterTheme = const DashTheme(); final CharacterTheme characterTheme; bool get isSparkySelected => characterTheme == const SparkyTheme(); bool get isDashSelected => characterTheme == const DashTheme(); bool get isAndroidSelected => characterTheme == const AndroidTheme(); bool get isDinoSelected => characterTheme == const DinoTheme(); @override List<Object> get props => [characterTheme]; }
pinball/lib/select_character/cubit/character_theme_state.dart/0
{ "file_path": "pinball/lib/select_character/cubit/character_theme_state.dart", "repo_id": "pinball", "token_count": 150 }
1,055
import 'package:authentication_repository/authentication_repository.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; class _MockFirebaseAuth extends Mock implements FirebaseAuth {} class _MockUserCredential extends Mock implements UserCredential {} void main() { late FirebaseAuth firebaseAuth; late UserCredential userCredential; late AuthenticationRepository authenticationRepository; group('AuthenticationRepository', () { setUp(() { firebaseAuth = _MockFirebaseAuth(); userCredential = _MockUserCredential(); authenticationRepository = AuthenticationRepository(firebaseAuth); }); group('authenticateAnonymously', () { test('completes if no exception is thrown', () async { when(() => firebaseAuth.signInAnonymously()) .thenAnswer((_) async => userCredential); await authenticationRepository.authenticateAnonymously(); verify(() => firebaseAuth.signInAnonymously()).called(1); }); test('throws AuthenticationException when firebase auth fails', () async { when(() => firebaseAuth.signInAnonymously()) .thenThrow(Exception('oops')); expect( () => authenticationRepository.authenticateAnonymously(), throwsA(isA<AuthenticationException>()), ); }); }); }); }
pinball/packages/authentication_repository/test/src/authentication_repository_test.dart/0
{ "file_path": "pinball/packages/authentication_repository/test/src/authentication_repository_test.dart", "repo_id": "pinball", "token_count": 503 }
1,056
export 'exceptions.dart'; export 'leaderboard_entry_data.dart';
pinball/packages/leaderboard_repository/lib/src/models/models.dart/0
{ "file_path": "pinball/packages/leaderboard_repository/lib/src/models/models.dart", "repo_id": "pinball", "token_count": 22 }
1,057
import 'package:bloc/bloc.dart'; part 'android_bumper_state.dart'; class AndroidBumperCubit extends Cubit<AndroidBumperState> { AndroidBumperCubit() : super(AndroidBumperState.lit); void onBallContacted() { emit(AndroidBumperState.dimmed); } void onBlinked() { emit(AndroidBumperState.lit); } }
pinball/packages/pinball_components/lib/src/components/android_bumper/cubit/android_bumper_cubit.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/android_bumper/cubit/android_bumper_cubit.dart", "repo_id": "pinball", "token_count": 117 }
1,058
part of 'ball_cubit.dart'; class BallState extends Equatable { const BallState({required this.characterTheme}); const BallState.initial() : this(characterTheme: const DashTheme()); final CharacterTheme characterTheme; @override List<Object> get props => [characterTheme]; }
pinball/packages/pinball_components/lib/src/components/ball/cubit/ball_state.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/ball/cubit/ball_state.dart", "repo_id": "pinball", "token_count": 80 }
1,059
export 'android_animatronic/android_animatronic.dart'; export 'android_bumper/android_bumper.dart'; export 'android_spaceship/android_spaceship.dart'; export 'arcade_background/arcade_background.dart'; export 'arrow_icon.dart'; export 'ball/ball.dart'; export 'baseboard.dart'; export 'board_background_sprite_component.dart'; export 'board_dimensions.dart'; export 'board_side.dart'; export 'boundaries.dart'; export 'camera_zoom.dart'; export 'chrome_dino/chrome_dino.dart'; export 'dash_animatronic.dart'; export 'dash_bumper/dash_bumper.dart'; export 'dino_walls.dart'; export 'error_component.dart'; export 'flapper/flapper.dart'; export 'flipper/flipper.dart'; export 'google_letter.dart'; export 'google_rollover/google_rollover.dart'; export 'google_word/google_word.dart'; export 'initial_position.dart'; export 'joint_anchor.dart'; export 'kicker/kicker.dart'; export 'launch_ramp.dart'; export 'layer_sensor/layer_sensor.dart'; export 'multiball/multiball.dart'; export 'multiplier/multiplier.dart'; export 'plunger/plunger.dart'; export 'rocket.dart'; export 'score_component/score_component.dart'; export 'signpost/signpost.dart'; export 'skill_shot/skill_shot.dart'; export 'slingshot.dart'; export 'spaceship_rail.dart'; export 'spaceship_ramp/spaceship_ramp.dart'; export 'sparky_animatronic.dart'; export 'sparky_bumper/sparky_bumper.dart'; export 'sparky_computer/sparky_computer.dart'; export 'z_indexes.dart';
pinball/packages/pinball_components/lib/src/components/components.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/components.dart", "repo_id": "pinball", "token_count": 537 }
1,060
import 'package:flame/components.dart'; import 'package:flame_bloc/flame_bloc.dart'; import 'package:pinball_audio/pinball_audio.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; class FlipperNoiseBehavior extends Component with FlameBlocListenable<FlipperCubit, FlipperState>, FlameBlocReader<FlipperCubit, FlipperState> { @override void onNewState(FlipperState state) { super.onNewState(state); if (bloc.state.isMovingUp) { readProvider<PinballAudioPlayer>().play(PinballAudio.flipper); } } }
pinball/packages/pinball_components/lib/src/components/flipper/behaviors/flipper_noise_behavior.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/flipper/behaviors/flipper_noise_behavior.dart", "repo_id": "pinball", "token_count": 232 }
1,061
import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; class KickerBallContactBehavior extends ContactBehavior<Kicker> { @override void beginContact(Object other, Contact contact) { super.beginContact(other, contact); if (other is! Ball) return; parent.bloc.onBallContacted(); } }
pinball/packages/pinball_components/lib/src/components/kicker/behaviors/kicker_ball_contact_behavior.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/kicker/behaviors/kicker_ball_contact_behavior.dart", "repo_id": "pinball", "token_count": 139 }
1,062
import 'package:flame/components.dart'; import 'package:flutter/material.dart'; import 'package:pinball_components/gen/assets.gen.dart'; import 'package:pinball_components/src/components/multiplier/cubit/multiplier_cubit.dart'; import 'package:pinball_flame/pinball_flame.dart'; export 'cubit/multiplier_cubit.dart'; /// {@template multiplier} /// Backlit multiplier decal displayed on the board. /// {@endtemplate} class Multiplier extends Component { /// {@macro multiplier} Multiplier._({ required MultiplierValue value, required Vector2 position, required double angle, required this.bloc, }) : _value = value, _position = position, _angle = angle, super(); /// {@macro multiplier} Multiplier.x2({ required Vector2 position, required double angle, }) : this._( value: MultiplierValue.x2, position: position, angle: angle, bloc: MultiplierCubit(MultiplierValue.x2), ); /// {@macro multiplier} Multiplier.x3({ required Vector2 position, required double angle, }) : this._( value: MultiplierValue.x3, position: position, angle: angle, bloc: MultiplierCubit(MultiplierValue.x3), ); /// {@macro multiplier} Multiplier.x4({ required Vector2 position, required double angle, }) : this._( value: MultiplierValue.x4, position: position, angle: angle, bloc: MultiplierCubit(MultiplierValue.x4), ); /// {@macro multiplier} Multiplier.x5({ required Vector2 position, required double angle, }) : this._( value: MultiplierValue.x5, position: position, angle: angle, bloc: MultiplierCubit(MultiplierValue.x5), ); /// {@macro multiplier} Multiplier.x6({ required Vector2 position, required double angle, }) : this._( value: MultiplierValue.x6, position: position, angle: angle, bloc: MultiplierCubit(MultiplierValue.x6), ); /// Creates a [Multiplier] without any children. /// /// This can be used for testing [Multiplier]'s behaviors in isolation. @visibleForTesting Multiplier.test({ required MultiplierValue value, required this.bloc, }) : _value = value, _position = Vector2.zero(), _angle = 0; final MultiplierCubit bloc; final MultiplierValue _value; final Vector2 _position; final double _angle; late final MultiplierSpriteGroupComponent _sprite; @override void onRemove() { bloc.close(); super.onRemove(); } @override Future<void> onLoad() async { await super.onLoad(); _sprite = MultiplierSpriteGroupComponent( position: _position, litAssetPath: _value.litAssetPath, dimmedAssetPath: _value.dimmedAssetPath, angle: _angle, current: bloc.state, ); await add(_sprite); } } /// Available multiplier values. enum MultiplierValue { x2, x3, x4, x5, x6, } extension on MultiplierValue { String get litAssetPath { switch (this) { case MultiplierValue.x2: return Assets.images.multiplier.x2.lit.keyName; case MultiplierValue.x3: return Assets.images.multiplier.x3.lit.keyName; case MultiplierValue.x4: return Assets.images.multiplier.x4.lit.keyName; case MultiplierValue.x5: return Assets.images.multiplier.x5.lit.keyName; case MultiplierValue.x6: return Assets.images.multiplier.x6.lit.keyName; } } String get dimmedAssetPath { switch (this) { case MultiplierValue.x2: return Assets.images.multiplier.x2.dimmed.keyName; case MultiplierValue.x3: return Assets.images.multiplier.x3.dimmed.keyName; case MultiplierValue.x4: return Assets.images.multiplier.x4.dimmed.keyName; case MultiplierValue.x5: return Assets.images.multiplier.x5.dimmed.keyName; case MultiplierValue.x6: return Assets.images.multiplier.x6.dimmed.keyName; } } } /// {@template multiplier_sprite_group_component} /// A [SpriteGroupComponent] for a [Multiplier] with lit and dimmed states. /// {@endtemplate} @visibleForTesting class MultiplierSpriteGroupComponent extends SpriteGroupComponent<MultiplierSpriteState> with HasGameRef, ParentIsA<Multiplier> { /// {@macro multiplier_sprite_group_component} MultiplierSpriteGroupComponent({ required Vector2 position, required String litAssetPath, required String dimmedAssetPath, required double angle, required MultiplierState current, }) : _litAssetPath = litAssetPath, _dimmedAssetPath = dimmedAssetPath, super( anchor: Anchor.center, position: position, angle: angle, current: current.spriteState, ); final String _litAssetPath; final String _dimmedAssetPath; @override Future<void> onLoad() async { await super.onLoad(); parent.bloc.stream.listen((state) => current = state.spriteState); final sprites = { MultiplierSpriteState.lit: Sprite(gameRef.images.fromCache(_litAssetPath)), MultiplierSpriteState.dimmed: Sprite(gameRef.images.fromCache(_dimmedAssetPath)), }; this.sprites = sprites; size = sprites[current]!.originalSize / 10; } }
pinball/packages/pinball_components/lib/src/components/multiplier/multiplier.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/multiplier/multiplier.dart", "repo_id": "pinball", "token_count": 2177 }
1,063
import 'package:flame/components.dart'; import 'package:flame_bloc/flame_bloc.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; export 'cubit/signpost_cubit.dart'; /// {@template signpost} /// A sign, found in the Flutter Forest. /// /// Lights up a new sign whenever all three [DashBumper]s are hit. /// {@endtemplate} class Signpost extends BodyComponent with InitialPosition { /// {@macro signpost} Signpost({ Iterable<Component>? children, }) : super( renderBody: false, children: [ _SignpostSpriteComponent(), ...?children, ], ); @override Future<void> onLoad() async { await super.onLoad(); await add( FlameBlocListener<DashBumpersCubit, DashBumpersState>( listenWhen: (_, state) => state.isFullyActivated, onNewState: (_) { readBloc<SignpostCubit, SignpostState>().onProgressed(); readBloc<DashBumpersCubit, DashBumpersState>().onReset(); }, ), ); } @override Body createBody() { final shape = CircleShape()..radius = 0.25; final bodyDef = BodyDef( position: initialPosition, ); return world.createBody(bodyDef)..createFixtureFromShape(shape); } } class _SignpostSpriteComponent extends SpriteGroupComponent<SignpostState> with HasGameRef, FlameBlocListenable<SignpostCubit, SignpostState> { _SignpostSpriteComponent() : super( anchor: Anchor.bottomCenter, position: Vector2(0.65, 0.45), ); @override void onNewState(SignpostState state) => current = state; @override Future<void> onLoad() async { await super.onLoad(); final sprites = <SignpostState, Sprite>{}; this.sprites = sprites; for (final spriteState in SignpostState.values) { sprites[spriteState] = Sprite( gameRef.images.fromCache(spriteState.path), ); } current = SignpostState.inactive; size = sprites[current]!.originalSize / 10; } } extension on SignpostState { String get path { switch (this) { case SignpostState.inactive: return Assets.images.signpost.inactive.keyName; case SignpostState.active1: return Assets.images.signpost.active1.keyName; case SignpostState.active2: return Assets.images.signpost.active2.keyName; case SignpostState.active3: return Assets.images.signpost.active3.keyName; } } }
pinball/packages/pinball_components/lib/src/components/signpost/signpost.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/signpost/signpost.dart", "repo_id": "pinball", "token_count": 1011 }
1,064
import 'package:dashbook/dashbook.dart'; import 'package:sandbox/common/common.dart'; import 'package:sandbox/stories/android_acres/android_bumper_a_game.dart'; import 'package:sandbox/stories/android_acres/android_bumper_b_game.dart'; import 'package:sandbox/stories/android_acres/android_bumper_cow_game.dart'; import 'package:sandbox/stories/android_acres/android_spaceship_game.dart'; import 'package:sandbox/stories/android_acres/spaceship_rail_game.dart'; import 'package:sandbox/stories/android_acres/spaceship_ramp_game.dart'; void addAndroidAcresStories(Dashbook dashbook) { dashbook.storiesOf('Android Acres') ..addGame( title: 'Android Bumper A', description: AndroidBumperAGame.description, gameBuilder: (_) => AndroidBumperAGame(), ) ..addGame( title: 'Android Bumper B', description: AndroidBumperBGame.description, gameBuilder: (_) => AndroidBumperBGame(), ) ..addGame( title: 'Android Bumper Cow', description: AndroidBumperCowGame.description, gameBuilder: (_) => AndroidBumperCowGame(), ) ..addGame( title: 'Android Spaceship', description: AndroidSpaceshipGame.description, gameBuilder: (_) => AndroidSpaceshipGame(), ) ..addGame( title: 'Spaceship Rail', description: SpaceshipRailGame.description, gameBuilder: (_) => SpaceshipRailGame(), ) ..addGame( title: 'Spaceship Ramp', description: SpaceshipRampGame.description, gameBuilder: (_) => SpaceshipRampGame(), ); }
pinball/packages/pinball_components/sandbox/lib/stories/android_acres/stories.dart/0
{ "file_path": "pinball/packages/pinball_components/sandbox/lib/stories/android_acres/stories.dart", "repo_id": "pinball", "token_count": 582 }
1,065
import 'package:dashbook/dashbook.dart'; import 'package:sandbox/common/common.dart'; import 'package:sandbox/stories/dino_desert/chrome_dino_game.dart'; import 'package:sandbox/stories/dino_desert/dino_walls_game.dart'; import 'package:sandbox/stories/dino_desert/slingshots_game.dart'; void addDinoDesertStories(Dashbook dashbook) { dashbook.storiesOf('Dino Desert') ..addGame( title: 'Chrome Dino', description: ChromeDinoGame.description, gameBuilder: (_) => ChromeDinoGame(), ) ..addGame( title: 'Dino Walls', description: DinoWallsGame.description, gameBuilder: (_) => DinoWallsGame(), ) ..addGame( title: 'Slingshots', description: SlingshotsGame.description, gameBuilder: (_) => SlingshotsGame(), ); }
pinball/packages/pinball_components/sandbox/lib/stories/dino_desert/stories.dart/0
{ "file_path": "pinball/packages/pinball_components/sandbox/lib/stories/dino_desert/stories.dart", "repo_id": "pinball", "token_count": 312 }
1,066
import 'package:flame/input.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:sandbox/stories/ball/basic_ball_game.dart'; class MultiballGame extends BallGame with KeyboardEvents { MultiballGame() : super( imagesFileNames: [ Assets.images.multiball.lit.keyName, Assets.images.multiball.dimmed.keyName, ], ); static const description = ''' Shows how the Multiball are rendered. - Tap anywhere on the screen to spawn a ball into the game. - Press space bar to animate multiballs. '''; final List<Multiball> multiballs = [ Multiball.a(), Multiball.b(), Multiball.c(), Multiball.d(), ]; @override Future<void> onLoad() async { await super.onLoad(); camera.followVector2(Vector2.zero()); await addAll(multiballs); await traceAllBodies(); } @override KeyEventResult onKeyEvent( RawKeyEvent event, Set<LogicalKeyboardKey> keysPressed, ) { if (event is RawKeyDownEvent && event.logicalKey == LogicalKeyboardKey.space) { for (final multiball in multiballs) { multiball.bloc.onBlink(); } return KeyEventResult.handled; } return KeyEventResult.ignored; } }
pinball/packages/pinball_components/sandbox/lib/stories/multiball/multiball_game.dart/0
{ "file_path": "pinball/packages/pinball_components/sandbox/lib/stories/multiball/multiball_game.dart", "repo_id": "pinball", "token_count": 539 }
1,067
import 'package:bloc_test/bloc_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_theme/pinball_theme.dart'; void main() { group( 'ArcadeBackgroundCubit', () { blocTest<ArcadeBackgroundCubit, ArcadeBackgroundState>( 'onCharacterSelected emits new theme', build: ArcadeBackgroundCubit.new, act: (bloc) => bloc.onCharacterSelected(const DinoTheme()), expect: () => [ const ArcadeBackgroundState( characterTheme: DinoTheme(), ), ], ); }, ); }
pinball/packages/pinball_components/test/src/components/arcade_background/cubit/arcade_background_cubit_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/arcade_background/cubit/arcade_background_cubit_test.dart", "repo_id": "pinball", "token_count": 262 }
1,068
// ignore_for_file: cascade_invocations import 'package:flame/components.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pinball_components/pinball_components.dart'; import '../../helpers/helpers.dart'; void main() { group('CameraZoom', () { final tester = FlameTester(TestGame.new); tester.testGameWidget( 'renders correctly', setUp: (game, tester) async { game.camera.followVector2(Vector2.zero()); game.camera.zoom = 10; final sprite = await game.loadSprite( Assets.images.signpost.inactive.keyName, ); await game.add( SpriteComponent( sprite: sprite, size: Vector2(4, 8), anchor: Anchor.center, ), ); await game.add(CameraZoom(value: 40)); }, verify: (game, tester) async { await expectLater( find.byGame<TestGame>(), matchesGoldenFile('golden/camera_zoom/no_zoom.png'), ); game.update(0.2); await tester.pump(); await expectLater( find.byGame<TestGame>(), matchesGoldenFile('golden/camera_zoom/in_between.png'), ); game.update(0.4); await tester.pump(); await expectLater( find.byGame<TestGame>(), matchesGoldenFile('golden/camera_zoom/finished.png'), ); game.update(0.1); await tester.pump(); expect(game.firstChild<CameraZoom>(), isNull); }, ); tester.test( 'completes when checked after it is finished', (game) async { await game.add(CameraZoom(value: 40)); game.update(10); final cameraZoom = game.firstChild<CameraZoom>(); final future = cameraZoom!.completed; expect(future, completes); }, ); tester.test( 'completes when checked before it is finished', (game) async { final zoom = CameraZoom(value: 40); final future = zoom.completed; await game.add(zoom); game.update(10); game.update(0); expect(future, completes); }, ); }); }
pinball/packages/pinball_components/test/src/components/camera_zoom_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/camera_zoom_test.dart", "repo_id": "pinball", "token_count": 1018 }
1,069
// ignore_for_file: cascade_invocations import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pinball_components/pinball_components.dart'; import '../../helpers/helpers.dart'; void main() { group('DinoWalls', () { TestWidgetsFlutterBinding.ensureInitialized(); final assets = [ Assets.images.dino.topWall.keyName, Assets.images.dino.topWallTunnel.keyName, Assets.images.dino.bottomWall.keyName, ]; final flameTester = FlameTester(() => TestGame(assets)); flameTester.test('loads correctly', (game) async { final component = DinoWalls(); await game.ensureAdd(component); expect(game.contains(component), isTrue); }); flameTester.testGameWidget( 'renders correctly', setUp: (game, tester) async { await game.images.loadAll(assets); await game.ensureAdd(DinoWalls()); game.camera.followVector2(Vector2.zero()); game.camera.zoom = 6.5; await tester.pump(); }, verify: (game, tester) async { await expectLater( find.byGame<TestGame>(), matchesGoldenFile('golden/dino_walls.png'), ); }, ); }); }
pinball/packages/pinball_components/test/src/components/dino_walls_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/dino_walls_test.dart", "repo_id": "pinball", "token_count": 536 }
1,070
// ignore_for_file: cascade_invocations import 'package:flame_bloc/flame_bloc.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pinball_components/pinball_components.dart'; class _TestGame extends Forge2DGame { @override Future<void> onLoad() async { images.prefix = ''; await images.loadAll([ Assets.images.googleWord.letter1.lit.keyName, Assets.images.googleWord.letter1.dimmed.keyName, Assets.images.googleWord.letter2.lit.keyName, Assets.images.googleWord.letter2.dimmed.keyName, Assets.images.googleWord.letter3.lit.keyName, Assets.images.googleWord.letter3.dimmed.keyName, Assets.images.googleWord.letter4.lit.keyName, Assets.images.googleWord.letter4.dimmed.keyName, Assets.images.googleWord.letter5.lit.keyName, Assets.images.googleWord.letter5.dimmed.keyName, Assets.images.googleWord.letter6.lit.keyName, Assets.images.googleWord.letter6.dimmed.keyName, ]); } Future<void> pump(GoogleWord child) async { await ensureAdd( FlameBlocProvider<GoogleWordCubit, GoogleWordState>.value( value: GoogleWordCubit(), children: [child], ), ); } } void main() { TestWidgetsFlutterBinding.ensureInitialized(); final flameTester = FlameTester(_TestGame.new); group('GoogleWord', () { test('can be instantiated', () { expect(GoogleWord(position: Vector2.zero()), isA<GoogleWord>()); }); flameTester.test( 'loads letters correctly', (game) async { final googleWord = GoogleWord(position: Vector2.zero()); await game.pump(googleWord); expect( googleWord.children.whereType<GoogleLetter>().length, equals(6), ); }, ); }); }
pinball/packages/pinball_components/test/src/components/google_word/google_word_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/google_word/google_word_test.dart", "repo_id": "pinball", "token_count": 744 }
1,071
// ignore_for_file: cascade_invocations, prefer_const_constructors import 'package:bloc_test/bloc_test.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:pinball_components/pinball_components.dart'; class _TestGame extends Forge2DGame { @override Future<void> onLoad() async { images.prefix = ''; await images.loadAll([ Assets.images.multiplier.x2.lit.keyName, Assets.images.multiplier.x2.dimmed.keyName, Assets.images.multiplier.x3.lit.keyName, Assets.images.multiplier.x3.dimmed.keyName, Assets.images.multiplier.x4.lit.keyName, Assets.images.multiplier.x4.dimmed.keyName, Assets.images.multiplier.x5.lit.keyName, Assets.images.multiplier.x5.dimmed.keyName, Assets.images.multiplier.x6.lit.keyName, Assets.images.multiplier.x6.dimmed.keyName, ]); } } class _MockMultiplierCubit extends Mock implements MultiplierCubit {} void main() { group('Multiplier', () { TestWidgetsFlutterBinding.ensureInitialized(); final flameTester = FlameTester(_TestGame.new); late MultiplierCubit bloc; setUp(() { bloc = _MockMultiplierCubit(); }); flameTester.test('"x2" loads correctly', (game) async { final multiplier = Multiplier.x2( position: Vector2.zero(), angle: 0, ); await game.ensureAdd(multiplier); expect(game.contains(multiplier), isTrue); }); flameTester.test('"x3" loads correctly', (game) async { final multiplier = Multiplier.x3( position: Vector2.zero(), angle: 0, ); await game.ensureAdd(multiplier); expect(game.contains(multiplier), isTrue); }); flameTester.test('"x4" loads correctly', (game) async { final multiplier = Multiplier.x4( position: Vector2.zero(), angle: 0, ); await game.ensureAdd(multiplier); expect(game.contains(multiplier), isTrue); }); flameTester.test('"x5" loads correctly', (game) async { final multiplier = Multiplier.x5( position: Vector2.zero(), angle: 0, ); await game.ensureAdd(multiplier); expect(game.contains(multiplier), isTrue); }); flameTester.test('"x6" loads correctly', (game) async { final multiplier = Multiplier.x6( position: Vector2.zero(), angle: 0, ); await game.ensureAdd(multiplier); expect(game.contains(multiplier), isTrue); }); group('renders correctly', () { group('x2', () { const multiplierValue = MultiplierValue.x2; flameTester.testGameWidget( 'lit when bloc state is lit', setUp: (game, tester) async { await game.onLoad(); whenListen( bloc, const Stream<MultiplierState>.empty(), initialState: MultiplierState( value: multiplierValue, spriteState: MultiplierSpriteState.lit, ), ); final multiplier = Multiplier.test( value: multiplierValue, bloc: bloc, ); await game.ensureAdd(multiplier); await tester.pump(); game.camera.followVector2(Vector2.zero()); }, verify: (game, tester) async { expect( game .descendants() .whereType<MultiplierSpriteGroupComponent>() .first .current, MultiplierSpriteState.lit, ); await expectLater( find.byGame<_TestGame>(), matchesGoldenFile('../golden/multipliers/x2_lit.png'), ); }, ); flameTester.testGameWidget( 'dimmed when bloc state is dimmed', setUp: (game, tester) async { await game.onLoad(); whenListen( bloc, const Stream<MultiplierState>.empty(), initialState: MultiplierState( value: multiplierValue, spriteState: MultiplierSpriteState.dimmed, ), ); final multiplier = Multiplier.test( value: multiplierValue, bloc: bloc, ); await game.ensureAdd(multiplier); await tester.pump(); game.camera.followVector2(Vector2.zero()); }, verify: (game, tester) async { expect( game .descendants() .whereType<MultiplierSpriteGroupComponent>() .first .current, MultiplierSpriteState.dimmed, ); await expectLater( find.byGame<_TestGame>(), matchesGoldenFile('../golden/multipliers/x2_dimmed.png'), ); }, ); }); group('x3', () { const multiplierValue = MultiplierValue.x3; flameTester.testGameWidget( 'lit when bloc state is lit', setUp: (game, tester) async { await game.onLoad(); whenListen( bloc, const Stream<MultiplierState>.empty(), initialState: MultiplierState( value: multiplierValue, spriteState: MultiplierSpriteState.lit, ), ); final multiplier = Multiplier.test( value: multiplierValue, bloc: bloc, ); await game.ensureAdd(multiplier); await tester.pump(); game.camera.followVector2(Vector2.zero()); }, verify: (game, tester) async { expect( game .descendants() .whereType<MultiplierSpriteGroupComponent>() .first .current, MultiplierSpriteState.lit, ); await expectLater( find.byGame<_TestGame>(), matchesGoldenFile('../golden/multipliers/x3_lit.png'), ); }, ); flameTester.testGameWidget( 'dimmed when bloc state is dimmed', setUp: (game, tester) async { await game.onLoad(); whenListen( bloc, const Stream<MultiplierState>.empty(), initialState: MultiplierState( value: multiplierValue, spriteState: MultiplierSpriteState.dimmed, ), ); final multiplier = Multiplier.test( value: multiplierValue, bloc: bloc, ); await game.ensureAdd(multiplier); await tester.pump(); game.camera.followVector2(Vector2.zero()); }, verify: (game, tester) async { expect( game .descendants() .whereType<MultiplierSpriteGroupComponent>() .first .current, MultiplierSpriteState.dimmed, ); await expectLater( find.byGame<_TestGame>(), matchesGoldenFile('../golden/multipliers/x3_dimmed.png'), ); }, ); }); group('x4', () { const multiplierValue = MultiplierValue.x4; flameTester.testGameWidget( 'lit when bloc state is lit', setUp: (game, tester) async { await game.onLoad(); whenListen( bloc, const Stream<MultiplierState>.empty(), initialState: MultiplierState( value: multiplierValue, spriteState: MultiplierSpriteState.lit, ), ); final multiplier = Multiplier.test( value: multiplierValue, bloc: bloc, ); await game.ensureAdd(multiplier); await tester.pump(); game.camera.followVector2(Vector2.zero()); }, verify: (game, tester) async { expect( game .descendants() .whereType<MultiplierSpriteGroupComponent>() .first .current, MultiplierSpriteState.lit, ); await expectLater( find.byGame<_TestGame>(), matchesGoldenFile('../golden/multipliers/x4_lit.png'), ); }, ); flameTester.testGameWidget( 'dimmed when bloc state is dimmed', setUp: (game, tester) async { await game.onLoad(); whenListen( bloc, const Stream<MultiplierState>.empty(), initialState: MultiplierState( value: multiplierValue, spriteState: MultiplierSpriteState.dimmed, ), ); final multiplier = Multiplier.test( value: multiplierValue, bloc: bloc, ); await game.ensureAdd(multiplier); await tester.pump(); game.camera.followVector2(Vector2.zero()); }, verify: (game, tester) async { expect( game .descendants() .whereType<MultiplierSpriteGroupComponent>() .first .current, MultiplierSpriteState.dimmed, ); await expectLater( find.byGame<_TestGame>(), matchesGoldenFile('../golden/multipliers/x4_dimmed.png'), ); }, ); }); group('x5', () { const multiplierValue = MultiplierValue.x5; flameTester.testGameWidget( 'lit when bloc state is lit', setUp: (game, tester) async { await game.onLoad(); whenListen( bloc, const Stream<MultiplierState>.empty(), initialState: MultiplierState( value: multiplierValue, spriteState: MultiplierSpriteState.lit, ), ); final multiplier = Multiplier.test( value: multiplierValue, bloc: bloc, ); await game.ensureAdd(multiplier); await tester.pump(); game.camera.followVector2(Vector2.zero()); }, verify: (game, tester) async { expect( game .descendants() .whereType<MultiplierSpriteGroupComponent>() .first .current, MultiplierSpriteState.lit, ); await expectLater( find.byGame<_TestGame>(), matchesGoldenFile('../golden/multipliers/x5_lit.png'), ); }, ); flameTester.testGameWidget( 'dimmed when bloc state is dimmed', setUp: (game, tester) async { await game.onLoad(); whenListen( bloc, const Stream<MultiplierState>.empty(), initialState: MultiplierState( value: multiplierValue, spriteState: MultiplierSpriteState.dimmed, ), ); final multiplier = Multiplier.test( value: multiplierValue, bloc: bloc, ); await game.ensureAdd(multiplier); await tester.pump(); game.camera.followVector2(Vector2.zero()); }, verify: (game, tester) async { expect( game .descendants() .whereType<MultiplierSpriteGroupComponent>() .first .current, MultiplierSpriteState.dimmed, ); await expectLater( find.byGame<_TestGame>(), matchesGoldenFile('../golden/multipliers/x5_dimmed.png'), ); }, ); }); group('x6', () { const multiplierValue = MultiplierValue.x6; flameTester.testGameWidget( 'lit when bloc state is lit', setUp: (game, tester) async { await game.onLoad(); whenListen( bloc, const Stream<MultiplierState>.empty(), initialState: MultiplierState( value: multiplierValue, spriteState: MultiplierSpriteState.lit, ), ); final multiplier = Multiplier.test( value: multiplierValue, bloc: bloc, ); await game.ensureAdd(multiplier); await tester.pump(); game.camera.followVector2(Vector2.zero()); }, verify: (game, tester) async { expect( game .descendants() .whereType<MultiplierSpriteGroupComponent>() .first .current, MultiplierSpriteState.lit, ); await expectLater( find.byGame<_TestGame>(), matchesGoldenFile('../golden/multipliers/x6_lit.png'), ); }, ); flameTester.testGameWidget( 'dimmed when bloc state is dimmed', setUp: (game, tester) async { await game.onLoad(); whenListen( bloc, const Stream<MultiplierState>.empty(), initialState: MultiplierState( value: multiplierValue, spriteState: MultiplierSpriteState.dimmed, ), ); final multiplier = Multiplier.test( value: multiplierValue, bloc: bloc, ); await game.ensureAdd(multiplier); await tester.pump(); game.camera.followVector2(Vector2.zero()); }, verify: (game, tester) async { expect( game .descendants() .whereType<MultiplierSpriteGroupComponent>() .first .current, MultiplierSpriteState.dimmed, ); await expectLater( find.byGame<_TestGame>(), matchesGoldenFile('../golden/multipliers/x6_dimmed.png'), ); }, ); }); }); flameTester.test('closes bloc when removed', (game) async { whenListen( bloc, const Stream<MultiplierState>.empty(), initialState: MultiplierState( value: MultiplierValue.x2, spriteState: MultiplierSpriteState.dimmed, ), ); when(bloc.close).thenAnswer((_) async {}); final multiplier = Multiplier.test(value: MultiplierValue.x2, bloc: bloc); await game.ensureAdd(multiplier); game.remove(multiplier); await game.ready(); verify(bloc.close).called(1); }); }); }
pinball/packages/pinball_components/test/src/components/multiplier/multiplier_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/multiplier/multiplier_test.dart", "repo_id": "pinball", "token_count": 8158 }
1,072
// ignore_for_file: prefer_const_constructors import 'package:flutter_test/flutter_test.dart'; import 'package:pinball_components/pinball_components.dart'; void main() { group('SkillShotState', () { test('supports value equality', () { expect( SkillShotState( spriteState: SkillShotSpriteState.lit, isBlinking: true, ), equals( const SkillShotState( spriteState: SkillShotSpriteState.lit, isBlinking: true, ), ), ); }); group('constructor', () { test('can be instantiated', () { expect( const SkillShotState( spriteState: SkillShotSpriteState.lit, isBlinking: true, ), isNotNull, ); }); test('initial is dimmed and not blinking', () { const initialState = SkillShotState( spriteState: SkillShotSpriteState.dimmed, isBlinking: false, ); expect(SkillShotState.initial(), equals(initialState)); }); }); group('copyWith', () { test( 'copies correctly ' 'when no argument specified', () { const skillShotState = SkillShotState( spriteState: SkillShotSpriteState.lit, isBlinking: true, ); expect( skillShotState.copyWith(), equals(skillShotState), ); }, ); test( 'copies correctly ' 'when all arguments specified', () { const skillShotState = SkillShotState( spriteState: SkillShotSpriteState.lit, isBlinking: true, ); final otherSkillShotState = SkillShotState( spriteState: SkillShotSpriteState.dimmed, isBlinking: false, ); expect(skillShotState, isNot(equals(otherSkillShotState))); expect( skillShotState.copyWith( spriteState: SkillShotSpriteState.dimmed, isBlinking: false, ), equals(otherSkillShotState), ); }, ); }); }); }
pinball/packages/pinball_components/test/src/components/skill_shot/cubit/skill_shot_state_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/skill_shot/cubit/skill_shot_state_test.dart", "repo_id": "pinball", "token_count": 1059 }
1,073
import 'package:flutter_test/flutter_test.dart'; import 'package:pinball_components/pinball_components.dart'; void main() { group('ScoreX', () { test('formatScore correctly formats int', () { expect(1000000.formatScore(), '1,000,000'); }); }); }
pinball/packages/pinball_components/test/src/extensions/score_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/extensions/score_test.dart", "repo_id": "pinball", "token_count": 98 }
1,074
import 'package:flame/components.dart'; /// A mixin that ensures a parent is of the given type [T]. mixin ParentIsA<T extends Component> on Component { @override T get parent => super.parent! as T; @override Future<void>? addToParent(covariant T parent) { return super.addToParent(parent); } }
pinball/packages/pinball_flame/lib/src/parent_is_a.dart/0
{ "file_path": "pinball/packages/pinball_flame/lib/src/parent_is_a.dart", "repo_id": "pinball", "token_count": 105 }
1,075
// ignore_for_file: prefer_const_constructors import 'package:flutter_test/flutter_test.dart'; import 'package:pinball_theme/pinball_theme.dart'; void main() { group('SparkyTheme', () { test('can be instantiated', () { expect(SparkyTheme(), isNotNull); }); test('supports value equality', () { expect(SparkyTheme(), equals(SparkyTheme())); }); }); }
pinball/packages/pinball_theme/test/src/themes/sparky_theme_test.dart/0
{ "file_path": "pinball/packages/pinball_theme/test/src/themes/sparky_theme_test.dart", "repo_id": "pinball", "token_count": 147 }
1,076
library pinball_ui; export 'package:url_launcher/url_launcher.dart'; export 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart'; export 'src/dialog/dialog.dart'; export 'src/external_links/external_links.dart'; export 'src/theme/theme.dart'; export 'src/widgets/widgets.dart';
pinball/packages/pinball_ui/lib/pinball_ui.dart/0
{ "file_path": "pinball/packages/pinball_ui/lib/pinball_ui.dart", "repo_id": "pinball", "token_count": 109 }
1,077
// ignore_for_file: prefer_const_constructors import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pinball_ui/pinball_ui.dart'; void main() { group('PinballDialog', () { group('with title only', () { testWidgets('renders the title and the body', (tester) async { tester.binding.window.physicalSizeTestValue = const Size(2000, 4000); addTearDown(tester.binding.window.clearPhysicalSizeTestValue); await tester.pumpWidget( const MaterialApp( home: PinballDialog(title: 'title', child: Placeholder()), ), ); expect(find.byType(PixelatedDecoration), findsOneWidget); expect(find.text('title'), findsOneWidget); expect(find.byType(Placeholder), findsOneWidget); }); }); group('with title and subtitle', () { testWidgets('renders the title, subtitle and the body', (tester) async { tester.binding.window.physicalSizeTestValue = const Size(2000, 4000); addTearDown(tester.binding.window.clearPhysicalSizeTestValue); await tester.pumpWidget( MaterialApp( home: PinballDialog( title: 'title', subtitle: 'sub', child: Icon(Icons.home), ), ), ); expect(find.byType(PixelatedDecoration), findsOneWidget); expect(find.text('title'), findsOneWidget); expect(find.text('sub'), findsOneWidget); expect(find.byType(Icon), findsOneWidget); }); }); }); }
pinball/packages/pinball_ui/test/src/dialog/pinball_dialog_test.dart/0
{ "file_path": "pinball/packages/pinball_ui/test/src/dialog/pinball_dialog_test.dart", "repo_id": "pinball", "token_count": 661 }
1,078
name: platform_helper description: Platform helper for Pinball application. version: 1.0.0+1 publish_to: none environment: sdk: ">=2.16.0 <3.0.0" dependencies: flutter: sdk: flutter dev_dependencies: flutter_test: sdk: flutter very_good_analysis: ^2.4.0
pinball/packages/platform_helper/pubspec.yaml/0
{ "file_path": "pinball/packages/platform_helper/pubspec.yaml", "repo_id": "pinball", "token_count": 112 }
1,079
import 'package:bloc_test/bloc_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:pinball/assets_manager/assets_manager.dart'; import 'package:pinball_ui/pinball_ui.dart'; import '../../helpers/helpers.dart'; class _MockAssetsManagerCubit extends Mock implements AssetsManagerCubit {} void main() { late AssetsManagerCubit assetsManagerCubit; setUp(() { const initialAssetsState = AssetsManagerState( assetsCount: 1, loaded: 0, ); assetsManagerCubit = _MockAssetsManagerCubit(); whenListen( assetsManagerCubit, Stream.value(initialAssetsState), initialState: initialAssetsState, ); }); group('AssetsLoadingPage', () { testWidgets('renders an animated text and a pinball loading indicator', (tester) async { await tester.pumpApp( const AssetsLoadingPage(), assetsManagerCubit: assetsManagerCubit, ); expect(find.byType(AnimatedEllipsisText), findsOneWidget); expect(find.byType(PinballLoadingIndicator), findsOneWidget); }); }); }
pinball/test/assets_manager/views/assets_loading_page_test.dart/0
{ "file_path": "pinball/test/assets_manager/views/assets_loading_page_test.dart", "repo_id": "pinball", "token_count": 416 }
1,080
// ignore_for_file: cascade_invocations import 'dart:async'; import 'package:bloc_test/bloc_test.dart'; import 'package:flame_bloc/flame_bloc.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:pinball/game/components/android_acres/behaviors/behaviors.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball_components/pinball_components.dart'; class _TestGame extends Forge2DGame { @override Future<void> onLoad() async { images.prefix = ''; await images.loadAll([ Assets.images.android.spaceship.saucer.keyName, Assets.images.android.spaceship.animatronic.keyName, Assets.images.android.spaceship.lightBeam.keyName, Assets.images.android.ramp.boardOpening.keyName, Assets.images.android.ramp.railingForeground.keyName, Assets.images.android.ramp.railingBackground.keyName, Assets.images.android.ramp.main.keyName, Assets.images.android.ramp.arrow.inactive.keyName, Assets.images.android.ramp.arrow.active1.keyName, Assets.images.android.ramp.arrow.active2.keyName, Assets.images.android.ramp.arrow.active3.keyName, Assets.images.android.ramp.arrow.active4.keyName, Assets.images.android.ramp.arrow.active5.keyName, Assets.images.android.rail.main.keyName, Assets.images.android.rail.exit.keyName, Assets.images.android.bumper.a.lit.keyName, Assets.images.android.bumper.a.dimmed.keyName, Assets.images.android.bumper.b.lit.keyName, Assets.images.android.bumper.b.dimmed.keyName, Assets.images.android.bumper.cow.lit.keyName, Assets.images.android.bumper.cow.dimmed.keyName, ]); } Future<void> pump( AndroidAcres child, { required GameBloc gameBloc, required AndroidSpaceshipCubit androidSpaceshipCubit, }) async { // Not needed once https://github.com/flame-engine/flame/issues/1607 // is fixed await onLoad(); await ensureAdd( FlameMultiBlocProvider( providers: [ FlameBlocProvider<GameBloc, GameState>.value( value: gameBloc, ), FlameBlocProvider<AndroidSpaceshipCubit, AndroidSpaceshipState>.value( value: androidSpaceshipCubit, ), ], children: [child], ), ); } } class _MockGameBloc extends Mock implements GameBloc {} class _MockAndroidSpaceshipCubit extends Mock implements AndroidSpaceshipCubit { } void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('AndroidSpaceshipBonusBehavior', () { late GameBloc gameBloc; setUp(() { gameBloc = _MockGameBloc(); }); final flameTester = FlameTester(_TestGame.new); flameTester.testGameWidget( 'adds GameBonus.androidSpaceship to the game ' 'when android spaceship has a bonus', setUp: (game, tester) async { final behavior = AndroidSpaceshipBonusBehavior(); final parent = AndroidAcres.test(); final androidSpaceship = AndroidSpaceship(position: Vector2.zero()); final androidSpaceshipCubit = _MockAndroidSpaceshipCubit(); final streamController = StreamController<AndroidSpaceshipState>(); whenListen( androidSpaceshipCubit, streamController.stream, initialState: AndroidSpaceshipState.withoutBonus, ); await parent.add(androidSpaceship); await game.pump( parent, androidSpaceshipCubit: androidSpaceshipCubit, gameBloc: gameBloc, ); await parent.ensureAdd(behavior); streamController.add(AndroidSpaceshipState.withBonus); await tester.pump(); verify( () => gameBloc.add(const BonusActivated(GameBonus.androidSpaceship)), ).called(1); }, ); }); }
pinball/test/game/components/android_acres/behaviors/android_spaceship_bonus_behavior_test.dart/0
{ "file_path": "pinball/test/game/components/android_acres/behaviors/android_spaceship_bonus_behavior_test.dart", "repo_id": "pinball", "token_count": 1596 }
1,081
// ignore_for_file: cascade_invocations import 'package:flame/components.dart'; import 'package:flame_bloc/flame_bloc.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:pinball/game/bloc/game_bloc.dart'; import 'package:pinball/game/components/backbox/displays/loading_display.dart'; import 'package:pinball/l10n/l10n.dart'; import 'package:pinball_flame/pinball_flame.dart'; class _TestGame extends Forge2DGame { Future<void> pump(LoadingDisplay component) { return ensureAdd( FlameBlocProvider<GameBloc, GameState>.value( value: GameBloc(), children: [ FlameProvider.value( _MockAppLocalizations(), children: [component], ), ], ), ); } } class _MockAppLocalizations extends Mock implements AppLocalizations { @override String get loading => 'Loading'; } void main() { group('LoadingDisplay', () { final flameTester = FlameTester(_TestGame.new); flameTester.test('renders correctly', (game) async { await game.pump(LoadingDisplay()); final component = game.descendants().whereType<TextComponent>().first; expect(component, isNotNull); expect(component.text, equals('Loading')); }); flameTester.test('use ellipses as animation', (game) async { await game.pump(LoadingDisplay()); final component = game.descendants().whereType<TextComponent>().first; expect(component.text, equals('Loading')); final timer = component.firstChild<TimerComponent>(); timer?.update(1.1); expect(component.text, equals('Loading.')); timer?.update(1.1); expect(component.text, equals('Loading..')); timer?.update(1.1); expect(component.text, equals('Loading...')); timer?.update(1.1); expect(component.text, equals('Loading')); }); }); }
pinball/test/game/components/backbox/displays/loading_display_test.dart/0
{ "file_path": "pinball/test/game/components/backbox/displays/loading_display_test.dart", "repo_id": "pinball", "token_count": 757 }
1,082
// ignore_for_file: cascade_invocations, prefer_const_constructors import 'dart:async'; import 'package:bloc_test/bloc_test.dart'; import 'package:flame/components.dart'; import 'package:flame_bloc/flame_bloc.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:pinball/game/components/multipliers/behaviors/behaviors.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball_components/pinball_components.dart'; class _TestGame extends Forge2DGame { @override Future<void> onLoad() async { images.prefix = ''; await images.loadAll([ Assets.images.multiplier.x2.lit.keyName, Assets.images.multiplier.x2.dimmed.keyName, Assets.images.multiplier.x3.lit.keyName, Assets.images.multiplier.x3.dimmed.keyName, Assets.images.multiplier.x4.lit.keyName, Assets.images.multiplier.x4.dimmed.keyName, Assets.images.multiplier.x5.lit.keyName, Assets.images.multiplier.x5.dimmed.keyName, Assets.images.multiplier.x6.lit.keyName, Assets.images.multiplier.x6.dimmed.keyName, ]); } Future<void> pump(Multipliers child) async { await ensureAdd( FlameBlocProvider<GameBloc, GameState>.value( value: GameBloc(), children: [child], ), ); } } class _MockGameBloc extends Mock implements GameBloc {} class _MockComponent extends Mock implements Component {} class _MockMultiplierCubit extends Mock implements MultiplierCubit {} void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('MultipliersBehavior', () { late GameBloc gameBloc; setUp(() { registerFallbackValue(_MockComponent()); gameBloc = _MockGameBloc(); whenListen( gameBloc, const Stream<GameState>.empty(), initialState: const GameState.initial(), ); }); final flameBlocTester = FlameTester(_TestGame.new); group('listenWhen', () { test('is true when the multiplier has changed', () { final state = GameState( totalScore: 0, roundScore: 10, multiplier: 2, rounds: 0, status: GameStatus.playing, bonusHistory: const [], ); final previous = GameState.initial(); expect( MultipliersBehavior().listenWhen(previous, state), isTrue, ); }); test('is false when the multiplier state is the same', () { final state = GameState( totalScore: 0, roundScore: 10, multiplier: 1, rounds: 0, status: GameStatus.playing, bonusHistory: const [], ); final previous = GameState.initial(); expect( MultipliersBehavior().listenWhen(previous, state), isFalse, ); }); }); group('onNewState', () { flameBlocTester.testGameWidget( "calls 'next' once per each multiplier when GameBloc emit state", setUp: (game, tester) async { await game.onLoad(); final behavior = MultipliersBehavior(); final parent = Multipliers.test(); final multiplierX2Cubit = _MockMultiplierCubit(); final multiplierX3Cubit = _MockMultiplierCubit(); final multipliers = [ Multiplier.test( value: MultiplierValue.x2, bloc: multiplierX2Cubit, ), Multiplier.test( value: MultiplierValue.x3, bloc: multiplierX3Cubit, ), ]; whenListen( multiplierX2Cubit, const Stream<MultiplierState>.empty(), initialState: MultiplierState.initial(MultiplierValue.x2), ); when(() => multiplierX2Cubit.next(any())).thenAnswer((_) async {}); whenListen( multiplierX3Cubit, const Stream<MultiplierState>.empty(), initialState: MultiplierState.initial(MultiplierValue.x2), ); when(() => multiplierX3Cubit.next(any())).thenAnswer((_) async {}); await parent.addAll(multipliers); await game.pump(parent); await parent.ensureAdd(behavior); await tester.pump(); behavior.onNewState( GameState.initial().copyWith(multiplier: 2), ); for (final multiplier in multipliers) { verify( () => multiplier.bloc.next(any()), ).called(1); } }, ); }); }); }
pinball/test/game/components/multipliers/behaviors/multipliers_behavior_test.dart/0
{ "file_path": "pinball/test/game/components/multipliers/behaviors/multipliers_behavior_test.dart", "repo_id": "pinball", "token_count": 2083 }
1,083
import 'package:bloc_test/bloc_test.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:leaderboard_repository/leaderboard_repository.dart'; import 'package:mocktail/mocktail.dart'; import 'package:pinball/assets_manager/assets_manager.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball/l10n/l10n.dart'; import 'package:pinball/select_character/select_character.dart'; import 'package:pinball/start_game/start_game.dart'; import 'package:pinball_audio/pinball_audio.dart'; import 'package:pinball_ui/pinball_ui.dart'; import 'package:platform_helper/platform_helper.dart'; import 'package:share_repository/share_repository.dart'; class _MockAssetsManagerCubit extends Mock implements AssetsManagerCubit {} class _MockLeaderboardRepository extends Mock implements LeaderboardRepository { } class _MockShareRepository extends Mock implements ShareRepository {} class _MockCharacterThemeCubit extends Mock implements CharacterThemeCubit {} class _MockGameBloc extends Mock implements GameBloc {} class _MockStartGameBloc extends Mock implements StartGameBloc {} class _MockPinballAudioPlayer extends Mock implements PinballAudioPlayer {} class _MockPlatformHelper extends Mock implements PlatformHelper {} PinballAudioPlayer _buildDefaultPinballAudioPlayer() { final audioPlayer = _MockPinballAudioPlayer(); when(audioPlayer.load).thenAnswer((_) => [Future.value]); return audioPlayer; } AssetsManagerCubit _buildDefaultAssetsManagerCubit() { final cubit = _MockAssetsManagerCubit(); const state = AssetsManagerState( assetsCount: 1, loaded: 1, ); whenListen( cubit, Stream.value(state), initialState: state, ); return cubit; } extension PumpApp on WidgetTester { Future<void> pumpApp( Widget widget, { GameBloc? gameBloc, StartGameBloc? startGameBloc, AssetsManagerCubit? assetsManagerCubit, CharacterThemeCubit? characterThemeCubit, LeaderboardRepository? leaderboardRepository, ShareRepository? shareRepository, PinballAudioPlayer? pinballAudioPlayer, PlatformHelper? platformHelper, }) { return runAsync(() { return pumpWidget( MultiRepositoryProvider( providers: [ RepositoryProvider.value( value: leaderboardRepository ?? _MockLeaderboardRepository(), ), RepositoryProvider.value( value: shareRepository ?? _MockShareRepository(), ), RepositoryProvider.value( value: pinballAudioPlayer ?? _buildDefaultPinballAudioPlayer(), ), RepositoryProvider.value( value: platformHelper ?? _MockPlatformHelper(), ), ], child: MultiBlocProvider( providers: [ BlocProvider.value( value: characterThemeCubit ?? _MockCharacterThemeCubit(), ), BlocProvider.value( value: gameBloc ?? _MockGameBloc(), ), BlocProvider.value( value: startGameBloc ?? _MockStartGameBloc(), ), BlocProvider.value( value: assetsManagerCubit ?? _buildDefaultAssetsManagerCubit(), ), ], child: MaterialApp( theme: PinballTheme.standard, localizationsDelegates: const [ AppLocalizations.delegate, GlobalMaterialLocalizations.delegate, ], supportedLocales: AppLocalizations.supportedLocales, home: widget, ), ), ), ); }); } }
pinball/test/helpers/pump_app.dart/0
{ "file_path": "pinball/test/helpers/pump_app.dart", "repo_id": "pinball", "token_count": 1541 }
1,084
tasks: - name: prepare tool script: .ci/scripts/prepare_tool.sh - name: create all_plugins app script: .ci/scripts/create_all_plugins_app.sh - name: build all_plugins for iOS debug script: .ci/scripts/build_all_plugins.sh args: ["ios", "debug", "--no-codesign"] - name: build all_plugins for iOS release script: .ci/scripts/build_all_plugins.sh args: ["ios", "release", "--no-codesign"]
plugins/.ci/targets/ios_build_all_plugins.yaml/0
{ "file_path": "plugins/.ci/targets/ios_build_all_plugins.yaml", "repo_id": "plugins", "token_count": 156 }
1,085
# Contributing to Flutter Plugins | **ARCHIVED** | |--------------| | This repository is no longer in use; all source has moved to [flutter/packages](https://github.com/flutter/packages) and future development work will be done there. | ## ARCHIVED CONTENT _See also: [Flutter's code of conduct](https://github.com/flutter/flutter/blob/master/CODE_OF_CONDUCT.md)_ ## Welcome For an introduction to contributing to Flutter, see [our contributor guide](https://github.com/flutter/flutter/blob/master/CONTRIBUTING.md). Additional resources specific to the plugins repository: - [Setting up the Plugins development environment](https://github.com/flutter/flutter/wiki/Setting-up-the-Plugins-development-environment), which covers the setup process for this repository. - [Plugins repository structure](https://github.com/flutter/flutter/wiki/Plugins-and-Packages-repository-structure), to get an overview of how this repository is laid out. - [Plugin tests](https://github.com/flutter/flutter/wiki/Plugin-Tests), which explains the different kinds of tests used for plugins, where to find them, and how to run them. As explained in the Flutter guide, [**PRs need tests**](https://github.com/flutter/flutter/wiki/Tree-hygiene#tests), so this is critical to read before submitting a PR. - [Contributing to Plugins and Packages](https://github.com/flutter/flutter/wiki/Contributing-to-Plugins-and-Packages), for more information about how to make PRs for this repository, especially when changing federated plugins. ## Other notes ### Style Flutter plugins follow Google style—or Flutter style for Dart—for the languages they use, and use auto-formatters: - [Dart](https://github.com/flutter/flutter/wiki/Style-guide-for-Flutter-repo) formatted with `dart format` - [C++](https://google.github.io/styleguide/cppguide.html) formatted with `clang-format` - **Note**: The Linux plugins generally follow idiomatic GObject-based C style. See [the engine style notes](https://github.com/flutter/engine/blob/main/CONTRIBUTING.md#style) for more details, and exceptions. - [Java](https://google.github.io/styleguide/javaguide.html) formatted with `google-java-format` - [Objective-C](https://google.github.io/styleguide/objcguide.html) formatted with `clang-format` ### Releasing If you are a team member landing a PR, or just want to know what the release process is for plugin changes, see [the release documentation](https://github.com/flutter/flutter/wiki/Releasing-a-Plugin-or-Package).
plugins/CONTRIBUTING.md/0
{ "file_path": "plugins/CONTRIBUTING.md", "repo_id": "plugins", "token_count": 764 }
1,086
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.camera.features.flash; import android.hardware.camera2.CaptureRequest; import io.flutter.plugins.camera.CameraProperties; import io.flutter.plugins.camera.features.CameraFeature; /** Controls the flash configuration on the {@link android.hardware.camera2} API. */ public class FlashFeature extends CameraFeature<FlashMode> { private FlashMode currentSetting = FlashMode.auto; /** * Creates a new instance of the {@link FlashFeature}. * * @param cameraProperties Collection of characteristics for the current camera device. */ public FlashFeature(CameraProperties cameraProperties) { super(cameraProperties); } @Override public String getDebugName() { return "FlashFeature"; } @Override public FlashMode getValue() { return currentSetting; } @Override public void setValue(FlashMode value) { this.currentSetting = value; } @Override public boolean checkIsSupported() { Boolean available = cameraProperties.getFlashInfoAvailable(); return available != null && available; } @Override public void updateBuilder(CaptureRequest.Builder requestBuilder) { if (!checkIsSupported()) { return; } switch (currentSetting) { case off: requestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON); requestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF); break; case always: requestBuilder.set( CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_ALWAYS_FLASH); requestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF); break; case torch: requestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON); requestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_TORCH); break; case auto: requestBuilder.set( CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH); requestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF); break; } } }
plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/flash/FlashFeature.java/0
{ "file_path": "plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/flash/FlashFeature.java", "repo_id": "plugins", "token_count": 794 }
1,087
name: camera_android description: Android implementation of the camera plugin. repository: https://github.com/flutter/plugins/tree/main/packages/camera/camera_android issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+camera%22 version: 0.10.4 environment: sdk: ">=2.14.0 <3.0.0" flutter: ">=3.0.0" flutter: plugin: implements: camera platforms: android: package: io.flutter.plugins.camera pluginClass: CameraPlugin dartPluginClass: AndroidCamera dependencies: camera_platform_interface: ^2.3.1 flutter: sdk: flutter flutter_plugin_android_lifecycle: ^2.0.2 stream_transform: ^2.0.0 dev_dependencies: async: ^2.5.0 flutter_driver: sdk: flutter flutter_test: sdk: flutter
plugins/packages/camera/camera_android/pubspec.yaml/0
{ "file_path": "plugins/packages/camera/camera_android/pubspec.yaml", "repo_id": "plugins", "token_count": 324 }
1,088
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.camerax; import androidx.annotation.NonNull; import androidx.camera.core.CameraInfo; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.CameraInfoHostApi; import java.util.Objects; public class CameraInfoHostApiImpl implements CameraInfoHostApi { private final InstanceManager instanceManager; public CameraInfoHostApiImpl(InstanceManager instanceManager) { this.instanceManager = instanceManager; } @Override public Long getSensorRotationDegrees(@NonNull Long identifier) { CameraInfo cameraInfo = (CameraInfo) Objects.requireNonNull(instanceManager.getInstance(identifier)); return Long.valueOf(cameraInfo.getSensorRotationDegrees()); } }
plugins/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraInfoHostApiImpl.java/0
{ "file_path": "plugins/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraInfoHostApiImpl.java", "repo_id": "plugins", "token_count": 256 }
1,089
group 'com.example.espresso' version '1.0' buildscript { repositories { google() mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:7.4.1' } } rootProject.allprojects { repositories { google() mavenCentral() } } apply plugin: 'com.android.library' android { compileSdkVersion 31 defaultConfig { minSdkVersion 16 testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } lintOptions { disable 'AndroidGradlePluginVersion', 'InvalidPackage', 'GradleDependency' baseline file("lint-baseline.xml") } testOptions { unitTests.includeAndroidResources = true unitTests.returnDefaultValues = true unitTests.all { testLogging { events "passed", "skipped", "failed", "standardOut", "standardError" outputs.upToDateWhen {false} showStandardStreams = true } } } } dependencies { implementation 'com.google.guava:guava:31.1-android' implementation 'com.squareup.okhttp3:okhttp:4.10.0' implementation 'com.google.code.gson:gson:2.10.1' androidTestImplementation 'org.hamcrest:hamcrest:2.2' testImplementation 'junit:junit:4.13.2' testImplementation "com.google.truth:truth:1.0" api 'androidx.test:runner:1.1.1' api 'androidx.test.espresso:espresso-core:3.1.1' // Core library api 'androidx.test:core:1.0.0' // AndroidJUnitRunner and JUnit Rules api 'androidx.test:runner:1.1.0' api 'androidx.test:rules:1.1.0' // Assertions api 'androidx.test.ext:junit:1.1.5' api 'androidx.test.ext:truth:1.5.0' api 'com.google.truth:truth:0.42' // Espresso dependencies api 'androidx.test.espresso:espresso-core:3.5.1' api 'androidx.test.espresso:espresso-contrib:3.5.1' api 'androidx.test.espresso:espresso-intents:3.5.1' api 'androidx.test.espresso:espresso-accessibility:3.5.1' api 'androidx.test.espresso:espresso-web:3.5.1' api 'androidx.test.espresso.idling:idling-concurrent:3.5.1' // The following Espresso dependency can be either "implementation" // or "androidTestImplementation", depending on whether you want the // dependency to appear on your APK's compile classpath or the test APK // classpath. api 'androidx.test.espresso:espresso-idling-resource:3.5.1' }
plugins/packages/espresso/android/build.gradle/0
{ "file_path": "plugins/packages/espresso/android/build.gradle", "repo_id": "plugins", "token_count": 1043 }
1,090
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package com.example.espresso_example; import static androidx.test.espresso.flutter.EspressoFlutter.onFlutterWidget; import static androidx.test.espresso.flutter.action.FlutterActions.click; import static androidx.test.espresso.flutter.action.FlutterActions.syntheticClick; import static androidx.test.espresso.flutter.assertion.FlutterAssertions.matches; import static androidx.test.espresso.flutter.matcher.FlutterMatchers.withText; import static androidx.test.espresso.flutter.matcher.FlutterMatchers.withTooltip; import static androidx.test.espresso.flutter.matcher.FlutterMatchers.withValueKey; import static com.google.common.truth.Truth.assertThat; import androidx.test.core.app.ActivityScenario; import androidx.test.espresso.flutter.EspressoFlutter.WidgetInteraction; import androidx.test.espresso.flutter.assertion.FlutterAssertions; import androidx.test.espresso.flutter.matcher.FlutterMatchers; import androidx.test.ext.junit.runners.AndroidJUnit4; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; /** Unit tests for {@link EspressoFlutter}. */ @RunWith(AndroidJUnit4.class) public class MainActivityTest { @Before public void setUp() throws Exception { ActivityScenario.launch(MainActivity.class); } @Test public void performTripleClick() { WidgetInteraction interaction = onFlutterWidget(withTooltip("Increment")).perform(click(), click()).perform(click()); assertThat(interaction).isNotNull(); onFlutterWidget(withValueKey("CountText")).check(matches(withText("Button tapped 3 times."))); } @Test public void performClick() { WidgetInteraction interaction = onFlutterWidget(withTooltip("Increment")).perform(click()); assertThat(interaction).isNotNull(); onFlutterWidget(withValueKey("CountText")).check(matches(withText("Button tapped 1 time."))); } @Test public void performSyntheticClick() { WidgetInteraction interaction = onFlutterWidget(withTooltip("Increment")).perform(syntheticClick()); assertThat(interaction).isNotNull(); onFlutterWidget(withValueKey("CountText")).check(matches(withText("Button tapped 1 time."))); } @Test public void performTwiceSyntheticClicks() { WidgetInteraction interaction = onFlutterWidget(withTooltip("Increment")).perform(syntheticClick(), syntheticClick()); assertThat(interaction).isNotNull(); onFlutterWidget(withValueKey("CountText")).check(matches(withText("Button tapped 2 times."))); } @Test public void isIncrementButtonExists() { onFlutterWidget(FlutterMatchers.withTooltip("Increment")) .check(FlutterAssertions.matches(FlutterMatchers.isExisting())); } @Test public void isAppBarExists() { onFlutterWidget(FlutterMatchers.withType("AppBar")) .check(FlutterAssertions.matches(FlutterMatchers.isExisting())); } }
plugins/packages/espresso/example/android/app/src/androidTest/java/com/example/MainActivityTest.java/0
{ "file_path": "plugins/packages/espresso/example/android/app/src/androidTest/java/com/example/MainActivityTest.java", "repo_id": "plugins", "token_count": 992 }
1,091
name: file_selector_linux description: Liunx implementation of the file_selector plugin. repository: https://github.com/flutter/plugins/tree/main/packages/file_selector/file_selector_linux issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+file_selector%22 version: 0.9.1 environment: sdk: ">=2.12.0 <3.0.0" flutter: ">=3.0.0" flutter: plugin: implements: file_selector platforms: linux: pluginClass: FileSelectorPlugin dartPluginClass: FileSelectorLinux dependencies: cross_file: ^0.3.1 file_selector_platform_interface: ^2.4.0 flutter: sdk: flutter dev_dependencies: flutter_test: sdk: flutter
plugins/packages/file_selector/file_selector_linux/pubspec.yaml/0
{ "file_path": "plugins/packages/file_selector/file_selector_linux/pubspec.yaml", "repo_id": "plugins", "token_count": 289 }
1,092
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:file_selector_platform_interface/file_selector_platform_interface.dart'; import 'src/messages.g.dart'; /// An implementation of [FileSelectorPlatform] for macOS. class FileSelectorMacOS extends FileSelectorPlatform { final FileSelectorApi _hostApi = FileSelectorApi(); /// Registers the macOS implementation. static void registerWith() { FileSelectorPlatform.instance = FileSelectorMacOS(); } @override Future<XFile?> openFile({ List<XTypeGroup>? acceptedTypeGroups, String? initialDirectory, String? confirmButtonText, }) async { final List<String?> paths = await _hostApi.displayOpenPanel(OpenPanelOptions( allowsMultipleSelection: false, canChooseDirectories: false, canChooseFiles: true, baseOptions: SavePanelOptions( allowedFileTypes: _allowedTypesFromTypeGroups(acceptedTypeGroups), directoryPath: initialDirectory, prompt: confirmButtonText, ))); return paths.isEmpty ? null : XFile(paths.first!); } @override Future<List<XFile>> openFiles({ List<XTypeGroup>? acceptedTypeGroups, String? initialDirectory, String? confirmButtonText, }) async { final List<String?> paths = await _hostApi.displayOpenPanel(OpenPanelOptions( allowsMultipleSelection: true, canChooseDirectories: false, canChooseFiles: true, baseOptions: SavePanelOptions( allowedFileTypes: _allowedTypesFromTypeGroups(acceptedTypeGroups), directoryPath: initialDirectory, prompt: confirmButtonText, ))); return paths.map((String? path) => XFile(path!)).toList(); } @override Future<String?> getSavePath({ List<XTypeGroup>? acceptedTypeGroups, String? initialDirectory, String? suggestedName, String? confirmButtonText, }) async { return _hostApi.displaySavePanel(SavePanelOptions( allowedFileTypes: _allowedTypesFromTypeGroups(acceptedTypeGroups), directoryPath: initialDirectory, nameFieldStringValue: suggestedName, prompt: confirmButtonText, )); } @override Future<String?> getDirectoryPath({ String? initialDirectory, String? confirmButtonText, }) async { final List<String?> paths = await _hostApi.displayOpenPanel(OpenPanelOptions( allowsMultipleSelection: false, canChooseDirectories: true, canChooseFiles: false, baseOptions: SavePanelOptions( directoryPath: initialDirectory, prompt: confirmButtonText, ))); return paths.isEmpty ? null : paths.first; } // Converts the type group list into a flat list of all allowed types, since // macOS doesn't support filter groups. AllowedTypes? _allowedTypesFromTypeGroups(List<XTypeGroup>? typeGroups) { if (typeGroups == null || typeGroups.isEmpty) { return null; } final AllowedTypes allowedTypes = AllowedTypes( extensions: <String>[], mimeTypes: <String>[], utis: <String>[], ); for (final XTypeGroup typeGroup in typeGroups) { // If any group allows everything, no filtering should be done. if (typeGroup.allowsAny) { return null; } // Reject a filter that isn't an allow-any, but doesn't set any // macOS-supported filter categories. if ((typeGroup.extensions?.isEmpty ?? true) && (typeGroup.macUTIs?.isEmpty ?? true) && (typeGroup.mimeTypes?.isEmpty ?? true)) { throw ArgumentError('Provided type group $typeGroup does not allow ' 'all files, but does not set any of the macOS-supported filter ' 'categories. At least one of "extensions", "macUTIs", or ' '"mimeTypes" must be non-empty for macOS if anything is ' 'non-empty.'); } allowedTypes.extensions.addAll(typeGroup.extensions ?? <String>[]); allowedTypes.mimeTypes.addAll(typeGroup.mimeTypes ?? <String>[]); allowedTypes.utis.addAll(typeGroup.macUTIs ?? <String>[]); } return allowedTypes; } }
plugins/packages/file_selector/file_selector_macos/lib/file_selector_macos.dart/0
{ "file_path": "plugins/packages/file_selector/file_selector_macos/lib/file_selector_macos.dart", "repo_id": "plugins", "token_count": 1655 }
1,093
name: file_selector_windows description: Windows implementation of the file_selector plugin. repository: https://github.com/flutter/plugins/tree/main/packages/file_selector/file_selector_windows issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+file_selector%22 version: 0.9.1+4 environment: sdk: ">=2.12.0 <3.0.0" flutter: ">=3.0.0" flutter: plugin: implements: file_selector platforms: windows: dartPluginClass: FileSelectorWindows pluginClass: FileSelectorWindows dependencies: cross_file: ^0.3.1 file_selector_platform_interface: ^2.2.0 flutter: sdk: flutter dev_dependencies: build_runner: 2.1.11 flutter_test: sdk: flutter mockito: ^5.1.0 pigeon: ^3.2.5
plugins/packages/file_selector/file_selector_windows/pubspec.yaml/0
{ "file_path": "plugins/packages/file_selector/file_selector_windows/pubspec.yaml", "repo_id": "plugins", "token_count": 321 }
1,094
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "file_selector_plugin.h" #include <flutter/method_call.h> #include <flutter/method_result_functions.h> #include <flutter/plugin_registrar_windows.h> #include <flutter/standard_method_codec.h> #include <gmock/gmock.h> #include <gtest/gtest.h> #include <windows.h> #include <functional> #include <memory> #include <string> #include <variant> #include "file_dialog_controller.h" #include "string_utils.h" #include "test/test_file_dialog_controller.h" #include "test/test_utils.h" namespace file_selector_windows { namespace test { namespace { using flutter::CustomEncodableValue; using flutter::EncodableList; using flutter::EncodableMap; using flutter::EncodableValue; // These structs and classes are a workaround for // https://github.com/flutter/flutter/issues/104286 and // https://github.com/flutter/flutter/issues/104653. struct AllowMultipleArg { bool value = false; AllowMultipleArg(bool val) : value(val) {} }; struct SelectFoldersArg { bool value = false; SelectFoldersArg(bool val) : value(val) {} }; SelectionOptions CreateOptions(AllowMultipleArg allow_multiple, SelectFoldersArg select_folders, const EncodableList& allowed_types) { SelectionOptions options; options.set_allow_multiple(allow_multiple.value); options.set_select_folders(select_folders.value); options.set_allowed_types(allowed_types); return options; } TypeGroup CreateTypeGroup(std::string_view label, const EncodableList& extensions) { TypeGroup group; group.set_label(label); group.set_extensions(extensions); return group; } } // namespace TEST(FileSelectorPlugin, TestOpenSimple) { const HWND fake_window = reinterpret_cast<HWND>(1337); ScopedTestShellItem fake_selected_file; IShellItemArrayPtr fake_result_array; ::SHCreateShellItemArrayFromShellItem(fake_selected_file.file(), IID_PPV_ARGS(&fake_result_array)); bool shown = false; MockShow show_validator = [&shown, fake_result_array, fake_window]( const TestFileDialogController& dialog, HWND parent) { shown = true; EXPECT_EQ(parent, fake_window); // Validate options. FILEOPENDIALOGOPTIONS options; dialog.GetOptions(&options); EXPECT_EQ(options & FOS_ALLOWMULTISELECT, 0U); EXPECT_EQ(options & FOS_PICKFOLDERS, 0U); return MockShowResult(fake_result_array); }; FileSelectorPlugin plugin( [fake_window] { return fake_window; }, std::make_unique<TestFileDialogControllerFactory>(show_validator)); ErrorOr<EncodableList> result = plugin.ShowOpenDialog( CreateOptions(AllowMultipleArg(false), SelectFoldersArg(false), EncodableList()), nullptr, nullptr); EXPECT_TRUE(shown); ASSERT_FALSE(result.has_error()); const EncodableList& paths = result.value(); EXPECT_EQ(paths.size(), 1); EXPECT_EQ(std::get<std::string>(paths[0]), Utf8FromUtf16(fake_selected_file.path())); } TEST(FileSelectorPlugin, TestOpenWithArguments) { const HWND fake_window = reinterpret_cast<HWND>(1337); ScopedTestShellItem fake_selected_file; IShellItemArrayPtr fake_result_array; ::SHCreateShellItemArrayFromShellItem(fake_selected_file.file(), IID_PPV_ARGS(&fake_result_array)); bool shown = false; MockShow show_validator = [&shown, fake_result_array, fake_window]( const TestFileDialogController& dialog, HWND parent) { shown = true; EXPECT_EQ(parent, fake_window); // Validate arguments. EXPECT_EQ(dialog.GetDialogFolderPath(), L"C:\\Program Files"); // Make sure that the folder was called via SetFolder, not SetDefaultFolder. EXPECT_EQ(dialog.GetSetFolderPath(), L"C:\\Program Files"); EXPECT_EQ(dialog.GetOkButtonLabel(), L"Open it!"); return MockShowResult(fake_result_array); }; FileSelectorPlugin plugin( [fake_window] { return fake_window; }, std::make_unique<TestFileDialogControllerFactory>(show_validator)); // This directory must exist. std::string initial_directory("C:\\Program Files"); std::string confirm_button("Open it!"); ErrorOr<EncodableList> result = plugin.ShowOpenDialog( CreateOptions(AllowMultipleArg(false), SelectFoldersArg(false), EncodableList()), &initial_directory, &confirm_button); EXPECT_TRUE(shown); ASSERT_FALSE(result.has_error()); const EncodableList& paths = result.value(); EXPECT_EQ(paths.size(), 1); EXPECT_EQ(std::get<std::string>(paths[0]), Utf8FromUtf16(fake_selected_file.path())); } TEST(FileSelectorPlugin, TestOpenMultiple) { const HWND fake_window = reinterpret_cast<HWND>(1337); ScopedTestFileIdList fake_selected_file_1; ScopedTestFileIdList fake_selected_file_2; LPCITEMIDLIST fake_selected_files[] = { fake_selected_file_1.file(), fake_selected_file_2.file(), }; IShellItemArrayPtr fake_result_array; ::SHCreateShellItemArrayFromIDLists(2, fake_selected_files, &fake_result_array); bool shown = false; MockShow show_validator = [&shown, fake_result_array, fake_window]( const TestFileDialogController& dialog, HWND parent) { shown = true; EXPECT_EQ(parent, fake_window); // Validate options. FILEOPENDIALOGOPTIONS options; dialog.GetOptions(&options); EXPECT_NE(options & FOS_ALLOWMULTISELECT, 0U); EXPECT_EQ(options & FOS_PICKFOLDERS, 0U); return MockShowResult(fake_result_array); }; FileSelectorPlugin plugin( [fake_window] { return fake_window; }, std::make_unique<TestFileDialogControllerFactory>(show_validator)); ErrorOr<EncodableList> result = plugin.ShowOpenDialog( CreateOptions(AllowMultipleArg(true), SelectFoldersArg(false), EncodableList()), nullptr, nullptr); EXPECT_TRUE(shown); ASSERT_FALSE(result.has_error()); const EncodableList& paths = result.value(); EXPECT_EQ(paths.size(), 2); EXPECT_EQ(std::get<std::string>(paths[0]), Utf8FromUtf16(fake_selected_file_1.path())); EXPECT_EQ(std::get<std::string>(paths[1]), Utf8FromUtf16(fake_selected_file_2.path())); } TEST(FileSelectorPlugin, TestOpenWithFilter) { const HWND fake_window = reinterpret_cast<HWND>(1337); ScopedTestShellItem fake_selected_file; IShellItemArrayPtr fake_result_array; ::SHCreateShellItemArrayFromShellItem(fake_selected_file.file(), IID_PPV_ARGS(&fake_result_array)); const EncodableValue text_group = CustomEncodableValue(CreateTypeGroup("Text", EncodableList({ EncodableValue("txt"), EncodableValue("json"), }))); const EncodableValue image_group = CustomEncodableValue(CreateTypeGroup("Images", EncodableList({ EncodableValue("png"), EncodableValue("gif"), EncodableValue("jpeg"), }))); const EncodableValue any_group = CustomEncodableValue(CreateTypeGroup("Any", EncodableList())); bool shown = false; MockShow show_validator = [&shown, fake_result_array, fake_window]( const TestFileDialogController& dialog, HWND parent) { shown = true; EXPECT_EQ(parent, fake_window); // Validate filter. const std::vector<DialogFilter>& filters = dialog.GetFileTypes(); EXPECT_EQ(filters.size(), 3U); if (filters.size() == 3U) { EXPECT_EQ(filters[0].name, L"Text"); EXPECT_EQ(filters[0].spec, L"*.txt;*.json"); EXPECT_EQ(filters[1].name, L"Images"); EXPECT_EQ(filters[1].spec, L"*.png;*.gif;*.jpeg"); EXPECT_EQ(filters[2].name, L"Any"); EXPECT_EQ(filters[2].spec, L"*.*"); } return MockShowResult(fake_result_array); }; FileSelectorPlugin plugin( [fake_window] { return fake_window; }, std::make_unique<TestFileDialogControllerFactory>(show_validator)); ErrorOr<EncodableList> result = plugin.ShowOpenDialog( CreateOptions(AllowMultipleArg(false), SelectFoldersArg(false), EncodableList({ text_group, image_group, any_group, })), nullptr, nullptr); EXPECT_TRUE(shown); ASSERT_FALSE(result.has_error()); const EncodableList& paths = result.value(); EXPECT_EQ(paths.size(), 1); EXPECT_EQ(std::get<std::string>(paths[0]), Utf8FromUtf16(fake_selected_file.path())); } TEST(FileSelectorPlugin, TestOpenCancel) { const HWND fake_window = reinterpret_cast<HWND>(1337); bool shown = false; MockShow show_validator = [&shown, fake_window]( const TestFileDialogController& dialog, HWND parent) { shown = true; return MockShowResult(); }; FileSelectorPlugin plugin( [fake_window] { return fake_window; }, std::make_unique<TestFileDialogControllerFactory>(show_validator)); ErrorOr<EncodableList> result = plugin.ShowOpenDialog( CreateOptions(AllowMultipleArg(false), SelectFoldersArg(false), EncodableList()), nullptr, nullptr); EXPECT_TRUE(shown); ASSERT_FALSE(result.has_error()); const EncodableList& paths = result.value(); EXPECT_EQ(paths.size(), 0); } TEST(FileSelectorPlugin, TestSaveSimple) { const HWND fake_window = reinterpret_cast<HWND>(1337); ScopedTestShellItem fake_selected_file; bool shown = false; MockShow show_validator = [&shown, fake_result = fake_selected_file.file(), fake_window]( const TestFileDialogController& dialog, HWND parent) { shown = true; EXPECT_EQ(parent, fake_window); // Validate options. FILEOPENDIALOGOPTIONS options; dialog.GetOptions(&options); EXPECT_EQ(options & FOS_ALLOWMULTISELECT, 0U); EXPECT_EQ(options & FOS_PICKFOLDERS, 0U); return MockShowResult(fake_result); }; FileSelectorPlugin plugin( [fake_window] { return fake_window; }, std::make_unique<TestFileDialogControllerFactory>(show_validator)); ErrorOr<EncodableList> result = plugin.ShowSaveDialog( CreateOptions(AllowMultipleArg(false), SelectFoldersArg(false), EncodableList()), nullptr, nullptr, nullptr); EXPECT_TRUE(shown); ASSERT_FALSE(result.has_error()); const EncodableList& paths = result.value(); EXPECT_EQ(paths.size(), 1); EXPECT_EQ(std::get<std::string>(paths[0]), Utf8FromUtf16(fake_selected_file.path())); } TEST(FileSelectorPlugin, TestSaveWithArguments) { const HWND fake_window = reinterpret_cast<HWND>(1337); ScopedTestShellItem fake_selected_file; bool shown = false; MockShow show_validator = [&shown, fake_result = fake_selected_file.file(), fake_window]( const TestFileDialogController& dialog, HWND parent) { shown = true; EXPECT_EQ(parent, fake_window); // Validate arguments. EXPECT_EQ(dialog.GetDialogFolderPath(), L"C:\\Program Files"); // Make sure that the folder was called via SetFolder, not // SetDefaultFolder. EXPECT_EQ(dialog.GetSetFolderPath(), L"C:\\Program Files"); EXPECT_EQ(dialog.GetFileName(), L"a name"); EXPECT_EQ(dialog.GetOkButtonLabel(), L"Save it!"); return MockShowResult(fake_result); }; FileSelectorPlugin plugin( [fake_window] { return fake_window; }, std::make_unique<TestFileDialogControllerFactory>(show_validator)); // This directory must exist. std::string initial_directory("C:\\Program Files"); std::string suggested_name("a name"); std::string confirm_button("Save it!"); ErrorOr<EncodableList> result = plugin.ShowSaveDialog( CreateOptions(AllowMultipleArg(false), SelectFoldersArg(false), EncodableList()), &initial_directory, &suggested_name, &confirm_button); EXPECT_TRUE(shown); ASSERT_FALSE(result.has_error()); const EncodableList& paths = result.value(); EXPECT_EQ(paths.size(), 1); EXPECT_EQ(std::get<std::string>(paths[0]), Utf8FromUtf16(fake_selected_file.path())); } TEST(FileSelectorPlugin, TestSaveCancel) { const HWND fake_window = reinterpret_cast<HWND>(1337); bool shown = false; MockShow show_validator = [&shown, fake_window]( const TestFileDialogController& dialog, HWND parent) { shown = true; return MockShowResult(); }; FileSelectorPlugin plugin( [fake_window] { return fake_window; }, std::make_unique<TestFileDialogControllerFactory>(show_validator)); ErrorOr<EncodableList> result = plugin.ShowSaveDialog( CreateOptions(AllowMultipleArg(false), SelectFoldersArg(false), EncodableList()), nullptr, nullptr, nullptr); EXPECT_TRUE(shown); ASSERT_FALSE(result.has_error()); const EncodableList& paths = result.value(); EXPECT_EQ(paths.size(), 0); } TEST(FileSelectorPlugin, TestGetDirectorySimple) { const HWND fake_window = reinterpret_cast<HWND>(1337); IShellItemPtr fake_selected_directory; // This must be a directory that actually exists. ::SHCreateItemFromParsingName(L"C:\\Program Files", nullptr, IID_PPV_ARGS(&fake_selected_directory)); IShellItemArrayPtr fake_result_array; ::SHCreateShellItemArrayFromShellItem(fake_selected_directory, IID_PPV_ARGS(&fake_result_array)); bool shown = false; MockShow show_validator = [&shown, fake_result_array, fake_window]( const TestFileDialogController& dialog, HWND parent) { shown = true; EXPECT_EQ(parent, fake_window); // Validate options. FILEOPENDIALOGOPTIONS options; dialog.GetOptions(&options); EXPECT_EQ(options & FOS_ALLOWMULTISELECT, 0U); EXPECT_NE(options & FOS_PICKFOLDERS, 0U); return MockShowResult(fake_result_array); }; FileSelectorPlugin plugin( [fake_window] { return fake_window; }, std::make_unique<TestFileDialogControllerFactory>(show_validator)); ErrorOr<EncodableList> result = plugin.ShowOpenDialog( CreateOptions(AllowMultipleArg(false), SelectFoldersArg(true), EncodableList()), nullptr, nullptr); EXPECT_TRUE(shown); ASSERT_FALSE(result.has_error()); const EncodableList& paths = result.value(); EXPECT_EQ(paths.size(), 1); EXPECT_EQ(std::get<std::string>(paths[0]), "C:\\Program Files"); } TEST(FileSelectorPlugin, TestGetDirectoryCancel) { const HWND fake_window = reinterpret_cast<HWND>(1337); bool shown = false; MockShow show_validator = [&shown, fake_window]( const TestFileDialogController& dialog, HWND parent) { shown = true; return MockShowResult(); }; FileSelectorPlugin plugin( [fake_window] { return fake_window; }, std::make_unique<TestFileDialogControllerFactory>(show_validator)); ErrorOr<EncodableList> result = plugin.ShowOpenDialog( CreateOptions(AllowMultipleArg(false), SelectFoldersArg(true), EncodableList()), nullptr, nullptr); EXPECT_TRUE(shown); ASSERT_FALSE(result.has_error()); const EncodableList& paths = result.value(); EXPECT_EQ(paths.size(), 0); } } // namespace test } // namespace file_selector_windows
plugins/packages/file_selector/file_selector_windows/windows/test/file_selector_plugin_test.cpp/0
{ "file_path": "plugins/packages/file_selector/file_selector_windows/windows/test/file_selector_plugin_test.cpp", "repo_id": "plugins", "token_count": 6842 }
1,095
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="io.flutter.plugins.flutter_plugin_android_lifecycle"> </manifest>
plugins/packages/flutter_plugin_android_lifecycle/android/src/main/AndroidManifest.xml/0
{ "file_path": "plugins/packages/flutter_plugin_android_lifecycle/android/src/main/AndroidManifest.xml", "repo_id": "plugins", "token_count": 52 }
1,096
## 2.4.5 * Fixes Initial padding not working when map has not been created yet. ## 2.4.4 * Fixes Points losing precision when converting to LatLng. * Updates minimum Flutter version to 3.0. ## 2.4.3 * Updates code for stricter lint checks. ## 2.4.2 * Updates code for stricter lint checks. ## 2.4.1 * Update `androidx.test.espresso:espresso-core` to 3.5.1. ## 2.4.0 * Adds the ability to request a specific map renderer. * Updates code for new analysis options. ## 2.3.3 * Update android gradle plugin to 7.3.1. ## 2.3.2 * Update `com.google.android.gms:play-services-maps` to 18.1.0. ## 2.3.1 * Updates imports for `prefer_relative_imports`. ## 2.3.0 * Switches the default for `useAndroidViewSurface` to true, and adds information about the current mode behaviors to the README. * Updates minimum Flutter version to 2.10. ## 2.2.0 * Updates `useAndroidViewSurface` to require Hybrid Composition, making the selection work again in Flutter 3.0+. Earlier versions of Flutter are no longer supported. * Fixes violations of new analysis option use_named_constants. * Fixes avoid_redundant_argument_values lint warnings and minor typos. ## 2.1.10 * Splits Android implementation out of `google_maps_flutter` as a federated implementation.
plugins/packages/google_maps_flutter/google_maps_flutter_android/CHANGELOG.md/0
{ "file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_android/CHANGELOG.md", "repo_id": "plugins", "token_count": 412 }
1,097
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:convert'; import 'dart:html' as html; import 'dart:typed_data'; import 'dart:ui'; import 'package:flutter_test/flutter_test.dart'; import 'package:google_maps/google_maps.dart' as gmaps; import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart'; import 'package:google_maps_flutter_web/google_maps_flutter_web.dart'; import 'package:http/http.dart' as http; import 'package:integration_test/integration_test.dart'; import 'resources/icon_image_base64.dart'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); group('MarkersController', () { late StreamController<MapEvent<Object?>> events; late MarkersController controller; late gmaps.GMap map; setUp(() { events = StreamController<MapEvent<Object?>>(); controller = MarkersController(stream: events); map = gmaps.GMap(html.DivElement()); controller.bindToMap(123, map); }); testWidgets('addMarkers', (WidgetTester tester) async { final Set<Marker> markers = <Marker>{ const Marker(markerId: MarkerId('1')), const Marker(markerId: MarkerId('2')), }; controller.addMarkers(markers); expect(controller.markers.length, 2); expect(controller.markers, contains(const MarkerId('1'))); expect(controller.markers, contains(const MarkerId('2'))); expect(controller.markers, isNot(contains(const MarkerId('66')))); }); testWidgets('changeMarkers', (WidgetTester tester) async { final Set<Marker> markers = <Marker>{ const Marker(markerId: MarkerId('1')), }; controller.addMarkers(markers); expect( controller.markers[const MarkerId('1')]?.marker?.draggable, isFalse); // Update the marker with radius 10 final Set<Marker> updatedMarkers = <Marker>{ const Marker(markerId: MarkerId('1'), draggable: true), }; controller.changeMarkers(updatedMarkers); expect(controller.markers.length, 1); expect( controller.markers[const MarkerId('1')]?.marker?.draggable, isTrue); }); testWidgets('removeMarkers', (WidgetTester tester) async { final Set<Marker> markers = <Marker>{ const Marker(markerId: MarkerId('1')), const Marker(markerId: MarkerId('2')), const Marker(markerId: MarkerId('3')), }; controller.addMarkers(markers); expect(controller.markers.length, 3); // Remove some markers... final Set<MarkerId> markerIdsToRemove = <MarkerId>{ const MarkerId('1'), const MarkerId('3'), }; controller.removeMarkers(markerIdsToRemove); expect(controller.markers.length, 1); expect(controller.markers, isNot(contains(const MarkerId('1')))); expect(controller.markers, contains(const MarkerId('2'))); expect(controller.markers, isNot(contains(const MarkerId('3')))); }); testWidgets('InfoWindow show/hide', (WidgetTester tester) async { final Set<Marker> markers = <Marker>{ const Marker( markerId: MarkerId('1'), infoWindow: InfoWindow(title: 'Title', snippet: 'Snippet'), ), }; controller.addMarkers(markers); expect(controller.markers[const MarkerId('1')]?.infoWindowShown, isFalse); controller.showMarkerInfoWindow(const MarkerId('1')); expect(controller.markers[const MarkerId('1')]?.infoWindowShown, isTrue); controller.hideMarkerInfoWindow(const MarkerId('1')); expect(controller.markers[const MarkerId('1')]?.infoWindowShown, isFalse); }); // https://github.com/flutter/flutter/issues/67380 testWidgets('only single InfoWindow is visible', (WidgetTester tester) async { final Set<Marker> markers = <Marker>{ const Marker( markerId: MarkerId('1'), infoWindow: InfoWindow(title: 'Title', snippet: 'Snippet'), ), const Marker( markerId: MarkerId('2'), infoWindow: InfoWindow(title: 'Title', snippet: 'Snippet'), ), }; controller.addMarkers(markers); expect(controller.markers[const MarkerId('1')]?.infoWindowShown, isFalse); expect(controller.markers[const MarkerId('2')]?.infoWindowShown, isFalse); controller.showMarkerInfoWindow(const MarkerId('1')); expect(controller.markers[const MarkerId('1')]?.infoWindowShown, isTrue); expect(controller.markers[const MarkerId('2')]?.infoWindowShown, isFalse); controller.showMarkerInfoWindow(const MarkerId('2')); expect(controller.markers[const MarkerId('1')]?.infoWindowShown, isFalse); expect(controller.markers[const MarkerId('2')]?.infoWindowShown, isTrue); }); // https://github.com/flutter/flutter/issues/66622 testWidgets('markers with custom bitmap icon work', (WidgetTester tester) async { final Uint8List bytes = const Base64Decoder().convert(iconImageBase64); final Set<Marker> markers = <Marker>{ Marker( markerId: const MarkerId('1'), icon: BitmapDescriptor.fromBytes(bytes), ), }; controller.addMarkers(markers); expect(controller.markers.length, 1); final gmaps.Icon? icon = controller.markers[const MarkerId('1')]?.marker?.icon as gmaps.Icon?; expect(icon, isNotNull); final String blobUrl = icon!.url!; expect(blobUrl, startsWith('blob:')); final http.Response response = await http.get(Uri.parse(blobUrl)); expect(response.bodyBytes, bytes, reason: 'Bytes from the Icon blob must match bytes used to create Marker'); }); // https://github.com/flutter/flutter/issues/73789 testWidgets('markers with custom bitmap icon pass size to sdk', (WidgetTester tester) async { final Uint8List bytes = const Base64Decoder().convert(iconImageBase64); final Set<Marker> markers = <Marker>{ Marker( markerId: const MarkerId('1'), icon: BitmapDescriptor.fromBytes(bytes, size: const Size(20, 30)), ), }; controller.addMarkers(markers); expect(controller.markers.length, 1); final gmaps.Icon? icon = controller.markers[const MarkerId('1')]?.marker?.icon as gmaps.Icon?; expect(icon, isNotNull); final gmaps.Size size = icon!.size!; final gmaps.Size scaledSize = icon.scaledSize!; expect(size.width, 20); expect(size.height, 30); expect(scaledSize.width, 20); expect(scaledSize.height, 30); }); // https://github.com/flutter/flutter/issues/67854 testWidgets('InfoWindow snippet can have links', (WidgetTester tester) async { final Set<Marker> markers = <Marker>{ const Marker( markerId: MarkerId('1'), infoWindow: InfoWindow( title: 'title for test', snippet: '<a href="https://www.google.com">Go to Google >>></a>', ), ), }; controller.addMarkers(markers); expect(controller.markers.length, 1); final html.HtmlElement? content = controller.markers[const MarkerId('1')] ?.infoWindow?.content as html.HtmlElement?; expect(content?.innerHtml, contains('title for test')); expect( content?.innerHtml, contains( '<a href="https://www.google.com">Go to Google &gt;&gt;&gt;</a>', )); }); // https://github.com/flutter/flutter/issues/67289 testWidgets('InfoWindow content is clickable', (WidgetTester tester) async { final Set<Marker> markers = <Marker>{ const Marker( markerId: MarkerId('1'), infoWindow: InfoWindow( title: 'title for test', snippet: 'some snippet', ), ), }; controller.addMarkers(markers); expect(controller.markers.length, 1); final html.HtmlElement? content = controller.markers[const MarkerId('1')] ?.infoWindow?.content as html.HtmlElement?; content?.click(); final MapEvent<Object?> event = await events.stream.first; expect(event, isA<InfoWindowTapEvent>()); expect((event as InfoWindowTapEvent).value, equals(const MarkerId('1'))); }); }); }
plugins/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/markers_test.dart/0
{ "file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/markers_test.dart", "repo_id": "plugins", "token_count": 3491 }
1,098
rootProject.name = 'image_picker_android'
plugins/packages/image_picker/image_picker_android/android/settings.gradle/0
{ "file_path": "plugins/packages/image_picker/image_picker_android/android/settings.gradle", "repo_id": "plugins", "token_count": 14 }
1,099
mock-maker-inline
plugins/packages/image_picker/image_picker_android/android/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker/0
{ "file_path": "plugins/packages/image_picker/image_picker_android/android/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker", "repo_id": "plugins", "token_count": 6 }
1,100
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:file_selector_platform_interface/file_selector_platform_interface.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:image_picker_platform_interface/image_picker_platform_interface.dart'; import 'package:image_picker_windows/image_picker_windows.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'image_picker_windows_test.mocks.dart'; @GenerateMocks(<Type>[FileSelectorPlatform]) void main() { TestWidgetsFlutterBinding.ensureInitialized(); // Returns the captured type groups from a mock call result, assuming that // exactly one call was made and only the type groups were captured. List<XTypeGroup> capturedTypeGroups(VerificationResult result) { return result.captured.single as List<XTypeGroup>; } group('$ImagePickerWindows()', () { final ImagePickerWindows plugin = ImagePickerWindows(); late MockFileSelectorPlatform mockFileSelectorPlatform; setUp(() { mockFileSelectorPlatform = MockFileSelectorPlatform(); when(mockFileSelectorPlatform.openFile( acceptedTypeGroups: anyNamed('acceptedTypeGroups'))) .thenAnswer((_) async => null); when(mockFileSelectorPlatform.openFiles( acceptedTypeGroups: anyNamed('acceptedTypeGroups'))) .thenAnswer((_) async => List<XFile>.empty()); ImagePickerWindows.fileSelector = mockFileSelectorPlatform; }); test('registered instance', () { ImagePickerWindows.registerWith(); expect(ImagePickerPlatform.instance, isA<ImagePickerWindows>()); }); group('images', () { test('pickImage passes the accepted type groups correctly', () async { await plugin.pickImage(source: ImageSource.gallery); final VerificationResult result = verify( mockFileSelectorPlatform.openFile( acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups'))); expect(capturedTypeGroups(result)[0].extensions, ImagePickerWindows.imageFormats); }); test('pickImage throws UnimplementedError when source is camera', () async { expect(() async => plugin.pickImage(source: ImageSource.camera), throwsA(isA<UnimplementedError>())); }); test('getImage passes the accepted type groups correctly', () async { await plugin.getImage(source: ImageSource.gallery); final VerificationResult result = verify( mockFileSelectorPlatform.openFile( acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups'))); expect(capturedTypeGroups(result)[0].extensions, ImagePickerWindows.imageFormats); }); test('getImage throws UnimplementedError when source is camera', () async { expect(() async => plugin.getImage(source: ImageSource.camera), throwsA(isA<UnimplementedError>())); }); test('getMultiImage passes the accepted type groups correctly', () async { await plugin.getMultiImage(); final VerificationResult result = verify( mockFileSelectorPlatform.openFiles( acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups'))); expect(capturedTypeGroups(result)[0].extensions, ImagePickerWindows.imageFormats); }); }); group('videos', () { test('pickVideo passes the accepted type groups correctly', () async { await plugin.pickVideo(source: ImageSource.gallery); final VerificationResult result = verify( mockFileSelectorPlatform.openFile( acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups'))); expect(capturedTypeGroups(result)[0].extensions, ImagePickerWindows.videoFormats); }); test('pickVideo throws UnimplementedError when source is camera', () async { expect(() async => plugin.pickVideo(source: ImageSource.camera), throwsA(isA<UnimplementedError>())); }); test('getVideo passes the accepted type groups correctly', () async { await plugin.getVideo(source: ImageSource.gallery); final VerificationResult result = verify( mockFileSelectorPlatform.openFile( acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups'))); expect(capturedTypeGroups(result)[0].extensions, ImagePickerWindows.videoFormats); }); test('getVideo throws UnimplementedError when source is camera', () async { expect(() async => plugin.getVideo(source: ImageSource.camera), throwsA(isA<UnimplementedError>())); }); }); }); }
plugins/packages/image_picker/image_picker_windows/test/image_picker_windows_test.dart/0
{ "file_path": "plugins/packages/image_picker/image_picker_windows/test/image_picker_windows_test.dart", "repo_id": "plugins", "token_count": 1799 }
1,101
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="io.flutter.plugins.inapppurchase"> </manifest>
plugins/packages/in_app_purchase/in_app_purchase_android/android/src/main/AndroidManifest.xml/0
{ "file_path": "plugins/packages/in_app_purchase/in_app_purchase_android/android/src/main/AndroidManifest.xml", "repo_id": "plugins", "token_count": 47 }
1,102
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter_test/flutter_test.dart'; import 'package:in_app_purchase_android/in_app_purchase_android.dart'; import 'package:in_app_purchase_platform_interface/in_app_purchase_platform_interface.dart'; import 'package:integration_test/integration_test.dart'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); testWidgets('Can create InAppPurchaseAndroid instance', (WidgetTester tester) async { InAppPurchaseAndroidPlatform.registerPlatform(); final InAppPurchasePlatform androidPlatform = InAppPurchasePlatform.instance; expect(androidPlatform, isNotNull); }); }
plugins/packages/in_app_purchase/in_app_purchase_android/example/integration_test/in_app_purchase_test.dart/0
{ "file_path": "plugins/packages/in_app_purchase/in_app_purchase_android/example/integration_test/in_app_purchase_test.dart", "repo_id": "plugins", "token_count": 244 }
1,103
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/services.dart'; import 'package:in_app_purchase_platform_interface/in_app_purchase_platform_interface.dart'; import '../billing_client_wrappers.dart'; import '../in_app_purchase_android.dart'; /// Contains InApp Purchase features that are only available on PlayStore. class InAppPurchaseAndroidPlatformAddition extends InAppPurchasePlatformAddition { /// Creates a [InAppPurchaseAndroidPlatformAddition] which uses the supplied /// `BillingClient` to provide Android specific features. InAppPurchaseAndroidPlatformAddition(this._billingClient); /// Whether pending purchase is enabled. /// /// **Deprecation warning:** it is no longer required to call /// [enablePendingPurchases] when initializing your application. From now on /// this is handled internally and the [enablePendingPurchase] property will /// always return `true`. /// // ignore: deprecated_member_use_from_same_package /// See also [enablePendingPurchases] for more on pending purchases. @Deprecated( 'The requirement to call `enablePendingPurchases()` has become obsolete ' "since Google Play no longer accepts app submissions that don't support " 'pending purchases.') static bool get enablePendingPurchase => true; /// Enable the [InAppPurchaseConnection] to handle pending purchases. /// /// **Deprecation warning:** it is no longer required to call /// [enablePendingPurchases] when initializing your application. @Deprecated( 'The requirement to call `enablePendingPurchases()` has become obsolete ' "since Google Play no longer accepts app submissions that don't support " 'pending purchases.') static void enablePendingPurchases() { // No-op, until it is time to completely remove this method from the API. } final BillingClient _billingClient; /// Mark that the user has consumed a product. /// /// You are responsible for consuming all consumable purchases once they are /// delivered. The user won't be able to buy the same product again until the /// purchase of the product is consumed. Future<BillingResultWrapper> consumePurchase(PurchaseDetails purchase) { if (purchase.verificationData == null) { throw ArgumentError( 'consumePurchase unsuccessful. The `purchase.verificationData` is not valid'); } return _billingClient .consumeAsync(purchase.verificationData.serverVerificationData); } /// Query all previous purchases. /// /// The `applicationUserName` should match whatever was sent in the initial /// `PurchaseParam`, if anything. If no `applicationUserName` was specified in /// the initial `PurchaseParam`, use `null`. /// /// This does not return consumed products. If you want to restore unused /// consumable products, you need to persist consumable product information /// for your user on your own server. /// /// See also: /// /// * [refreshPurchaseVerificationData], for reloading failed /// [PurchaseDetails.verificationData]. Future<QueryPurchaseDetailsResponse> queryPastPurchases( {String? applicationUserName}) async { List<PurchasesResultWrapper> responses; PlatformException? exception; try { responses = await Future.wait(<Future<PurchasesResultWrapper>>[ _billingClient.queryPurchases(SkuType.inapp), _billingClient.queryPurchases(SkuType.subs) ]); } on PlatformException catch (e) { exception = e; responses = <PurchasesResultWrapper>[ PurchasesResultWrapper( responseCode: BillingResponse.error, purchasesList: const <PurchaseWrapper>[], billingResult: BillingResultWrapper( responseCode: BillingResponse.error, debugMessage: e.details.toString(), ), ), PurchasesResultWrapper( responseCode: BillingResponse.error, purchasesList: const <PurchaseWrapper>[], billingResult: BillingResultWrapper( responseCode: BillingResponse.error, debugMessage: e.details.toString(), ), ) ]; } final Set<String> errorCodeSet = responses .where((PurchasesResultWrapper response) => response.responseCode != BillingResponse.ok) .map((PurchasesResultWrapper response) => response.responseCode.toString()) .toSet(); final String errorMessage = errorCodeSet.isNotEmpty ? errorCodeSet.join(', ') : ''; final List<GooglePlayPurchaseDetails> pastPurchases = responses.expand((PurchasesResultWrapper response) { return response.purchasesList; }).map((PurchaseWrapper purchaseWrapper) { return GooglePlayPurchaseDetails.fromPurchase(purchaseWrapper); }).toList(); IAPError? error; if (exception != null) { error = IAPError( source: kIAPSource, code: exception.code, message: exception.message ?? '', details: exception.details); } else if (errorMessage.isNotEmpty) { error = IAPError( source: kIAPSource, code: kRestoredPurchaseErrorCode, message: errorMessage); } return QueryPurchaseDetailsResponse( pastPurchases: pastPurchases, error: error); } /// Checks if the specified feature or capability is supported by the Play Store. /// Call this to check if a [BillingClientFeature] is supported by the device. Future<bool> isFeatureSupported(BillingClientFeature feature) async { return _billingClient.isFeatureSupported(feature); } /// Initiates a flow to confirm the change of price for an item subscribed by the user. /// /// When the price of a user subscribed item has changed, launch this flow to take users to /// a screen with price change information. User can confirm the new price or cancel the flow. /// /// The skuDetails needs to have already been fetched in a /// [InAppPurchaseAndroidPlatform.queryProductDetails] call. Future<BillingResultWrapper> launchPriceChangeConfirmationFlow( {required String sku}) { return _billingClient.launchPriceChangeConfirmationFlow(sku: sku); } }
plugins/packages/in_app_purchase/in_app_purchase_android/lib/src/in_app_purchase_android_platform_addition.dart/0
{ "file_path": "plugins/packages/in_app_purchase/in_app_purchase_android/lib/src/in_app_purchase_android_platform_addition.dart", "repo_id": "plugins", "token_count": 2037 }
1,104
## NEXT * Updates minimum Flutter version to 3.0. ## 1.3.2 * Updates imports for `prefer_relative_imports`. * Updates minimum Flutter version to 2.10. * Removes unnecessary imports. ## 1.3.1 * Update to use the `verify` method introduced in plugin_platform_interface 2.1.0. ## 1.3.0 * Added new `PurchaseStatus` named `canceled` to distinguish between an error and user cancellation. ## 1.2.0 * Added `toString()` to `IAPError` ## 1.1.0 * Added `currencySymbol` in ProductDetails. ## 1.0.1 * Fixed `Restoring previous purchases` link. ## 1.0.0 * Initial open-source release.
plugins/packages/in_app_purchase/in_app_purchase_platform_interface/CHANGELOG.md/0
{ "file_path": "plugins/packages/in_app_purchase/in_app_purchase_platform_interface/CHANGELOG.md", "repo_id": "plugins", "token_count": 205 }
1,105
hello
plugins/packages/ios_platform_images/example/ios/Runner/textfile/0
{ "file_path": "plugins/packages/ios_platform_images/example/ios/Runner/textfile", "repo_id": "plugins", "token_count": 2 }
1,106
org.gradle.jvmargs=-Xmx4G android.useAndroidX=true android.enableJetifier=true android.enableR8=true
plugins/packages/local_auth/local_auth/example/android/gradle.properties/0
{ "file_path": "plugins/packages/local_auth/local_auth/example/android/gradle.properties", "repo_id": "plugins", "token_count": 38 }
1,107
group 'io.flutter.plugins.localauth' version '1.0-SNAPSHOT' buildscript { repositories { google() mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:7.3.1' } } rootProject.allprojects { repositories { google() mavenCentral() } } apply plugin: 'com.android.library' android { compileSdkVersion 33 defaultConfig { minSdkVersion 16 testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } lintOptions { disable 'AndroidGradlePluginVersion', 'InvalidPackage', 'GradleDependency' baseline file("lint-baseline.xml") } testOptions { unitTests.includeAndroidResources = true unitTests.returnDefaultValues = true unitTests.all { testLogging { events "passed", "skipped", "failed", "standardOut", "standardError" outputs.upToDateWhen {false} showStandardStreams = true } } } } dependencies { api "androidx.core:core:1.9.0" api "androidx.biometric:biometric:1.1.0" api "androidx.fragment:fragment:1.5.5" testImplementation 'junit:junit:4.13.2' testImplementation 'org.mockito:mockito-inline:5.0.0' testImplementation 'org.robolectric:robolectric:4.5' androidTestImplementation 'androidx.test:runner:1.2.0' androidTestImplementation 'androidx.test:rules:1.2.0' androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1' }
plugins/packages/local_auth/local_auth_android/android/build.gradle/0
{ "file_path": "plugins/packages/local_auth/local_auth_android/android/build.gradle", "repo_id": "plugins", "token_count": 675 }
1,108
<resources> <!-- Fingerprint dialog theme. --> <style name="AlertDialogCustom" parent="@android:style/Theme.Material.Dialog.Alert"> <item name="android:background">#FFFFFFFF</item> <item name="android:textStyle">bold</item> <item name="android:textSize">14sp</item> <item name="android:colorAccent">#FF009688</item> </style> </resources>
plugins/packages/local_auth/local_auth_android/android/src/main/res/values/styles.xml/0
{ "file_path": "plugins/packages/local_auth/local_auth_android/android/src/main/res/values/styles.xml", "repo_id": "plugins", "token_count": 121 }
1,109
#include "../../Flutter/Flutter-Debug.xcconfig" #include "Warnings.xcconfig"
plugins/packages/path_provider/path_provider/example/macos/Runner/Configs/Debug.xcconfig/0
{ "file_path": "plugins/packages/path_provider/path_provider/example/macos/Runner/Configs/Debug.xcconfig", "repo_id": "plugins", "token_count": 32 }
1,110
name: path_provider_android description: Android implementation of the path_provider plugin. repository: https://github.com/flutter/plugins/tree/main/packages/path_provider/path_provider_android issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+path_provider%22 version: 2.0.22 environment: sdk: ">=2.14.0 <3.0.0" flutter: ">=3.0.0" flutter: plugin: implements: path_provider platforms: android: package: io.flutter.plugins.pathprovider pluginClass: PathProviderPlugin dartPluginClass: PathProviderAndroid dependencies: flutter: sdk: flutter path_provider_platform_interface: ^2.0.1 dev_dependencies: flutter_driver: sdk: flutter flutter_test: sdk: flutter integration_test: sdk: flutter pigeon: ^3.1.5 test: ^1.16.0
plugins/packages/path_provider/path_provider_android/pubspec.yaml/0
{ "file_path": "plugins/packages/path_provider/path_provider_android/pubspec.yaml", "repo_id": "plugins", "token_count": 346 }
1,111