code
stringlengths
8
3.25M
repository
stringlengths
15
175
metadata
stringlengths
66
249
// 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/foundation.dart'; import 'package:flutter/material.dart'; /// Screen that allows the user to select multiple image files using /// `openFiles`, then displays the selected images in a gallery dialog. class OpenMultipleImagesPage extends StatelessWidget { /// Default Constructor const OpenMultipleImagesPage({super.key}); Future<void> _openImageFile(BuildContext context) async { const XTypeGroup jpgsTypeGroup = XTypeGroup( label: 'JPEGs', extensions: <String>['jpg', 'jpeg'], uniformTypeIdentifiers: <String>['public.jpeg'], ); const XTypeGroup pngTypeGroup = XTypeGroup( label: 'PNGs', extensions: <String>['png'], uniformTypeIdentifiers: <String>['public.png'], ); final List<XFile> files = await FileSelectorPlatform.instance .openFiles(acceptedTypeGroups: <XTypeGroup>[ jpgsTypeGroup, pngTypeGroup, ]); if (files.isEmpty) { // Operation was canceled by the user. return; } final List<Uint8List> imageBytes = <Uint8List>[]; for (final XFile file in files) { imageBytes.add(await file.readAsBytes()); } if (context.mounted) { await showDialog<void>( context: context, builder: (BuildContext context) => MultipleImagesDisplay(imageBytes), ); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Open multiple images'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ ElevatedButton( style: ElevatedButton.styleFrom( foregroundColor: Colors.blue, backgroundColor: Colors.white, ), child: const Text('Press to open multiple images (png, jpg)'), onPressed: () => _openImageFile(context), ), ], ), ), ); } } /// Widget that displays a text file in a dialog. class MultipleImagesDisplay extends StatelessWidget { /// Default Constructor. const MultipleImagesDisplay(this.fileBytes, {super.key}); /// The bytes containing the images. final List<Uint8List> fileBytes; @override Widget build(BuildContext context) { return AlertDialog( title: const Text('Gallery'), // On web the filePath is a blob url // while on other platforms it is a system path. content: Center( child: Row( children: <Widget>[ for (int i = 0; i < fileBytes.length; i++) Flexible( key: Key('result_image_name$i'), child: Image.memory(fileBytes[i]), ) ], ), ), actions: <Widget>[ TextButton( child: const Text('Close'), onPressed: () { Navigator.pop(context); }, ), ], ); } }
packages/packages/file_selector/file_selector_android/example/lib/open_multiple_images_page.dart/0
{'file_path': 'packages/packages/file_selector/file_selector_android/example/lib/open_multiple_images_page.dart', 'repo_id': 'packages', 'token_count': 1319}
// 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 iOS. class FileSelectorIOS extends FileSelectorPlatform { final FileSelectorApi _hostApi = FileSelectorApi(); /// Registers the iOS implementation. static void registerWith() { FileSelectorPlatform.instance = FileSelectorIOS(); } @override Future<XFile?> openFile({ List<XTypeGroup>? acceptedTypeGroups, String? initialDirectory, String? confirmButtonText, }) async { final List<String> path = (await _hostApi.openFile(FileSelectorConfig( utis: _allowedUtiListFromTypeGroups(acceptedTypeGroups), allowMultiSelection: false))) .cast<String>(); return path.isEmpty ? null : XFile(path.first); } @override Future<List<XFile>> openFiles({ List<XTypeGroup>? acceptedTypeGroups, String? initialDirectory, String? confirmButtonText, }) async { final List<String> pathList = (await _hostApi.openFile(FileSelectorConfig( utis: _allowedUtiListFromTypeGroups(acceptedTypeGroups), allowMultiSelection: true))) .cast<String>(); return pathList.map((String path) => XFile(path)).toList(); } // Converts the type group list into a list of all allowed UTIs, since // iOS doesn't support filter groups. List<String> _allowedUtiListFromTypeGroups(List<XTypeGroup>? typeGroups) { // iOS requires a list of allowed types, so allowing all is expressed via // a root type rather than an empty list. const List<String> allowAny = <String>['public.data']; if (typeGroups == null || typeGroups.isEmpty) { return allowAny; } final List<String> allowedUTIs = <String>[]; for (final XTypeGroup typeGroup in typeGroups) { // If any group allows everything, no filtering should be done. if (typeGroup.allowsAny) { return allowAny; } if (typeGroup.uniformTypeIdentifiers?.isEmpty ?? true) { throw ArgumentError('The provided type group $typeGroup should either ' 'allow all files, or have a non-empty "uniformTypeIdentifiers"'); } allowedUTIs.addAll(typeGroup.uniformTypeIdentifiers!); } return allowedUTIs; } }
packages/packages/file_selector/file_selector_ios/lib/file_selector_ios.dart/0
{'file_path': 'packages/packages/file_selector/file_selector_ios/lib/file_selector_ios.dart', 'repo_id': 'packages', 'token_count': 869}
// 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/foundation.dart' show visibleForTesting; import 'package:flutter/services.dart'; const MethodChannel _channel = MethodChannel('plugins.flutter.dev/file_selector_linux'); const String _typeGroupLabelKey = 'label'; const String _typeGroupExtensionsKey = 'extensions'; const String _typeGroupMimeTypesKey = 'mimeTypes'; const String _openFileMethod = 'openFile'; const String _getSavePathMethod = 'getSavePath'; const String _getDirectoryPathMethod = 'getDirectoryPath'; const String _acceptedTypeGroupsKey = 'acceptedTypeGroups'; const String _confirmButtonTextKey = 'confirmButtonText'; const String _initialDirectoryKey = 'initialDirectory'; const String _multipleKey = 'multiple'; const String _suggestedNameKey = 'suggestedName'; /// An implementation of [FileSelectorPlatform] for Linux. class FileSelectorLinux extends FileSelectorPlatform { /// The MethodChannel that is being used by this implementation of the plugin. @visibleForTesting MethodChannel get channel => _channel; /// Registers the Linux implementation. static void registerWith() { FileSelectorPlatform.instance = FileSelectorLinux(); } @override Future<XFile?> openFile({ List<XTypeGroup>? acceptedTypeGroups, String? initialDirectory, String? confirmButtonText, }) async { final List<Map<String, Object>> serializedTypeGroups = _serializeTypeGroups(acceptedTypeGroups); final List<String>? path = await _channel.invokeListMethod<String>( _openFileMethod, <String, dynamic>{ if (serializedTypeGroups.isNotEmpty) _acceptedTypeGroupsKey: serializedTypeGroups, 'initialDirectory': initialDirectory, _confirmButtonTextKey: confirmButtonText, _multipleKey: false, }, ); return path == null ? null : XFile(path.first); } @override Future<List<XFile>> openFiles({ List<XTypeGroup>? acceptedTypeGroups, String? initialDirectory, String? confirmButtonText, }) async { final List<Map<String, Object>> serializedTypeGroups = _serializeTypeGroups(acceptedTypeGroups); final List<String>? pathList = await _channel.invokeListMethod<String>( _openFileMethod, <String, dynamic>{ if (serializedTypeGroups.isNotEmpty) _acceptedTypeGroupsKey: serializedTypeGroups, _initialDirectoryKey: initialDirectory, _confirmButtonTextKey: confirmButtonText, _multipleKey: true, }, ); return pathList?.map((String path) => XFile(path)).toList() ?? <XFile>[]; } @override Future<String?> getSavePath({ List<XTypeGroup>? acceptedTypeGroups, String? initialDirectory, String? suggestedName, String? confirmButtonText, }) async { final FileSaveLocation? location = await getSaveLocation( acceptedTypeGroups: acceptedTypeGroups, options: SaveDialogOptions( initialDirectory: initialDirectory, suggestedName: suggestedName, confirmButtonText: confirmButtonText, )); return location?.path; } @override Future<FileSaveLocation?> getSaveLocation({ List<XTypeGroup>? acceptedTypeGroups, SaveDialogOptions options = const SaveDialogOptions(), }) async { final List<Map<String, Object>> serializedTypeGroups = _serializeTypeGroups(acceptedTypeGroups); // TODO(stuartmorgan): Add the selected type group here and return it. See // https://github.com/flutter/flutter/issues/107093 final String? path = await _channel.invokeMethod<String>( _getSavePathMethod, <String, dynamic>{ if (serializedTypeGroups.isNotEmpty) _acceptedTypeGroupsKey: serializedTypeGroups, _initialDirectoryKey: options.initialDirectory, _suggestedNameKey: options.suggestedName, _confirmButtonTextKey: options.confirmButtonText, }, ); return path == null ? null : FileSaveLocation(path); } @override Future<String?> getDirectoryPath({ String? initialDirectory, String? confirmButtonText, }) async { final List<String>? path = await _channel .invokeListMethod<String>(_getDirectoryPathMethod, <String, dynamic>{ _initialDirectoryKey: initialDirectory, _confirmButtonTextKey: confirmButtonText, }); return path?.first; } @override Future<List<String>> getDirectoryPaths({ String? initialDirectory, String? confirmButtonText, }) async { final List<String>? pathList = await _channel .invokeListMethod<String>(_getDirectoryPathMethod, <String, dynamic>{ _initialDirectoryKey: initialDirectory, _confirmButtonTextKey: confirmButtonText, _multipleKey: true, }); return pathList ?? <String>[]; } } List<Map<String, Object>> _serializeTypeGroups(List<XTypeGroup>? groups) { return (groups ?? <XTypeGroup>[]).map(_serializeTypeGroup).toList(); } Map<String, Object> _serializeTypeGroup(XTypeGroup group) { final Map<String, Object> serialization = <String, Object>{ _typeGroupLabelKey: group.label ?? '', }; if (group.allowsAny) { serialization[_typeGroupExtensionsKey] = <String>['*']; } else { if ((group.extensions?.isEmpty ?? true) && (group.mimeTypes?.isEmpty ?? true)) { throw ArgumentError('Provided type group $group does not allow ' 'all files, but does not set any of the Linux-supported filter ' 'categories. "extensions" or "mimeTypes" must be non-empty for Linux ' 'if anything is non-empty.'); } if (group.extensions?.isNotEmpty ?? false) { serialization[_typeGroupExtensionsKey] = group.extensions ?.map((String extension) => '*.$extension') .toList() ?? <String>[]; } if (group.mimeTypes?.isNotEmpty ?? false) { serialization[_typeGroupMimeTypesKey] = group.mimeTypes ?? <String>[]; } } return serialization; }
packages/packages/file_selector/file_selector_linux/lib/file_selector_linux.dart/0
{'file_path': 'packages/packages/file_selector/file_selector_linux/lib/file_selector_linux.dart', 'repo_id': 'packages', 'token_count': 2163}
// 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/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_markdown/flutter_markdown.dart'; import 'package:flutter_test/flutter_test.dart'; import 'utils.dart'; void main() => defineTests(); void defineTests() { group('Style Sheet', () { testWidgets( 'equality - Cupertino', (WidgetTester tester) async { const CupertinoThemeData theme = CupertinoThemeData(brightness: Brightness.light); final MarkdownStyleSheet style1 = MarkdownStyleSheet.fromCupertinoTheme(theme); final MarkdownStyleSheet style2 = MarkdownStyleSheet.fromCupertinoTheme(theme); expect(style1, equals(style2)); expect(style1.hashCode, equals(style2.hashCode)); }, ); testWidgets( 'equality - Material', (WidgetTester tester) async { final ThemeData theme = ThemeData.light().copyWith(textTheme: textTheme); final MarkdownStyleSheet style1 = MarkdownStyleSheet.fromTheme(theme); final MarkdownStyleSheet style2 = MarkdownStyleSheet.fromTheme(theme); expect(style1, equals(style2)); expect(style1.hashCode, equals(style2.hashCode)); }, ); testWidgets( 'MarkdownStyleSheet.fromCupertinoTheme', (WidgetTester tester) async { const CupertinoThemeData cTheme = CupertinoThemeData( brightness: Brightness.dark, ); final MarkdownStyleSheet style = MarkdownStyleSheet.fromCupertinoTheme(cTheme); // a expect(style.a!.color, CupertinoColors.link.darkColor); expect(style.a!.fontSize, cTheme.textTheme.textStyle.fontSize); // p expect(style.p, cTheme.textTheme.textStyle); // code expect(style.code!.color, cTheme.textTheme.textStyle.color); expect( style.code!.fontSize, cTheme.textTheme.textStyle.fontSize! * 0.85); expect(style.code!.fontFamily, 'monospace'); expect( style.code!.backgroundColor, CupertinoColors.systemGrey6.darkColor); // H1 expect(style.h1!.color, cTheme.textTheme.textStyle.color); expect(style.h1!.fontSize, cTheme.textTheme.textStyle.fontSize! + 10); expect(style.h1!.fontWeight, FontWeight.w500); // H2 expect(style.h2!.color, cTheme.textTheme.textStyle.color); expect(style.h2!.fontSize, cTheme.textTheme.textStyle.fontSize! + 8); expect(style.h2!.fontWeight, FontWeight.w500); // H3 expect(style.h3!.color, cTheme.textTheme.textStyle.color); expect(style.h3!.fontSize, cTheme.textTheme.textStyle.fontSize! + 6); expect(style.h3!.fontWeight, FontWeight.w500); // H4 expect(style.h4!.color, cTheme.textTheme.textStyle.color); expect(style.h4!.fontSize, cTheme.textTheme.textStyle.fontSize! + 4); expect(style.h4!.fontWeight, FontWeight.w500); // H5 expect(style.h5!.color, cTheme.textTheme.textStyle.color); expect(style.h5!.fontSize, cTheme.textTheme.textStyle.fontSize! + 2); expect(style.h5!.fontWeight, FontWeight.w500); // H6 expect(style.h6!.color, cTheme.textTheme.textStyle.color); expect(style.h6!.fontSize, cTheme.textTheme.textStyle.fontSize); expect(style.h6!.fontWeight, FontWeight.w500); // em expect(style.em!.color, cTheme.textTheme.textStyle.color); expect(style.em!.fontSize, cTheme.textTheme.textStyle.fontSize); expect(style.em!.fontStyle, FontStyle.italic); // strong expect(style.strong!.color, cTheme.textTheme.textStyle.color); expect(style.strong!.fontSize, cTheme.textTheme.textStyle.fontSize); expect(style.strong!.fontWeight, FontWeight.bold); // del expect(style.del!.color, cTheme.textTheme.textStyle.color); expect(style.del!.fontSize, cTheme.textTheme.textStyle.fontSize); expect(style.del!.decoration, TextDecoration.lineThrough); // blockqoute expect(style.blockquote, cTheme.textTheme.textStyle); // img expect(style.img, cTheme.textTheme.textStyle); // checkbox expect(style.checkbox!.color, cTheme.primaryColor); expect(style.checkbox!.fontSize, cTheme.textTheme.textStyle.fontSize); // tableHead expect(style.tableHead!.color, cTheme.textTheme.textStyle.color); expect(style.tableHead!.fontSize, cTheme.textTheme.textStyle.fontSize); expect(style.tableHead!.fontWeight, FontWeight.w600); // tableBody expect(style.tableBody, cTheme.textTheme.textStyle); }, ); testWidgets( 'MarkdownStyleSheet.fromTheme', (WidgetTester tester) async { final ThemeData theme = ThemeData.dark().copyWith( textTheme: const TextTheme( bodyMedium: TextStyle(fontSize: 12.0), ), ); final MarkdownStyleSheet style = MarkdownStyleSheet.fromTheme(theme); // a expect(style.a!.color, Colors.blue); // p expect(style.p, theme.textTheme.bodyMedium); // code expect(style.code!.color, theme.textTheme.bodyMedium!.color); expect( style.code!.fontSize, theme.textTheme.bodyMedium!.fontSize! * 0.85); expect(style.code!.fontFamily, 'monospace'); expect(style.code!.backgroundColor, theme.cardColor); // H1 expect(style.h1, theme.textTheme.headlineSmall); // H2 expect(style.h2, theme.textTheme.titleLarge); // H3 expect(style.h3, theme.textTheme.titleMedium); // H4 expect(style.h4, theme.textTheme.bodyLarge); // H5 expect(style.h5, theme.textTheme.bodyLarge); // H6 expect(style.h6, theme.textTheme.bodyLarge); // em expect(style.em!.fontStyle, FontStyle.italic); expect(style.em!.color, theme.textTheme.bodyMedium!.color); // strong expect(style.strong!.fontWeight, FontWeight.bold); expect(style.strong!.color, theme.textTheme.bodyMedium!.color); // del expect(style.del!.decoration, TextDecoration.lineThrough); expect(style.del!.color, theme.textTheme.bodyMedium!.color); // blockqoute expect(style.blockquote, theme.textTheme.bodyMedium); // img expect(style.img, theme.textTheme.bodyMedium); // checkbox expect(style.checkbox!.color, theme.primaryColor); expect(style.checkbox!.fontSize, theme.textTheme.bodyMedium!.fontSize); // tableHead expect(style.tableHead!.fontWeight, FontWeight.w600); // tableBody expect(style.tableBody, theme.textTheme.bodyMedium); }, ); testWidgets( 'merge 2 style sheets', (WidgetTester tester) async { final ThemeData theme = ThemeData.light().copyWith(textTheme: textTheme); final MarkdownStyleSheet style1 = MarkdownStyleSheet.fromTheme(theme); final MarkdownStyleSheet style2 = MarkdownStyleSheet( p: const TextStyle(color: Colors.red), blockquote: const TextStyle(fontSize: 16), ); final MarkdownStyleSheet merged = style1.merge(style2); expect(merged.p!.color, Colors.red); expect(merged.blockquote!.fontSize, 16); expect(merged.blockquote!.color, theme.textTheme.bodyMedium!.color); }, ); testWidgets( 'create based on which theme', (WidgetTester tester) async { const String data = '[title](url)'; await tester.pumpWidget( boilerplate( const Markdown( data: data, styleSheetTheme: MarkdownStyleSheetBaseTheme.cupertino, ), ), ); final RichText widget = tester.widget(find.byType(RichText)); expect(widget.text.style!.color, CupertinoColors.link.color); }, ); testWidgets( 'apply 2 distinct style sheets', (WidgetTester tester) async { final ThemeData theme = ThemeData.light().copyWith(textTheme: textTheme); final MarkdownStyleSheet style1 = MarkdownStyleSheet.fromTheme(theme); final MarkdownStyleSheet style2 = MarkdownStyleSheet.largeFromTheme(theme); expect(style1, isNot(style2)); await tester.pumpWidget( boilerplate( Markdown( data: '# Test', styleSheet: style1, ), ), ); final RichText text1 = tester.widget(find.byType(RichText)); await tester.pumpWidget( boilerplate( Markdown( data: '# Test', styleSheet: style2, ), ), ); final RichText text2 = tester.widget(find.byType(RichText)); expect(text1.text, isNot(text2.text)); }, ); testWidgets( 'use stylesheet option listBulletPadding', (WidgetTester tester) async { const double paddingX = 20.0; final MarkdownStyleSheet style = MarkdownStyleSheet( listBulletPadding: const EdgeInsets.symmetric(horizontal: paddingX)); await tester.pumpWidget( boilerplate( Markdown( data: '1. Bullet\n 2. Bullet\n * Bullet', styleSheet: style, ), ), ); final List<Padding> paddings = tester.widgetList<Padding>(find.byType(Padding)).toList(); expect(paddings.length, 3); expect( paddings.every( (Padding p) => p.padding.along(Axis.horizontal) == paddingX * 2, ), true, ); }, ); testWidgets( 'check widgets for use stylesheet option h1Padding', (WidgetTester tester) async { const String data = '# Header'; const double paddingX = 20.0; final MarkdownStyleSheet style = MarkdownStyleSheet( h1Padding: const EdgeInsets.symmetric(horizontal: paddingX), ); await tester.pumpWidget(boilerplate(MarkdownBody( data: data, styleSheet: style, ))); final Iterable<Widget> widgets = selfAndDescendantWidgetsOf( find.byType(MarkdownBody), tester, ); expectWidgetTypes(widgets, <Type>[ MarkdownBody, Column, Padding, Wrap, RichText, ]); expectTextStrings(widgets, <String>['Header']); }, ); testWidgets( 'use stylesheet option pPadding', (WidgetTester tester) async { const double paddingX = 20.0; final MarkdownStyleSheet style = MarkdownStyleSheet( pPadding: const EdgeInsets.symmetric(horizontal: paddingX), ); await tester.pumpWidget( boilerplate( Markdown( data: 'Test line 1\n\nTest line 2\n\nTest line 3\n# H1', styleSheet: style, ), ), ); final List<Padding> paddings = tester.widgetList<Padding>(find.byType(Padding)).toList(); expect(paddings.length, 3); expect( paddings.every( (Padding p) => p.padding.along(Axis.horizontal) == paddingX * 2, ), true, ); }, ); testWidgets( 'use stylesheet option h1Padding-h6Padding', (WidgetTester tester) async { const double paddingX = 20.0; final MarkdownStyleSheet style = MarkdownStyleSheet( h1Padding: const EdgeInsets.symmetric(horizontal: paddingX), h2Padding: const EdgeInsets.symmetric(horizontal: paddingX), h3Padding: const EdgeInsets.symmetric(horizontal: paddingX), h4Padding: const EdgeInsets.symmetric(horizontal: paddingX), h5Padding: const EdgeInsets.symmetric(horizontal: paddingX), h6Padding: const EdgeInsets.symmetric(horizontal: paddingX), ); await tester.pumpWidget( boilerplate( Markdown( data: 'Test\n\n# H1\n## H2\n### H3\n#### H4\n##### H5\n###### H6\n', styleSheet: style, ), ), ); final List<Padding> paddings = tester.widgetList<Padding>(find.byType(Padding)).toList(); expect(paddings.length, 6); expect( paddings.every( (Padding p) => p.padding.along(Axis.horizontal) == paddingX * 2, ), true, ); }, ); }); }
packages/packages/flutter_markdown/test/style_sheet_test.dart/0
{'file_path': 'packages/packages/flutter_markdown/test/style_sheet_test.dart', 'repo_id': 'packages', 'token_count': 5858}
// 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:args/command_runner.dart'; import 'logger.dart'; import 'project.dart'; enum ExitStatus { success, warning, fail, killed, } const String flutterNoPubspecMessage = 'Error: No pubspec.yaml file found.\n' 'This command should be run from the root of your Flutter project.'; class CommandResult { const CommandResult(this.exitStatus); /// A command that succeeded. It is used to log the result of a command invocation. factory CommandResult.success() { return const CommandResult(ExitStatus.success); } /// A command that exited with a warning. It is used to log the result of a command invocation. factory CommandResult.warning() { return const CommandResult(ExitStatus.warning); } /// A command that failed. It is used to log the result of a command invocation. factory CommandResult.fail() { return const CommandResult(ExitStatus.fail); } final ExitStatus exitStatus; @override String toString() { switch (exitStatus) { case ExitStatus.success: return 'success'; case ExitStatus.warning: return 'warning'; case ExitStatus.fail: return 'fail'; case ExitStatus.killed: return 'killed'; } } } abstract class MigrateCommand extends Command<void> { @override Future<void> run() async { await runCommand(); return; } Future<CommandResult> runCommand(); /// Gets the parsed command-line option named [name] as a `bool?`. bool? boolArg(String name) { if (!argParser.options.containsKey(name)) { return null; } return argResults == null ? null : argResults![name] as bool; } String? stringArg(String name) { if (!argParser.options.containsKey(name)) { return null; } return argResults == null ? null : argResults![name] as String?; } /// Gets the parsed command-line option named [name] as an `int`. int? intArg(String name) => argResults?[name] as int?; bool validateWorkingDirectory(FlutterProject project, Logger logger) { if (!project.pubspecFile.existsSync()) { logger.printError(flutterNoPubspecMessage); return false; } return true; } }
packages/packages/flutter_migrate/lib/src/base/command.dart/0
{'file_path': 'packages/packages/flutter_migrate/lib/src/base/command.dart', 'repo_id': 'packages', 'token_count': 767}
// 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 '../data.dart'; /// The author list view. class AuthorList extends StatelessWidget { /// Creates an [AuthorList]. const AuthorList({ required this.authors, this.onTap, super.key, }); /// The list of authors to be shown. final List<Author> authors; /// Called when the user taps an author. final ValueChanged<Author>? onTap; @override Widget build(BuildContext context) => ListView.builder( itemCount: authors.length, itemBuilder: (BuildContext context, int index) => ListTile( title: Text( authors[index].name, ), subtitle: Text( '${authors[index].books.length} books', ), onTap: onTap != null ? () => onTap!(authors[index]) : null, ), ); }
packages/packages/go_router/example/lib/books/src/widgets/author_list.dart/0
{'file_path': 'packages/packages/go_router/example/lib/books/src/widgets/author_list.dart', 'repo_id': 'packages', 'token_count': 370}
// 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 'package:go_router/go_router.dart'; void main() => runApp(App()); /// The main app. class App extends StatelessWidget { /// Creates an [App]. App({super.key}); /// The title of the app. static const String title = 'GoRouter Example: Custom Transitions'; @override Widget build(BuildContext context) => MaterialApp.router( routerConfig: _router, title: title, ); final GoRouter _router = GoRouter( routes: <GoRoute>[ GoRoute( path: '/', redirect: (_, __) => '/none', ), GoRoute( path: '/fade', pageBuilder: (BuildContext context, GoRouterState state) => CustomTransitionPage<void>( key: state.pageKey, child: const ExampleTransitionsScreen( kind: 'fade', color: Colors.red, ), transitionsBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) => FadeTransition(opacity: animation, child: child), ), ), GoRoute( path: '/scale', pageBuilder: (BuildContext context, GoRouterState state) => CustomTransitionPage<void>( key: state.pageKey, child: const ExampleTransitionsScreen( kind: 'scale', color: Colors.green, ), transitionsBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) => ScaleTransition(scale: animation, child: child), ), ), GoRoute( path: '/slide', pageBuilder: (BuildContext context, GoRouterState state) => CustomTransitionPage<void>( key: state.pageKey, child: const ExampleTransitionsScreen( kind: 'slide', color: Colors.yellow, ), transitionsBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) => SlideTransition( position: animation.drive( Tween<Offset>( begin: const Offset(0.25, 0.25), end: Offset.zero, ).chain(CurveTween(curve: Curves.easeIn)), ), child: child, ), ), ), GoRoute( path: '/rotation', pageBuilder: (BuildContext context, GoRouterState state) => CustomTransitionPage<void>( key: state.pageKey, child: const ExampleTransitionsScreen( kind: 'rotation', color: Colors.purple, ), transitionsBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) => RotationTransition(turns: animation, child: child), ), ), GoRoute( path: '/none', pageBuilder: (BuildContext context, GoRouterState state) => NoTransitionPage<void>( key: state.pageKey, child: const ExampleTransitionsScreen( kind: 'none', color: Colors.white, ), ), ), ], ); } /// An Example transitions screen. class ExampleTransitionsScreen extends StatelessWidget { /// Creates an [ExampleTransitionsScreen]. const ExampleTransitionsScreen({ required this.color, required this.kind, super.key, }); /// The available transition kinds. static final List<String> kinds = <String>[ 'fade', 'scale', 'slide', 'rotation', 'none' ]; /// The color of the container. final Color color; /// The transition kind. final String kind; @override Widget build(BuildContext context) => Scaffold( appBar: AppBar(title: Text('${App.title}: $kind')), body: ColoredBox( color: color, child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ for (final String kind in kinds) Padding( padding: const EdgeInsets.all(8), child: ElevatedButton( onPressed: () => context.go('/$kind'), child: Text('$kind transition'), ), ) ], ), ), ), ); }
packages/packages/go_router/example/lib/others/transitions.dart/0
{'file_path': 'packages/packages/go_router/example/lib/others/transitions.dart', 'repo_id': 'packages', 'token_count': 2286}
// 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. // ignore_for_file: diagnostic_describe_all_properties import 'package:flutter/cupertino.dart'; import '../misc/extensions.dart'; /// Checks for CupertinoApp in the widget tree. bool isCupertinoApp(BuildContext context) => context.findAncestorWidgetOfExactType<CupertinoApp>() != null; /// Creates a Cupertino HeroController. HeroController createCupertinoHeroController() => CupertinoApp.createCupertinoHeroController(); /// Builds a Cupertino page. CupertinoPage<void> pageBuilderForCupertinoApp({ required LocalKey key, required String? name, required Object? arguments, required String restorationId, required Widget child, }) => CupertinoPage<void>( name: name, arguments: arguments, key: key, restorationId: restorationId, child: child, ); /// Default error page implementation for Cupertino. class CupertinoErrorScreen extends StatelessWidget { /// Provide an exception to this page for it to be displayed. const CupertinoErrorScreen(this.error, {super.key}); /// The exception to be displayed. final Exception? error; @override Widget build(BuildContext context) => CupertinoPageScaffold( navigationBar: const CupertinoNavigationBar(middle: Text('Page Not Found')), child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text(error?.toString() ?? 'page not found'), CupertinoButton( onPressed: () => context.go('/'), child: const Text('Home'), ), ], ), ), ); }
packages/packages/go_router/lib/src/pages/cupertino.dart/0
{'file_path': 'packages/packages/go_router/lib/src/pages/cupertino.dart', 'repo_id': 'packages', 'token_count': 671}
// 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 'package:flutter_test/flutter_test.dart'; import 'package:go_router/src/misc/error_screen.dart'; import 'helpers/error_screen_helpers.dart'; void main() { testWidgets( 'shows "page not found" by default', testPageNotFound( widget: widgetsAppBuilder( home: const ErrorScreen(null), ), ), ); final Exception exception = Exception('Something went wrong!'); testWidgets( 'shows the exception message when provided', testPageShowsExceptionMessage( exception: exception, widget: widgetsAppBuilder( home: ErrorScreen(exception), ), ), ); testWidgets( 'clicking the button should redirect to /', testClickingTheButtonRedirectsToRoot( buttonFinder: find.byWidgetPredicate((Widget widget) => widget is GestureDetector), widget: widgetsAppBuilder( home: const ErrorScreen(null), ), ), ); } Widget widgetsAppBuilder({required Widget home}) { return WidgetsApp( onGenerateRoute: (_) { return MaterialPageRoute<void>( builder: (BuildContext _) => home, ); }, color: Colors.white, ); }
packages/packages/go_router/test/error_page_test.dart/0
{'file_path': 'packages/packages/go_router/test/error_page_test.dart', 'repo_id': 'packages', 'token_count': 495}
// 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 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; import 'test_helpers.dart'; void main() { testWidgets('back button works synchronously', (WidgetTester tester) async { bool allow = false; final UniqueKey home = UniqueKey(); final UniqueKey page1 = UniqueKey(); final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) => DummyScreen(key: home), routes: <GoRoute>[ GoRoute( path: '1', builder: (BuildContext context, GoRouterState state) => DummyScreen(key: page1), onExit: (BuildContext context) { return allow; }, ) ], ), ]; final GoRouter router = await createRouter(routes, tester, initialLocation: '/1'); expect(find.byKey(page1), findsOneWidget); router.pop(); await tester.pumpAndSettle(); expect(find.byKey(page1), findsOneWidget); allow = true; router.pop(); await tester.pumpAndSettle(); expect(find.byKey(home), findsOneWidget); }); testWidgets('context.go works synchronously', (WidgetTester tester) async { bool allow = false; final UniqueKey home = UniqueKey(); final UniqueKey page1 = UniqueKey(); final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) => DummyScreen(key: home), ), GoRoute( path: '/1', builder: (BuildContext context, GoRouterState state) => DummyScreen(key: page1), onExit: (BuildContext context) { return allow; }, ) ]; final GoRouter router = await createRouter(routes, tester, initialLocation: '/1'); expect(find.byKey(page1), findsOneWidget); router.go('/'); await tester.pumpAndSettle(); expect(find.byKey(page1), findsOneWidget); allow = true; router.go('/'); await tester.pumpAndSettle(); expect(find.byKey(home), findsOneWidget); }); testWidgets('back button works asynchronously', (WidgetTester tester) async { Completer<bool> allow = Completer<bool>(); final UniqueKey home = UniqueKey(); final UniqueKey page1 = UniqueKey(); final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) => DummyScreen(key: home), routes: <GoRoute>[ GoRoute( path: '1', builder: (BuildContext context, GoRouterState state) => DummyScreen(key: page1), onExit: (BuildContext context) async { return allow.future; }, ) ], ), ]; final GoRouter router = await createRouter(routes, tester, initialLocation: '/1'); expect(find.byKey(page1), findsOneWidget); router.pop(); await tester.pumpAndSettle(); expect(find.byKey(page1), findsOneWidget); allow.complete(false); await tester.pumpAndSettle(); expect(find.byKey(page1), findsOneWidget); allow = Completer<bool>(); router.pop(); await tester.pumpAndSettle(); expect(find.byKey(page1), findsOneWidget); allow.complete(true); await tester.pumpAndSettle(); expect(find.byKey(home), findsOneWidget); }); testWidgets('context.go works asynchronously', (WidgetTester tester) async { Completer<bool> allow = Completer<bool>(); final UniqueKey home = UniqueKey(); final UniqueKey page1 = UniqueKey(); final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) => DummyScreen(key: home), ), GoRoute( path: '/1', builder: (BuildContext context, GoRouterState state) => DummyScreen(key: page1), onExit: (BuildContext context) async { return allow.future; }, ) ]; final GoRouter router = await createRouter(routes, tester, initialLocation: '/1'); expect(find.byKey(page1), findsOneWidget); router.go('/'); await tester.pumpAndSettle(); expect(find.byKey(page1), findsOneWidget); allow.complete(false); await tester.pumpAndSettle(); expect(find.byKey(page1), findsOneWidget); allow = Completer<bool>(); router.go('/'); await tester.pumpAndSettle(); expect(find.byKey(page1), findsOneWidget); allow.complete(true); await tester.pumpAndSettle(); expect(find.byKey(home), findsOneWidget); }); testWidgets('android back button respects the last route.', (WidgetTester tester) async { bool allow = false; final UniqueKey home = UniqueKey(); final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) => DummyScreen(key: home), onExit: (BuildContext context) { return allow; }, ), ]; final GoRouter router = await createRouter(routes, tester); expect(find.byKey(home), findsOneWidget); // Not allow system pop. expect(await router.routerDelegate.popRoute(), true); allow = true; expect(await router.routerDelegate.popRoute(), false); }); testWidgets('android back button respects the last route. async', (WidgetTester tester) async { bool allow = false; final UniqueKey home = UniqueKey(); final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) => DummyScreen(key: home), onExit: (BuildContext context) async { return allow; }, ), ]; final GoRouter router = await createRouter(routes, tester); expect(find.byKey(home), findsOneWidget); // Not allow system pop. expect(await router.routerDelegate.popRoute(), true); allow = true; expect(await router.routerDelegate.popRoute(), false); }); testWidgets('android back button respects the last route with shell route.', (WidgetTester tester) async { bool allow = false; final UniqueKey home = UniqueKey(); final List<RouteBase> routes = <RouteBase>[ ShellRoute(builder: (_, __, Widget child) => child, routes: <RouteBase>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) => DummyScreen(key: home), onExit: (BuildContext context) { return allow; }, ), ]) ]; final GoRouter router = await createRouter(routes, tester); expect(find.byKey(home), findsOneWidget); // Not allow system pop. expect(await router.routerDelegate.popRoute(), true); allow = true; expect(await router.routerDelegate.popRoute(), false); }); }
packages/packages/go_router/test/on_exit_test.dart/0
{'file_path': 'packages/packages/go_router/test/on_exit_test.dart', 'repo_id': 'packages', 'token_count': 2957}
// GENERATED CODE - DO NOT MODIFY BY HAND // ignore_for_file: always_specify_types, public_member_api_docs part of 'shell_route_example.dart'; // ************************************************************************** // GoRouterGenerator // ************************************************************************** List<RouteBase> get $appRoutes => [ $myShellRouteData, $loginRoute, ]; RouteBase get $myShellRouteData => ShellRouteData.$route( factory: $MyShellRouteDataExtension._fromState, routes: [ GoRouteData.$route( path: '/foo', factory: $FooRouteDataExtension._fromState, ), GoRouteData.$route( path: '/bar', factory: $BarRouteDataExtension._fromState, ), ], ); extension $MyShellRouteDataExtension on MyShellRouteData { static MyShellRouteData _fromState(GoRouterState state) => const MyShellRouteData(); } extension $FooRouteDataExtension on FooRouteData { static FooRouteData _fromState(GoRouterState state) => const FooRouteData(); String get location => GoRouteData.$location( '/foo', ); void go(BuildContext context) => context.go(location); Future<T?> push<T>(BuildContext context) => context.push<T>(location); void pushReplacement(BuildContext context) => context.pushReplacement(location); void replace(BuildContext context) => context.replace(location); } extension $BarRouteDataExtension on BarRouteData { static BarRouteData _fromState(GoRouterState state) => const BarRouteData(); String get location => GoRouteData.$location( '/bar', ); void go(BuildContext context) => context.go(location); Future<T?> push<T>(BuildContext context) => context.push<T>(location); void pushReplacement(BuildContext context) => context.pushReplacement(location); void replace(BuildContext context) => context.replace(location); } RouteBase get $loginRoute => GoRouteData.$route( path: '/login', factory: $LoginRouteExtension._fromState, ); extension $LoginRouteExtension on LoginRoute { static LoginRoute _fromState(GoRouterState state) => const LoginRoute(); String get location => GoRouteData.$location( '/login', ); void go(BuildContext context) => context.go(location); Future<T?> push<T>(BuildContext context) => context.push<T>(location); void pushReplacement(BuildContext context) => context.pushReplacement(location); void replace(BuildContext context) => context.replace(location); }
packages/packages/go_router_builder/example/lib/shell_route_example.g.dart/0
{'file_path': 'packages/packages/go_router_builder/example/lib/shell_route_example.g.dart', 'repo_id': 'packages', 'token_count': 839}
// 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 'package:flutter_test/flutter_test.dart'; import 'package:go_router_builder_example/shared/data.dart'; import 'package:go_router_builder_example/simple_example.dart'; void main() { testWidgets('App starts on HomeScreen and displays families', (WidgetTester tester) async { await tester.pumpWidget(App()); expect(find.byType(HomeScreen), findsOneWidget); expect(find.byType(ListTile), findsNWidgets(familyData.length)); for (final Family family in familyData) { expect(find.text(family.name), findsOneWidget); } }); }
packages/packages/go_router_builder/example/test/simple_example_test.dart/0
{'file_path': 'packages/packages/go_router_builder/example/test/simple_example_test.dart', 'repo_id': 'packages', 'token_count': 252}
// 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. library google_maps_flutter; import 'dart:async'; import 'dart:io'; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:google_maps_flutter_android/google_maps_flutter_android.dart'; import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart'; export 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart' show ArgumentCallback, ArgumentCallbacks, BitmapDescriptor, CameraPosition, CameraPositionCallback, CameraTargetBounds, CameraUpdate, Cap, Circle, CircleId, InfoWindow, JointType, LatLng, LatLngBounds, MapStyleException, MapType, Marker, MarkerId, MinMaxZoomPreference, PatternItem, Polygon, PolygonId, Polyline, PolylineId, ScreenCoordinate, Tile, TileOverlay, TileOverlayId, TileProvider, WebGestureHandling; part 'src/controller.dart'; part 'src/google_map.dart';
packages/packages/google_maps_flutter/google_maps_flutter/lib/google_maps_flutter.dart/0
{'file_path': 'packages/packages/google_maps_flutter/google_maps_flutter/lib/google_maps_flutter.dart', 'repo_id': 'packages', 'token_count': 579}
// 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:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart'; import 'package:mockito/mockito.dart'; void main() { // Store the initial instance before any tests change it. final GoogleMapsInspectorPlatform? initialInstance = GoogleMapsInspectorPlatform.instance; test('default instance is null', () { expect(initialInstance, isNull); }); test('cannot be implemented with `implements`', () { expect(() { GoogleMapsInspectorPlatform.instance = ImplementsGoogleMapsInspectorPlatform(); }, throwsA(isInstanceOf<AssertionError>())); }); test('can be implement with `extends`', () { GoogleMapsInspectorPlatform.instance = ExtendsGoogleMapsInspectorPlatform(); }); } class ImplementsGoogleMapsInspectorPlatform extends Mock implements GoogleMapsInspectorPlatform {} class ExtendsGoogleMapsInspectorPlatform extends GoogleMapsInspectorPlatform {}
packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/platform_interface/google_maps_inspector_platform_test.dart/0
{'file_path': 'packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/platform_interface/google_maps_inspector_platform_test.dart', 'repo_id': 'packages', 'token_count': 348}
// 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:ui'; import 'package:flutter_test/flutter_test.dart'; import 'package:google_maps/google_maps.dart' as gmaps; import 'package:google_maps/google_maps_geometry.dart' as geometry; 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:integration_test/integration_test.dart'; // This value is used when comparing the results of // converting from a byte value to a double between 0 and 1. // (For Color opacity values, for example) const double _acceptableDelta = 0.01; /// Test Shapes (Circle, Polygon, Polyline) void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); late gmaps.GMap map; setUp(() { map = gmaps.GMap(html.DivElement()); }); group('CirclesController', () { late StreamController<MapEvent<Object?>> events; late CirclesController controller; setUp(() { events = StreamController<MapEvent<Object?>>(); controller = CirclesController(stream: events); controller.bindToMap(123, map); }); testWidgets('addCircles', (WidgetTester tester) async { final Set<Circle> circles = <Circle>{ const Circle(circleId: CircleId('1')), const Circle(circleId: CircleId('2')), }; controller.addCircles(circles); expect(controller.circles.length, 2); expect(controller.circles, contains(const CircleId('1'))); expect(controller.circles, contains(const CircleId('2'))); expect(controller.circles, isNot(contains(const CircleId('66')))); }); testWidgets('changeCircles', (WidgetTester tester) async { final Set<Circle> circles = <Circle>{ const Circle(circleId: CircleId('1')), }; controller.addCircles(circles); expect(controller.circles[const CircleId('1')]?.circle?.visible, isTrue); final Set<Circle> updatedCircles = <Circle>{ const Circle(circleId: CircleId('1'), visible: false), }; controller.changeCircles(updatedCircles); expect(controller.circles.length, 1); expect(controller.circles[const CircleId('1')]?.circle?.visible, isFalse); }); testWidgets('removeCircles', (WidgetTester tester) async { final Set<Circle> circles = <Circle>{ const Circle(circleId: CircleId('1')), const Circle(circleId: CircleId('2')), const Circle(circleId: CircleId('3')), }; controller.addCircles(circles); expect(controller.circles.length, 3); // Remove some circles... final Set<CircleId> circleIdsToRemove = <CircleId>{ const CircleId('1'), const CircleId('3'), }; controller.removeCircles(circleIdsToRemove); expect(controller.circles.length, 1); expect(controller.circles, isNot(contains(const CircleId('1')))); expect(controller.circles, contains(const CircleId('2'))); expect(controller.circles, isNot(contains(const CircleId('3')))); }); testWidgets('Converts colors to CSS', (WidgetTester tester) async { final Set<Circle> circles = <Circle>{ const Circle( circleId: CircleId('1'), fillColor: Color(0x7FFABADA), strokeColor: Color(0xFFC0FFEE), ), }; controller.addCircles(circles); final gmaps.Circle circle = controller.circles.values.first.circle!; expect(circle.get('fillColor'), '#fabada'); expect(circle.get('fillOpacity'), closeTo(0.5, _acceptableDelta)); expect(circle.get('strokeColor'), '#c0ffee'); expect(circle.get('strokeOpacity'), closeTo(1, _acceptableDelta)); }); }); group('PolygonsController', () { late StreamController<MapEvent<Object?>> events; late PolygonsController controller; setUp(() { events = StreamController<MapEvent<Object?>>(); controller = PolygonsController(stream: events); controller.bindToMap(123, map); }); testWidgets('addPolygons', (WidgetTester tester) async { final Set<Polygon> polygons = <Polygon>{ const Polygon(polygonId: PolygonId('1')), const Polygon(polygonId: PolygonId('2')), }; controller.addPolygons(polygons); expect(controller.polygons.length, 2); expect(controller.polygons, contains(const PolygonId('1'))); expect(controller.polygons, contains(const PolygonId('2'))); expect(controller.polygons, isNot(contains(const PolygonId('66')))); }); testWidgets('changePolygons', (WidgetTester tester) async { final Set<Polygon> polygons = <Polygon>{ const Polygon(polygonId: PolygonId('1')), }; controller.addPolygons(polygons); expect( controller.polygons[const PolygonId('1')]?.polygon?.visible, isTrue); // Update the polygon final Set<Polygon> updatedPolygons = <Polygon>{ const Polygon(polygonId: PolygonId('1'), visible: false), }; controller.changePolygons(updatedPolygons); expect(controller.polygons.length, 1); expect( controller.polygons[const PolygonId('1')]?.polygon?.visible, isFalse); }); testWidgets('removePolygons', (WidgetTester tester) async { final Set<Polygon> polygons = <Polygon>{ const Polygon(polygonId: PolygonId('1')), const Polygon(polygonId: PolygonId('2')), const Polygon(polygonId: PolygonId('3')), }; controller.addPolygons(polygons); expect(controller.polygons.length, 3); // Remove some polygons... final Set<PolygonId> polygonIdsToRemove = <PolygonId>{ const PolygonId('1'), const PolygonId('3'), }; controller.removePolygons(polygonIdsToRemove); expect(controller.polygons.length, 1); expect(controller.polygons, isNot(contains(const PolygonId('1')))); expect(controller.polygons, contains(const PolygonId('2'))); expect(controller.polygons, isNot(contains(const PolygonId('3')))); }); testWidgets('Converts colors to CSS', (WidgetTester tester) async { final Set<Polygon> polygons = <Polygon>{ const Polygon( polygonId: PolygonId('1'), fillColor: Color(0x7FFABADA), strokeColor: Color(0xFFC0FFEE), ), }; controller.addPolygons(polygons); final gmaps.Polygon polygon = controller.polygons.values.first.polygon!; expect(polygon.get('fillColor'), '#fabada'); expect(polygon.get('fillOpacity'), closeTo(0.5, _acceptableDelta)); expect(polygon.get('strokeColor'), '#c0ffee'); expect(polygon.get('strokeOpacity'), closeTo(1, _acceptableDelta)); }); testWidgets('Handle Polygons with holes', (WidgetTester tester) async { final Set<Polygon> polygons = <Polygon>{ const Polygon( polygonId: PolygonId('BermudaTriangle'), points: <LatLng>[ LatLng(25.774, -80.19), LatLng(18.466, -66.118), LatLng(32.321, -64.757), ], holes: <List<LatLng>>[ <LatLng>[ LatLng(28.745, -70.579), LatLng(29.57, -67.514), LatLng(27.339, -66.668), ], ], ), }; controller.addPolygons(polygons); expect(controller.polygons.length, 1); expect(controller.polygons, contains(const PolygonId('BermudaTriangle'))); expect(controller.polygons, isNot(contains(const PolygonId('66')))); }); testWidgets('Polygon with hole has a hole', (WidgetTester tester) async { final Set<Polygon> polygons = <Polygon>{ const Polygon( polygonId: PolygonId('BermudaTriangle'), points: <LatLng>[ LatLng(25.774, -80.19), LatLng(18.466, -66.118), LatLng(32.321, -64.757), ], holes: <List<LatLng>>[ <LatLng>[ LatLng(28.745, -70.579), LatLng(29.57, -67.514), LatLng(27.339, -66.668), ], ], ), }; controller.addPolygons(polygons); final gmaps.Polygon? polygon = controller.polygons.values.first.polygon; final gmaps.LatLng pointInHole = gmaps.LatLng(28.632, -68.401); expect(geometry.Poly.containsLocation(pointInHole, polygon), false); }); testWidgets('Hole Path gets reversed to display correctly', (WidgetTester tester) async { final Set<Polygon> polygons = <Polygon>{ const Polygon( polygonId: PolygonId('BermudaTriangle'), points: <LatLng>[ LatLng(25.774, -80.19), LatLng(18.466, -66.118), LatLng(32.321, -64.757), ], holes: <List<LatLng>>[ <LatLng>[ LatLng(27.339, -66.668), LatLng(29.57, -67.514), LatLng(28.745, -70.579), ], ], ), }; controller.addPolygons(polygons); final gmaps.MVCArray<gmaps.MVCArray<gmaps.LatLng?>?> paths = controller.polygons.values.first.polygon!.paths!; expect(paths.getAt(1)?.getAt(0)?.lat, 28.745); expect(paths.getAt(1)?.getAt(1)?.lat, 29.57); expect(paths.getAt(1)?.getAt(2)?.lat, 27.339); }); }); group('PolylinesController', () { late StreamController<MapEvent<Object?>> events; late PolylinesController controller; setUp(() { events = StreamController<MapEvent<Object?>>(); controller = PolylinesController(stream: events); controller.bindToMap(123, map); }); testWidgets('addPolylines', (WidgetTester tester) async { final Set<Polyline> polylines = <Polyline>{ const Polyline(polylineId: PolylineId('1')), const Polyline(polylineId: PolylineId('2')), }; controller.addPolylines(polylines); expect(controller.lines.length, 2); expect(controller.lines, contains(const PolylineId('1'))); expect(controller.lines, contains(const PolylineId('2'))); expect(controller.lines, isNot(contains(const PolylineId('66')))); }); testWidgets('changePolylines', (WidgetTester tester) async { final Set<Polyline> polylines = <Polyline>{ const Polyline(polylineId: PolylineId('1')), }; controller.addPolylines(polylines); expect(controller.lines[const PolylineId('1')]?.line?.visible, isTrue); final Set<Polyline> updatedPolylines = <Polyline>{ const Polyline(polylineId: PolylineId('1'), visible: false), }; controller.changePolylines(updatedPolylines); expect(controller.lines.length, 1); expect(controller.lines[const PolylineId('1')]?.line?.visible, isFalse); }); testWidgets('removePolylines', (WidgetTester tester) async { final Set<Polyline> polylines = <Polyline>{ const Polyline(polylineId: PolylineId('1')), const Polyline(polylineId: PolylineId('2')), const Polyline(polylineId: PolylineId('3')), }; controller.addPolylines(polylines); expect(controller.lines.length, 3); // Remove some polylines... final Set<PolylineId> polylineIdsToRemove = <PolylineId>{ const PolylineId('1'), const PolylineId('3'), }; controller.removePolylines(polylineIdsToRemove); expect(controller.lines.length, 1); expect(controller.lines, isNot(contains(const PolylineId('1')))); expect(controller.lines, contains(const PolylineId('2'))); expect(controller.lines, isNot(contains(const PolylineId('3')))); }); testWidgets('Converts colors to CSS', (WidgetTester tester) async { final Set<Polyline> lines = <Polyline>{ const Polyline( polylineId: PolylineId('1'), color: Color(0x7FFABADA), ), }; controller.addPolylines(lines); final gmaps.Polyline line = controller.lines.values.first.line!; expect(line.get('strokeColor'), '#fabada'); expect(line.get('strokeOpacity'), closeTo(0.5, _acceptableDelta)); }); }); }
packages/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/shapes_test.dart/0
{'file_path': 'packages/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/shapes_test.dart', 'repo_id': 'packages', 'token_count': 5242}
// 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:flutter_test/flutter_test.dart'; import 'package:google_sign_in_android/google_sign_in_android.dart'; import 'package:google_sign_in_android/src/messages.g.dart'; import 'package:google_sign_in_platform_interface/google_sign_in_platform_interface.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'google_sign_in_android_test.mocks.dart'; final GoogleSignInUserData _user = GoogleSignInUserData( email: 'john.doe@gmail.com', id: '8162538176523816253123', photoUrl: 'https://lh5.googleusercontent.com/photo.jpg', displayName: 'John Doe', idToken: '123', serverAuthCode: '789', ); final GoogleSignInTokenData _token = GoogleSignInTokenData( accessToken: '456', ); @GenerateMocks(<Type>[GoogleSignInApi]) void main() { TestWidgetsFlutterBinding.ensureInitialized(); late GoogleSignInAndroid googleSignIn; late MockGoogleSignInApi api; setUp(() { api = MockGoogleSignInApi(); googleSignIn = GoogleSignInAndroid(api: api); }); test('registered instance', () { GoogleSignInAndroid.registerWith(); expect(GoogleSignInPlatform.instance, isA<GoogleSignInAndroid>()); }); test('signInSilently transforms platform data to GoogleSignInUserData', () async { when(api.signInSilently()).thenAnswer((_) async => UserData( email: _user.email, id: _user.id, photoUrl: _user.photoUrl, displayName: _user.displayName, idToken: _user.idToken, serverAuthCode: _user.serverAuthCode, )); final dynamic response = await googleSignIn.signInSilently(); expect(response, _user); }); test('signInSilently Exceptions -> throws', () async { when(api.signInSilently()) .thenAnswer((_) async => throw PlatformException(code: 'fail')); expect(googleSignIn.signInSilently(), throwsA(isInstanceOf<PlatformException>())); }); test('signIn transforms platform data to GoogleSignInUserData', () async { when(api.signIn()).thenAnswer((_) async => UserData( email: _user.email, id: _user.id, photoUrl: _user.photoUrl, displayName: _user.displayName, idToken: _user.idToken, serverAuthCode: _user.serverAuthCode, )); final dynamic response = await googleSignIn.signIn(); expect(response, _user); }); test('signIn Exceptions -> throws', () async { when(api.signIn()) .thenAnswer((_) async => throw PlatformException(code: 'fail')); expect(googleSignIn.signIn(), throwsA(isInstanceOf<PlatformException>())); }); test('getTokens transforms platform data to GoogleSignInTokenData', () async { const bool recoverAuth = false; when(api.getAccessToken(_user.email, recoverAuth)) .thenAnswer((_) async => _token.accessToken!); final GoogleSignInTokenData response = await googleSignIn.getTokens( email: _user.email, shouldRecoverAuth: recoverAuth); expect(response, _token); }); test('getTokens will not pass null for shouldRecoverAuth', () async { when(api.getAccessToken(_user.email, true)) .thenAnswer((_) async => _token.accessToken!); final GoogleSignInTokenData response = await googleSignIn.getTokens( email: _user.email, shouldRecoverAuth: null); expect(response, _token); }); test('initWithParams passes arguments', () async { const SignInInitParameters initParams = SignInInitParameters( hostedDomain: 'example.com', scopes: <String>['two', 'scopes'], signInOption: SignInOption.games, clientId: 'fakeClientId', ); await googleSignIn.init( hostedDomain: initParams.hostedDomain, scopes: initParams.scopes, signInOption: initParams.signInOption, clientId: initParams.clientId, ); final VerificationResult result = verify(api.init(captureAny)); final InitParams passedParams = result.captured[0] as InitParams; expect(passedParams.hostedDomain, initParams.hostedDomain); expect(passedParams.scopes, initParams.scopes); expect(passedParams.signInType, SignInType.games); expect(passedParams.clientId, initParams.clientId); // These should use whatever the SignInInitParameters defaults are. expect(passedParams.serverClientId, initParams.serverClientId); expect(passedParams.forceCodeForRefreshToken, initParams.forceCodeForRefreshToken); }); test('initWithParams passes arguments', () async { const SignInInitParameters initParams = SignInInitParameters( hostedDomain: 'example.com', scopes: <String>['two', 'scopes'], signInOption: SignInOption.games, clientId: 'fakeClientId', serverClientId: 'fakeServerClientId', forceCodeForRefreshToken: true, ); await googleSignIn.initWithParams(initParams); final VerificationResult result = verify(api.init(captureAny)); final InitParams passedParams = result.captured[0] as InitParams; expect(passedParams.hostedDomain, initParams.hostedDomain); expect(passedParams.scopes, initParams.scopes); expect(passedParams.signInType, SignInType.games); expect(passedParams.clientId, initParams.clientId); expect(passedParams.serverClientId, initParams.serverClientId); expect(passedParams.forceCodeForRefreshToken, initParams.forceCodeForRefreshToken); }); test('clearAuthCache passes arguments', () async { const String token = 'abc'; await googleSignIn.clearAuthCache(token: token); verify(api.clearAuthCache(token)); }); test('requestScopens passes arguments', () async { const List<String> scopes = <String>['newScope', 'anotherScope']; when(api.requestScopes(scopes)).thenAnswer((_) async => true); final bool response = await googleSignIn.requestScopes(scopes); expect(response, true); }); test('signOut calls through', () async { await googleSignIn.signOut(); verify(api.signOut()); }); test('disconnect calls through', () async { await googleSignIn.disconnect(); verify(api.disconnect()); }); test('isSignedIn passes true response', () async { when(api.isSignedIn()).thenAnswer((_) async => true); expect(await googleSignIn.isSignedIn(), true); }); test('isSignedIn passes false response', () async { when(api.isSignedIn()).thenAnswer((_) async => false); expect(await googleSignIn.isSignedIn(), false); }); }
packages/packages/google_sign_in/google_sign_in_android/test/google_sign_in_android_test.dart/0
{'file_path': 'packages/packages/google_sign_in/google_sign_in_android/test/google_sign_in_android_test.dart', 'repo_id': 'packages', 'token_count': 2366}
// 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 'package:flutter/foundation.dart' show visibleForTesting; import 'package:flutter/services.dart'; import '../google_sign_in_platform_interface.dart'; import 'utils.dart'; /// An implementation of [GoogleSignInPlatform] that uses method channels. class MethodChannelGoogleSignIn extends GoogleSignInPlatform { /// This is only exposed for test purposes. It shouldn't be used by clients of /// the plugin as it may break or change at any time. @visibleForTesting MethodChannel channel = const MethodChannel('plugins.flutter.io/google_sign_in'); @override Future<void> init({ List<String> scopes = const <String>[], SignInOption signInOption = SignInOption.standard, String? hostedDomain, String? clientId, }) { return initWithParams(SignInInitParameters( scopes: scopes, signInOption: signInOption, hostedDomain: hostedDomain, clientId: clientId)); } @override Future<void> initWithParams(SignInInitParameters params) { return channel.invokeMethod<void>('init', <String, dynamic>{ 'signInOption': params.signInOption.toString(), 'scopes': params.scopes, 'hostedDomain': params.hostedDomain, 'clientId': params.clientId, 'serverClientId': params.serverClientId, 'forceCodeForRefreshToken': params.forceCodeForRefreshToken, }); } @override Future<GoogleSignInUserData?> signInSilently() { return channel .invokeMapMethod<String, dynamic>('signInSilently') .then(getUserDataFromMap); } @override Future<GoogleSignInUserData?> signIn() { return channel .invokeMapMethod<String, dynamic>('signIn') .then(getUserDataFromMap); } @override Future<GoogleSignInTokenData> getTokens( {required String email, bool? shouldRecoverAuth = true}) { return channel .invokeMapMethod<String, dynamic>('getTokens', <String, dynamic>{ 'email': email, 'shouldRecoverAuth': shouldRecoverAuth, }).then((Map<String, dynamic>? result) => getTokenDataFromMap(result!)); } @override Future<void> signOut() { return channel.invokeMapMethod<String, dynamic>('signOut'); } @override Future<void> disconnect() { return channel.invokeMapMethod<String, dynamic>('disconnect'); } @override Future<bool> isSignedIn() async { return (await channel.invokeMethod<bool>('isSignedIn'))!; } @override Future<void> clearAuthCache({required String token}) { return channel.invokeMethod<void>( 'clearAuthCache', <String, String?>{'token': token}, ); } @override Future<bool> requestScopes(List<String> scopes) async { return (await channel.invokeMethod<bool>( 'requestScopes', <String, List<String>>{'scopes': scopes}, ))!; } }
packages/packages/google_sign_in/google_sign_in_platform_interface/lib/src/method_channel_google_sign_in.dart/0
{'file_path': 'packages/packages/google_sign_in/google_sign_in_platform_interface/lib/src/method_channel_google_sign_in.dart', 'repo_id': 'packages', 'token_count': 1049}
// 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:js_interop'; /// Converts a [data] object into a JS Object of type `T`. T jsifyAs<T>(Map<String, Object?> data) { return data.jsify() as T; }
packages/packages/google_sign_in/google_sign_in_web/example/integration_test/src/jsify_as.dart/0
{'file_path': 'packages/packages/google_sign_in/google_sign_in_web/example/integration_test/src/jsify_as.dart', 'repo_id': 'packages', 'token_count': 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 'dart:convert'; import 'package:flutter/foundation.dart'; import 'package:google_identity_services_web/oauth2.dart'; import 'package:google_sign_in_platform_interface/google_sign_in_platform_interface.dart'; import 'package:http/http.dart' as http; /// Basic scopes for self-id const List<String> scopes = <String>[ 'https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email', ]; /// People API to return my profile info... const String MY_PROFILE = 'https://content-people.googleapis.com/v1/people/me' '?sources=READ_SOURCE_TYPE_PROFILE' '&personFields=photos%2Cnames%2CemailAddresses'; /// Requests user data from the People API using the given [tokenResponse]. Future<GoogleSignInUserData?> requestUserData( TokenResponse tokenResponse, { @visibleForTesting http.Client? overrideClient, }) async { // Request my profile from the People API. final Map<String, Object?> person = await _doRequest( MY_PROFILE, tokenResponse, overrideClient: overrideClient, ); // Now transform the Person response into a GoogleSignInUserData. return extractUserData(person); } /// Extracts user data from a Person resource. /// /// See: https://developers.google.com/people/api/rest/v1/people#Person GoogleSignInUserData? extractUserData(Map<String, Object?> json) { final String? userId = _extractUserId(json); final String? email = _extractPrimaryField( json['emailAddresses'] as List<Object?>?, 'value', ); assert(userId != null); assert(email != null); return GoogleSignInUserData( id: userId!, email: email!, displayName: _extractPrimaryField( json['names'] as List<Object?>?, 'displayName', ), photoUrl: _extractPrimaryField( json['photos'] as List<Object?>?, 'url', ), // Synthetic user data doesn't contain an idToken! ); } /// Extracts the ID from a Person resource. /// /// The User ID looks like this: /// { /// 'resourceName': 'people/PERSON_ID', /// ... /// } String? _extractUserId(Map<String, Object?> profile) { final String? resourceName = profile['resourceName'] as String?; return resourceName?.split('/').last; } /// Extracts the [fieldName] marked as 'primary' from a list of [values]. /// /// Values can be one of: /// * `emailAddresses` /// * `names` /// * `photos` /// /// From a Person object. T? _extractPrimaryField<T>(List<Object?>? values, String fieldName) { if (values != null) { for (final Object? value in values) { if (value != null && value is Map<String, Object?>) { final bool isPrimary = _extractPath( value, path: <String>['metadata', 'primary'], defaultValue: false, ); if (isPrimary) { return value[fieldName] as T?; } } } } return null; } /// Attempts to get the property in [path] of type `T` from a deeply nested [source]. /// /// Returns [default] if the property is not found. T _extractPath<T>( Map<String, Object?> source, { required List<String> path, required T defaultValue, }) { final String valueKey = path.removeLast(); Object? data = source; for (final String key in path) { if (data != null && data is Map) { data = data[key]; } else { break; } } if (data != null && data is Map) { return (data[valueKey] ?? defaultValue) as T; } else { return defaultValue; } } /// Gets from [url] with an authorization header defined by [token]. /// /// Attempts to [jsonDecode] the result. Future<Map<String, Object?>> _doRequest( String url, TokenResponse token, { http.Client? overrideClient, }) async { final Uri uri = Uri.parse(url); final http.Client client = overrideClient ?? http.Client(); try { final http.Response response = await client.get(uri, headers: <String, String>{ 'Authorization': '${token.token_type} ${token.access_token}', }); if (response.statusCode != 200) { throw http.ClientException(response.body, uri); } return jsonDecode(response.body) as Map<String, Object?>; } finally { client.close(); } }
packages/packages/google_sign_in/google_sign_in_web/lib/src/people.dart/0
{'file_path': 'packages/packages/google_sign_in/google_sign_in_web/lib/src/people.dart', 'repo_id': 'packages', 'token_count': 1509}
// 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:pigeon/pigeon.dart'; @ConfigurePigeon(PigeonOptions( dartOut: 'lib/src/messages.g.dart', dartTestOut: 'test/test_api.g.dart', javaOut: 'android/src/main/java/io/flutter/plugins/imagepicker/Messages.java', javaOptions: JavaOptions( package: 'io.flutter.plugins.imagepicker', ), copyrightHeader: 'pigeons/copyright.txt', )) class GeneralOptions { GeneralOptions(this.allowMultiple, this.usePhotoPicker); bool allowMultiple; bool usePhotoPicker; } /// Options for image selection and output. class ImageSelectionOptions { ImageSelectionOptions({this.maxWidth, this.maxHeight, required this.quality}); /// If set, the max width that the image should be resized to fit in. double? maxWidth; /// If set, the max height that the image should be resized to fit in. double? maxHeight; /// The quality of the output image, from 0-100. /// /// 100 indicates original quality. int quality; } class MediaSelectionOptions { MediaSelectionOptions({ required this.imageSelectionOptions, }); ImageSelectionOptions imageSelectionOptions; } /// Options for image selection and output. class VideoSelectionOptions { VideoSelectionOptions({this.maxDurationSeconds}); /// The maximum desired length for the video, in seconds. int? maxDurationSeconds; } // Corresponds to `CameraDevice` from the platform interface package. enum SourceCamera { rear, front } // Corresponds to `ImageSource` from the platform interface package. enum SourceType { camera, gallery } /// Specification for the source of an image or video selection. class SourceSpecification { SourceSpecification(this.type, this.camera); SourceType type; SourceCamera? camera; } /// An error that occurred during lost result retrieval. /// /// The data here maps to the `PlatformException` that will be created from it. class CacheRetrievalError { CacheRetrievalError({required this.code, this.message}); final String code; final String? message; } // Corresponds to `RetrieveType` from the platform interface package. enum CacheRetrievalType { image, video } /// The result of retrieving cached results from a previous run. class CacheRetrievalResult { CacheRetrievalResult( {required this.type, this.error, this.paths = const <String>[]}); /// The type of the retrieved data. final CacheRetrievalType type; /// The error from the last selection, if any. final CacheRetrievalError? error; /// The results from the last selection, if any. /// /// Elements must not be null, by convention. See /// https://github.com/flutter/flutter/issues/97848 final List<String?> paths; } @HostApi(dartHostTestHandler: 'TestHostImagePickerApi') abstract class ImagePickerApi { /// Selects images and returns their paths. /// /// Elements must not be null, by convention. See /// https://github.com/flutter/flutter/issues/97848 @TaskQueue(type: TaskQueueType.serialBackgroundThread) @async List<String?> pickImages( SourceSpecification source, ImageSelectionOptions options, GeneralOptions generalOptions, ); /// Selects video and returns their paths. /// /// Elements must not be null, by convention. See /// https://github.com/flutter/flutter/issues/97848 @TaskQueue(type: TaskQueueType.serialBackgroundThread) @async List<String?> pickVideos( SourceSpecification source, VideoSelectionOptions options, GeneralOptions generalOptions, ); /// Selects images and videos and returns their paths. /// /// Elements must not be null, by convention. See /// https://github.com/flutter/flutter/issues/97848 @async List<String?> pickMedia( MediaSelectionOptions mediaSelectionOptions, GeneralOptions generalOptions, ); /// Returns results from a previous app session, if any. @TaskQueue(type: TaskQueueType.serialBackgroundThread) CacheRetrievalResult? retrieveLostResults(); }
packages/packages/image_picker/image_picker_android/pigeons/messages.dart/0
{'file_path': 'packages/packages/image_picker/image_picker_android/pigeons/messages.dart', 'repo_id': 'packages', 'token_count': 1191}
// 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:math'; import 'dart:ui'; import 'package:image_picker_platform_interface/image_picker_platform_interface.dart'; import 'image_resizer_utils.dart'; /// Helper class that resizes images. class ImageResizer { /// Resizes the image if needed. /// (Does not support gif images) Future<XFile> resizeImageIfNeeded(XFile file, double? maxWidth, double? maxHeight, int? imageQuality) async { if (!imageResizeNeeded(maxWidth, maxHeight, imageQuality) || file.mimeType == 'image/gif') { // Implement maxWidth and maxHeight for image/gif return file; } try { final html.ImageElement imageElement = await loadImage(file.path); final html.CanvasElement canvas = resizeImageElement(imageElement, maxWidth, maxHeight); final XFile resizedImage = await writeCanvasToFile(file, canvas, imageQuality); html.Url.revokeObjectUrl(file.path); return resizedImage; } catch (e) { return file; } } /// function that loads the blobUrl into an imageElement Future<html.ImageElement> loadImage(String blobUrl) { final Completer<html.ImageElement> imageLoadCompleter = Completer<html.ImageElement>(); final html.ImageElement imageElement = html.ImageElement(); // ignore: unsafe_html imageElement.src = blobUrl; imageElement.onLoad.listen((html.Event event) { imageLoadCompleter.complete(imageElement); }); imageElement.onError.listen((html.Event event) { const String exception = 'Error while loading image.'; imageElement.remove(); imageLoadCompleter.completeError(exception); }); return imageLoadCompleter.future; } /// Draws image to a canvas while resizing the image to fit the [maxWidth],[maxHeight] constraints html.CanvasElement resizeImageElement( html.ImageElement source, double? maxWidth, double? maxHeight) { final Size newImageSize = calculateSizeOfDownScaledImage( Size(source.width!.toDouble(), source.height!.toDouble()), maxWidth, maxHeight); final html.CanvasElement canvas = html.CanvasElement(); canvas.width = newImageSize.width.toInt(); canvas.height = newImageSize.height.toInt(); final html.CanvasRenderingContext2D context = canvas.context2D; if (maxHeight == null && maxWidth == null) { context.drawImage(source, 0, 0); } else { context.drawImageScaled(source, 0, 0, canvas.width!, canvas.height!); } return canvas; } /// function that converts a canvas element to Xfile /// [imageQuality] is only supported for jpeg and webp images. Future<XFile> writeCanvasToFile( XFile originalFile, html.CanvasElement canvas, int? imageQuality) async { final double calculatedImageQuality = (min(imageQuality ?? 100, 100)) / 100.0; final html.Blob blob = await canvas.toBlob(originalFile.mimeType, calculatedImageQuality); return XFile(html.Url.createObjectUrlFromBlob(blob), mimeType: originalFile.mimeType, name: 'scaled_${originalFile.name}', lastModified: DateTime.now(), length: blob.size); } }
packages/packages/image_picker/image_picker_for_web/lib/src/image_resizer.dart/0
{'file_path': 'packages/packages/image_picker/image_picker_for_web/lib/src/image_resizer.dart', 'repo_id': 'packages', 'token_count': 1181}
// 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:cross_file/cross_file.dart'; import 'package:flutter/foundation.dart' show immutable; import 'camera_device.dart'; /// Options for [ImagePickerCameraDelegate] methods. /// /// New options may be added in the future. @immutable class ImagePickerCameraDelegateOptions { /// Creates a new set of options for taking an image or video. const ImagePickerCameraDelegateOptions({ this.preferredCameraDevice = CameraDevice.rear, this.maxVideoDuration, }); /// The camera device to default to, if available. /// /// Defaults to [CameraDevice.rear]. final CameraDevice preferredCameraDevice; /// The maximum duration to allow when recording a video. /// /// Defaults to null, meaning no maximum duration. final Duration? maxVideoDuration; } /// A delegate for `ImagePickerPlatform` implementations that do not provide /// a camera implementation, or that have a default but allow substituting an /// alternate implementation. abstract class ImagePickerCameraDelegate { /// Takes a photo with the given [options] and returns an [XFile] to the /// resulting image file. /// /// Returns null if the photo could not be taken, or the user cancelled. Future<XFile?> takePhoto({ ImagePickerCameraDelegateOptions options = const ImagePickerCameraDelegateOptions(), }); /// Records a video with the given [options] and returns an [XFile] to the /// resulting video file. /// /// Returns null if the video could not be recorded, or the user cancelled. Future<XFile?> takeVideo({ ImagePickerCameraDelegateOptions options = const ImagePickerCameraDelegateOptions(), }); }
packages/packages/image_picker/image_picker_platform_interface/lib/src/types/camera_delegate.dart/0
{'file_path': 'packages/packages/image_picker/image_picker_platform_interface/lib/src/types/camera_delegate.dart', 'repo_id': 'packages', 'token_count': 500}
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'product_details_wrapper.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** ProductDetailsWrapper _$ProductDetailsWrapperFromJson(Map json) => ProductDetailsWrapper( description: json['description'] as String? ?? '', name: json['name'] as String? ?? '', oneTimePurchaseOfferDetails: json['oneTimePurchaseOfferDetails'] == null ? null : OneTimePurchaseOfferDetailsWrapper.fromJson( Map<String, dynamic>.from( json['oneTimePurchaseOfferDetails'] as Map)), productId: json['productId'] as String? ?? '', productType: json['productType'] == null ? ProductType.subs : const ProductTypeConverter() .fromJson(json['productType'] as String?), subscriptionOfferDetails: (json['subscriptionOfferDetails'] as List<dynamic>?) ?.map((e) => SubscriptionOfferDetailsWrapper.fromJson( Map<String, dynamic>.from(e as Map))) .toList(), title: json['title'] as String? ?? '', ); ProductDetailsResponseWrapper _$ProductDetailsResponseWrapperFromJson( Map json) => ProductDetailsResponseWrapper( billingResult: BillingResultWrapper.fromJson((json['billingResult'] as Map?)?.map( (k, e) => MapEntry(k as String, e), )), productDetailsList: (json['productDetailsList'] as List<dynamic>?) ?.map((e) => ProductDetailsWrapper.fromJson( Map<String, dynamic>.from(e as Map))) .toList() ?? [], ); const _$RecurrenceModeEnumMap = { RecurrenceMode.finiteRecurring: 2, RecurrenceMode.infiniteRecurring: 1, RecurrenceMode.nonRecurring: 3, };
packages/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/product_details_wrapper.g.dart/0
{'file_path': 'packages/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/product_details_wrapper.g.dart', 'repo_id': 'packages', 'token_count': 751}
// 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:in_app_purchase_platform_interface/in_app_purchase_platform_interface.dart'; import '../../store_kit_wrappers.dart'; /// The class represents the information of a product as registered in the Apple /// AppStore. class AppStoreProductDetails extends ProductDetails { /// Creates a new AppStore specific product details object with the provided /// details. AppStoreProductDetails({ required super.id, required super.title, required super.description, required super.price, required super.rawPrice, required super.currencyCode, required this.skProduct, required super.currencySymbol, }); /// Generate a [AppStoreProductDetails] object based on an iOS [SKProductWrapper] object. factory AppStoreProductDetails.fromSKProduct(SKProductWrapper product) { return AppStoreProductDetails( id: product.productIdentifier, title: product.localizedTitle, description: product.localizedDescription, price: product.priceLocale.currencySymbol + product.price, rawPrice: double.parse(product.price), currencyCode: product.priceLocale.currencyCode, currencySymbol: product.priceLocale.currencySymbol.isNotEmpty ? product.priceLocale.currencySymbol : product.priceLocale.currencyCode, skProduct: product, ); } /// Points back to the [SKProductWrapper] object that was used to generate /// this [AppStoreProductDetails] object. final SKProductWrapper skProduct; }
packages/packages/in_app_purchase/in_app_purchase_storekit/lib/src/types/app_store_product_details.dart/0
{'file_path': 'packages/packages/in_app_purchase/in_app_purchase_storekit/lib/src/types/app_store_product_details.dart', 'repo_id': 'packages', 'token_count': 505}
// 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. // This is a temporary ignore to allow us to land a new set of linter rules in a // series of manageable patches instead of one gigantic PR. It disables some of // the new lints that are already failing on this plugin, for this plugin. It // should be deleted and the failing lints addressed as soon as possible. // ignore_for_file: public_member_api_docs import 'dart:async'; import 'package:flutter/services.dart'; import 'package:local_auth_android/local_auth_android.dart'; import 'package:local_auth_ios/local_auth_ios.dart'; import 'package:local_auth_platform_interface/local_auth_platform_interface.dart'; import 'package:local_auth_windows/local_auth_windows.dart'; /// A Flutter plugin for authenticating the user identity locally. class LocalAuthentication { /// Authenticates the user with biometrics available on the device while also /// allowing the user to use device authentication - pin, pattern, passcode. /// /// Returns true if the user successfully authenticated, false otherwise. /// /// [localizedReason] is the message to show to user while prompting them /// for authentication. This is typically along the lines of: 'Authenticate /// to access MyApp.'. This must not be empty. /// /// Provide [authMessages] if you want to /// customize messages in the dialogs. /// /// Provide [options] for configuring further authentication related options. /// /// Throws a [PlatformException] if there were technical problems with local /// authentication (e.g. lack of relevant hardware). This might throw /// [PlatformException] with error code [otherOperatingSystem] on the iOS /// simulator. Future<bool> authenticate( {required String localizedReason, Iterable<AuthMessages> authMessages = const <AuthMessages>[ IOSAuthMessages(), AndroidAuthMessages(), WindowsAuthMessages() ], AuthenticationOptions options = const AuthenticationOptions()}) { return LocalAuthPlatform.instance.authenticate( localizedReason: localizedReason, authMessages: authMessages, options: options, ); } /// Cancels any in-progress authentication, returning true if auth was /// cancelled successfully. /// /// This API is not supported by all platforms. /// Returns false if there was some error, no authentication in progress, /// or the current platform lacks support. Future<bool> stopAuthentication() async { return LocalAuthPlatform.instance.stopAuthentication(); } /// Returns true if device is capable of checking biometrics. Future<bool> get canCheckBiometrics => LocalAuthPlatform.instance.deviceSupportsBiometrics(); /// Returns true if device is capable of checking biometrics or is able to /// fail over to device credentials. Future<bool> isDeviceSupported() async => LocalAuthPlatform.instance.isDeviceSupported(); /// Returns a list of enrolled biometrics. Future<List<BiometricType>> getAvailableBiometrics() => LocalAuthPlatform.instance.getEnrolledBiometrics(); }
packages/packages/local_auth/local_auth/lib/src/local_auth.dart/0
{'file_path': 'packages/packages/local_auth/local_auth/lib/src/local_auth.dart', 'repo_id': 'packages', 'token_count': 879}
// 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:local_auth_platform_interface/local_auth_platform_interface.dart'; import 'src/messages.g.dart'; export 'package:local_auth_platform_interface/types/auth_messages.dart'; export 'package:local_auth_platform_interface/types/auth_options.dart'; export 'package:local_auth_platform_interface/types/biometric_type.dart'; export 'package:local_auth_windows/types/auth_messages_windows.dart'; /// The implementation of [LocalAuthPlatform] for Windows. class LocalAuthWindows extends LocalAuthPlatform { /// Creates a new plugin implementation instance. LocalAuthWindows({ @visibleForTesting LocalAuthApi? api, }) : _api = api ?? LocalAuthApi(); final LocalAuthApi _api; /// Registers this class as the default instance of [LocalAuthPlatform]. static void registerWith() { LocalAuthPlatform.instance = LocalAuthWindows(); } @override Future<bool> authenticate({ required String localizedReason, required Iterable<AuthMessages> authMessages, AuthenticationOptions options = const AuthenticationOptions(), }) async { assert(localizedReason.isNotEmpty); if (options.biometricOnly) { throw UnsupportedError( "Windows doesn't support the biometricOnly parameter."); } return _api.authenticate(localizedReason); } @override Future<bool> deviceSupportsBiometrics() async { // Biometrics are supported on any supported device. return isDeviceSupported(); } @override Future<List<BiometricType>> getEnrolledBiometrics() async { // Windows doesn't support querying specific biometric types. Since the // OS considers this a strong authentication API, return weak+strong on // any supported device. if (await isDeviceSupported()) { return <BiometricType>[BiometricType.weak, BiometricType.strong]; } return <BiometricType>[]; } @override Future<bool> isDeviceSupported() async => _api.isDeviceSupported(); /// Always returns false as this method is not supported on Windows. @override Future<bool> stopAuthentication() async => false; }
packages/packages/local_auth/local_auth_windows/lib/local_auth_windows.dart/0
{'file_path': 'packages/packages/local_auth/local_auth_windows/lib/local_auth_windows.dart', 'repo_id': 'packages', 'token_count': 678}
// 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:metrics_center/src/constants.dart'; import 'package:metrics_center/src/flutter.dart'; import 'common.dart'; import 'utility.dart'; void main() { const String gitRevision = 'ca799fa8b2254d09664b78ee80c43b434788d112'; final FlutterEngineMetricPoint simplePoint = FlutterEngineMetricPoint( 'BM_ParagraphLongLayout', 287235, gitRevision, ); test('FlutterEngineMetricPoint works.', () { expect(simplePoint.value, equals(287235)); expect(simplePoint.tags[kGithubRepoKey], kFlutterEngineRepo); expect(simplePoint.tags[kGitRevisionKey], gitRevision); expect(simplePoint.tags[kNameKey], 'BM_ParagraphLongLayout'); final FlutterEngineMetricPoint detailedPoint = FlutterEngineMetricPoint( 'BM_ParagraphLongLayout', 287224, 'ca799fa8b2254d09664b78ee80c43b434788d112', moreTags: const <String, String>{ 'executable': 'txt_benchmarks', 'sub_result': 'CPU', kUnitKey: 'ns', }, ); expect(detailedPoint.value, equals(287224)); expect(detailedPoint.tags['executable'], equals('txt_benchmarks')); expect(detailedPoint.tags['sub_result'], equals('CPU')); expect(detailedPoint.tags[kUnitKey], equals('ns')); }); final Map<String, dynamic>? credentialsJson = getTestGcpCredentialsJson(); test('FlutterDestination integration test with update.', () async { final FlutterDestination dst = await FlutterDestination.makeFromCredentialsJson(credentialsJson!, isTesting: true); await dst.update(<FlutterEngineMetricPoint>[simplePoint], DateTime.fromMillisecondsSinceEpoch(123), 'test'); }, skip: credentialsJson == null); }
packages/packages/metrics_center/test/flutter_test.dart/0
{'file_path': 'packages/packages/metrics_center/test/flutter_test.dart', 'repo_id': 'packages', 'token_count': 680}
// 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'; /// The IPv4 mDNS Address. final InternetAddress mDnsAddressIPv4 = InternetAddress('224.0.0.251'); /// The IPv6 mDNS Address. final InternetAddress mDnsAddressIPv6 = InternetAddress('FF02::FB'); /// The mDNS port. const int mDnsPort = 5353; /// Enumeration of supported resource record class types. abstract class ResourceRecordClass { // This class is intended to be used as a namespace, and should not be // extended directly. ResourceRecordClass._(); /// Internet address class ("IN"). static const int internet = 1; } /// Enumeration of DNS question types. abstract class QuestionType { // This class is intended to be used as a namespace, and should not be // extended directly. QuestionType._(); /// "QU" Question. static const int unicast = 0x8000; /// "QM" Question. static const int multicast = 0x0000; }
packages/packages/multicast_dns/lib/src/constants.dart/0
{'file_path': 'packages/packages/multicast_dns/lib/src/constants.dart', 'repo_id': 'packages', 'token_count': 298}
// 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:integration_test/integration_test.dart'; import 'package:pigeon_example_app/main.dart'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); testWidgets('gets host language', (WidgetTester tester) async { await tester.pumpWidget(const MyApp()); await tester.pumpAndSettle(); expect(find.textContaining('Hello from'), findsOneWidget); }); }
packages/packages/pigeon/example/app/integration_test/example_app_test.dart/0
{'file_path': 'packages/packages/pigeon/example/app/integration_test/example_app_test.dart', 'repo_id': 'packages', 'token_count': 192}
buildFlags: _pluginToolsConfigGlobalKey: - "--no-tree-shake-icons" - "--dart-define=buildmode=testing"
packages/packages/quick_actions/quick_actions/example/.pluginToolsConfig.yaml/0
{'file_path': 'packages/packages/quick_actions/quick_actions/example/.pluginToolsConfig.yaml', 'repo_id': 'packages', 'token_count': 45}
// 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. /// # Remote Flutter Widgets - formats only import /// /// This is a subset of the [rfw] library that only exposes features that /// do not depend on Flutter. /// /// Specifically, the following APIs are exposed by this library: /// /// * [parseLibraryFile] and [parseDataFile], for parsing Remote Flutter /// Widgets text library and data files respectively. (These are not exposed /// by the [rfw] library since they are not intended for use in client-side /// code.) /// /// * [encodeLibraryBlob] and [encodeDataBlob], for encoding the output of the /// previous methods into binary form. /// /// * [decodeLibraryBlob] and [decodeDataBlob], which decode those binary /// forms. /// /// * The [DynamicMap], [DynamicList], and [BlobNode] types (and subclasses), /// which are used to represent the data model and remote widget libraries in /// memory. /// /// For client-side code, import `package:rfw/rfw.dart` instead. library formats; export 'src/dart/binary.dart'; export 'src/dart/model.dart'; export 'src/dart/text.dart';
packages/packages/rfw/lib/formats.dart/0
{'file_path': 'packages/packages/rfw/lib/formats.dart', 'repo_id': 'packages', 'token_count': 360}
// 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:integration_test/integration_test.dart'; import 'package:shared_preferences/shared_preferences.dart'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); const String testString = 'hello world'; const bool testBool = true; const int testInt = 42; const double testDouble = 3.14159; const List<String> testList = <String>['foo', 'bar']; const String testString2 = 'goodbye world'; const bool testBool2 = false; const int testInt2 = 1337; const double testDouble2 = 2.71828; const List<String> testList2 = <String>['baz', 'quox']; late SharedPreferences preferences; void runAllTests() { testWidgets('reading', (WidgetTester _) async { expect(preferences.get('String'), isNull); expect(preferences.get('bool'), isNull); expect(preferences.get('int'), isNull); expect(preferences.get('double'), isNull); expect(preferences.get('List'), isNull); expect(preferences.getString('String'), isNull); expect(preferences.getBool('bool'), isNull); expect(preferences.getInt('int'), isNull); expect(preferences.getDouble('double'), isNull); expect(preferences.getStringList('List'), isNull); }); testWidgets('writing', (WidgetTester _) async { await Future.wait(<Future<bool>>[ preferences.setString('String', testString2), preferences.setBool('bool', testBool2), preferences.setInt('int', testInt2), preferences.setDouble('double', testDouble2), preferences.setStringList('List', testList2) ]); expect(preferences.getString('String'), testString2); expect(preferences.getBool('bool'), testBool2); expect(preferences.getInt('int'), testInt2); expect(preferences.getDouble('double'), testDouble2); expect(preferences.getStringList('List'), testList2); }); testWidgets('removing', (WidgetTester _) async { const String key = 'testKey'; await preferences.setString(key, testString); await preferences.setBool(key, testBool); await preferences.setInt(key, testInt); await preferences.setDouble(key, testDouble); await preferences.setStringList(key, testList); await preferences.remove(key); expect(preferences.get('testKey'), isNull); }); testWidgets('clearing', (WidgetTester _) async { await preferences.setString('String', testString); await preferences.setBool('bool', testBool); await preferences.setInt('int', testInt); await preferences.setDouble('double', testDouble); await preferences.setStringList('List', testList); await preferences.clear(); expect(preferences.getString('String'), null); expect(preferences.getBool('bool'), null); expect(preferences.getInt('int'), null); expect(preferences.getDouble('double'), null); expect(preferences.getStringList('List'), null); }); testWidgets('simultaneous writes', (WidgetTester _) async { final List<Future<bool>> writes = <Future<bool>>[]; const int writeCount = 100; for (int i = 1; i <= writeCount; i++) { writes.add(preferences.setInt('int', i)); } final List<bool> result = await Future.wait(writes, eagerError: true); // All writes should succeed. expect(result.where((bool element) => !element), isEmpty); // The last write should win. expect(preferences.getInt('int'), writeCount); }); } group('SharedPreferences', () { setUp(() async { preferences = await SharedPreferences.getInstance(); }); tearDown(() async { await preferences.clear(); SharedPreferences.resetStatic(); }); runAllTests(); }); group('setPrefix', () { setUp(() async { SharedPreferences.resetStatic(); SharedPreferences.setPrefix('prefix.'); preferences = await SharedPreferences.getInstance(); }); tearDown(() async { await preferences.clear(); SharedPreferences.resetStatic(); }); runAllTests(); }); group('setNoPrefix', () { setUp(() async { SharedPreferences.resetStatic(); SharedPreferences.setPrefix(''); preferences = await SharedPreferences.getInstance(); }); tearDown(() async { await preferences.clear(); SharedPreferences.resetStatic(); }); runAllTests(); }); testWidgets('allowList only gets allowed items', (WidgetTester _) async { const String allowedString = 'stringKey'; const String allowedBool = 'boolKey'; const String notAllowedDouble = 'doubleKey'; const String resultString = 'resultString'; const Set<String> allowList = <String>{allowedString, allowedBool}; SharedPreferences.resetStatic(); SharedPreferences.setPrefix('', allowList: allowList); final SharedPreferences prefs = await SharedPreferences.getInstance(); await prefs.setString(allowedString, resultString); await prefs.setBool(allowedBool, true); await prefs.setDouble(notAllowedDouble, 3.14); await prefs.reload(); final String? testString = prefs.getString(allowedString); expect(testString, resultString); final bool? testBool = prefs.getBool(allowedBool); expect(testBool, true); final double? testDouble = prefs.getDouble(notAllowedDouble); expect(testDouble, null); }); }
packages/packages/shared_preferences/shared_preferences/example/integration_test/shared_preferences_test.dart/0
{'file_path': 'packages/packages/shared_preferences/shared_preferences/example/integration_test/shared_preferences_test.dart', 'repo_id': 'packages', 'token_count': 1990}
// 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:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences_example/readme_excerpts.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); test('sanity check readmeSnippets', () async { // This key is set and cleared in the snippets. const String clearedKey = 'counter'; // Set a mock store so that there's a platform implementation. SharedPreferences.setMockInitialValues(<String, Object>{clearedKey: 2}); final SharedPreferences prefs = await SharedPreferences.getInstance(); // Ensure that the snippet code runs successfully. await readmeSnippets(); // Spot-check some functionality to ensure that it's showing working calls. // It should also set some preferences. expect(prefs.getBool('repeat'), isNotNull); expect(prefs.getDouble('decimal'), isNotNull); // It should clear this preference. expect(prefs.getInt(clearedKey), isNull); }); test('readmeTestSnippets', () async { await readmeTestSnippets(); final SharedPreferences prefs = await SharedPreferences.getInstance(); // The snippet sets a single initial pref. expect(prefs.getKeys().length, 1); }); }
packages/packages/shared_preferences/shared_preferences/example/test/readme_excerpts_test.dart/0
{'file_path': 'packages/packages/shared_preferences/shared_preferences/example/test/readme_excerpts_test.dart', 'repo_id': 'packages', 'token_count': 434}
// 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:plugin_platform_interface/plugin_platform_interface.dart'; import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart'; import 'package:shared_preferences_platform_interface/types.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); group(SharedPreferencesStorePlatform, () { test('disallows implementing interface', () { expect(() { SharedPreferencesStorePlatform.instance = IllegalImplementation(); }, // In versions of `package:plugin_platform_interface` prior to fixing // https://github.com/flutter/flutter/issues/109339, an attempt to // implement a platform interface using `implements` would sometimes // throw a `NoSuchMethodError` and other times throw an // `AssertionError`. After the issue is fixed, an `AssertionError` will // always be thrown. For the purpose of this test, we don't really care // what exception is thrown, so just allow any exception. throwsA(anything)); }); test('supports MockPlatformInterfaceMixin', () { SharedPreferencesStorePlatform.instance = ModernMockImplementation(); }); test('still supports legacy isMock', () { SharedPreferencesStorePlatform.instance = LegacyIsMockImplementation(); }); }); } /// An implementation using `implements` that isn't a mock, which isn't allowed. class IllegalImplementation implements SharedPreferencesStorePlatform { // Intentionally declare self as not a mock to trigger the // compliance check. @override bool get isMock => false; @override Future<bool> clear() { throw UnimplementedError(); } @override Future<bool> clearWithPrefix(String prefix) { throw UnimplementedError(); } @override Future<bool> clearWithParameters(ClearParameters parameters) { throw UnimplementedError(); } @override Future<Map<String, Object>> getAll() { throw UnimplementedError(); } @override Future<Map<String, Object>> getAllWithPrefix(String prefix) { throw UnimplementedError(); } @override Future<Map<String, Object>> getAllWithParameters( GetAllParameters parameters) { throw UnimplementedError(); } @override Future<bool> remove(String key) { throw UnimplementedError(); } @override Future<bool> setValue(String valueType, String key, Object value) { throw UnimplementedError(); } } class LegacyIsMockImplementation implements SharedPreferencesStorePlatform { @override bool get isMock => true; @override Future<bool> clear() { throw UnimplementedError(); } @override Future<bool> clearWithPrefix(String prefix) { throw UnimplementedError(); } @override Future<bool> clearWithParameters(ClearParameters parameters) { throw UnimplementedError(); } @override Future<Map<String, Object>> getAll() { throw UnimplementedError(); } @override Future<Map<String, Object>> getAllWithPrefix(String prefix) { throw UnimplementedError(); } @override Future<Map<String, Object>> getAllWithParameters( GetAllParameters parameters) { throw UnimplementedError(); } @override Future<bool> remove(String key) { throw UnimplementedError(); } @override Future<bool> setValue(String valueType, String key, Object value) { throw UnimplementedError(); } } class ModernMockImplementation with MockPlatformInterfaceMixin implements SharedPreferencesStorePlatform { @override bool get isMock => false; @override Future<bool> clear() { throw UnimplementedError(); } @override Future<bool> clearWithPrefix(String prefix) { throw UnimplementedError(); } @override Future<bool> clearWithParameters(ClearParameters parameters) { throw UnimplementedError(); } @override Future<Map<String, Object>> getAll() { throw UnimplementedError(); } @override Future<Map<String, Object>> getAllWithPrefix(String prefix) { throw UnimplementedError(); } @override Future<Map<String, Object>> getAllWithParameters( GetAllParameters parameters) { throw UnimplementedError(); } @override Future<bool> remove(String key) { throw UnimplementedError(); } @override Future<bool> setValue(String valueType, String key, Object value) { throw UnimplementedError(); } }
packages/packages/shared_preferences/shared_preferences_platform_interface/test/shared_preferences_platform_interface_test.dart/0
{'file_path': 'packages/packages/shared_preferences/shared_preferences_platform_interface/test/shared_preferences_platform_interface_test.dart', 'repo_id': 'packages', 'token_count': 1506}
// 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/widgets.dart'; import 'table.dart'; import 'table_cell.dart'; import 'table_span.dart'; /// Signature for a function that creates a [TableSpan] for a given index of row /// or column in a [TableView]. /// /// Used by the [TableCellDelegateMixin.buildColumn] and /// [TableCellDelegateMixin.buildRow] to configure rows and columns in the /// [TableView]. typedef TableSpanBuilder = TableSpan Function(int index); /// Signature for a function that creates a child [Widget] for a given /// [TableVicinity] in a [TableView], but may return null. /// /// Used by [TableCellBuilderDelegate.builder] to build cells on demand for the /// table. typedef TableViewCellBuilder = Widget? Function( BuildContext context, TableVicinity vicinity, ); /// A mixin that defines the model for a [TwoDimensionalChildDelegate] to be /// used with a [TableView]. mixin TableCellDelegateMixin on TwoDimensionalChildDelegate { /// The number of columns that the table has content for. /// /// The [buildColumn] method will be called for indices smaller than the value /// provided here to learn more about the extent and visual appearance of a /// particular column. // TODO(Piinks): land infinite separately, https://github.com/flutter/flutter/issues/131226 // If null, the table will have an infinite number of columns. /// /// The value returned by this getter may be an estimate of the total /// available columns, but [buildColumn] method must provide a valid /// [TableSpan] for all indices smaller than this integer. /// /// The integer returned by this getter must be larger than (or equal to) the /// integer returned by [pinnedColumnCount]. /// /// If the value returned by this getter changes throughout the lifetime of /// the delegate object, [notifyListeners] must be called. int get columnCount; /// The number of rows that the table has content for. /// /// The [buildRow] method will be called for indices smaller than the value /// provided here to learn more about the extent and visual appearance of a /// particular row. // TODO(Piinks): land infinite separately, https://github.com/flutter/flutter/issues/131226 // If null, the table will have an infinite number of rows. /// /// The value returned by this getter may be an estimate of the total /// available rows, but [buildRow] method must provide a valid /// [TableSpan] for all indices smaller than this integer. /// /// The integer returned by this getter must be larger than (or equal to) the /// integer returned by [pinnedRowCount]. /// /// If the value returned by this getter changes throughout the lifetime of /// the delegate object, [notifyListeners] must be called. int get rowCount; /// The number of columns that are permanently shown on the leading vertical /// edge of the viewport. /// /// If scrolling is enabled, other columns will scroll underneath the pinned /// columns. /// /// Just like for regular columns, [buildColumn] method will be consulted for /// additional information about the pinned column. The indices of pinned /// columns start at zero and go to `pinnedColumnCount - 1`. /// /// The integer returned by this getter must be smaller than (or equal to) the /// integer returned by [columnCount]. /// /// If the value returned by this getter changes throughout the lifetime of /// the delegate object, [notifyListeners] must be called. int get pinnedColumnCount => 0; /// The number of rows that are permanently shown on the leading horizontal /// edge of the viewport. /// /// If scrolling is enabled, other rows will scroll underneath the pinned /// rows. /// /// Just like for regular rows, [buildRow] will be consulted for /// additional information about the pinned row. The indices of pinned rows /// start at zero and go to `pinnedRowCount - 1`. /// /// The integer returned by this getter must be smaller than (or equal to) the /// integer returned by [rowCount]. /// /// If the value returned by this getter changes throughout the lifetime of /// the delegate object, [notifyListeners] must be called. int get pinnedRowCount => 0; /// Builds the [TableSpan] that describes the column at the provided index. /// /// The builder must return a valid [TableSpan] for all indices smaller than /// [columnCount]. TableSpan buildColumn(int index); /// Builds the [TableSpan] that describe the row at the provided index. /// /// The builder must return a valid [TableSpan] for all indices smaller than /// [rowCount]. TableSpan buildRow(int index); } /// A delegate that supplies children for a [TableViewport] on demand using a /// builder callback. class TableCellBuilderDelegate extends TwoDimensionalChildBuilderDelegate with TableCellDelegateMixin { /// Creates a lazy building delegate to use with a [TableView]. TableCellBuilderDelegate({ required int columnCount, required int rowCount, int pinnedColumnCount = 0, int pinnedRowCount = 0, super.addRepaintBoundaries, super.addAutomaticKeepAlives, required TableViewCellBuilder cellBuilder, required TableSpanBuilder columnBuilder, required TableSpanBuilder rowBuilder, }) : assert(pinnedColumnCount >= 0), assert(pinnedRowCount >= 0), assert(rowCount >= 0), assert(columnCount >= 0), assert(pinnedColumnCount <= columnCount), assert(pinnedRowCount <= rowCount), _rowBuilder = rowBuilder, _columnBuilder = columnBuilder, _pinnedColumnCount = pinnedColumnCount, _pinnedRowCount = pinnedRowCount, super( builder: (BuildContext context, ChildVicinity vicinity) => cellBuilder(context, vicinity as TableVicinity), maxXIndex: columnCount - 1, maxYIndex: rowCount - 1, ); @override int get columnCount => maxXIndex! + 1; set columnCount(int value) { assert(pinnedColumnCount <= value); maxXIndex = value - 1; } /// Builds the [TableSpan] that describes the column at the provided index. /// /// The builder must return a valid [TableSpan] for all indices smaller than /// [columnCount]. final TableSpanBuilder _columnBuilder; @override TableSpan buildColumn(int index) => _columnBuilder(index); @override int get pinnedColumnCount => _pinnedColumnCount; int _pinnedColumnCount; set pinnedColumnCount(int value) { assert(value >= 0); assert(value <= columnCount); if (pinnedColumnCount == value) { return; } _pinnedColumnCount = value; notifyListeners(); } @override int get rowCount => maxYIndex! + 1; set rowCount(int value) { assert(pinnedRowCount <= value); maxYIndex = value - 1; } /// Builds the [TableSpan] that describes the row at the provided index. /// /// The builder must return a valid [TableSpan] for all indices smaller than /// [rowCount]. final TableSpanBuilder _rowBuilder; @override TableSpan buildRow(int index) => _rowBuilder(index); @override int get pinnedRowCount => _pinnedRowCount; int _pinnedRowCount; set pinnedRowCount(int value) { assert(value >= 0); assert(value <= rowCount); if (pinnedRowCount == value) { return; } _pinnedRowCount = value; notifyListeners(); } } /// A delegate that supplies children for a [TableViewport] using an /// explicit two dimensional array. /// /// The [children] are accessed for each [TableVicinity.row] and /// [TableVicinity.column] of the [TwoDimensionalViewport] as /// `children[vicinity.row][vicinity.column]`. class TableCellListDelegate extends TwoDimensionalChildListDelegate with TableCellDelegateMixin { /// Creates a delegate that supplies children for a [TableView]. TableCellListDelegate({ int pinnedColumnCount = 0, int pinnedRowCount = 0, super.addRepaintBoundaries, super.addAutomaticKeepAlives, required List<List<Widget>> cells, required TableSpanBuilder columnBuilder, required TableSpanBuilder rowBuilder, }) : assert(pinnedColumnCount >= 0), assert(pinnedRowCount >= 0), _columnBuilder = columnBuilder, _rowBuilder = rowBuilder, _pinnedColumnCount = pinnedColumnCount, _pinnedRowCount = pinnedRowCount, super(children: cells) { // Even if there are merged cells, they should be represented by the same // child in each cell location. So all arrays of cells should have the same // length. assert( children.map((List<Widget> array) => array.length).toSet().length == 1, 'Each list of Widgets within cells must be of the same length.', ); assert(rowCount >= pinnedRowCount); assert(columnCount >= pinnedColumnCount); } @override int get columnCount => children.isEmpty ? 0 : children[0].length; /// Builds the [TableSpan] that describes the column at the provided index. /// /// The builder must return a valid [TableSpan] for all indices smaller than /// [columnCount]. final TableSpanBuilder _columnBuilder; @override TableSpan buildColumn(int index) => _columnBuilder(index); @override int get pinnedColumnCount => _pinnedColumnCount; int _pinnedColumnCount; set pinnedColumnCount(int value) { assert(value >= 0); assert(value <= columnCount); if (pinnedColumnCount == value) { return; } _pinnedColumnCount = value; notifyListeners(); } @override int get rowCount => children.length; /// Builds the [TableSpan] that describes the row at the provided index. /// /// The builder must return a valid [TableSpan] for all indices smaller than /// [rowCount]. final TableSpanBuilder _rowBuilder; @override TableSpan buildRow(int index) => _rowBuilder(index); @override int get pinnedRowCount => _pinnedRowCount; int _pinnedRowCount; set pinnedRowCount(int value) { assert(value >= 0); assert(value <= rowCount); if (pinnedRowCount == value) { return; } _pinnedRowCount = value; notifyListeners(); } @override bool shouldRebuild(covariant TableCellListDelegate oldDelegate) { return columnCount != oldDelegate.columnCount || _columnBuilder != oldDelegate._columnBuilder || pinnedColumnCount != oldDelegate.pinnedColumnCount || rowCount != oldDelegate.rowCount || _rowBuilder != oldDelegate._rowBuilder || pinnedRowCount != oldDelegate.pinnedRowCount || super.shouldRebuild(oldDelegate); } }
packages/packages/two_dimensional_scrollables/lib/src/table_view/table_delegate.dart/0
{'file_path': 'packages/packages/two_dimensional_scrollables/lib/src/table_view/table_delegate.dart', 'repo_id': 'packages', 'token_count': 3265}
// 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. // Provides a String-based alterantive to the Uri-based primary API. // // This is provided as a separate import because it's much easier to use // incorrectly, so should require explicit opt-in (to avoid issues such as // IDE auto-complete to the more error-prone APIs just by importing the // main API). export 'src/types.dart'; export 'src/url_launcher_string.dart';
packages/packages/url_launcher/url_launcher/lib/url_launcher_string.dart/0
{'file_path': 'packages/packages/url_launcher/url_launcher/lib/url_launcher_string.dart', 'repo_id': 'packages', 'token_count': 143}
// 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:video_player_platform_interface/video_player_platform_interface.dart'; void main() { test( 'VideoPlayerOptions controls defaults to VideoPlayerWebOptionsControls.disabled()', () { const VideoPlayerWebOptions options = VideoPlayerWebOptions(); expect(options.controls, const VideoPlayerWebOptionsControls.disabled()); }, ); test( 'VideoPlayerOptions allowContextMenu defaults to true', () { const VideoPlayerWebOptions options = VideoPlayerWebOptions(); expect(options.allowContextMenu, isTrue); }, ); test( 'VideoPlayerOptions allowRemotePlayback defaults to true', () { const VideoPlayerWebOptions options = VideoPlayerWebOptions(); expect(options.allowRemotePlayback, isTrue); }, ); }
packages/packages/video_player/video_player_platform_interface/test/video_player_web_options_test.dart/0
{'file_path': 'packages/packages/video_player/video_player_platform_interface/test/video_player_web_options_test.dart', 'repo_id': 'packages', 'token_count': 310}
// 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'; import 'dart:ui_web' as ui_web; import 'package:flutter/material.dart'; import 'package:flutter_web_plugins/flutter_web_plugins.dart'; import 'package:video_player_platform_interface/video_player_platform_interface.dart'; import 'src/video_player.dart'; /// The web implementation of [VideoPlayerPlatform]. /// /// This class implements the `package:video_player` functionality for the web. class VideoPlayerPlugin extends VideoPlayerPlatform { /// Registers this class as the default instance of [VideoPlayerPlatform]. static void registerWith(Registrar registrar) { VideoPlayerPlatform.instance = VideoPlayerPlugin(); } // Map of textureId -> VideoPlayer instances final Map<int, VideoPlayer> _videoPlayers = <int, VideoPlayer>{}; // Simulate the native "textureId". int _textureCounter = 1; @override Future<void> init() async { return _disposeAllPlayers(); } @override Future<void> dispose(int textureId) async { _player(textureId).dispose(); _videoPlayers.remove(textureId); return; } void _disposeAllPlayers() { for (final VideoPlayer videoPlayer in _videoPlayers.values) { videoPlayer.dispose(); } _videoPlayers.clear(); } @override Future<int> create(DataSource dataSource) async { final int textureId = _textureCounter++; late String uri; switch (dataSource.sourceType) { case DataSourceType.network: // Do NOT modify the incoming uri, it can be a Blob, and Safari doesn't // like blobs that have changed. uri = dataSource.uri ?? ''; case DataSourceType.asset: String assetUrl = dataSource.asset!; if (dataSource.package != null && dataSource.package!.isNotEmpty) { assetUrl = 'packages/${dataSource.package}/$assetUrl'; } assetUrl = ui_web.assetManager.getAssetUrl(assetUrl); uri = assetUrl; case DataSourceType.file: return Future<int>.error(UnimplementedError( 'web implementation of video_player cannot play local files')); case DataSourceType.contentUri: return Future<int>.error(UnimplementedError( 'web implementation of video_player cannot play content uri')); } final VideoElement videoElement = VideoElement() ..id = 'videoElement-$textureId' ..style.border = 'none' ..style.height = '100%' ..style.width = '100%'; // TODO(hterkelsen): Use initialization parameters once they are available ui_web.platformViewRegistry.registerViewFactory( 'videoPlayer-$textureId', (int viewId) => videoElement); final VideoPlayer player = VideoPlayer(videoElement: videoElement) ..initialize( src: uri, ); _videoPlayers[textureId] = player; return textureId; } @override Future<void> setLooping(int textureId, bool looping) async { return _player(textureId).setLooping(looping); } @override Future<void> play(int textureId) async { return _player(textureId).play(); } @override Future<void> pause(int textureId) async { return _player(textureId).pause(); } @override Future<void> setVolume(int textureId, double volume) async { return _player(textureId).setVolume(volume); } @override Future<void> setPlaybackSpeed(int textureId, double speed) async { return _player(textureId).setPlaybackSpeed(speed); } @override Future<void> seekTo(int textureId, Duration position) async { return _player(textureId).seekTo(position); } @override Future<Duration> getPosition(int textureId) async { return _player(textureId).getPosition(); } @override Stream<VideoEvent> videoEventsFor(int textureId) { return _player(textureId).events; } @override Future<void> setWebOptions(int textureId, VideoPlayerWebOptions options) { return _player(textureId).setOptions(options); } // Retrieves a [VideoPlayer] by its internal `id`. // It must have been created earlier from the [create] method. VideoPlayer _player(int id) { return _videoPlayers[id]!; } @override Widget buildView(int textureId) { return HtmlElementView(viewType: 'videoPlayer-$textureId'); } /// Sets the audio mode to mix with other sources (ignored) @override Future<void> setMixWithOthers(bool mixWithOthers) => Future<void>.value(); }
packages/packages/video_player/video_player_web/lib/video_player_web.dart/0
{'file_path': 'packages/packages/video_player/video_player_web/lib/video_player_web.dart', 'repo_id': 'packages', 'token_count': 1546}
// 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'; const ValueKey<String> textKey = ValueKey<String>('textKey'); const ValueKey<String> aboutPageKey = ValueKey<String>('aboutPageKey'); class HomePage extends StatefulWidget { const HomePage({super.key, required this.title}); final String title; @override State<HomePage> createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { int _counter = 0; void _incrementCounter() { setState(() { _counter++; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), actions: <Widget>[ IconButton( key: aboutPageKey, icon: const Icon(Icons.alternate_email), onPressed: () => Navigator.of(context).pushNamed('about'), ), ], ), body: Center( child: ListView.builder( itemExtent: 80, itemBuilder: (BuildContext context, int index) { if (index == 0) { return Column( key: textKey, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ const Text('You have pushed the button this many times:'), Text( '$_counter', style: Theme.of(context).textTheme.headlineMedium, ), ], ); } else { return SizedBox( height: 80, child: Padding( padding: const EdgeInsets.all(12), child: Card( elevation: 8, child: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( 'Line $index', style: Theme.of(context).textTheme.headlineSmall, ), Expanded(child: Container()), const Icon(Icons.camera), const Icon(Icons.face), ], ), ), ), ); } }, ), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: const Icon(Icons.add), ), ); } }
packages/packages/web_benchmarks/testing/test_app/lib/home_page.dart/0
{'file_path': 'packages/packages/web_benchmarks/testing/test_app/lib/home_page.dart', 'repo_id': 'packages', 'token_count': 1391}
buildFlags: _pluginToolsConfigGlobalKey: - "--no-tree-shake-icons" - "--dart-define=buildmode=testing"
packages/packages/webview_flutter/webview_flutter/example/.pluginToolsConfig.yaml/0
{'file_path': 'packages/packages/webview_flutter/webview_flutter/example/.pluginToolsConfig.yaml', 'repo_id': 'packages', 'token_count': 45}
// 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 '../platform_webview_controller.dart'; /// Defines the supported HTTP methods for loading a page in [PlatformWebViewController]. enum LoadRequestMethod { /// HTTP GET method. get, /// HTTP POST method. post, } /// Extension methods on the [LoadRequestMethod] enum. extension LoadRequestMethodExtensions on LoadRequestMethod { /// Converts [LoadRequestMethod] to [String] format. String serialize() { switch (this) { case LoadRequestMethod.get: return 'get'; case LoadRequestMethod.post: return 'post'; } } } /// Defines the parameters that can be used to load a page with the [PlatformWebViewController]. /// /// Platform specific implementations can add additional fields by extending /// this class. /// /// {@tool sample} /// This example demonstrates how to extend the [LoadRequestParams] to /// provide additional platform specific parameters. /// /// When extending [LoadRequestParams] additional parameters should always /// accept `null` or have a default value to prevent breaking changes. /// /// ```dart /// class AndroidLoadRequestParams extends LoadRequestParams { /// AndroidLoadRequestParams._({ /// required LoadRequestParams params, /// this.historyUrl, /// }) : super( /// uri: params.uri, /// method: params.method, /// body: params.body, /// headers: params.headers, /// ); /// /// factory AndroidLoadRequestParams.fromLoadRequestParams( /// LoadRequestParams params, { /// Uri? historyUrl, /// }) { /// return AndroidLoadRequestParams._(params, historyUrl: historyUrl); /// } /// /// final Uri? historyUrl; /// } /// ``` /// {@end-tool} @immutable class LoadRequestParams { /// Used by the platform implementation to create a new [LoadRequestParams]. const LoadRequestParams({ required this.uri, this.method = LoadRequestMethod.get, this.headers = const <String, String>{}, this.body, }); /// URI for the request. final Uri uri; /// HTTP method used to make the request. /// /// Defaults to [LoadRequestMethod.get]. final LoadRequestMethod method; /// Headers for the request. final Map<String, String> headers; /// HTTP body for the request. final Uint8List? body; }
packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/load_request_params.dart/0
{'file_path': 'packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/load_request_params.dart', 'repo_id': 'packages', 'token_count': 745}
// Mocks generated by Mockito 5.4.4 from annotations // in webview_flutter_platform_interface/test/webview_platform_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'package:mockito/mockito.dart' as _i1; import 'package:webview_flutter_platform_interface/src/platform_navigation_delegate.dart' as _i3; import 'package:webview_flutter_platform_interface/src/platform_webview_controller.dart' as _i4; import 'package:webview_flutter_platform_interface/src/platform_webview_cookie_manager.dart' as _i2; import 'package:webview_flutter_platform_interface/src/platform_webview_widget.dart' as _i5; import 'package:webview_flutter_platform_interface/src/types/types.dart' as _i7; import 'package:webview_flutter_platform_interface/src/webview_platform.dart' as _i6; // ignore_for_file: type=lint // ignore_for_file: avoid_redundant_argument_values // ignore_for_file: avoid_setters_without_getters // ignore_for_file: comment_references // ignore_for_file: deprecated_member_use // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types // ignore_for_file: subtype_of_sealed_class class _FakePlatformWebViewCookieManager_0 extends _i1.SmartFake implements _i2.PlatformWebViewCookieManager { _FakePlatformWebViewCookieManager_0( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakePlatformNavigationDelegate_1 extends _i1.SmartFake implements _i3.PlatformNavigationDelegate { _FakePlatformNavigationDelegate_1( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakePlatformWebViewController_2 extends _i1.SmartFake implements _i4.PlatformWebViewController { _FakePlatformWebViewController_2( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakePlatformWebViewWidget_3 extends _i1.SmartFake implements _i5.PlatformWebViewWidget { _FakePlatformWebViewWidget_3( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } /// A class which mocks [WebViewPlatform]. /// /// See the documentation for Mockito's code generation for more information. class MockWebViewPlatform extends _i1.Mock implements _i6.WebViewPlatform { MockWebViewPlatform() { _i1.throwOnMissingStub(this); } @override _i2.PlatformWebViewCookieManager createPlatformCookieManager( _i7.PlatformWebViewCookieManagerCreationParams? params) => (super.noSuchMethod( Invocation.method( #createPlatformCookieManager, [params], ), returnValue: _FakePlatformWebViewCookieManager_0( this, Invocation.method( #createPlatformCookieManager, [params], ), ), ) as _i2.PlatformWebViewCookieManager); @override _i3.PlatformNavigationDelegate createPlatformNavigationDelegate( _i7.PlatformNavigationDelegateCreationParams? params) => (super.noSuchMethod( Invocation.method( #createPlatformNavigationDelegate, [params], ), returnValue: _FakePlatformNavigationDelegate_1( this, Invocation.method( #createPlatformNavigationDelegate, [params], ), ), ) as _i3.PlatformNavigationDelegate); @override _i4.PlatformWebViewController createPlatformWebViewController( _i7.PlatformWebViewControllerCreationParams? params) => (super.noSuchMethod( Invocation.method( #createPlatformWebViewController, [params], ), returnValue: _FakePlatformWebViewController_2( this, Invocation.method( #createPlatformWebViewController, [params], ), ), ) as _i4.PlatformWebViewController); @override _i5.PlatformWebViewWidget createPlatformWebViewWidget( _i7.PlatformWebViewWidgetCreationParams? params) => (super.noSuchMethod( Invocation.method( #createPlatformWebViewWidget, [params], ), returnValue: _FakePlatformWebViewWidget_3( this, Invocation.method( #createPlatformWebViewWidget, [params], ), ), ) as _i5.PlatformWebViewWidget); }
packages/packages/webview_flutter/webview_flutter_platform_interface/test/webview_platform_test.mocks.dart/0
{'file_path': 'packages/packages/webview_flutter/webview_flutter_platform_interface/test/webview_platform_test.mocks.dart', 'repo_id': 'packages', 'token_count': 1920}
// 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 'package:flutter_test/flutter_test.dart'; import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart'; import 'package:webview_flutter_web/webview_flutter_web.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('WebWebViewWidget', () { testWidgets('build returns a HtmlElementView', (WidgetTester tester) async { final WebWebViewController controller = WebWebViewController(WebWebViewControllerCreationParams()); final WebWebViewWidget widget = WebWebViewWidget( PlatformWebViewWidgetCreationParams( key: const Key('keyValue'), controller: controller, ), ); await tester.pumpWidget( Builder(builder: (BuildContext context) => widget.build(context)), ); expect(find.byType(HtmlElementView), findsOneWidget); expect(find.byKey(const Key('keyValue')), findsOneWidget); }); }); }
packages/packages/webview_flutter/webview_flutter_web/test/web_webview_widget_test.dart/0
{'file_path': 'packages/packages/webview_flutter/webview_flutter_web/test/web_webview_widget_test.dart', 'repo_id': 'packages', 'token_count': 404}
// 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 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart'; import 'package:webview_flutter_wkwebview/src/common/web_kit.g.dart'; import 'package:webview_flutter_wkwebview/src/foundation/foundation.dart'; import 'package:webview_flutter_wkwebview/src/web_kit/web_kit.dart'; import 'package:webview_flutter_wkwebview/src/webkit_proxy.dart'; import 'package:webview_flutter_wkwebview/webview_flutter_wkwebview.dart'; void main() { WidgetsFlutterBinding.ensureInitialized(); group('WebKitNavigationDelegate', () { test('WebKitNavigationDelegate uses params field in constructor', () async { await runZonedGuarded( () async => WebKitNavigationDelegate( const PlatformNavigationDelegateCreationParams(), ), (Object error, __) { expect(error, isNot(isA<TypeError>())); }, ); }); test('setOnPageFinished', () { final WebKitNavigationDelegate webKitDelegate = WebKitNavigationDelegate( const WebKitNavigationDelegateCreationParams( webKitProxy: WebKitProxy( createNavigationDelegate: CapturingNavigationDelegate.new, createUIDelegate: CapturingUIDelegate.new, ), ), ); late final String callbackUrl; webKitDelegate.setOnPageFinished((String url) => callbackUrl = url); CapturingNavigationDelegate.lastCreatedDelegate.didFinishNavigation!( WKWebView.detached(), 'https://www.google.com', ); expect(callbackUrl, 'https://www.google.com'); }); test('setOnPageStarted', () { final WebKitNavigationDelegate webKitDelegate = WebKitNavigationDelegate( const WebKitNavigationDelegateCreationParams( webKitProxy: WebKitProxy( createNavigationDelegate: CapturingNavigationDelegate.new, createUIDelegate: CapturingUIDelegate.new, ), ), ); late final String callbackUrl; webKitDelegate.setOnPageStarted((String url) => callbackUrl = url); CapturingNavigationDelegate .lastCreatedDelegate.didStartProvisionalNavigation!( WKWebView.detached(), 'https://www.google.com', ); expect(callbackUrl, 'https://www.google.com'); }); test('onWebResourceError from didFailNavigation', () { final WebKitNavigationDelegate webKitDelegate = WebKitNavigationDelegate( const WebKitNavigationDelegateCreationParams( webKitProxy: WebKitProxy( createNavigationDelegate: CapturingNavigationDelegate.new, createUIDelegate: CapturingUIDelegate.new, ), ), ); late final WebKitWebResourceError callbackError; void onWebResourceError(WebResourceError error) { callbackError = error as WebKitWebResourceError; } webKitDelegate.setOnWebResourceError(onWebResourceError); CapturingNavigationDelegate.lastCreatedDelegate.didFailNavigation!( WKWebView.detached(), const NSError( code: WKErrorCode.webViewInvalidated, domain: 'domain', userInfo: <String, Object?>{ NSErrorUserInfoKey.NSURLErrorFailingURLStringError: 'www.flutter.dev', NSErrorUserInfoKey.NSLocalizedDescription: 'my desc', }, ), ); expect(callbackError.description, 'my desc'); expect(callbackError.errorCode, WKErrorCode.webViewInvalidated); expect(callbackError.url, 'www.flutter.dev'); expect(callbackError.domain, 'domain'); expect(callbackError.errorType, WebResourceErrorType.webViewInvalidated); expect(callbackError.isForMainFrame, true); }); test('onWebResourceError from didFailProvisionalNavigation', () { final WebKitNavigationDelegate webKitDelegate = WebKitNavigationDelegate( const WebKitNavigationDelegateCreationParams( webKitProxy: WebKitProxy( createNavigationDelegate: CapturingNavigationDelegate.new, createUIDelegate: CapturingUIDelegate.new, ), ), ); late final WebKitWebResourceError callbackError; void onWebResourceError(WebResourceError error) { callbackError = error as WebKitWebResourceError; } webKitDelegate.setOnWebResourceError(onWebResourceError); CapturingNavigationDelegate .lastCreatedDelegate.didFailProvisionalNavigation!( WKWebView.detached(), const NSError( code: WKErrorCode.webViewInvalidated, domain: 'domain', userInfo: <String, Object?>{ NSErrorUserInfoKey.NSURLErrorFailingURLStringError: 'www.flutter.dev', NSErrorUserInfoKey.NSLocalizedDescription: 'my desc', }, ), ); expect(callbackError.description, 'my desc'); expect(callbackError.url, 'www.flutter.dev'); expect(callbackError.errorCode, WKErrorCode.webViewInvalidated); expect(callbackError.domain, 'domain'); expect(callbackError.errorType, WebResourceErrorType.webViewInvalidated); expect(callbackError.isForMainFrame, true); }); test('onWebResourceError from webViewWebContentProcessDidTerminate', () { final WebKitNavigationDelegate webKitDelegate = WebKitNavigationDelegate( const WebKitNavigationDelegateCreationParams( webKitProxy: WebKitProxy( createNavigationDelegate: CapturingNavigationDelegate.new, createUIDelegate: CapturingUIDelegate.new, ), ), ); late final WebKitWebResourceError callbackError; void onWebResourceError(WebResourceError error) { callbackError = error as WebKitWebResourceError; } webKitDelegate.setOnWebResourceError(onWebResourceError); CapturingNavigationDelegate .lastCreatedDelegate.webViewWebContentProcessDidTerminate!( WKWebView.detached(), ); expect(callbackError.description, ''); expect(callbackError.errorCode, WKErrorCode.webContentProcessTerminated); expect(callbackError.domain, 'WKErrorDomain'); expect( callbackError.errorType, WebResourceErrorType.webContentProcessTerminated, ); expect(callbackError.isForMainFrame, true); }); test('onNavigationRequest from decidePolicyForNavigationAction', () { final WebKitNavigationDelegate webKitDelegate = WebKitNavigationDelegate( const WebKitNavigationDelegateCreationParams( webKitProxy: WebKitProxy( createNavigationDelegate: CapturingNavigationDelegate.new, createUIDelegate: CapturingUIDelegate.new, ), ), ); late final NavigationRequest callbackRequest; FutureOr<NavigationDecision> onNavigationRequest( NavigationRequest request) { callbackRequest = request; return NavigationDecision.navigate; } webKitDelegate.setOnNavigationRequest(onNavigationRequest); expect( CapturingNavigationDelegate .lastCreatedDelegate.decidePolicyForNavigationAction!( WKWebView.detached(), const WKNavigationAction( request: NSUrlRequest(url: 'https://www.google.com'), targetFrame: WKFrameInfo( isMainFrame: false, request: NSUrlRequest(url: 'https://google.com')), navigationType: WKNavigationType.linkActivated, ), ), completion(WKNavigationActionPolicy.allow), ); expect(callbackRequest.url, 'https://www.google.com'); expect(callbackRequest.isMainFrame, isFalse); }); test('onHttpBasicAuthRequest emits host and realm', () { final WebKitNavigationDelegate iosNavigationDelegate = WebKitNavigationDelegate( const WebKitNavigationDelegateCreationParams( webKitProxy: WebKitProxy( createNavigationDelegate: CapturingNavigationDelegate.new, ), ), ); String? callbackHost; String? callbackRealm; iosNavigationDelegate.setOnHttpAuthRequest((HttpAuthRequest request) { callbackHost = request.host; callbackRealm = request.realm; }); const String expectedHost = 'expectedHost'; const String expectedRealm = 'expectedRealm'; CapturingNavigationDelegate .lastCreatedDelegate.didReceiveAuthenticationChallenge!( WKWebView.detached(), NSUrlAuthenticationChallenge.detached( protectionSpace: NSUrlProtectionSpace.detached( host: expectedHost, realm: expectedRealm, authenticationMethod: NSUrlAuthenticationMethod.httpBasic, ), ), (NSUrlSessionAuthChallengeDisposition disposition, NSUrlCredential? credential) {}); expect(callbackHost, expectedHost); expect(callbackRealm, expectedRealm); }); }); } // Records the last created instance of itself. class CapturingNavigationDelegate extends WKNavigationDelegate { CapturingNavigationDelegate({ super.didFinishNavigation, super.didStartProvisionalNavigation, super.didFailNavigation, super.didFailProvisionalNavigation, super.decidePolicyForNavigationAction, super.webViewWebContentProcessDidTerminate, super.didReceiveAuthenticationChallenge, }) : super.detached() { lastCreatedDelegate = this; } static CapturingNavigationDelegate lastCreatedDelegate = CapturingNavigationDelegate(); } // Records the last created instance of itself. class CapturingUIDelegate extends WKUIDelegate { CapturingUIDelegate({ super.onCreateWebView, super.requestMediaCapturePermission, super.runJavaScriptAlertDialog, super.runJavaScriptConfirmDialog, super.runJavaScriptTextInputDialog, super.instanceManager, }) : super.detached() { lastCreatedDelegate = this; } static CapturingUIDelegate lastCreatedDelegate = CapturingUIDelegate(); }
packages/packages/webview_flutter/webview_flutter_wkwebview/test/webkit_navigation_delegate_test.dart/0
{'file_path': 'packages/packages/webview_flutter/webview_flutter_wkwebview/test/webkit_navigation_delegate_test.dart', 'repo_id': 'packages', 'token_count': 4077}
# The list of external dependencies that are allowed as pinned dependencies. # See https://github.com/flutter/flutter/wiki/Contributing-to-Plugins-and-Packages#Dependencies # # All entries here should have an explanation for why they are here. # TODO(stuartmorgan): Eliminate this in favor of standardizing on # mockito. See https://github.com/flutter/flutter/issues/130757 - mocktail # Test-only dependency, so does not impact package clients, and # has limited impact so could be easily removed if there are # ever maintenance issues in the future. - lcov_parser # This should be removed; see # https://github.com/flutter/flutter/issues/130897 - provider ## Allowed by default # Dart-owned - dart_style - mockito # Google-owned - file_testing
packages/script/configs/allowed_pinned_deps.yaml/0
{'file_path': 'packages/script/configs/allowed_pinned_deps.yaml', 'repo_id': 'packages', 'token_count': 219}
# Packages that are excluded from dart unit test on Windows. # Exclude flutter_image because its tests need a test server, so are run via custom_package_tests. - flutter_image # This test is very slow, so isn't worth running a second time # on Windows; the Linux run is enough coverage. - flutter_migrate # TODO(stuartmorgan): Fix these tests to run correctly on a # Windows host and enable them. - path_provider_linux - webview_flutter_android # Unit tests for plugins that support web currently run in # Chrome, which isn't currently supported by web infrastructure. # TODO(ditman): Fix this in the repo tooling. - camera_web - file_selector_web - google_maps_flutter_web - google_sign_in_web - image_picker_for_web - shared_preferences_web - url_launcher_web - video_player_web - webview_flutter_web
packages/script/configs/windows_unit_tests_exceptions.yaml/0
{'file_path': 'packages/script/configs/windows_unit_tests_exceptions.yaml', 'repo_id': 'packages', 'token_count': 240}
// 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:pub_semver/pub_semver.dart'; import 'package:yaml_edit/yaml_edit.dart'; import 'common/core.dart'; import 'common/output_utils.dart'; import 'common/package_looping_command.dart'; import 'common/repository_package.dart'; const int _exitUnknownVersion = 3; /// A command to update the minimum Flutter and Dart SDKs of packages. class UpdateMinSdkCommand extends PackageLoopingCommand { /// Creates a publish metadata updater command instance. UpdateMinSdkCommand(super.packagesDir) { argParser.addOption(_flutterMinFlag, mandatory: true, help: 'The minimum version of Flutter to set SDK constraints to.'); } static const String _flutterMinFlag = 'flutter-min'; late final Version _flutterMinVersion; late final Version _dartMinVersion; @override final String name = 'update-min-sdk'; @override final String description = 'Updates the Flutter and Dart SDK minimums ' 'in pubspec.yaml to match the given Flutter version.'; @override final PackageLoopingType packageLoopingType = PackageLoopingType.includeAllSubpackages; @override bool get hasLongOutput => false; @override Future<void> initializeRun() async { _flutterMinVersion = Version.parse(getStringArg(_flutterMinFlag)); final Version? dartMinVersion = getDartSdkForFlutterSdk(_flutterMinVersion); if (dartMinVersion == null) { printError('Dart SDK version for Fluter SDK version ' '$_flutterMinVersion is unknown. ' 'Please update the map for getDartSdkForFlutterSdk with the ' 'corresponding Dart version.'); throw ToolExit(_exitUnknownVersion); } _dartMinVersion = dartMinVersion; } @override Future<PackageResult> runForPackage(RepositoryPackage package) async { final Pubspec pubspec = package.parsePubspec(); const String environmentKey = 'environment'; const String dartSdkKey = 'sdk'; const String flutterSdkKey = 'flutter'; final VersionRange? dartRange = _sdkRange(pubspec, dartSdkKey); final VersionRange? flutterRange = _sdkRange(pubspec, flutterSdkKey); final YamlEditor editablePubspec = YamlEditor(package.pubspecFile.readAsStringSync()); if (dartRange != null && (dartRange.min ?? Version.none) < _dartMinVersion) { editablePubspec .update(<String>[environmentKey, dartSdkKey], '^$_dartMinVersion'); print('${indentation}Updating Dart minimum to $_dartMinVersion'); } if (flutterRange != null && (flutterRange.min ?? Version.none) < _flutterMinVersion) { editablePubspec.update(<String>[environmentKey, flutterSdkKey], VersionRange(min: _flutterMinVersion, includeMin: true).toString()); print('${indentation}Updating Flutter minimum to $_flutterMinVersion'); } package.pubspecFile.writeAsStringSync(editablePubspec.toString()); return PackageResult.success(); } /// Returns the given "environment" section's [key] constraint as a range, /// if the key is present and has a range. VersionRange? _sdkRange(Pubspec pubspec, String key) { final VersionConstraint? constraint = pubspec.environment?[key]; if (constraint is VersionRange) { return constraint; } return null; } }
packages/script/tool/lib/src/update_min_sdk_command.dart/0
{'file_path': 'packages/script/tool/lib/src/update_min_sdk_command.dart', 'repo_id': 'packages', 'token_count': 1156}
// 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/file.dart'; import 'package:file/memory.dart'; import 'package:flutter_plugin_tools/src/common/pub_utils.dart'; import 'package:test/test.dart'; import '../mocks.dart'; import '../util.dart'; void main() { late FileSystem fileSystem; late Directory packagesDir; late RecordingProcessRunner processRunner; setUp(() { fileSystem = MemoryFileSystem(); packagesDir = createPackagesDirectory(fileSystem: fileSystem); processRunner = RecordingProcessRunner(); }); test('runs with Dart for a non-Flutter package by default', () async { final RepositoryPackage package = createFakePackage('a_package', packagesDir); final MockPlatform platform = MockPlatform(); await runPubGet(package, processRunner, platform); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall('dart', const <String>['pub', 'get'], package.path), ])); }); test('runs with Flutter for a Flutter package by default', () async { final RepositoryPackage package = createFakePackage('a_package', packagesDir, isFlutter: true); final MockPlatform platform = MockPlatform(); await runPubGet(package, processRunner, platform); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall('flutter', const <String>['pub', 'get'], package.path), ])); }); test('runs with Flutter for a Dart package when requested', () async { final RepositoryPackage package = createFakePackage('a_package', packagesDir); final MockPlatform platform = MockPlatform(); await runPubGet(package, processRunner, platform, alwaysUseFlutter: true); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall('flutter', const <String>['pub', 'get'], package.path), ])); }); test('uses the correct Flutter command on Windows', () async { final RepositoryPackage package = createFakePackage('a_package', packagesDir, isFlutter: true); final MockPlatform platform = MockPlatform(isWindows: true); await runPubGet(package, processRunner, platform); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( 'flutter.bat', const <String>['pub', 'get'], package.path), ])); }); test('reports success', () async { final RepositoryPackage package = createFakePackage('a_package', packagesDir); final MockPlatform platform = MockPlatform(); final bool result = await runPubGet(package, processRunner, platform); expect(result, true); }); test('reports failure', () async { final RepositoryPackage package = createFakePackage('a_package', packagesDir); final MockPlatform platform = MockPlatform(); processRunner.mockProcessesForExecutable['dart'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(exitCode: 1), <String>['pub', 'get']) ]; final bool result = await runPubGet(package, processRunner, platform); expect(result, false); }); }
packages/script/tool/test/common/pub_utils_test.dart/0
{'file_path': 'packages/script/tool/test/common/pub_utils_test.dart', 'repo_id': 'packages', 'token_count': 1095}
// 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: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/common/plugin_utils.dart'; import 'package:flutter_plugin_tools/src/lint_android_command.dart'; import 'package:test/test.dart'; import 'mocks.dart'; import 'util.dart'; void main() { group('LintAndroidCommand', () { FileSystem fileSystem; late Directory packagesDir; late CommandRunner<void> runner; late MockPlatform mockPlatform; late RecordingProcessRunner processRunner; setUp(() { fileSystem = MemoryFileSystem(); packagesDir = createPackagesDirectory(fileSystem: fileSystem); mockPlatform = MockPlatform(); processRunner = RecordingProcessRunner(); final LintAndroidCommand command = LintAndroidCommand( packagesDir, processRunner: processRunner, platform: mockPlatform, ); runner = CommandRunner<void>( 'lint_android_test', 'Test for $LintAndroidCommand'); runner.addCommand(command); }); test('runs gradle lint', () async { final RepositoryPackage plugin = createFakePlugin('plugin1', packagesDir, extraFiles: <String>[ 'example/android/gradlew', ], platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.inline) }); final Directory androidDir = plugin.getExamples().first.platformDirectory(FlutterPlatform.android); final List<String> output = await runCapturingPrint(runner, <String>['lint-android']); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( androidDir.childFile('gradlew').path, const <String>['plugin1:lintDebug'], androidDir.path, ), ]), ); expect( output, containsAllInOrder(<Matcher>[ contains('Running for plugin1'), contains('No issues found!'), ])); }); test('runs on all examples', () async { final List<String> examples = <String>['example1', 'example2']; final RepositoryPackage plugin = createFakePlugin('plugin1', packagesDir, examples: examples, extraFiles: <String>[ 'example/example1/android/gradlew', 'example/example2/android/gradlew', ], platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.inline) }); final Iterable<Directory> exampleAndroidDirs = plugin.getExamples().map( (RepositoryPackage example) => example.platformDirectory(FlutterPlatform.android)); final List<String> output = await runCapturingPrint(runner, <String>['lint-android']); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ for (final Directory directory in exampleAndroidDirs) ProcessCall( directory.childFile('gradlew').path, const <String>['plugin1:lintDebug'], directory.path, ), ]), ); expect( output, containsAllInOrder(<Matcher>[ contains('Running for plugin1'), contains('No issues found!'), ])); }); test('runs --config-only build if gradlew is missing', () async { final RepositoryPackage plugin = createFakePlugin('plugin1', packagesDir, platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.inline) }); final Directory androidDir = plugin.getExamples().first.platformDirectory(FlutterPlatform.android); final List<String> output = await runCapturingPrint(runner, <String>['lint-android']); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( getFlutterCommand(mockPlatform), const <String>['build', 'apk', '--config-only'], plugin.getExamples().first.directory.path, ), ProcessCall( androidDir.childFile('gradlew').path, const <String>['plugin1:lintDebug'], androidDir.path, ), ]), ); expect( output, containsAllInOrder(<Matcher>[ contains('Running for plugin1'), contains('No issues found!'), ])); }); test('fails if gradlew generation fails', () async { createFakePlugin('plugin1', packagesDir, platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.inline) }); processRunner .mockProcessesForExecutable[getFlutterCommand(mockPlatform)] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(exitCode: 1)), ]; Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['lint-android'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder( <Matcher>[ contains('Unable to configure Gradle project'), ], )); }); test('fails if linting finds issues', () async { final RepositoryPackage plugin = createFakePlugin('plugin1', packagesDir, extraFiles: <String>[ 'example/android/gradlew', ], platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.inline) }); 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>['lint-android'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder( <Matcher>[ contains('The following packages had errors:'), ], )); }); test('skips non-Android plugins', () async { createFakePlugin('plugin1', packagesDir); final List<String> output = await runCapturingPrint(runner, <String>['lint-android']); expect( output, containsAllInOrder( <Matcher>[ contains( 'SKIPPING: Plugin does not have an Android implementation.') ], )); }); test('skips non-inline plugins', () async { createFakePlugin('plugin1', packagesDir, platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.federated) }); final List<String> output = await runCapturingPrint(runner, <String>['lint-android']); expect( output, containsAllInOrder( <Matcher>[ contains( 'SKIPPING: Plugin does not have an Android implementation.') ], )); }); }); }
packages/script/tool/test/lint_android_command_test.dart/0
{'file_path': 'packages/script/tool/test/lint_android_command_test.dart', 'repo_id': 'packages', 'token_count': 3266}
// 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: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/common/file_utils.dart'; import 'package:flutter_plugin_tools/src/common/plugin_utils.dart'; import 'package:flutter_plugin_tools/src/common/process_runner.dart'; import 'package:flutter_plugin_tools/src/common/repository_package.dart'; import 'package:meta/meta.dart'; import 'package:path/path.dart' as p; import 'package:platform/platform.dart'; import 'package:quiver/collection.dart'; import 'mocks.dart'; export 'package:flutter_plugin_tools/src/common/repository_package.dart'; const String _defaultDartConstraint = '>=2.14.0 <4.0.0'; const String _defaultFlutterConstraint = '>=2.5.0'; /// Returns the exe name that command will use when running Flutter on /// [platform]. String getFlutterCommand(Platform platform) => platform.isWindows ? 'flutter.bat' : 'flutter'; /// Creates a packages directory in the given location. /// /// If [parentDir] is set the packages directory will be created there, /// otherwise [fileSystem] must be provided and it will be created an arbitrary /// location in that filesystem. Directory createPackagesDirectory( {Directory? parentDir, FileSystem? fileSystem}) { assert(parentDir != null || fileSystem != null, 'One of parentDir or fileSystem must be provided'); assert(fileSystem == null || fileSystem is MemoryFileSystem, 'If using a real filesystem, parentDir must be provided'); final Directory packagesDir = (parentDir ?? fileSystem!.currentDirectory).childDirectory('packages'); packagesDir.createSync(); return packagesDir; } /// Details for platform support in a plugin. @immutable class PlatformDetails { const PlatformDetails( this.type, { this.hasNativeCode = true, this.hasDartCode = false, }); /// The type of support for the platform. final PlatformSupport type; /// Whether or not the plugin includes native code. /// /// Ignored for web, which does not have native code. final bool hasNativeCode; /// Whether or not the plugin includes Dart code. /// /// Ignored for web, which always has native code. final bool hasDartCode; } /// Returns the 'example' directory for [package]. /// /// This is deliberately not a method on [RepositoryPackage] since actual tool /// code should essentially never need this, and instead be using /// [RepositoryPackage.getExamples] to avoid assuming there's a single example /// directory. However, needing to construct paths with the example directory /// is very common in test code. /// /// This returns a Directory rather than a RepositoryPackage because there is no /// guarantee that the returned directory is a package. Directory getExampleDir(RepositoryPackage package) { return package.directory.childDirectory('example'); } /// Creates a plugin package with the given [name] in [packagesDirectory]. /// /// [platformSupport] is a map of platform string to the support details for /// that platform. /// /// [extraFiles] is an optional list of plugin-relative paths, using Posix /// separators, of extra files to create in the plugin. RepositoryPackage createFakePlugin( String name, Directory parentDirectory, { List<String> examples = const <String>['example'], List<String> extraFiles = const <String>[], Map<String, PlatformDetails> platformSupport = const <String, PlatformDetails>{}, String? version = '0.0.1', String flutterConstraint = _defaultFlutterConstraint, String dartConstraint = _defaultDartConstraint, }) { final RepositoryPackage package = createFakePackage( name, parentDirectory, isFlutter: true, examples: examples, extraFiles: extraFiles, version: version, flutterConstraint: flutterConstraint, dartConstraint: dartConstraint, ); createFakePubspec( package, name: name, isPlugin: true, platformSupport: platformSupport, version: version, flutterConstraint: flutterConstraint, dartConstraint: dartConstraint, ); return package; } /// Creates a plugin package with the given [name] in [packagesDirectory]. /// /// [extraFiles] is an optional list of package-relative paths, using unix-style /// separators, of extra files to create in the package. /// /// If [includeCommonFiles] is true, common but non-critical files like /// CHANGELOG.md, README.md, and AUTHORS will be included. /// /// If non-null, [directoryName] will be used for the directory instead of /// [name]. RepositoryPackage createFakePackage( String name, Directory parentDirectory, { List<String> examples = const <String>['example'], List<String> extraFiles = const <String>[], bool isFlutter = false, String? version = '0.0.1', String flutterConstraint = _defaultFlutterConstraint, String dartConstraint = _defaultDartConstraint, bool includeCommonFiles = true, String? directoryName, String? publishTo, }) { final RepositoryPackage package = RepositoryPackage(parentDirectory.childDirectory(directoryName ?? name)); package.directory.createSync(recursive: true); package.libDirectory.createSync(); createFakePubspec(package, name: name, isFlutter: isFlutter, version: version, flutterConstraint: flutterConstraint, dartConstraint: dartConstraint, publishTo: publishTo); if (includeCommonFiles) { package.changelogFile.writeAsStringSync(''' ## $version * Some changes. '''); package.readmeFile.writeAsStringSync('A very useful package'); package.authorsFile.writeAsStringSync('Google Inc.'); } if (examples.length == 1) { createFakePackage('${name}_example', package.directory, directoryName: examples.first, examples: <String>[], includeCommonFiles: false, isFlutter: isFlutter, publishTo: 'none', flutterConstraint: flutterConstraint, dartConstraint: dartConstraint); } else if (examples.isNotEmpty) { final Directory examplesDirectory = getExampleDir(package)..createSync(); for (final String exampleName in examples) { createFakePackage(exampleName, examplesDirectory, examples: <String>[], includeCommonFiles: false, isFlutter: isFlutter, publishTo: 'none', flutterConstraint: flutterConstraint, dartConstraint: dartConstraint); } } final p.Context posixContext = p.posix; for (final String file in extraFiles) { childFileWithSubcomponents(package.directory, posixContext.split(file)) .createSync(recursive: true); } return package; } /// Creates a `pubspec.yaml` file for [package]. /// /// [platformSupport] is a map of platform string to the support details for /// that platform. If empty, no `plugin` entry will be created unless `isPlugin` /// is set to `true`. void createFakePubspec( RepositoryPackage package, { String name = 'fake_package', bool isFlutter = true, bool isPlugin = false, Map<String, PlatformDetails> platformSupport = const <String, PlatformDetails>{}, String? publishTo, String? version, String dartConstraint = _defaultDartConstraint, String flutterConstraint = _defaultFlutterConstraint, }) { isPlugin |= platformSupport.isNotEmpty; String environmentSection = ''' environment: sdk: "$dartConstraint" '''; String dependenciesSection = ''' dependencies: '''; String pluginSection = ''; // Add Flutter-specific entries if requested. if (isFlutter) { environmentSection += ''' flutter: "$flutterConstraint" '''; dependenciesSection += ''' flutter: sdk: flutter '''; if (isPlugin) { pluginSection += ''' flutter: plugin: platforms: '''; for (final MapEntry<String, PlatformDetails> platform in platformSupport.entries) { pluginSection += _pluginPlatformSection(platform.key, platform.value, name); } } } // Default to a fake server to avoid ever accidentally publishing something // from a test. Does not use 'none' since that changes the behavior of some // commands. final String publishToSection = 'publish_to: ${publishTo ?? 'http://no_pub_server.com'}'; final String yaml = ''' name: $name ${(version != null) ? 'version: $version' : ''} $publishToSection $environmentSection $dependenciesSection $pluginSection '''; package.pubspecFile.createSync(); package.pubspecFile.writeAsStringSync(yaml); } String _pluginPlatformSection( String platform, PlatformDetails support, String packageName) { String entry = ''; // Build the main plugin entry. if (support.type == PlatformSupport.federated) { entry = ''' $platform: default_package: ${packageName}_$platform '''; } else { final List<String> lines = <String>[ ' $platform:', ]; switch (platform) { case platformAndroid: lines.add(' package: io.flutter.plugins.fake'); continue nativeByDefault; nativeByDefault: case platformIOS: case platformLinux: case platformMacOS: case platformWindows: if (support.hasNativeCode) { final String className = platform == platformIOS ? 'FLTFakePlugin' : 'FakePlugin'; lines.add(' pluginClass: $className'); } if (support.hasDartCode) { lines.add(' dartPluginClass: FakeDartPlugin'); } break; case platformWeb: lines.addAll(<String>[ ' pluginClass: FakePlugin', ' fileName: ${packageName}_web.dart', ]); break; default: assert(false, 'Unrecognized platform: $platform'); break; } entry = '${lines.join('\n')}\n'; } return entry; } /// Run the command [runner] with the given [args] and return /// what was printed. /// A custom [errorHandler] can be used to handle the runner error as desired without throwing. Future<List<String>> runCapturingPrint( CommandRunner<void> runner, List<String> args, { void Function(Error error)? errorHandler, void Function(Exception error)? exceptionHandler, }) async { final List<String> prints = <String>[]; final ZoneSpecification spec = ZoneSpecification( print: (_, __, ___, String message) { prints.add(message); }, ); try { await Zone.current .fork(specification: spec) .run<Future<void>>(() => runner.run(args)); } on Error catch (e) { if (errorHandler == null) { rethrow; } errorHandler(e); } on Exception catch (e) { if (exceptionHandler == null) { rethrow; } exceptionHandler(e); } return prints; } /// Information about a process to return from [RecordingProcessRunner]. class FakeProcessInfo { const FakeProcessInfo(this.process, [this.expectedInitialArgs = const <String>[]]); /// The process to return. final io.Process process; /// The expected start of the argument array for the call. /// /// This does not have to be a full list of arguments, only enough of the /// start to ensure that the call is as expected. final List<String> expectedInitialArgs; } /// A mock [ProcessRunner] which records process calls. class RecordingProcessRunner extends ProcessRunner { final List<ProcessCall> recordedCalls = <ProcessCall>[]; /// Maps an executable to a list of processes that should be used for each /// successive call to it via [run], [runAndStream], or [start]. /// /// If `expectedInitialArgs` are provided for a fake process, trying to /// return that process when the arguments don't match will throw a /// [StateError]. This allows tests to enforce that the fake results are /// for the expected calls when the process name itself isn't enough to tell /// (e.g., multiple different `dart` or `flutter` calls), without going all /// the way to a complex argument matching scheme that can make tests /// difficult to write and debug. final Map<String, List<FakeProcessInfo>> mockProcessesForExecutable = <String, List<FakeProcessInfo>>{}; @override Future<int> runAndStream( String executable, List<String> args, { Directory? workingDir, Map<String, String>? environment, bool exitOnError = false, }) async { recordedCalls.add(ProcessCall(executable, args, workingDir?.path)); final io.Process? processToReturn = _getProcessToReturn(executable, args); final int exitCode = processToReturn == null ? 0 : await processToReturn.exitCode; if (exitOnError && (exitCode != 0)) { throw io.ProcessException(executable, args); } return Future<int>.value(exitCode); } /// Returns [io.ProcessResult] created from [mockProcessesForExecutable]. @override Future<io.ProcessResult> run( String executable, List<String> args, { Directory? workingDir, Map<String, String>? environment, bool exitOnError = false, bool logOnError = false, Encoding stdoutEncoding = io.systemEncoding, Encoding stderrEncoding = io.systemEncoding, }) async { recordedCalls.add(ProcessCall(executable, args, workingDir?.path)); final io.Process? process = _getProcessToReturn(executable, args); final List<String>? processStdout = await process?.stdout.transform(stdoutEncoding.decoder).toList(); final String stdout = processStdout?.join() ?? ''; final List<String>? processStderr = await process?.stderr.transform(stderrEncoding.decoder).toList(); final String stderr = processStderr?.join() ?? ''; final io.ProcessResult result = process == null ? io.ProcessResult(1, 0, '', '') : io.ProcessResult(process.pid, await process.exitCode, stdout, stderr); if (exitOnError && (result.exitCode != 0)) { throw io.ProcessException(executable, args); } return Future<io.ProcessResult>.value(result); } @override Future<io.Process> start(String executable, List<String> args, {Directory? workingDirectory}) async { recordedCalls.add(ProcessCall(executable, args, workingDirectory?.path)); return Future<io.Process>.value( _getProcessToReturn(executable, args) ?? MockProcess()); } io.Process? _getProcessToReturn(String executable, List<String> args) { final List<FakeProcessInfo> fakes = mockProcessesForExecutable[executable] ?? <FakeProcessInfo>[]; if (fakes.isNotEmpty) { final FakeProcessInfo fake = fakes.removeAt(0); if (args.length < fake.expectedInitialArgs.length || !listsEqual(args.sublist(0, fake.expectedInitialArgs.length), fake.expectedInitialArgs)) { throw StateError('Next fake process for $executable expects arguments ' '[${fake.expectedInitialArgs.join(', ')}] but was called with ' 'arguments [${args.join(', ')}]'); } return fake.process; } return null; } } /// A recorded process call. @immutable class ProcessCall { const ProcessCall(this.executable, this.args, this.workingDir); /// The executable that was called. final String executable; /// The arguments passed to [executable] in the call. final List<String> args; /// The working directory this process was called from. final String? workingDir; @override bool operator ==(Object other) { return other is ProcessCall && executable == other.executable && listsEqual(args, other.args) && workingDir == other.workingDir; } @override int get hashCode => Object.hash(executable, args, workingDir); @override String toString() { final List<String> command = <String>[executable, ...args]; return '"${command.join(' ')}" in $workingDir'; } }
packages/script/tool/test/util.dart/0
{'file_path': 'packages/script/tool/test/util.dart', 'repo_id': 'packages', 'token_count': 5322}
// Copyright (c) 2021, the Dart project authors. Please see the AUTHORS file // for details. 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:json_annotation/json_annotation.dart'; part 'batch_model.g.dart'; @JsonSerializable() class BatchConfig { /// The path of the Dart SDK final String? dartSdk; /// The path of the Flutter SDK final String? flutterSdk; /// The environment variables that need to be set. final Map<String, String>? environment; /// The URI of the analysis options (https:// or local file). final String? analysisOptions; BatchConfig({ this.dartSdk, this.flutterSdk, this.environment, this.analysisOptions, }); factory BatchConfig.fromJson(Map<String, dynamic> json) => _$BatchConfigFromJson(json); Map<String, dynamic> toJson() => _$BatchConfigToJson(this); } @JsonSerializable() class BatchResult { final int unchangedCount; final BatchChanged increased; final BatchChanged decreased; BatchResult({ required this.unchangedCount, required this.increased, required this.decreased, }); factory BatchResult.fromJson(Map<String, dynamic> json) => _$BatchResultFromJson(json); Map<String, dynamic> toJson() => _$BatchResultToJson(this); } @JsonSerializable() class BatchChanged { final int count; final Map<String, int> packages; BatchChanged({ required this.count, required this.packages, }); factory BatchChanged.fromJson(Map<String, dynamic> json) => _$BatchChangedFromJson(json); Map<String, dynamic> toJson() => _$BatchChangedToJson(this); }
pana/lib/src/batch/batch_model.dart/0
{'file_path': 'pana/lib/src/batch/batch_model.dart', 'repo_id': 'pana', 'token_count': 560}
// Diff Match and Patch // Copyright 2018 The diff-match-patch Authors. // https://github.com/google/diff-match-patch // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:collection'; import 'dart:math'; import 'package:meta/meta.dart'; part 'utils.dart'; enum Operation { delete, insert, equal } /// Class representing one diff operation. class Diff { /// One of: Operation.insert, Operation.delete or Operation.equal. Operation operation; /// The text associated with this diff operation. String text; /// Constructor. Initializes the diff with the provided values. /// /// [operation] is one of Operation.insert, Operation.delete or Operation.equal. /// [text] is the text being applied. Diff(this.operation, this.text); /// Display a human-readable version of this Diff. /// Returns a text version. @override String toString() { var prettyText = text.replaceAll('\n', '\u00b6'); return 'Diff($operation,"$prettyText")'; } /// Is this Diff equivalent to another Diff? /// [other] is another Diff to compare against. /// Returns true or false. @override bool operator ==(Object other) => identical(this, other) || other is Diff && runtimeType == other.runtimeType && operation == other.operation && text == other.text; /// Generate a uniquely identifiable hashcode for this Diff. /// Returns numeric hashcode. @override int get hashCode => operation.hashCode ^ text.hashCode; } double diffTimeout = 1.0; /// Find the differences between two texts. /// /// Simplifies the problem by stripping any common prefix or suffix /// off the texts before diffing. /// [text1] is the old string to be diffed. /// [text2] is the new string to be diffed. /// [checklines] is an optional speedup flag. If present and false, then don't /// run a line-level diff first to identify the changed areas. /// Defaults to true, which does a faster, slightly less optimal diff. /// [deadline] is an optional time when the diff should be complete by. Used /// internally for recursive calls. Users should set DiffTimeout instead. /// Returns a List of Diff objects. List<Diff> diffMain( String text1, String text2, { bool checklines = true, DateTime? deadline, }) { // Set a deadline by which time the diff must be complete. if (deadline == null) { deadline = DateTime.now(); if (diffTimeout <= 0) { // One year should be sufficient for 'infinity'. deadline = deadline.add(const Duration(days: 365)); } else { deadline = deadline.add(Duration(milliseconds: (diffTimeout * 1000).toInt())); } } // Check for equality (speedup). var diffs = <Diff>[]; if (text1 == text2) { if (text1.isNotEmpty) { diffs.add(Diff(Operation.equal, text1)); } return diffs; } // Trim off common prefix (speedup). var commonlength = diffCommonPrefix(text1, text2); var commonprefix = text1.substring(0, commonlength); text1 = text1.substring(commonlength); text2 = text2.substring(commonlength); // Trim off common suffix (speedup). commonlength = diffCommonSuffix(text1, text2); var commonsuffix = text1.substring(text1.length - commonlength); text1 = text1.substring(0, text1.length - commonlength); text2 = text2.substring(0, text2.length - commonlength); // Compute the diff on the middle block. diffs = diffCompute(text1, text2, checklines, deadline); // Restore the prefix and suffix. if (commonprefix.isNotEmpty) { diffs.insert(0, Diff(Operation.equal, commonprefix)); } if (commonsuffix.isNotEmpty) { diffs.add(Diff(Operation.equal, commonsuffix)); } diffCleanupMerge(diffs); return diffs; } /// Find the differences between two texts. /// /// Assumes that the texts do not have any common prefix or suffix. /// [text1] is the old string to be diffed. /// [text2] is the new string to be diffed. /// [checklines] is a speedup flag. If false, then don't run a /// line-level diff first to identify the changed areas. /// If true, then run a faster slightly less optimal diff. /// [deadline] is the time when the diff should be complete by. /// Returns a List of Diff objects. @visibleForTesting List<Diff> diffCompute( String text1, String text2, bool checklines, DateTime deadline, ) { var diffs = <Diff>[]; if (text1.isEmpty) { // Just add some text (speedup). diffs.add(Diff(Operation.insert, text2)); return diffs; } if (text2.isEmpty) { // Just delete some text (speedup). diffs.add(Diff(Operation.delete, text1)); return diffs; } final longText = text1.length > text2.length ? text1 : text2; final shortText = text1.length > text2.length ? text2 : text1; final i = longText.indexOf(shortText); if (i != -1) { // Shorter text is inside the longer text (speedup). final op = (text1.length > text2.length) ? Operation.delete : Operation.insert; diffs.add(Diff(op, longText.substring(0, i))); diffs.add(Diff(Operation.equal, shortText)); diffs.add(Diff(op, longText.substring(i + shortText.length))); return diffs; } if (shortText.length == 1) { // Single character string. // After the previous speedup, the character can't be an equality. diffs.add(Diff(Operation.delete, text1)); diffs.add(Diff(Operation.insert, text2)); return diffs; } // Check to see if the problem can be split in two. final hm = diffHalfMatch(text1, text2); if (hm != null) { // A half-match was found, sort out the return data. final text1A = hm[0]; final textB = hm[1]; final text2A = hm[2]; final text2B = hm[3]; final midCommon = hm[4]; // Send both pairs off for separate processing. final diffsA = diffMain( text1A, text2A, checklines: checklines, deadline: deadline, ); final diffsB = diffMain( textB, text2B, checklines: checklines, deadline: deadline, ); // Merge the results. diffs = diffsA; diffs.add(Diff(Operation.equal, midCommon)); diffs.addAll(diffsB); return diffs; } if (checklines && text1.length > 100 && text2.length > 100) { return _diffLineMode(text1, text2, deadline); } return diffBisect(text1, text2, deadline); } /// Reorder and merge like edit sections. Merge equalities. /// /// Any edit section can move as long as it doesn't cross an equality. /// [diffs] is a List of Diff objects. @visibleForTesting void diffCleanupMerge(List<Diff> diffs) { diffs.add(Diff(Operation.equal, '')); // Add a dummy entry at the end. var pointer = 0; var countDelete = 0; var countInsert = 0; var textDelete = ''; var textInsert = ''; int commonlength; while (pointer < diffs.length) { switch (diffs[pointer].operation) { case Operation.insert: countInsert++; textInsert += diffs[pointer].text; pointer++; break; case Operation.delete: countDelete++; textDelete += diffs[pointer].text; pointer++; break; case Operation.equal: // Upon reaching an equality, check for prior redundancies. if (countDelete + countInsert > 1) { if (countDelete != 0 && countInsert != 0) { // Factor out any common prefixes. commonlength = diffCommonPrefix(textInsert, textDelete); if (commonlength != 0) { if ((pointer - countDelete - countInsert) > 0 && diffs[pointer - countDelete - countInsert - 1].operation == Operation.equal) { final i = pointer - countDelete - countInsert - 1; diffs[i].text = diffs[i].text + textInsert.substring(0, commonlength); } else { diffs.insert( 0, Diff(Operation.equal, textInsert.substring(0, commonlength))); pointer++; } textInsert = textInsert.substring(commonlength); textDelete = textDelete.substring(commonlength); } // Factor out any common suffixes. commonlength = diffCommonSuffix(textInsert, textDelete); if (commonlength != 0) { diffs[pointer].text = textInsert.substring(textInsert.length - commonlength) + diffs[pointer].text; textInsert = textInsert.substring(0, textInsert.length - commonlength); textDelete = textDelete.substring(0, textDelete.length - commonlength); } } // Delete the offending records and add the merged ones. pointer -= countDelete + countInsert; diffs.removeRange(pointer, pointer + countDelete + countInsert); if (textDelete.isNotEmpty) { diffs.insert(pointer, Diff(Operation.delete, textDelete)); pointer++; } if (textInsert.isNotEmpty) { diffs.insert(pointer, Diff(Operation.insert, textInsert)); pointer++; } pointer++; } else if (pointer != 0 && diffs[pointer - 1].operation == Operation.equal) { // Merge this equality with the previous one. diffs[pointer - 1].text = diffs[pointer - 1].text + diffs[pointer].text; diffs.removeAt(pointer); } else { pointer++; } countInsert = 0; countDelete = 0; textDelete = ''; textInsert = ''; break; } } if (diffs.last.text.isEmpty) { diffs.removeLast(); // Remove the dummy entry at the end. } // Second pass: look for single edits surrounded on both sides by equalities // which can be shifted sideways to eliminate an equality. // e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC var changes = false; pointer = 1; // Intentionally ignore the first and last element (don't need checking). while (pointer < diffs.length - 1) { if (diffs[pointer - 1].operation == Operation.equal && diffs[pointer + 1].operation == Operation.equal) { // This is a single edit surrounded by equalities. if (diffs[pointer].text.endsWith(diffs[pointer - 1].text)) { // Shift the edit over the previous equality. diffs[pointer].text = diffs[pointer - 1].text + diffs[pointer].text.substring( 0, diffs[pointer].text.length - diffs[pointer - 1].text.length, ); diffs[pointer + 1].text = diffs[pointer - 1].text + diffs[pointer + 1].text; diffs.removeAt(pointer - 1); changes = true; } else if (diffs[pointer].text.startsWith(diffs[pointer + 1].text)) { // Shift the edit over the next equality. diffs[pointer - 1].text = diffs[pointer - 1].text + diffs[pointer + 1].text; diffs[pointer].text = diffs[pointer].text.substring(diffs[pointer + 1].text.length) + diffs[pointer + 1].text; diffs.removeAt(pointer + 1); changes = true; } } pointer++; } // If shifts were made, the diff needs reordering and another shift sweep. if (changes) { diffCleanupMerge(diffs); } } /// Do the two texts share a substring which is at least half the length of the longer text? /// /// This speedup can produce non-minimal diffs. /// [text1] is the first string. /// [text2] is the second string. /// Returns a five element List of Strings, containing the prefix of text1, /// the suffix of text1, the prefix of text2, the suffix of text2 and the /// common middle. Or null if there was no match. @visibleForTesting List<String>? diffHalfMatch(String text1, String text2) { if (diffTimeout <= 0) { // Don't risk returning a non-optimal diff if we have unlimited time. return null; } final longtext = text1.length > text2.length ? text1 : text2; final shorttext = text1.length > text2.length ? text2 : text1; if (longtext.length < 4 || shorttext.length * 2 < longtext.length) { return null; // Pointless. } // First check if the second quarter is the seed for a half-match. final hm1 = _diffHalfMatchI( longtext, shorttext, ((longtext.length + 3) / 4).ceil().toInt(), ); // Check again based on the third quarter. final hm2 = _diffHalfMatchI( longtext, shorttext, ((longtext.length + 1) / 2).ceil().toInt(), ); List<String>? hm; if (hm1 == null && hm2 == null) { return null; } else if (hm2 == null) { hm = hm1; } else if (hm1 == null) { hm = hm2; } else { // Both matched. Select the longest. hm = hm1[4].length > hm2[4].length ? hm1 : hm2; } // A half-match was found, sort out the return data. if (text1.length > text2.length) { return hm; //return [hm[0], hm[1], hm[2], hm[3], hm[4]]; } else { return [hm![2], hm[3], hm[0], hm[1], hm[4]]; } } /// Do a quick line-level diff on both strings, then rediff the parts for greater accuracy. /// /// This speedup can produce non-minimal diffs. /// [text1] is the old string to be diffed. /// [text2] is the new string to be diffed. /// [deadline] is the time when the diff should be complete by. /// Returns a List of Diff objects. List<Diff> _diffLineMode(String text1, String text2, DateTime deadline) { // Scan the text on a line-by-line basis first. final a = diffLinesToChars(text1, text2); final linearray = a['lineArray'] as List<String>; text1 = a['chars1'] as String; text2 = a['chars2'] as String; final diffs = diffMain( text1, text2, checklines: false, deadline: deadline, ); // Convert the diff back to original text. diffCharsToLines(diffs, linearray); // Eliminate freak matches (e.g. blank lines) diffCleanupSemantic(diffs); // Rediff any replacement blocks, this time character-by-character. // Add a dummy entry at the end. diffs.add(Diff(Operation.equal, '')); var pointer = 0; var countDelete = 0; var countInsert = 0; final textDelete = StringBuffer(); final textInsert = StringBuffer(); while (pointer < diffs.length) { switch (diffs[pointer].operation) { case Operation.insert: countInsert++; textInsert.write(diffs[pointer].text); break; case Operation.delete: countDelete++; textDelete.write(diffs[pointer].text); break; case Operation.equal: // Upon reaching an equality, check for prior redundancies. if (countDelete >= 1 && countInsert >= 1) { // Delete the offending records and add the merged ones. diffs.removeRange(pointer - countDelete - countInsert, pointer); pointer = pointer - countDelete - countInsert; final subDiff = diffMain( textDelete.toString(), textInsert.toString(), checklines: false, deadline: deadline, ); for (var j = subDiff.length - 1; j >= 0; j--) { diffs.insert(pointer, subDiff[j]); } pointer = pointer + subDiff.length; } countInsert = 0; countDelete = 0; textDelete.clear(); textInsert.clear(); break; } pointer++; } diffs.removeLast(); // Remove the dummy entry at the end. return diffs; } /// Find the 'middle snake' of a diff, split the problem in two /// and return the recursively constructed diff. /// /// See [Myers 1986 paper][1]: An O(ND) Difference Algorithm and Its Variations. /// [text1] is the old string to be diffed. /// [text2] is the new string to be diffed. /// [deadline] is the time at which to bail if not yet complete. /// Returns a List of Diff objects. /// /// [1]: https://neil.fraser.name/writing/diff/myers.pdf @visibleForTesting List<Diff> diffBisect(String text1, String text2, DateTime deadline) { // Cache the text lengths to prevent multiple calls. final text1Length = text1.length; final text2Length = text2.length; final maxD = (text1Length + text2Length + 1) ~/ 2; final vOffset = maxD; final vLength = 2 * maxD; final v1 = List<int>.filled(vLength, 0); final v2 = List<int>.filled(vLength, 0); for (var x = 0; x < vLength; x++) { v1[x] = -1; v2[x] = -1; } v1[vOffset + 1] = 0; v2[vOffset + 1] = 0; final delta = text1Length - text2Length; // If the total number of characters is odd, then the front path will // collide with the reverse path. final front = (delta % 2 != 0); // Offsets for start and end of k loop. // Prevents mapping of space beyond the grid. var k1start = 0; var k1end = 0; var k2start = 0; var k2end = 0; for (var d = 0; d < maxD; d++) { // Bail out if deadline is reached. if ((DateTime.now()).compareTo(deadline) == 1) { break; } // Walk the front path one step. for (var k1 = -d + k1start; k1 <= d - k1end; k1 += 2) { var k1Offset = vOffset + k1; int x1; if (k1 == -d || k1 != d && v1[k1Offset - 1] < v1[k1Offset + 1]) { x1 = v1[k1Offset + 1]; } else { x1 = v1[k1Offset - 1] + 1; } var y1 = x1 - k1; while (x1 < text1Length && y1 < text2Length && text1[x1] == text2[y1]) { x1++; y1++; } v1[k1Offset] = x1; if (x1 > text1Length) { // Ran off the right of the graph. k1end += 2; } else if (y1 > text2Length) { // Ran off the bottom of the graph. k1start += 2; } else if (front) { var k2Offset = vOffset + delta - k1; if (k2Offset >= 0 && k2Offset < vLength && v2[k2Offset] != -1) { // Mirror x2 onto top-left coordinate system. var x2 = text1Length - v2[k2Offset]; if (x1 >= x2) { // Overlap detected. return _diffBisectSplit(text1, text2, x1, y1, deadline); } } } } // Walk the reverse path one step. for (var k2 = -d + k2start; k2 <= d - k2end; k2 += 2) { var k2Offset = vOffset + k2; int x2; if (k2 == -d || k2 != d && v2[k2Offset - 1] < v2[k2Offset + 1]) { x2 = v2[k2Offset + 1]; } else { x2 = v2[k2Offset - 1] + 1; } var y2 = x2 - k2; while (x2 < text1Length && y2 < text2Length && text1[text1Length - x2 - 1] == text2[text2Length - y2 - 1]) { x2++; y2++; } v2[k2Offset] = x2; if (x2 > text1Length) { // Ran off the left of the graph. k2end += 2; } else if (y2 > text2Length) { // Ran off the top of the graph. k2start += 2; } else if (!front) { var k1Offset = vOffset + delta - k2; if (k1Offset >= 0 && k1Offset < vLength && v1[k1Offset] != -1) { var x1 = v1[k1Offset]; var y1 = vOffset + x1 - k1Offset; // Mirror x2 onto top-left coordinate system. x2 = text1Length - x2; if (x1 >= x2) { // Overlap detected. return _diffBisectSplit(text1, text2, x1, y1, deadline); } } } } } // Diff took too long and hit the deadline or // number of diffs equals number of characters, no commonality at all. return [Diff(Operation.delete, text1), Diff(Operation.insert, text2)]; } /// Does a substring of shorttext exist within longtext such that the /// substring is at least half the length of longtext? /// /// [longtext] is the longer string. [shorttext] is the shorter string. /// [i] Start index of quarter length substring within longtext. /// Returns a five element String array, containing the prefix of longtext, /// the suffix of longtext, the prefix of shorttext, the suffix of /// shorttext and the common middle. Or null if there was no match. List<String>? _diffHalfMatchI(String longtext, String shorttext, int i) { // Start with a 1/4 length substring at position i as a seed. final seed = longtext.substring(i, i + (longtext.length / 4).floor().toInt()); var j = -1; var bestCommon = ''; var bestLongtextA = '', bestLongtextB = ''; var bestShortTextA = '', bestShortTextB = ''; while ((j = shorttext.indexOf(seed, j + 1)) != -1) { final prefixLength = diffCommonPrefix( longtext.substring(i), shorttext.substring(j), ); final suffixLength = diffCommonSuffix( longtext.substring(0, i), shorttext.substring(0, j), ); if (bestCommon.length < suffixLength + prefixLength) { bestCommon = shorttext.substring(j - suffixLength, j) + shorttext.substring(j, j + prefixLength); bestLongtextA = longtext.substring(0, i - suffixLength); bestLongtextB = longtext.substring(i + prefixLength); bestShortTextA = shorttext.substring(0, j - suffixLength); bestShortTextB = shorttext.substring(j + prefixLength); } } if (bestCommon.length * 2 >= longtext.length) { return [ bestLongtextA, bestLongtextB, bestShortTextA, bestShortTextB, bestCommon ]; } else { return null; } } /// Rehydrate the text in a diff from a string of line hashes to real lines of text. /// /// [diffs] is a List of Diff objects. /// [lineArray] is a List of unique strings. @visibleForTesting void diffCharsToLines(List<Diff> diffs, List<String>? lineArray) { final text = StringBuffer(); for (var diff in diffs) { for (var j = 0; j < diff.text.length; j++) { text.write(lineArray![diff.text.codeUnitAt(j)]); } diff.text = text.toString(); text.clear(); } } /// Given the location of the 'middle snake', split the diff in two parts /// and recurse. /// /// [text1] is the old string to be diffed. /// [text2] is the new string to be diffed. /// [x] is the index of split point in text1. /// [y] is the index of split point in text2. /// [deadline] is the time at which to bail if not yet complete. /// Returns a List of Diff objects. List<Diff> _diffBisectSplit( String text1, String text2, int x, int y, DateTime? deadline, ) { final text1a = text1.substring(0, x); final text2a = text2.substring(0, y); final text1b = text1.substring(x); final text2b = text2.substring(y); // Compute both diffs serially. final diffs = diffMain( text1a, text2a, checklines: false, deadline: deadline, ); final diffsb = diffMain( text1b, text2b, checklines: false, deadline: deadline, ); diffs.addAll(diffsb); return diffs; }
pana/lib/src/third_party/diff_match_patch/diff.dart/0
{'file_path': 'pana/lib/src/third_party/diff_match_patch/diff.dart', 'repo_id': 'pana', 'token_count': 9020}
// Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:io'; import 'package:test/test.dart'; /// Will test [actual] against the contests of the file at [goldenFilePath]. /// /// If the file doesn't exist, the file is instead created containing [actual]. void expectMatchesGoldenFile(String actual, String goldenFilePath) { var goldenFile = File(goldenFilePath); if (goldenFile.existsSync()) { expect(actual.replaceAll('\r\n', '\n'), equals(goldenFile.readAsStringSync().replaceAll('\r\n', '\n')), reason: 'goldenFilePath: "$goldenFilePath". ' 'To update the expectation delete this file and rerun the test.'); } else { goldenFile ..createSync(recursive: true) ..writeAsStringSync(actual); fail('Golden file $goldenFilePath was recreated!'); } }
pana/test/golden_file.dart/0
{'file_path': 'pana/test/golden_file.dart', 'repo_id': 'pana', 'token_count': 326}
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file // for details. 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:pana/src/license.dart'; import 'package:pana/src/model.dart'; import 'package:test/test.dart'; void main() { Future expectFile(String path, LicenseFile expected) async { final relativePath = path.substring('test/licenses/'.length); expect(await detectLicenseInFile(File(path), relativePath: relativePath), expected); } test('bad encoding', () async { await expectFile('test/licenses/bad_encoding.txt', LicenseFile('bad_encoding.txt', 'Zlib')); }); group('AGPL', () { test('explicit', () async { expect( await detectLicenseInContent('GNU AFFERO GENERAL PUBLIC LICENSE', relativePath: 'LICENSE'), null); await expectFile( 'test/licenses/agpl_v3.txt', LicenseFile('agpl_v3.txt', 'AGPL-3.0')); }); }); group('Apache', () { test('explicit', () async { expect( await detectLicenseInContent( ' Apache License\n Version 2.0, January 2004\n', relativePath: 'LICENSE'), null); await expectFile('test/licenses/apache_v2.txt', LicenseFile('apache_v2.txt', 'Apache-2.0')); }); }); group('BSD', () { test('explicit', () async { await expectFile('test/licenses/bsd_2_clause.txt', LicenseFile('bsd_2_clause.txt', 'BSD-2-Clause')); await expectFile('test/licenses/bsd_2_clause_in_comments.txt', LicenseFile('bsd_2_clause_in_comments.txt', 'BSD-2-Clause')); await expectFile('test/licenses/bsd_3_clause.txt', LicenseFile('bsd_3_clause.txt', 'unknown')); await expectFile('test/licenses/bsd_revised.txt', LicenseFile('bsd_revised.txt', 'BSD-3-Clause')); }); }); group('GPL', () { test('explicit', () async { expect( await detectLicenseInContent( ['GNU GENERAL PUBLIC LICENSE', 'Version 2, June 1991'].join('\n'), relativePath: 'LICENSE'), null); expect( await detectLicenseInContent(['GNU GPL Version 2'].join('\n'), relativePath: 'LICENSE'), null); await expectFile( 'test/licenses/gpl_v3.txt', LicenseFile('gpl_v3.txt', 'GPL-3.0')); }); }); group('LGPL', () { test('explicit', () async { expect( await detectLicenseInContent( '\nGNU LESSER GENERAL PUBLIC LICENSE\n Version 3, 29 June 2007', relativePath: 'LICENSE'), null); await expectFile( 'test/licenses/lgpl_v3.txt', LicenseFile( 'lgpl_v3.txt', 'LGPL-3.0', )); }); }); group('MIT', () { test('explicit', () async { expect( await detectLicenseInContent('\n\n The MIT license\n\n blah...', relativePath: 'LICENSE'), null); expect( await detectLicenseInContent('MIT license\n\n blah...', relativePath: 'LICENSE'), null); await expectFile('test/licenses/mit.txt', LicenseFile('mit.txt', 'MIT')); await expectFile('test/licenses/mit_without_mit.txt', LicenseFile('mit_without_mit.txt', 'MIT')); }); }); group('MPL', () { test('explicit', () async { expect( await detectLicenseInContent( '\n\n Mozilla Public License Version 2.0\n\n blah...', relativePath: 'LICENSE'), null); await expectFile( 'test/licenses/mpl_v2.txt', LicenseFile('mpl_v2.txt', 'MPL-2.0')); }); }); group('Unlicense', () { test('explicit', () async { expect( await detectLicenseInContent( '\n\n This is free and unencumbered software released into the public domain.\n', relativePath: 'LICENSE'), null); await expectFile('test/licenses/unlicense.txt', LicenseFile('unlicense.txt', 'Unlicense')); }); }); group('unknown', () { test('empty content', () async { expect(await detectLicenseInContent('', relativePath: 'LICENSE'), isNull); }); }); group('Directory scans', () { test('detect pana LICENSE', () async { expect(await detectLicenseInDir('.'), LicenseFile('LICENSE', 'BSD-3-Clause')); }); test('no license files', () async { expect(await detectLicenseInDir('lib/src/'), null); }); }); }
pana/test/license_test.dart/0
{'file_path': 'pana/test/license_test.dart', 'repo_id': 'pana', 'token_count': 2066}
// Copyright (c) 2021, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:io'; import 'package:pana/pana.dart'; import 'package:test_descriptor/test_descriptor.dart' as d; Future<ToolEnvironment> testToolEnvironment() async { final fakeFlutterRoot = d.dir('fake_flutter_root', [d.file('version', '2.0.0')]); await fakeFlutterRoot.create(); return ToolEnvironment.fake( dartCmd: [Platform.resolvedExecutable], pubCmd: [Platform.resolvedExecutable, 'pub'], environment: {'FLUTTER_ROOT': fakeFlutterRoot.io.path}, runtimeInfo: PanaRuntimeInfo( panaVersion: '1.2.3', sdkVersion: '2.12.0', flutterVersions: { 'frameworkVersion': '2.0.0', 'channel': 'stable', 'repositoryUrl': 'https://github.com/flutter/flutter', 'frameworkRevision': '13c6ad50e980cad1844457869c2b4c5dc3311d03', 'frameworkCommitDate': '2021-02-19 10:03:46 +0100', 'engineRevision': 'b04955656c87de0d80d259792e3a0e4a23b7c260', 'dartSdkVersion': '2.12.0 (build 2.12.0)', 'flutterRoot': fakeFlutterRoot.io.path }, ), ); }
pana/test/report/_tool_environment.dart/0
{'file_path': 'pana/test/report/_tool_environment.dart', 'repo_id': 'pana', 'token_count': 526}
import 'package:flutter/widgets.dart'; class GalleryExampleItem { GalleryExampleItem({ required this.id, required this.resource, this.isSvg = false, }); final String id; final String resource; final bool isSvg; } class GalleryExampleItemThumbnail extends StatelessWidget { const GalleryExampleItemThumbnail({ Key? key, required this.galleryExampleItem, required this.onTap, }) : super(key: key); final GalleryExampleItem galleryExampleItem; final GestureTapCallback onTap; @override Widget build(BuildContext context) { return Container( padding: const EdgeInsets.symmetric(horizontal: 5.0), child: GestureDetector( onTap: onTap, child: Hero( tag: galleryExampleItem.id, child: Image.asset(galleryExampleItem.resource, height: 80.0), ), ), ); } } List<GalleryExampleItem> galleryItems = <GalleryExampleItem>[ GalleryExampleItem( id: "tag1", resource: "assets/gallery1.jpg", ), GalleryExampleItem(id: "tag2", resource: "assets/firefox.svg", isSvg: true), GalleryExampleItem( id: "tag3", resource: "assets/gallery2.jpg", ), GalleryExampleItem( id: "tag4", resource: "assets/gallery3.jpg", ), ];
photo_view/example/lib/screens/examples/gallery/gallery_example_item.dart/0
{'file_path': 'photo_view/example/lib/screens/examples/gallery/gallery_example_item.dart', 'repo_id': 'photo_view', 'token_count': 466}
import 'package:flutter/material.dart'; class PhotoViewDefaultError extends StatelessWidget { const PhotoViewDefaultError({Key? key, required this.decoration}) : super(key: key); final BoxDecoration decoration; @override Widget build(BuildContext context) { return DecoratedBox( decoration: decoration, child: Center( child: Icon( Icons.broken_image, color: Colors.grey[400], size: 40.0, ), ), ); } } class PhotoViewDefaultLoading extends StatelessWidget { const PhotoViewDefaultLoading({Key? key, this.event}) : super(key: key); final ImageChunkEvent? event; @override Widget build(BuildContext context) { final expectedBytes = event?.expectedTotalBytes; final loadedBytes = event?.cumulativeBytesLoaded; final value = loadedBytes != null && expectedBytes != null ? loadedBytes / expectedBytes : null; return Center( child: Container( width: 20.0, height: 20.0, child: CircularProgressIndicator(value: value), ), ); } }
photo_view/lib/src/photo_view_default_widgets.dart/0
{'file_path': 'photo_view/lib/src/photo_view_default_widgets.dart', 'repo_id': 'photo_view', 'token_count': 415}
export 'footer.dart'; export 'footer_link.dart'; export 'icon_link.dart';
photobooth/lib/footer/widgets/widgets.dart/0
{'file_path': 'photobooth/lib/footer/widgets/widgets.dart', 'repo_id': 'photobooth', 'token_count': 30}
import 'package:flutter/material.dart'; import 'package:io_photobooth/footer/footer.dart'; import 'package:io_photobooth/landing/landing.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; class LandingPage extends StatelessWidget { const LandingPage({super.key}); @override Widget build(BuildContext context) { return const Scaffold( backgroundColor: PhotoboothColors.white, body: LandingView(), ); } } class LandingView extends StatelessWidget { const LandingView({super.key}); @override Widget build(BuildContext context) { return const AppPageView( background: LandingBackground(), body: LandingBody(), footer: BlackFooter(), ); } }
photobooth/lib/landing/view/landing_page.dart/0
{'file_path': 'photobooth/lib/landing/view/landing_page.dart', 'repo_id': 'photobooth', 'token_count': 248}
import 'package:flutter/material.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; const _characterIconButtonSizeLandscape = 90.0; const _characterIconButtonSizePortait = 60.0; class CharacterIconButton extends StatelessWidget { const CharacterIconButton({ required this.icon, required this.isSelected, required this.label, this.onPressed, super.key, }); final AssetImage icon; final VoidCallback? onPressed; final bool isSelected; final String label; @override Widget build(BuildContext context) { final orientation = MediaQuery.of(context).orientation; return Semantics( focusable: true, button: true, label: label, onTap: onPressed, child: Opacity( opacity: isSelected ? 0.6 : 1, child: Padding( padding: const EdgeInsets.all(12), child: Material( color: PhotoboothColors.transparent, shape: const CircleBorder(), clipBehavior: Clip.hardEdge, child: Ink.image( fit: BoxFit.cover, image: icon, width: orientation == Orientation.landscape ? _characterIconButtonSizeLandscape : _characterIconButtonSizePortait, height: orientation == Orientation.landscape ? _characterIconButtonSizeLandscape : _characterIconButtonSizePortait, child: InkWell(onTap: onPressed), ), ), ), ), ); } }
photobooth/lib/photobooth/widgets/character_icon_button.dart/0
{'file_path': 'photobooth/lib/photobooth/widgets/character_icon_button.dart', 'repo_id': 'photobooth', 'token_count': 672}
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 ShareErrorBottomSheet extends StatelessWidget { const ShareErrorBottomSheet({super.key}); @override Widget build(BuildContext context) { final theme = Theme.of(context); final l10n = context.l10n; return Stack( children: [ SingleChildScrollView( child: Padding( padding: const EdgeInsets.symmetric( horizontal: 24, vertical: 32, ), child: Column( mainAxisSize: MainAxisSize.min, children: [ const SizedBox(height: 32), Padding( padding: const EdgeInsets.symmetric(horizontal: 58), child: Image.asset( 'assets/images/error_photo_mobile.png', ), ), const SizedBox(height: 60), Text( l10n.shareErrorDialogHeading, key: const Key('shareErrorBottomSheet_heading'), style: theme.textTheme.displayLarge?.copyWith(fontSize: 32), textAlign: TextAlign.center, ), const SizedBox(height: 24), Text( l10n.shareErrorDialogSubheading, key: const Key('shareErrorBottomSheet_subheading'), style: theme.textTheme.displaySmall?.copyWith(fontSize: 18), textAlign: TextAlign.center, ), const SizedBox(height: 42), const ShareTryAgainButton(), const SizedBox(height: 16), ], ), ), ), 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_error_bottom_sheet.dart/0
{'file_path': 'photobooth/lib/share/view/share_error_bottom_sheet.dart', 'repo_id': 'photobooth', 'token_count': 1171}
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:io_photobooth/share/share.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; import 'package:platform_helper/platform_helper.dart'; class ShareStateListener extends StatelessWidget { ShareStateListener({ required this.child, super.key, PlatformHelper? platformHelper, }) : platformHelper = platformHelper ?? PlatformHelper(); final Widget child; /// Optional [PlatformHelper] instance. final PlatformHelper platformHelper; @override Widget build(BuildContext context) { return BlocListener<ShareBloc, ShareState>( listener: _onShareStateChange, child: child, ); } void _onShareStateChange(BuildContext context, ShareState state) { if (state.uploadStatus.isFailure) { _onShareError(context, state); } else if (state.uploadStatus.isSuccess) { _onShareSuccess(context, state); } } void _onShareError(BuildContext context, ShareState state) { showAppModal<void>( platformHelper: platformHelper, context: context, portraitChild: const ShareErrorBottomSheet(), landscapeChild: const ShareErrorDialog(), ); } void _onShareSuccess(BuildContext context, ShareState state) { openLink( state.shareUrl == ShareUrl.twitter ? state.twitterShareUrl : state.facebookShareUrl, ); } }
photobooth/lib/share/widgets/share_state_listener.dart/0
{'file_path': 'photobooth/lib/share/widgets/share_state_listener.dart', 'repo_id': 'photobooth', 'token_count': 493}
import 'package:flutter/material.dart'; import 'package:io_photobooth/l10n/l10n.dart'; import 'package:io_photobooth/stickers/stickers.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; class MobileStickersDrawer extends StatelessWidget { const MobileStickersDrawer({ required this.initialIndex, required this.onStickerSelected, required this.onTabChanged, required this.bucket, super.key, }); final int initialIndex; final ValueSetter<Asset> onStickerSelected; final ValueSetter<int> onTabChanged; final PageStorageBucket bucket; @override Widget build(BuildContext context) { final l10n = context.l10n; final screenHeight = MediaQuery.of(context).size.height; return PageStorage( bucket: bucket, child: Container( margin: const EdgeInsets.only(top: 30), height: screenHeight < PhotoboothBreakpoints.small ? screenHeight : screenHeight * 0.75, decoration: const BoxDecoration( color: PhotoboothColors.white, borderRadius: BorderRadius.vertical(top: Radius.circular(12)), ), child: Stack( children: [ Column( children: [ const SizedBox(height: 32), Align( alignment: Alignment.topLeft, child: Padding( padding: const EdgeInsets.only(left: 24), child: Text( l10n.stickersDrawerTitle, style: Theme.of(context) .textTheme .displaySmall ?.copyWith(fontSize: 24), ), ), ), const SizedBox(height: 35), Flexible( child: StickersTabs( initialIndex: initialIndex, onTabChanged: onTabChanged, onStickerSelected: onStickerSelected, ), ), ], ), Positioned( right: 24, top: 24, child: IconButton( key: const Key('stickersDrawer_close_iconButton'), icon: const Icon( Icons.clear, color: PhotoboothColors.black54, ), onPressed: () => Navigator.of(context).pop(), ), ), ], ), ), ); } }
photobooth/lib/stickers/widgets/stickers_drawer_layer/mobile_stickers_drawer.dart/0
{'file_path': 'photobooth/lib/stickers/widgets/stickers_drawer_layer/mobile_stickers_drawer.dart', 'repo_id': 'photobooth', 'token_count': 1349}
part of '../camera.dart'; typedef PlaceholderBuilder = Widget Function(BuildContext); typedef PreviewBuilder = Widget Function(BuildContext, Widget); typedef ErrorBuilder = Widget Function(BuildContext, CameraException); class Camera extends StatefulWidget { Camera({ required this.controller, PlaceholderBuilder? placeholder, PreviewBuilder? preview, ErrorBuilder? error, super.key, }) : placeholder = (placeholder ?? (_) => const SizedBox()), preview = (preview ?? (_, preview) => preview), error = (error ?? (_, __) => const SizedBox()); final CameraController controller; final PlaceholderBuilder placeholder; final PreviewBuilder preview; final ErrorBuilder error; @override State<Camera> createState() => _CameraState(); } class _CameraState extends State<Camera> { Widget? _preview; Widget get preview { return _preview ??= CameraPlatform.instance.buildView(widget.controller.textureId); } @override Widget build(BuildContext context) { return ValueListenableBuilder( valueListenable: widget.controller, builder: (BuildContext context, CameraState state, _) { switch (state.status) { case CameraStatus.uninitialized: return widget.placeholder(context); case CameraStatus.available: return widget.preview(context, preview); case CameraStatus.unavailable: return widget.error(context, state.error!); } }, ); } }
photobooth/packages/camera/camera/lib/src/camera.dart/0
{'file_path': 'photobooth/packages/camera/camera/lib/src/camera.dart', 'repo_id': 'photobooth', 'token_count': 513}
// 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:html' as html; import 'package:meta/meta.dart'; /// The HTML engine used by the current browser. enum BrowserEngine { /// The engine that powers Chrome, Samsung Internet Browser, UC Browser, /// Microsoft Edge, Opera, and others. blink, /// The engine that powers Safari. webkit, /// The engine that powers Firefox. firefox, /// The engine that powers Edge. edge, /// The engine that powers Internet Explorer 11. ie11, /// The engine that powers Samsung stock browser. It is based on blink. samsung, /// We were unable to detect the current browser engine. unknown, } /// html webgl version qualifier constants. abstract class WebGLVersion { // WebGL 1.0 is based on OpenGL ES 2.0 / GLSL 1.00 static const int webgl1 = 1; // WebGL 2.0 is based on OpenGL ES 3.0 / GLSL 3.00 static const int webgl2 = 2; } /// Lazily initialized current browser engine. // ignore: unnecessary_late late final BrowserEngine _browserEngine = _detectBrowserEngine(); /// Override the value of [browserEngine]. /// /// Setting this to `null` lets [browserEngine] detect the browser that the /// app is running on. /// /// This is intended to be used for testing and debugging only. BrowserEngine? debugBrowserEngineOverride; /// Returns the [BrowserEngine] used by the current browser. /// /// This is used to implement browser-specific behavior. BrowserEngine get browserEngine { return debugBrowserEngineOverride ?? _browserEngine; } BrowserEngine _detectBrowserEngine() { final vendor = html.window.navigator.vendor; final agent = html.window.navigator.userAgent.toLowerCase(); return detectBrowserEngineByVendorAgent(vendor, agent); } /// Detects samsung blink variants. /// /// Example patterns: /// Note 2 : GT-N7100 /// Note 3 : SM-N900T /// Tab 4 : SM-T330NU /// Galaxy S4: SHV-E330S /// Galaxy Note2: SHV-E250L /// Note: SAMSUNG-SGH-I717 /// SPH/SCH are very old Palm models. bool _isSamsungBrowser(String agent) { final exp = RegExp( 'SAMSUNG|SGH-[I|N|T]|GT-[I|N]|SM-[A|N|P|T|Z]|SHV-E|SCH-[I|J|R|S]|SPH-L', ); return exp.hasMatch(agent.toUpperCase()); } @visibleForTesting BrowserEngine detectBrowserEngineByVendorAgent(String vendor, String agent) { if (vendor == 'Google Inc.') { // Samsung browser is based on blink, check for variant. if (_isSamsungBrowser(agent)) { return BrowserEngine.samsung; } return BrowserEngine.blink; } else if (vendor == 'Apple Computer, Inc.') { return BrowserEngine.webkit; } else if (agent.contains('edge/')) { return BrowserEngine.edge; } else if (agent.contains('Edg/')) { // Chromium based Microsoft Edge has `Edg` in the user-agent. // https://docs.microsoft.com/en-us/microsoft-edge/web-platform/user-agent-string return BrowserEngine.blink; } else if (agent.contains('trident/7.0')) { return BrowserEngine.ie11; } else if (vendor == '' && agent.contains('firefox')) { // An empty string means firefox: // https://developer.mozilla.org/en-US/docs/Web/API/Navigator/vendor return BrowserEngine.firefox; } // Assume unknown otherwise, but issue a warning. // ignore: avoid_print print('WARNING: failed to detect current browser engine.'); return BrowserEngine.unknown; } /// Operating system where the current browser runs. /// /// Taken from the navigator platform. /// <https://developer.mozilla.org/en-US/docs/Web/API/NavigatorID/platform> enum OperatingSystem { /// iOS: <http://www.apple.com/ios/> iOs, /// Android: <https://www.android.com/> android, /// Linux: <https://www.linux.org/> linux, /// Windows: <https://www.microsoft.com/windows/> windows, /// MacOs: <https://www.apple.com/macos/> macOs, /// We were unable to detect the current operating system. unknown, } /// Lazily initialized current operating system. // ignore: unnecessary_late late final _operatingSystem = _detectOperatingSystem(); /// Returns the [OperatingSystem] the current browsers works on. /// /// This is used to implement operating system specific behavior such as /// soft keyboards. OperatingSystem get operatingSystem { return debugOperatingSystemOverride ?? _operatingSystem; } /// Override the value of [operatingSystem]. /// /// Setting this to `null` lets [operatingSystem] detect the real OS that the /// app is running on. /// /// This is intended to be used for testing and debugging only. OperatingSystem? debugOperatingSystemOverride; OperatingSystem _detectOperatingSystem() { final platform = html.window.navigator.platform!; final userAgent = html.window.navigator.userAgent; if (platform.startsWith('Mac')) { return OperatingSystem.macOs; } else if (platform.toLowerCase().contains('iphone') || platform.toLowerCase().contains('ipad') || platform.toLowerCase().contains('ipod')) { return OperatingSystem.iOs; } else if (userAgent.contains('Android')) { // The Android OS reports itself as "Linux armv8l" in // [html.window.navigator.platform]. So we have to check the user-agent to // determine if the OS is Android or not. return OperatingSystem.android; } else if (platform.startsWith('Linux')) { return OperatingSystem.linux; } else if (platform.startsWith('Win')) { return OperatingSystem.windows; } else { return OperatingSystem.unknown; } } /// List of Operating Systems we know to be working on laptops/desktops. /// /// These devices tend to behave differently on many core issues such as events, /// screen readers, input devices. const Set<OperatingSystem> _desktopOperatingSystems = { OperatingSystem.macOs, OperatingSystem.linux, OperatingSystem.windows, }; /// A flag to check if the current operating system is a laptop/desktop /// operating system. /// /// See [_desktopOperatingSystems]. bool get isDesktop => _desktopOperatingSystems.contains(operatingSystem); int? _cachedWebGLVersion; /// The highest WebGL version supported by the current browser, or -1 if WebGL /// is not supported. int get webGLVersion => _cachedWebGLVersion ?? (_cachedWebGLVersion = _detectWebGLVersion()); /// Detects the highest WebGL version supported by the current browser, or /// -1 if WebGL is not supported. int _detectWebGLVersion() { final canvas = html.CanvasElement( width: 1, height: 1, ); if (canvas.getContext('webgl2') != null) { return WebGLVersion.webgl2; } if (canvas.getContext('webgl') != null) { return WebGLVersion.webgl1; } return -1; }
photobooth/packages/camera/camera_web/lib/src/browser_detection.dart/0
{'file_path': 'photobooth/packages/camera/camera_web/lib/src/browser_detection.dart', 'repo_id': 'photobooth', 'token_count': 2094}
import 'package:flutter/widgets.dart'; /// {@template asset} /// A Dart object which holds metadata for a given asset. /// {@endtemplate} class Asset { /// {@macro asset} const Asset({ required this.name, required this.path, required this.size, }); /// The name of the image. final String name; /// The path to the asset. final String path; /// The size of the asset. final Size size; }
photobooth/packages/photobooth_ui/lib/src/models/asset.dart/0
{'file_path': 'photobooth/packages/photobooth_ui/lib/src/models/asset.dart', 'repo_id': 'photobooth', 'token_count': 137}
import 'package:flutter/material.dart'; /// {@template app_page_view} /// A widget that constructs a page view consisting of a [background] /// [body], [footer] pinned to the bottom of the page and an optional /// list of overlay widgets displayed on top of the [body]. /// {@endtemplate} class AppPageView extends StatelessWidget { /// {@macro app_page_view} const AppPageView({ required this.body, required this.footer, this.background = const SizedBox(), this.overlays = const <Widget>[], super.key, }); /// A body of the [AppPageView] final Widget body; /// Sticky footer displayed at the bottom of the [AppPageView] final Widget footer; /// An optional background of the [AppPageView] final Widget background; /// An optional list of overlays displayed on top of the [body] final List<Widget> overlays; @override Widget build(BuildContext context) { return Stack( fit: StackFit.expand, children: [ background, CustomScrollView( slivers: [ SliverToBoxAdapter(child: body), SliverFillRemaining( hasScrollBody: false, child: Container( alignment: Alignment.bottomCenter, height: 200, child: footer, ), ), ], ), ...overlays, ], ); } }
photobooth/packages/photobooth_ui/lib/src/widgets/app_page_view.dart/0
{'file_path': 'photobooth/packages/photobooth_ui/lib/src/widgets/app_page_view.dart', 'repo_id': 'photobooth', 'token_count': 563}
// ignore_for_file: prefer_const_constructors import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; void main() { group('Asset', () { test('does not support value equality', () { const name = 'image'; const path = 'path/to/image.png'; const size = Size(10, 10); final assetA = Asset(name: name, path: path, size: size); final assetB = Asset(name: name, path: path, size: size); expect(assetA, isNot(equals(assetB))); }); }); }
photobooth/packages/photobooth_ui/test/src/models/asset_test.dart/0
{'file_path': 'photobooth/packages/photobooth_ui/test/src/models/asset_test.dart', 'repo_id': 'photobooth', 'token_count': 220}
// ignore_for_file: prefer_const_constructors import 'dart:convert'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; import '../../helpers/helpers.dart'; void main() { final data = 'data:image/png,${base64.encode(transparentImage)}'; group('PreviewImage', () { testWidgets('renders with height and width', (tester) async { await tester.pumpWidget( PreviewImage( data: data, height: 100, width: 100, ), ); expect(find.byType(Image), findsOneWidget); }); testWidgets('anti-aliasing is enabled', (tester) async { await tester.pumpWidget( PreviewImage( data: data, height: 100, width: 100, ), ); final image = tester.widget<Image>(find.byType(Image)); expect(image.isAntiAlias, isTrue); }); testWidgets('renders without width as parameter', (tester) async { await tester.pumpWidget(PreviewImage(data: data, height: 100)); expect(find.byType(Image), findsOneWidget); }); testWidgets('renders without height as parameter', (tester) async { await tester.pumpWidget(PreviewImage(data: data, width: 100)); expect(find.byType(Image), findsOneWidget); }); testWidgets('renders without height/width as parameter', (tester) async { await tester.pumpWidget(PreviewImage(data: data)); expect(find.byType(Image), findsOneWidget); }); testWidgets('renders error with empty image', (tester) async { await tester.pumpWidget(PreviewImage(data: '')); await tester.pumpAndSettle(); final exception = tester.takeException(); expect(exception, isNotNull); expect(find.byKey(const Key('previewImage_errorText')), findsOneWidget); }); }); }
photobooth/packages/photobooth_ui/test/src/widgets/preview_image_test.dart/0
{'file_path': 'photobooth/packages/photobooth_ui/test/src/widgets/preview_image_test.dart', 'repo_id': 'photobooth', 'token_count': 747}
// ignore_for_file: prefer_const_constructors import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:io_photobooth/footer/footer.dart'; import 'package:io_photobooth/landing/landing.dart'; import 'package:io_photobooth/photobooth/photobooth.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; import '../../helpers/helpers.dart'; void main() { group('LandingPage', () { testWidgets('renders landing view', (tester) async { await tester.pumpApp(const LandingPage()); expect(find.byType(LandingView), findsOneWidget); }); }); group('LandingView', () { testWidgets('renders background', (tester) async { await tester.pumpApp(const LandingView()); expect(find.byKey(Key('landingPage_background')), findsOneWidget); }); testWidgets('renders heading', (tester) async { await tester.pumpApp(const LandingView()); expect(find.byKey(Key('landingPage_heading_text')), findsOneWidget); }); testWidgets('renders image', (tester) async { await tester.pumpApp(const LandingView()); expect(find.byType(Image), findsOneWidget); }); testWidgets('renders image on small screens', (tester) async { tester.setDisplaySize(const Size(PhotoboothBreakpoints.small, 1000)); await tester.pumpApp(const LandingView()); expect(find.byType(Image), findsOneWidget); }); testWidgets('renders subheading', (tester) async { await tester.pumpApp(const LandingView()); expect(find.byKey(Key('landingPage_subheading_text')), findsOneWidget); }); testWidgets('renders take photo button', (tester) async { await tester.pumpApp(const LandingView()); expect(find.byType(LandingTakePhotoButton), findsOneWidget); }); testWidgets('renders black footer', (tester) async { await tester.pumpApp(const LandingView()); await tester.ensureVisible(find.byType(BlackFooter, skipOffstage: false)); await tester.pumpAndSettle(); expect(find.byType(BlackFooter), findsOneWidget); }); testWidgets('tapping on take photo button navigates to PhotoboothPage', (tester) async { await runZonedGuarded( () async { await tester.pumpApp(const LandingView()); await tester.ensureVisible( find.byType( LandingTakePhotoButton, skipOffstage: false, ), ); await tester.pumpAndSettle(); await tester.tap( find.byType( LandingTakePhotoButton, skipOffstage: false, ), ); await tester.pumpAndSettle(); }, (_, __) {}, ); expect(find.byType(PhotoboothPage), findsOneWidget); expect(find.byType(LandingView), findsNothing); }); }); }
photobooth/test/landing/view/landing_page_test.dart/0
{'file_path': 'photobooth/test/landing/view/landing_page_test.dart', 'repo_id': 'photobooth', 'token_count': 1184}
// ignore_for_file: prefer_const_constructors import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:io_photobooth/share/share.dart'; import '../../helpers/helpers.dart'; void main() { group('ShareErrorDialog', () { testWidgets('displays heading', (tester) async { await tester.pumpApp(Scaffold(body: ShareErrorDialog())); expect(find.byKey(Key('shareErrorDialog_heading')), findsOneWidget); }); testWidgets('displays subheading', (tester) async { await tester.pumpApp(Scaffold(body: ShareErrorDialog())); expect(find.byKey(Key('shareErrorDialog_subheading')), findsOneWidget); }); testWidgets('displays a ShareTryAgainButton button', (tester) async { await tester.pumpApp(Scaffold(body: ShareErrorDialog())); expect(find.byType(ShareTryAgainButton), findsOneWidget); }); testWidgets('pops when tapped on ShareTryAgainButton button', (tester) async { await tester.pumpApp(Scaffold(body: ShareErrorDialog())); await tester.ensureVisible(find.byType(ShareTryAgainButton)); await tester.tap(find.byType(ShareTryAgainButton)); await tester.pumpAndSettle(); expect(find.byType(ShareErrorDialog), findsNothing); }); testWidgets('pops when tapped on close button', (tester) async { await tester.pumpApp(Scaffold(body: ShareErrorDialog())); await tester.tap(find.byIcon(Icons.clear)); await tester.pumpAndSettle(); expect(find.byType(ShareErrorDialog), findsNothing); }); }); }
photobooth/test/share/view/share_error_dialog_test.dart/0
{'file_path': 'photobooth/test/share/view/share_error_dialog_test.dart', 'repo_id': 'photobooth', 'token_count': 586}
name: pinball_ui concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true on: push: paths: - "packages/pinball_ui/**" - ".github/workflows/pinball_ui.yaml" pull_request: paths: - "packages/pinball_ui/**" - ".github/workflows/pinball_ui.yaml" jobs: build: uses: VeryGoodOpenSource/very_good_workflows/.github/workflows/flutter_package.yml@v1 with: working_directory: packages/pinball_ui coverage_excludes: "lib/gen/*.dart"
pinball/.github/workflows/pinball_ui.yaml/0
{'file_path': 'pinball/.github/workflows/pinball_ui.yaml', 'repo_id': 'pinball', 'token_count': 221}
import 'package:authentication_repository/authentication_repository.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:leaderboard_repository/leaderboard_repository.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 App extends StatelessWidget { const App({ Key? key, required AuthenticationRepository authenticationRepository, required LeaderboardRepository leaderboardRepository, required ShareRepository shareRepository, required PinballAudioPlayer pinballAudioPlayer, required PlatformHelper platformHelper, }) : _authenticationRepository = authenticationRepository, _leaderboardRepository = leaderboardRepository, _shareRepository = shareRepository, _pinballAudioPlayer = pinballAudioPlayer, _platformHelper = platformHelper, super(key: key); final AuthenticationRepository _authenticationRepository; final LeaderboardRepository _leaderboardRepository; final ShareRepository _shareRepository; final PinballAudioPlayer _pinballAudioPlayer; final PlatformHelper _platformHelper; @override Widget build(BuildContext context) { return MultiRepositoryProvider( providers: [ RepositoryProvider.value(value: _authenticationRepository), RepositoryProvider.value(value: _leaderboardRepository), RepositoryProvider.value(value: _shareRepository), RepositoryProvider.value(value: _pinballAudioPlayer), RepositoryProvider.value(value: _platformHelper), ], child: MultiBlocProvider( providers: [ BlocProvider(create: (_) => CharacterThemeCubit()), BlocProvider(create: (_) => StartGameBloc()), BlocProvider(create: (_) => GameBloc()), ], child: MaterialApp( title: 'I/O Pinball', theme: PinballTheme.standard, localizationsDelegates: const [ AppLocalizations.delegate, GlobalMaterialLocalizations.delegate, ], supportedLocales: AppLocalizations.supportedLocales, home: const PinballGamePage(), ), ), ); } }
pinball/lib/app/view/app.dart/0
{'file_path': 'pinball/lib/app/view/app.dart', 'repo_id': 'pinball', 'token_count': 918}
import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:pinball_audio/pinball_audio.dart'; import 'package:pinball_flame/pinball_flame.dart'; class KickerNoiseBehavior extends ContactBehavior { @override void beginContact(Object other, Contact contact) { super.beginContact(other, contact); readProvider<PinballAudioPlayer>().play(PinballAudio.kicker); } }
pinball/lib/game/behaviors/kicker_noise_behavior.dart/0
{'file_path': 'pinball/lib/game/behaviors/kicker_noise_behavior.dart', 'repo_id': 'pinball', 'token_count': 128}
part of 'backbox_bloc.dart'; /// {@template backbox_event} /// Base class for backbox events. /// {@endtemplate} abstract class BackboxEvent extends Equatable { /// {@macro backbox_event} const BackboxEvent(); } /// {@template player_initials_requested} /// Event that triggers the user initials display. /// {@endtemplate} class PlayerInitialsRequested extends BackboxEvent { /// {@macro player_initials_requested} const PlayerInitialsRequested({ required this.score, required this.character, }); /// Player's score. final int score; /// Player's character. final CharacterTheme character; @override List<Object?> get props => [score, character]; } /// {@template player_initials_submitted} /// Event that submits the user score and initials. /// {@endtemplate} class PlayerInitialsSubmitted extends BackboxEvent { /// {@macro player_initials_submitted} const PlayerInitialsSubmitted({ required this.score, required this.initials, required this.character, }); /// Player's score. final int score; /// Player's initials. final String initials; /// Player's character. final CharacterTheme character; @override List<Object?> get props => [score, initials, character]; } /// {@template share_score_requested} /// Event when user requests to share their score. /// {@endtemplate} class ShareScoreRequested extends BackboxEvent { /// {@macro share_score_requested} const ShareScoreRequested({ required this.score, }); /// Player's score. final int score; @override List<Object?> get props => [score]; } /// Event that triggers the fetching of the leaderboard class LeaderboardRequested extends BackboxEvent { @override List<Object?> get props => []; }
pinball/lib/game/components/backbox/bloc/backbox_event.dart/0
{'file_path': 'pinball/lib/game/components/backbox/bloc/backbox_event.dart', 'repo_id': 'pinball', 'token_count': 524}
export 'draining_behavior.dart';
pinball/lib/game/components/drain/behaviors/behaviors.dart/0
{'file_path': 'pinball/lib/game/components/drain/behaviors/behaviors.dart', 'repo_id': 'pinball', 'token_count': 11}
import 'dart:math' as math; import 'package:flame/components.dart'; import 'package:flutter/material.dart'; import 'package:pinball/game/components/multipliers/behaviors/behaviors.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; /// {@template multipliers} /// A group for the multipliers on the board. /// {@endtemplate} class Multipliers extends Component with ZIndex { /// {@macro multipliers} Multipliers() : super( children: [ Multiplier.x2( position: Vector2(-19.6, -2), angle: -15 * math.pi / 180, ), Multiplier.x3( position: Vector2(12.8, -9.4), angle: 15 * math.pi / 180, ), Multiplier.x4( position: Vector2(-0.3, -21.2), angle: 3 * math.pi / 180, ), Multiplier.x5( position: Vector2(-8.9, -28), angle: -3 * math.pi / 180, ), Multiplier.x6( position: Vector2(9.8, -30.7), angle: 8 * math.pi / 180, ), MultipliersBehavior(), ], ) { zIndex = ZIndexes.decal; } /// Creates [Multipliers] without any children. /// /// This can be used for testing [Multipliers]'s behaviors in isolation. @visibleForTesting Multipliers.test(); }
pinball/lib/game/components/multipliers/multipliers.dart/0
{'file_path': 'pinball/lib/game/components/multipliers/multipliers.dart', 'repo_id': 'pinball', 'token_count': 705}
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_components/pinball_components.dart'; /// {@template score_view} /// [Widget] that displays the score. /// {@endtemplate} class ScoreView extends StatelessWidget { /// {@macro score_view} const ScoreView({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final isGameOver = context.select((GameBloc bloc) => bloc.state.status.isGameOver); return Padding( padding: const EdgeInsets.only( left: 12, top: 2, bottom: 2, ), child: AnimatedSwitcher( duration: kThemeAnimationDuration, child: isGameOver ? const _GameOver() : const _ScoreDisplay(), ), ); } } class _GameOver extends StatelessWidget { const _GameOver({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final l10n = context.l10n; return Text( l10n.gameOver, style: Theme.of(context).textTheme.headline1, ); } } class _ScoreDisplay extends StatelessWidget { const _ScoreDisplay({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final l10n = context.l10n; return Row( children: [ FittedBox( child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Text( l10n.score.toLowerCase(), style: Theme.of(context).textTheme.subtitle1, ), const _ScoreText(), const RoundCountDisplay(), ], ), ), ], ); } } class _ScoreText extends StatelessWidget { const _ScoreText({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final score = context.select((GameBloc bloc) => bloc.state.displayScore); return Text( score.formatScore(), style: Theme.of(context).textTheme.headline1, ); } }
pinball/lib/game/view/widgets/score_view.dart/0
{'file_path': 'pinball/lib/game/view/widgets/score_view.dart', 'repo_id': 'pinball', 'token_count': 915}
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.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_theme/pinball_theme.dart'; import 'package:pinball_ui/pinball_ui.dart'; /// {@template character_selection_dialog} /// Dialog used to select the playing character of the game. /// {@endtemplate character_selection_dialog} class CharacterSelectionDialog extends StatelessWidget { /// {@macro character_selection_dialog} const CharacterSelectionDialog({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final l10n = context.l10n; return PinballDialog( title: l10n.characterSelectionTitle, subtitle: l10n.characterSelectionSubtitle, child: Padding( padding: const EdgeInsets.all(12), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Expanded( child: Row( children: [ Expanded(child: _CharacterPreview()), Expanded(child: _CharacterGrid()), ], ), ), const SizedBox(height: 8), const _SelectCharacterButton(), ], ), ), ); } } class _SelectCharacterButton extends StatelessWidget { const _SelectCharacterButton({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final l10n = context.l10n; return PinballButton( onTap: () async { Navigator.of(context).pop(); context.read<StartGameBloc>().add(const CharacterSelected()); }, text: l10n.select, ); } } class _CharacterGrid extends StatelessWidget { @override Widget build(BuildContext context) { return BlocBuilder<CharacterThemeCubit, CharacterThemeState>( builder: (context, state) { return Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Expanded( child: Column( children: [ _Character( key: const Key('dash_character_selection'), character: const DashTheme(), isSelected: state.isDashSelected, ), const SizedBox(height: 6), _Character( key: const Key('android_character_selection'), character: const AndroidTheme(), isSelected: state.isAndroidSelected, ), ], ), ), const SizedBox(width: 6), Expanded( child: Column( children: [ _Character( key: const Key('sparky_character_selection'), character: const SparkyTheme(), isSelected: state.isSparkySelected, ), const SizedBox(height: 6), _Character( key: const Key('dino_character_selection'), character: const DinoTheme(), isSelected: state.isDinoSelected, ), ], ), ), ], ); }, ); } } class _CharacterPreview extends StatelessWidget { @override Widget build(BuildContext context) { return BlocBuilder<CharacterThemeCubit, CharacterThemeState>( builder: (context, state) { return SelectedCharacter(currentCharacter: state.characterTheme); }, ); } } class _Character extends StatelessWidget { const _Character({ Key? key, required this.character, required this.isSelected, }) : super(key: key); final CharacterTheme character; final bool isSelected; @override Widget build(BuildContext context) { return Expanded( child: Opacity( opacity: isSelected ? 1 : 0.4, child: TextButton( onPressed: () => context.read<CharacterThemeCubit>().characterSelected(character), style: ButtonStyle( overlayColor: MaterialStateProperty.all( PinballColors.transparent, ), ), child: character.icon.image(fit: BoxFit.contain), ), ), ); } }
pinball/lib/select_character/view/character_selection_page.dart/0
{'file_path': 'pinball/lib/select_character/view/character_selection_page.dart', 'repo_id': 'pinball', 'token_count': 2091}
import 'dart:async'; import 'dart:math' as math; import 'package:flame/components.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flutter/material.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; export 'cubit/android_spaceship_cubit.dart'; class AndroidSpaceship extends Component { AndroidSpaceship({required Vector2 position}) : super( children: [ _SpaceshipSaucer()..initialPosition = position, _SpaceshipSaucerSpriteAnimationComponent()..position = position, _LightBeamSpriteComponent()..position = position + Vector2(2.5, 5), _SpaceshipHole( outsideLayer: Layer.spaceshipExitRail, outsidePriority: ZIndexes.ballOnSpaceshipRail, )..initialPosition = position - Vector2(5.3, -5.4), _SpaceshipHole( outsideLayer: Layer.board, outsidePriority: ZIndexes.ballOnBoard, )..initialPosition = position - Vector2(-7.5, -1.1), ], ); /// Creates an [AndroidSpaceship] without any children. /// /// This can be used for testing [AndroidSpaceship]'s behaviors in isolation. @visibleForTesting AndroidSpaceship.test({ Iterable<Component>? children, }) : super(children: children); } class _SpaceshipSaucer extends BodyComponent with InitialPosition, Layered { _SpaceshipSaucer() : super(renderBody: false) { layer = Layer.spaceship; } @override Body createBody() { final shape = _SpaceshipSaucerShape(); final bodyDef = BodyDef( position: initialPosition, userData: this, angle: -1.7, ); return world.createBody(bodyDef)..createFixtureFromShape(shape); } } class _SpaceshipSaucerShape extends ChainShape { _SpaceshipSaucerShape() { const minorRadius = 9.75; const majorRadius = 11.9; createChain( [ for (var angle = 0.2618; angle <= 6.0214; angle += math.pi / 180) Vector2( minorRadius * math.cos(angle), majorRadius * math.sin(angle), ), ], ); } } class _SpaceshipSaucerSpriteAnimationComponent extends SpriteAnimationComponent with HasGameRef, ZIndex { _SpaceshipSaucerSpriteAnimationComponent() : super( anchor: Anchor.center, ) { zIndex = ZIndexes.spaceshipSaucer; } @override Future<void> onLoad() async { await super.onLoad(); final spriteSheet = gameRef.images.fromCache( Assets.images.android.spaceship.saucer.keyName, ); const amountPerRow = 5; const amountPerColumn = 3; final textureSize = Vector2( spriteSheet.width / amountPerRow, spriteSheet.height / amountPerColumn, ); size = textureSize / 10; animation = SpriteAnimation.fromFrameData( spriteSheet, SpriteAnimationData.sequenced( amount: amountPerRow * amountPerColumn, amountPerRow: amountPerRow, stepTime: 1 / 12, textureSize: textureSize, ), ); } } class _LightBeamSpriteComponent extends SpriteComponent with HasGameRef, ZIndex { _LightBeamSpriteComponent() : super( anchor: Anchor.center, ) { zIndex = ZIndexes.spaceshipLightBeam; } @override Future<void> onLoad() async { await super.onLoad(); final sprite = Sprite( gameRef.images.fromCache( Assets.images.android.spaceship.lightBeam.keyName, ), ); this.sprite = sprite; size = sprite.originalSize / 10; } } class _SpaceshipHole extends LayerSensor { _SpaceshipHole({required Layer outsideLayer, required int outsidePriority}) : super( insideLayer: Layer.spaceship, outsideLayer: outsideLayer, orientation: LayerEntranceOrientation.down, insideZIndex: ZIndexes.ballOnSpaceship, outsideZIndex: outsidePriority, ) { layer = Layer.spaceship; } @override Shape get shape { return ArcShape( center: Vector2(0, -3.2), arcRadius: 5, angle: 1, rotation: -2, ); } }
pinball/packages/pinball_components/lib/src/components/android_spaceship/android_spaceship.dart/0
{'file_path': 'pinball/packages/pinball_components/lib/src/components/android_spaceship/android_spaceship.dart', 'repo_id': 'pinball', 'token_count': 1724}
import 'package:flame/components.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; class BoardBackgroundSpriteComponent extends SpriteComponent with HasGameRef, ZIndex { BoardBackgroundSpriteComponent() : super( anchor: Anchor.center, position: Vector2(-0.2, 0.1), ) { zIndex = ZIndexes.boardBackground; } @override Future<void> onLoad() async { await super.onLoad(); final sprite = Sprite( gameRef.images.fromCache( Assets.images.boardBackground.keyName, ), ); this.sprite = sprite; size = sprite.originalSize / 10; } }
pinball/packages/pinball_components/lib/src/components/board_background_sprite_component.dart/0
{'file_path': 'pinball/packages/pinball_components/lib/src/components/board_background_sprite_component.dart', 'repo_id': 'pinball', 'token_count': 266}
export 'dash_bumper_ball_contact_behavior.dart';
pinball/packages/pinball_components/lib/src/components/dash_bumper/behaviors/behaviors.dart/0
{'file_path': 'pinball/packages/pinball_components/lib/src/components/dash_bumper/behaviors/behaviors.dart', 'repo_id': 'pinball', 'token_count': 17}
part of 'flipper_cubit.dart'; enum FlipperState { movingDown, movingUp, } extension FlipperStateX on FlipperState { bool get isMovingDown => this == FlipperState.movingDown; bool get isMovingUp => this == FlipperState.movingUp; }
pinball/packages/pinball_components/lib/src/components/flipper/cubit/flipper_state.dart/0
{'file_path': 'pinball/packages/pinball_components/lib/src/components/flipper/cubit/flipper_state.dart', 'repo_id': 'pinball', 'token_count': 82}
import 'package:bloc/bloc.dart'; part 'kicker_state.dart'; class KickerCubit extends Cubit<KickerState> { KickerCubit() : super(KickerState.lit); void onBallContacted() { emit(KickerState.dimmed); } void onBlinked() { emit(KickerState.lit); } }
pinball/packages/pinball_components/lib/src/components/kicker/cubit/kicker_cubit.dart/0
{'file_path': 'pinball/packages/pinball_components/lib/src/components/kicker/cubit/kicker_cubit.dart', 'repo_id': 'pinball', 'token_count': 109}
import 'package:flame/components.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; class PlungerJointingBehavior extends Component with ParentIsA<Plunger> { PlungerJointingBehavior({required double compressionDistance}) : _compressionDistance = compressionDistance; final double _compressionDistance; @override Future<void> onLoad() async { await super.onLoad(); final anchor = JointAnchor() ..initialPosition = Vector2(0, _compressionDistance); await add(anchor); final jointDef = _PlungerAnchorPrismaticJointDef( plunger: parent, anchor: anchor, ); parent.world.createJoint( PrismaticJoint(jointDef)..setLimits(-_compressionDistance, 0), ); } } /// [PrismaticJointDef] between a [Plunger] and an [JointAnchor] with motion on /// the vertical axis. /// /// The [Plunger] is constrained vertically between its starting position and /// the [JointAnchor]. The [JointAnchor] must be below the [Plunger]. class _PlungerAnchorPrismaticJointDef extends PrismaticJointDef { /// {@macro plunger_anchor_prismatic_joint_def} _PlungerAnchorPrismaticJointDef({ required Plunger plunger, required BodyComponent anchor, }) { initialize( plunger.body, anchor.body, plunger.body.position + anchor.body.position, Vector2(16, BoardDimensions.bounds.height), ); enableLimit = true; lowerTranslation = double.negativeInfinity; enableMotor = true; motorSpeed = 1000; maxMotorForce = motorSpeed; collideConnected = true; } }
pinball/packages/pinball_components/lib/src/components/plunger/behaviors/plunger_jointing_behavior.dart/0
{'file_path': 'pinball/packages/pinball_components/lib/src/components/plunger/behaviors/plunger_jointing_behavior.dart', 'repo_id': 'pinball', 'token_count': 601}
import 'package:flame/components.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; class SkillShotBallContactBehavior extends ContactBehavior<SkillShot> { @override void beginContact(Object other, Contact contact) { super.beginContact(other, contact); if (other is! Ball) return; parent.bloc.onBallContacted(); parent.firstChild<SpriteAnimationComponent>()?.playing = true; } }
pinball/packages/pinball_components/lib/src/components/skill_shot/behaviors/skill_shot_ball_contact_behavior.dart/0
{'file_path': 'pinball/packages/pinball_components/lib/src/components/skill_shot/behaviors/skill_shot_ball_contact_behavior.dart', 'repo_id': 'pinball', 'token_count': 173}
import 'package:bloc/bloc.dart'; part 'sparky_bumper_state.dart'; class SparkyBumperCubit extends Cubit<SparkyBumperState> { SparkyBumperCubit() : super(SparkyBumperState.lit); void onBallContacted() { emit(SparkyBumperState.dimmed); } void onBlinked() { emit(SparkyBumperState.lit); } }
pinball/packages/pinball_components/lib/src/components/sparky_bumper/cubit/sparky_bumper_cubit.dart/0
{'file_path': 'pinball/packages/pinball_components/lib/src/components/sparky_bumper/cubit/sparky_bumper_cubit.dart', 'repo_id': 'pinball', 'token_count': 129}
import 'package:dashbook/dashbook.dart'; import 'package:sandbox/common/common.dart'; import 'package:sandbox/stories/arrow_icon/arrow_icon_game.dart'; void addArrowIconStories(Dashbook dashbook) { dashbook.storiesOf('ArrowIcon').addGame( title: 'Basic', description: ArrowIconGame.description, gameBuilder: (context) => ArrowIconGame(), ); }
pinball/packages/pinball_components/sandbox/lib/stories/arrow_icon/stories.dart/0
{'file_path': 'pinball/packages/pinball_components/sandbox/lib/stories/arrow_icon/stories.dart', 'repo_id': 'pinball', 'token_count': 140}
import 'package:dashbook/dashbook.dart'; import 'package:sandbox/common/common.dart'; import 'package:sandbox/stories/effects/camera_zoom_game.dart'; void addEffectsStories(Dashbook dashbook) { dashbook.storiesOf('Effects').addGame( title: 'CameraZoom', description: CameraZoomGame.description, gameBuilder: (_) => CameraZoomGame(), ); }
pinball/packages/pinball_components/sandbox/lib/stories/effects/stories.dart/0
{'file_path': 'pinball/packages/pinball_components/sandbox/lib/stories/effects/stories.dart', 'repo_id': 'pinball', 'token_count': 138}
import 'dart:math' as math; 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 MultipliersGame extends BallGame with KeyboardEvents { MultipliersGame() : super( imagesFileNames: [ 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, ], ); static const description = ''' Shows how the Multipliers are rendered. - Tap anywhere on the screen to spawn a ball into the game. - Press digits 2 to 6 for toggle state multipliers 2 to 6. '''; final List<Multiplier> multipliers = [ Multiplier.x2( position: Vector2(-20, 0), angle: -15 * math.pi / 180, ), Multiplier.x3( position: Vector2(20, -5), angle: 15 * math.pi / 180, ), Multiplier.x4( position: Vector2(0, -15), angle: 0, ), Multiplier.x5( position: Vector2(-10, -25), angle: -3 * math.pi / 180, ), Multiplier.x6( position: Vector2(10, -35), angle: 8 * math.pi / 180, ), ]; @override Future<void> onLoad() async { await super.onLoad(); camera.followVector2(Vector2.zero()); await addAll(multipliers); await traceAllBodies(); } @override KeyEventResult onKeyEvent( RawKeyEvent event, Set<LogicalKeyboardKey> keysPressed, ) { if (event is RawKeyDownEvent) { var currentMultiplier = 1; if (event.logicalKey == LogicalKeyboardKey.digit2) { currentMultiplier = 2; } if (event.logicalKey == LogicalKeyboardKey.digit3) { currentMultiplier = 3; } if (event.logicalKey == LogicalKeyboardKey.digit4) { currentMultiplier = 4; } if (event.logicalKey == LogicalKeyboardKey.digit5) { currentMultiplier = 5; } if (event.logicalKey == LogicalKeyboardKey.digit6) { currentMultiplier = 6; } for (final multiplier in multipliers) { multiplier.bloc.next(currentMultiplier); } return KeyEventResult.handled; } return KeyEventResult.ignored; } }
pinball/packages/pinball_components/sandbox/lib/stories/multipliers/multipliers_game.dart/0
{'file_path': 'pinball/packages/pinball_components/sandbox/lib/stories/multipliers/multipliers_game.dart', 'repo_id': 'pinball', 'token_count': 1192}
// ignore_for_file: cascade_invocations, one_member_abstracts import 'package:flame/components.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'; import '../../helpers/helpers.dart'; abstract class _VoidCallbackStubBase { void onCall(); } class _VoidCallbackStub extends Mock implements _VoidCallbackStubBase {} void main() { group('ArrowIcon', () { TestWidgetsFlutterBinding.ensureInitialized(); final assets = [ Assets.images.displayArrows.arrowLeft.keyName, Assets.images.displayArrows.arrowRight.keyName, ]; final flameTester = FlameTester(() => TappablesTestGame(assets)); flameTester.testGameWidget( 'is tappable', setUp: (game, tester) async { final stub = _VoidCallbackStub(); await game.images.loadAll(assets); await game.ensureAdd( ArrowIcon( position: Vector2.zero(), direction: ArrowIconDirection.left, onTap: stub.onCall, ), ); await tester.pump(); await tester.tapAt(Offset.zero); await tester.pump(); }, verify: (game, tester) async { final icon = game.descendants().whereType<ArrowIcon>().single; verify(icon.onTap).called(1); }, ); group('left', () { flameTester.testGameWidget( 'renders correctly', setUp: (game, tester) async { await game.images.loadAll(assets); game.camera.followVector2(Vector2.zero()); await game.add( ArrowIcon( position: Vector2.zero(), direction: ArrowIconDirection.left, onTap: () {}, ), ); await tester.pump(); }, verify: (game, tester) async { await expectLater( find.byGame<TestGame>(), matchesGoldenFile('golden/arrow_icon_left.png'), ); }, ); }); group('right', () { flameTester.testGameWidget( 'renders correctly', setUp: (game, tester) async { await game.images.loadAll(assets); game.camera.followVector2(Vector2.zero()); await game.add( ArrowIcon( position: Vector2.zero(), direction: ArrowIconDirection.right, onTap: () {}, ), ); await tester.pump(); }, verify: (game, tester) async { await expectLater( find.byGame<TestGame>(), matchesGoldenFile('golden/arrow_icon_right.png'), ); }, ); }); }); }
pinball/packages/pinball_components/test/src/components/arrow_icon_test.dart/0
{'file_path': 'pinball/packages/pinball_components/test/src/components/arrow_icon_test.dart', 'repo_id': 'pinball', 'token_count': 1298}
// ignore_for_file: cascade_invocations 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'; import 'package:pinball_components/src/components/chrome_dino/behaviors/behaviors.dart'; import '../../../../helpers/helpers.dart'; class _MockChromeDinoCubit extends Mock implements ChromeDinoCubit {} class _MockContact extends Mock implements Contact {} class _MockFixture extends Mock implements Fixture {} class _MockBall extends Mock implements Ball {} void main() { TestWidgetsFlutterBinding.ensureInitialized(); final flameTester = FlameTester(TestGame.new); group( 'ChromeDinoMouthOpeningBehavior', () { test('can be instantiated', () { expect( ChromeDinoMouthOpeningBehavior(), isA<ChromeDinoMouthOpeningBehavior>(), ); }); flameTester.test( 'preSolve disables contact when the mouth is open ' 'and there is not ball in the mouth', (game) async { final behavior = ChromeDinoMouthOpeningBehavior(); final bloc = _MockChromeDinoCubit(); whenListen( bloc, const Stream<ChromeDinoState>.empty(), initialState: const ChromeDinoState( status: ChromeDinoStatus.idle, isMouthOpen: true, ), ); final chromeDino = ChromeDino.test(bloc: bloc); await chromeDino.add(behavior); await game.ensureAdd(chromeDino); final contact = _MockContact(); final fixture = _MockFixture(); when(() => contact.fixtureA).thenReturn(fixture); when(() => fixture.userData).thenReturn('mouth_opening'); behavior.preSolve(_MockBall(), contact, Manifold()); verify(() => contact.setEnabled(false)).called(1); }, ); }, ); }
pinball/packages/pinball_components/test/src/components/chrome_dino/behaviors/chrome_dino_mouth_opening_behavior_test.dart/0
{'file_path': 'pinball/packages/pinball_components/test/src/components/chrome_dino/behaviors/chrome_dino_mouth_opening_behavior_test.dart', 'repo_id': 'pinball', 'token_count': 856}
// 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:mocktail/mocktail.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_components/src/components/flapper/behaviors/behaviors.dart'; import '../../../../helpers/helpers.dart'; class _MockBall extends Mock implements Ball {} class _MockContact extends Mock implements Contact {} void main() { TestWidgetsFlutterBinding.ensureInitialized(); final assets = [ Assets.images.flapper.flap.keyName, Assets.images.flapper.backSupport.keyName, Assets.images.flapper.frontSupport.keyName, ]; final flameTester = FlameTester(() => TestGame(assets)); group( 'FlapperSpinningBehavior', () { test('can be instantiated', () { expect( FlapperSpinningBehavior(), isA<FlapperSpinningBehavior>(), ); }); flameTester.test( 'beginContact plays the flapper animation', (game) async { final behavior = FlapperSpinningBehavior(); final entrance = FlapperEntrance(); final flap = FlapSpriteAnimationComponent(); final flapper = Flapper.test(); await flapper.addAll([entrance, flap]); await entrance.add(behavior); await game.ensureAdd(flapper); behavior.beginContact(_MockBall(), _MockContact()); expect(flap.playing, isTrue); }, ); }, ); }
pinball/packages/pinball_components/test/src/components/flapper/behaviors/flapper_spinning_behavior_test.dart/0
{'file_path': 'pinball/packages/pinball_components/test/src/components/flapper/behaviors/flapper_spinning_behavior_test.dart', 'repo_id': 'pinball', 'token_count': 622}
// 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'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); final flameTester = FlameTester(Forge2DGame.new); group('JointAnchor', () { flameTester.test( 'loads correctly', (game) async { final anchor = JointAnchor(); await game.ready(); await game.ensureAdd(anchor); expect(game.contains(anchor), isTrue); }, ); group('body', () { flameTester.test( 'is static', (game) async { await game.ready(); final anchor = JointAnchor(); await game.ensureAdd(anchor); expect(anchor.body.bodyType, equals(BodyType.static)); }, ); }); group('fixtures', () { flameTester.test( 'has none', (game) async { final anchor = JointAnchor(); await game.ensureAdd(anchor); expect(anchor.body.fixtures, isEmpty); }, ); }); }); }
pinball/packages/pinball_components/test/src/components/joint_anchor_test.dart/0
{'file_path': 'pinball/packages/pinball_components/test/src/components/joint_anchor_test.dart', 'repo_id': 'pinball', 'token_count': 532}
// 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/foundation.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:pinball_components/pinball_components.dart'; class _TestGame extends Forge2DGame { Future<void> pump( PlungerKeyControllingBehavior child, { PlungerCubit? plungerBloc, }) async { final plunger = Plunger.test(); await ensureAdd(plunger); return plunger.ensureAdd( FlameBlocProvider<PlungerCubit, PlungerState>.value( value: plungerBloc ?? _MockPlungerCubit(), children: [child], ), ); } } class _MockRawKeyDownEvent extends Mock implements RawKeyDownEvent { @override String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) { return super.toString(); } } class _MockRawKeyUpEvent extends Mock implements RawKeyUpEvent { @override String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) { return super.toString(); } } class _MockPlungerCubit extends Mock implements PlungerCubit {} void main() { TestWidgetsFlutterBinding.ensureInitialized(); final flameTester = FlameTester(_TestGame.new); group('PlungerKeyControllingBehavior', () { test('can be instantiated', () { expect( PlungerKeyControllingBehavior(), isA<PlungerKeyControllingBehavior>(), ); }); flameTester.test('can be loaded', (game) async { final behavior = PlungerKeyControllingBehavior(); await game.pump(behavior); expect(game.descendants(), contains(behavior)); }); group('onKeyEvent', () { late PlungerCubit plungerBloc; setUp(() { plungerBloc = _MockPlungerCubit(); }); group('pulls when', () { flameTester.test( 'down arrow is pressed', (game) async { final behavior = PlungerKeyControllingBehavior(); await game.pump( behavior, plungerBloc: plungerBloc, ); final event = _MockRawKeyDownEvent(); when(() => event.logicalKey).thenReturn( LogicalKeyboardKey.arrowDown, ); behavior.onKeyEvent(event, {}); verify(() => plungerBloc.pulled()).called(1); }, ); flameTester.test( '"s" is pressed', (game) async { final behavior = PlungerKeyControllingBehavior(); await game.pump( behavior, plungerBloc: plungerBloc, ); final event = _MockRawKeyDownEvent(); when(() => event.logicalKey).thenReturn( LogicalKeyboardKey.keyS, ); behavior.onKeyEvent(event, {}); verify(() => plungerBloc.pulled()).called(1); }, ); flameTester.test( 'space is pressed', (game) async { final behavior = PlungerKeyControllingBehavior(); await game.pump( behavior, plungerBloc: plungerBloc, ); final event = _MockRawKeyDownEvent(); when(() => event.logicalKey).thenReturn( LogicalKeyboardKey.space, ); behavior.onKeyEvent(event, {}); verify(() => plungerBloc.pulled()).called(1); }, ); }); group('releases when', () { flameTester.test( 'down arrow is released', (game) async { final behavior = PlungerKeyControllingBehavior(); await game.pump( behavior, plungerBloc: plungerBloc, ); final event = _MockRawKeyUpEvent(); when(() => event.logicalKey).thenReturn( LogicalKeyboardKey.arrowDown, ); behavior.onKeyEvent(event, {}); verify(() => plungerBloc.released()).called(1); }, ); flameTester.test( '"s" is released', (game) async { final behavior = PlungerKeyControllingBehavior(); await game.pump( behavior, plungerBloc: plungerBloc, ); final event = _MockRawKeyUpEvent(); when(() => event.logicalKey).thenReturn( LogicalKeyboardKey.keyS, ); behavior.onKeyEvent(event, {}); verify(() => plungerBloc.released()).called(1); }, ); flameTester.test( 'space is released', (game) async { final behavior = PlungerKeyControllingBehavior(); await game.pump( behavior, plungerBloc: plungerBloc, ); final event = _MockRawKeyUpEvent(); when(() => event.logicalKey).thenReturn( LogicalKeyboardKey.space, ); behavior.onKeyEvent(event, {}); verify(() => plungerBloc.released()).called(1); }, ); }); }); }); }
pinball/packages/pinball_components/test/src/components/plunger/behaviors/plunger_key_controlling_behavior_test.dart/0
{'file_path': 'pinball/packages/pinball_components/test/src/components/plunger/behaviors/plunger_key_controlling_behavior_test.dart', 'repo_id': 'pinball', 'token_count': 2536}
// 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 'package:pinball_components/src/components/bumping_behavior.dart'; import '../../helpers/helpers.dart'; void main() { group('Slingshot', () { final assets = [ Assets.images.slingshot.upper.keyName, Assets.images.slingshot.lower.keyName, ]; final flameTester = FlameTester(() => TestGame(assets)); flameTester.test('loads correctly', (game) async { final component = Slingshots(); 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(Slingshots()); game.camera.followVector2(Vector2.zero()); await game.ready(); await tester.pump(); }, verify: (game, tester) async { await expectLater( find.byGame<TestGame>(), matchesGoldenFile('golden/slingshots.png'), ); }, ); flameTester.test('adds BumpingBehavior', (game) async { final slingshots = Slingshots(); await game.ensureAdd(slingshots); for (final slingshot in slingshots.children) { expect(slingshot.firstChild<BumpingBehavior>(), isNotNull); } }); }); }
pinball/packages/pinball_components/test/src/components/slingshot_test.dart/0
{'file_path': 'pinball/packages/pinball_components/test/src/components/slingshot_test.dart', 'repo_id': 'pinball', 'token_count': 624}
import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:geometry/geometry.dart'; /// {@template arc_shape} /// Creates an arc. /// {@endtemplate} class ArcShape extends ChainShape { /// {@macro arc_shape} ArcShape({ required this.center, required this.arcRadius, required this.angle, this.rotation = 0, }) { createChain( calculateArc( center: center, radius: arcRadius, angle: angle, offsetAngle: rotation, ), ); } /// The center of the arc. final Vector2 center; /// The radius of the arc. final double arcRadius; /// Specifies the size of the arc, in radians. /// /// For example, two pi returns a complete circumference. final double angle; /// Angle in radians to rotate the arc around its [center]. final double rotation; }
pinball/packages/pinball_flame/lib/src/shapes/arc_shape.dart/0
{'file_path': 'pinball/packages/pinball_flame/lib/src/shapes/arc_shape.dart', 'repo_id': 'pinball', 'token_count': 303}
// ignore_for_file: cascade_invocations, one_member_abstracts import 'package:flame/game.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:pinball_flame/pinball_flame.dart'; class _TestGame extends FlameGame { bool pressed = false; @override Future<void>? onLoad() async { await super.onLoad(); await add( KeyboardInputController( keyUp: { LogicalKeyboardKey.enter: () { pressed = true; return true; }, LogicalKeyboardKey.escape: () { return false; }, }, ), ); } } abstract class _KeyCall { bool onCall(); } class _MockKeyCall extends Mock implements _KeyCall {} class _MockRawKeyUpEvent extends Mock implements RawKeyUpEvent { @override String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) { return super.toString(); } } RawKeyUpEvent _mockKeyUp(LogicalKeyboardKey key) { final event = _MockRawKeyUpEvent(); when(() => event.logicalKey).thenReturn(key); return event; } void main() { group('KeyboardInputController', () { test('calls registered handlers', () { final stub = _MockKeyCall(); when(stub.onCall).thenReturn(true); final input = KeyboardInputController( keyUp: { LogicalKeyboardKey.arrowUp: stub.onCall, }, ); input.onKeyEvent(_mockKeyUp(LogicalKeyboardKey.arrowUp), {}); verify(stub.onCall).called(1); }); test( 'returns false the handler return value', () { final stub = _MockKeyCall(); when(stub.onCall).thenReturn(false); final input = KeyboardInputController( keyUp: { LogicalKeyboardKey.arrowUp: stub.onCall, }, ); expect( input.onKeyEvent(_mockKeyUp(LogicalKeyboardKey.arrowUp), {}), isFalse, ); }, ); test( 'returns true (allowing event to bubble) when no handler is registered', () { final stub = _MockKeyCall(); when(stub.onCall).thenReturn(true); final input = KeyboardInputController(); expect( input.onKeyEvent(_mockKeyUp(LogicalKeyboardKey.arrowUp), {}), isTrue, ); }, ); }); group('VirtualKeyEvents', () { final flameTester = FlameTester(_TestGame.new); group('onVirtualKeyUp', () { flameTester.test('triggers the event', (game) async { await game.ready(); game.triggerVirtualKeyUp(LogicalKeyboardKey.enter); expect(game.pressed, isTrue); }); }); }); }
pinball/packages/pinball_flame/test/src/keyboard_input_controller_test.dart/0
{'file_path': 'pinball/packages/pinball_flame/test/src/keyboard_input_controller_test.dart', 'repo_id': 'pinball', 'token_count': 1182}
import 'package:flutter/material.dart'; import 'package:pinball_ui/pinball_ui.dart'; /// {@template pinball_dialog} /// Pinball-themed dialog. /// {@endtemplate} class PinballDialog extends StatelessWidget { /// {@macro pinball_dialog} const PinballDialog({ Key? key, required this.title, required this.child, this.subtitle, }) : super(key: key); /// Title shown in the dialog. final String title; /// Optional subtitle shown below the [title]. final String? subtitle; /// Body of the dialog. final Widget child; @override Widget build(BuildContext context) { final height = MediaQuery.of(context).size.height * 0.5; return Center( child: SizedBox( height: height, width: height * 1.4, child: PixelatedDecoration( header: subtitle != null ? _TitleAndSubtitle(title: title, subtitle: subtitle!) : _Title(title: title), body: child, ), ), ); } } class _Title extends StatelessWidget { const _Title({Key? key, required this.title}) : super(key: key); final String title; @override Widget build(BuildContext context) => Text( title, style: Theme.of(context).textTheme.headline3!.copyWith( fontWeight: FontWeight.bold, color: PinballColors.darkBlue, ), overflow: TextOverflow.ellipsis, textAlign: TextAlign.center, ); } class _TitleAndSubtitle extends StatelessWidget { const _TitleAndSubtitle({ Key? key, required this.title, required this.subtitle, }) : super(key: key); final String title; final String subtitle; @override Widget build(BuildContext context) { final textTheme = Theme.of(context).textTheme; return Column( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisAlignment: MainAxisAlignment.center, children: [ _Title(title: title), Text( subtitle, overflow: TextOverflow.ellipsis, textAlign: TextAlign.center, style: textTheme.headline3!.copyWith(fontWeight: FontWeight.normal), ), ], ); } }
pinball/packages/pinball_ui/lib/src/dialog/pinball_dialog.dart/0
{'file_path': 'pinball/packages/pinball_ui/lib/src/dialog/pinball_dialog.dart', 'repo_id': 'pinball', 'token_count': 873}
import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:pinball_ui/pinball_ui.dart'; import 'package:plugin_platform_interface/plugin_platform_interface.dart'; class _MockUrlLauncher extends Mock with MockPlatformInterfaceMixin implements UrlLauncherPlatform {} void main() { late UrlLauncherPlatform urlLauncher; setUp(() { urlLauncher = _MockUrlLauncher(); UrlLauncherPlatform.instance = urlLauncher; }); group('openLink', () { test('launches the link', () async { when( () => urlLauncher.canLaunch(any()), ).thenAnswer( (_) async => true, ); when( () => urlLauncher.launch( any(), useSafariVC: any(named: 'useSafariVC'), useWebView: any(named: 'useWebView'), enableJavaScript: any(named: 'enableJavaScript'), enableDomStorage: any(named: 'enableDomStorage'), universalLinksOnly: any(named: 'universalLinksOnly'), headers: any(named: 'headers'), ), ).thenAnswer( (_) async => true, ); await openLink('uri'); verify( () => urlLauncher.launch( any(), useSafariVC: any(named: 'useSafariVC'), useWebView: any(named: 'useWebView'), enableJavaScript: any(named: 'enableJavaScript'), enableDomStorage: any(named: 'enableDomStorage'), universalLinksOnly: any(named: 'universalLinksOnly'), headers: any(named: 'headers'), ), ); }); test('executes the onError callback when it cannot launch', () async { var wasCalled = false; when( () => urlLauncher.canLaunch(any()), ).thenAnswer( (_) async => false, ); when( () => urlLauncher.launch( any(), useSafariVC: any(named: 'useSafariVC'), useWebView: any(named: 'useWebView'), enableJavaScript: any(named: 'enableJavaScript'), enableDomStorage: any(named: 'enableDomStorage'), universalLinksOnly: any(named: 'universalLinksOnly'), headers: any(named: 'headers'), ), ).thenAnswer( (_) async => true, ); await openLink( 'url', onError: () { wasCalled = true; }, ); await expectLater(wasCalled, isTrue); }); }); }
pinball/packages/pinball_ui/test/src/external_links/external_links_test.dart/0
{'file_path': 'pinball/packages/pinball_ui/test/src/external_links/external_links_test.dart', 'repo_id': 'pinball', 'token_count': 1065}