text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
buildFlags: _pluginToolsConfigGlobalKey: - "--no-tree-shake-icons" - "--dart-define=buildmode=testing"
packages/packages/shared_preferences/shared_preferences_android/example/.pluginToolsConfig.yaml/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences_android/example/.pluginToolsConfig.yaml", "repo_id": "packages", "token_count": 45 }
1,112
// 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. // Autogenerated from Pigeon (v10.1.6), do not edit directly. // See also: https://pub.dev/packages/pigeon // ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import import 'dart:async'; import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; import 'package:flutter/services.dart'; class UserDefaultsApi { /// Constructor for [UserDefaultsApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. UserDefaultsApi({BinaryMessenger? binaryMessenger}) : _binaryMessenger = binaryMessenger; final BinaryMessenger? _binaryMessenger; static const MessageCodec<Object?> codec = StandardMessageCodec(); Future<void> remove(String arg_key) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.shared_preferences_foundation.UserDefaultsApi.remove', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_key]) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else { return; } } Future<void> setBool(String arg_key, bool arg_value) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.shared_preferences_foundation.UserDefaultsApi.setBool', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_key, arg_value]) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else { return; } } Future<void> setDouble(String arg_key, double arg_value) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.shared_preferences_foundation.UserDefaultsApi.setDouble', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_key, arg_value]) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else { return; } } Future<void> setValue(String arg_key, Object arg_value) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.shared_preferences_foundation.UserDefaultsApi.setValue', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_key, arg_value]) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else { return; } } Future<Map<String?, Object?>> getAll( String arg_prefix, List<String?>? arg_allowList) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.shared_preferences_foundation.UserDefaultsApi.getAll', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel .send(<Object?>[arg_prefix, arg_allowList]) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (replyList[0] as Map<Object?, Object?>?)!.cast<String?, Object?>(); } } Future<bool> clear(String arg_prefix, List<String?>? arg_allowList) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.shared_preferences_foundation.UserDefaultsApi.clear', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel .send(<Object?>[arg_prefix, arg_allowList]) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (replyList[0] as bool?)!; } } }
packages/packages/shared_preferences/shared_preferences_foundation/lib/messages.g.dart/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences_foundation/lib/messages.g.dart", "repo_id": "packages", "token_count": 2479 }
1,113
// 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_linux/shared_preferences_linux.dart'; import 'package:shared_preferences_platform_interface/types.dart'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); group('SharedPreferencesLinux', () { late SharedPreferencesLinux preferences; const Map<String, Object> flutterTestValues = <String, Object>{ 'flutter.String': 'hello world', 'flutter.Bool': true, 'flutter.Int': 42, 'flutter.Double': 3.14159, 'flutter.StringList': <String>['foo', 'bar'], }; const Map<String, Object> prefixTestValues = <String, Object>{ 'prefix.String': 'hello world', 'prefix.Bool': true, 'prefix.Int': 42, 'prefix.Double': 3.14159, 'prefix.StringList': <String>['foo', 'bar'], }; const Map<String, Object> nonPrefixTestValues = <String, Object>{ 'String': 'hello world', 'Bool': true, 'Int': 42, 'Double': 3.14159, 'StringList': <String>['foo', 'bar'], }; final Map<String, Object> allTestValues = <String, Object>{}; allTestValues.addAll(flutterTestValues); allTestValues.addAll(prefixTestValues); allTestValues.addAll(nonPrefixTestValues); Future<void> addData() async { await preferences.setValue('String', 'String', allTestValues['String']!); await preferences.setValue('Bool', 'Bool', allTestValues['Bool']!); await preferences.setValue('Int', 'Int', allTestValues['Int']!); await preferences.setValue('Double', 'Double', allTestValues['Double']!); await preferences.setValue( 'StringList', 'StringList', allTestValues['StringList']!); await preferences.setValue( 'String', 'prefix.String', allTestValues['prefix.String']!); await preferences.setValue( 'Bool', 'prefix.Bool', allTestValues['prefix.Bool']!); await preferences.setValue( 'Int', 'prefix.Int', allTestValues['prefix.Int']!); await preferences.setValue( 'Double', 'prefix.Double', allTestValues['prefix.Double']!); await preferences.setValue('StringList', 'prefix.StringList', allTestValues['prefix.StringList']!); await preferences.setValue( 'String', 'flutter.String', allTestValues['flutter.String']!); await preferences.setValue( 'Bool', 'flutter.Bool', allTestValues['flutter.Bool']!); await preferences.setValue( 'Int', 'flutter.Int', allTestValues['flutter.Int']!); await preferences.setValue( 'Double', 'flutter.Double', allTestValues['flutter.Double']!); await preferences.setValue('StringList', 'flutter.StringList', allTestValues['flutter.StringList']!); } setUp(() async { preferences = SharedPreferencesLinux(); await addData(); }); tearDown(() async { await preferences.clearWithParameters( ClearParameters( filter: PreferencesFilter(prefix: ''), ), ); }); testWidgets('getAll', (WidgetTester _) async { final Map<String, Object> values = await preferences.getAll(); expect(values['flutter.String'], allTestValues['flutter.String']); expect(values['flutter.Bool'], allTestValues['flutter.Bool']); expect(values['flutter.Int'], allTestValues['flutter.Int']); expect(values['flutter.Double'], allTestValues['flutter.Double']); expect(values['flutter.StringList'], allTestValues['flutter.StringList']); }); group('withPrefix', () { testWidgets('remove', (WidgetTester _) async { const String key = 'flutter.String'; await preferences.remove(key); final Map<String, Object> values = await preferences.getAllWithPrefix(''); expect(values[key], isNull); }); testWidgets('clear', (WidgetTester _) async { await preferences.clear(); final Map<String, Object> values = await preferences.getAll(); expect(values['flutter.String'], null); expect(values['flutter.Bool'], null); expect(values['flutter.Int'], null); expect(values['flutter.Double'], null); expect(values['flutter.StringList'], null); }); testWidgets('get all with prefix', (WidgetTester _) async { final Map<String, Object> values = await preferences.getAllWithPrefix('prefix.'); expect(values['prefix.String'], allTestValues['prefix.String']); expect(values['prefix.Bool'], allTestValues['prefix.Bool']); expect(values['prefix.Int'], allTestValues['prefix.Int']); expect(values['prefix.Double'], allTestValues['prefix.Double']); expect(values['prefix.StringList'], allTestValues['prefix.StringList']); }); testWidgets('getAllWithNoPrefix', (WidgetTester _) async { final Map<String, Object> values = await preferences.getAllWithPrefix(''); expect(values['String'], allTestValues['String']); expect(values['Bool'], allTestValues['Bool']); expect(values['Int'], allTestValues['Int']); expect(values['Double'], allTestValues['Double']); expect(values['StringList'], allTestValues['StringList']); expect(values['flutter.String'], allTestValues['flutter.String']); expect(values['flutter.Bool'], allTestValues['flutter.Bool']); expect(values['flutter.Int'], allTestValues['flutter.Int']); expect(values['flutter.Double'], allTestValues['flutter.Double']); expect( values['flutter.StringList'], allTestValues['flutter.StringList']); }); testWidgets('clearWithPrefix', (WidgetTester _) async { await preferences.clearWithPrefix('prefix.'); Map<String, Object> values = await preferences.getAllWithPrefix('prefix.'); expect(values['prefix.String'], null); expect(values['prefix.Bool'], null); expect(values['prefix.Int'], null); expect(values['prefix.Double'], null); expect(values['prefix.StringList'], null); values = await preferences.getAllWithPrefix('flutter.'); expect(values['flutter.String'], allTestValues['flutter.String']); expect(values['flutter.Bool'], allTestValues['flutter.Bool']); expect(values['flutter.Int'], allTestValues['flutter.Int']); expect(values['flutter.Double'], allTestValues['flutter.Double']); expect( values['flutter.StringList'], allTestValues['flutter.StringList']); }); testWidgets('clearWithNoPrefix', (WidgetTester _) async { await preferences.clearWithPrefix(''); final Map<String, Object> values = await preferences.getAllWithPrefix(''); expect(values['String'], null); expect(values['Bool'], null); expect(values['Int'], null); expect(values['Double'], null); expect(values['StringList'], null); expect(values['flutter.String'], null); expect(values['flutter.Bool'], null); expect(values['flutter.Int'], null); expect(values['flutter.Double'], null); expect(values['flutter.StringList'], null); }); }); group('withParameters', () { testWidgets('remove', (WidgetTester _) async { const String key = 'flutter.String'; await preferences.remove(key); final Map<String, Object> values = await preferences.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: ''), ), ); expect(values[key], isNull); }); testWidgets('clear', (WidgetTester _) async { await preferences.clear(); final Map<String, Object> values = await preferences.getAll(); expect(values['flutter.String'], null); expect(values['flutter.Bool'], null); expect(values['flutter.Int'], null); expect(values['flutter.Double'], null); expect(values['flutter.StringList'], null); }); testWidgets('get all with prefix', (WidgetTester _) async { final Map<String, Object> values = await preferences.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: 'prefix.'), ), ); expect(values['prefix.String'], allTestValues['prefix.String']); expect(values['prefix.Bool'], allTestValues['prefix.Bool']); expect(values['prefix.Int'], allTestValues['prefix.Int']); expect(values['prefix.Double'], allTestValues['prefix.Double']); expect(values['prefix.StringList'], allTestValues['prefix.StringList']); }); testWidgets('get all with allow list', (WidgetTester _) async { final Map<String, Object> values = await preferences.getAllWithParameters( GetAllParameters( filter: PreferencesFilter( prefix: 'prefix.', allowList: <String>{'prefix.String'}, ), ), ); expect(values['prefix.String'], allTestValues['prefix.String']); expect(values['prefix.Bool'], null); expect(values['prefix.Int'], null); expect(values['prefix.Double'], null); expect(values['prefix.StringList'], null); }); testWidgets('getAllWithNoPrefix', (WidgetTester _) async { final Map<String, Object> values = await preferences.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: ''), ), ); expect(values['String'], allTestValues['String']); expect(values['Bool'], allTestValues['Bool']); expect(values['Int'], allTestValues['Int']); expect(values['Double'], allTestValues['Double']); expect(values['StringList'], allTestValues['StringList']); expect(values['flutter.String'], allTestValues['flutter.String']); expect(values['flutter.Bool'], allTestValues['flutter.Bool']); expect(values['flutter.Int'], allTestValues['flutter.Int']); expect(values['flutter.Double'], allTestValues['flutter.Double']); expect( values['flutter.StringList'], allTestValues['flutter.StringList']); }); testWidgets('clearWithParameters', (WidgetTester _) async { await preferences.clearWithParameters( ClearParameters( filter: PreferencesFilter(prefix: 'prefix.'), ), ); Map<String, Object> values = await preferences.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: 'prefix.'), ), ); expect(values['prefix.String'], null); expect(values['prefix.Bool'], null); expect(values['prefix.Int'], null); expect(values['prefix.Double'], null); expect(values['prefix.StringList'], null); values = await preferences.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: 'flutter.'), ), ); expect(values['flutter.String'], allTestValues['flutter.String']); expect(values['flutter.Bool'], allTestValues['flutter.Bool']); expect(values['flutter.Int'], allTestValues['flutter.Int']); expect(values['flutter.Double'], allTestValues['flutter.Double']); expect( values['flutter.StringList'], allTestValues['flutter.StringList']); }); testWidgets('clearWithParameters with allow list', (WidgetTester _) async { await addData(); await preferences.clearWithParameters( ClearParameters( filter: PreferencesFilter( prefix: 'prefix.', allowList: <String>{'prefix.StringList'}, ), ), ); Map<String, Object> values = await preferences.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: 'prefix.'), ), ); expect(values['prefix.String'], allTestValues['prefix.String']); expect(values['prefix.Bool'], allTestValues['prefix.Bool']); expect(values['prefix.Int'], allTestValues['prefix.Int']); expect(values['prefix.Double'], allTestValues['prefix.Double']); expect(values['prefix.StringList'], null); values = await preferences.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: 'flutter.'), ), ); expect(values['flutter.String'], allTestValues['flutter.String']); expect(values['flutter.Bool'], allTestValues['flutter.Bool']); expect(values['flutter.Int'], allTestValues['flutter.Int']); expect(values['flutter.Double'], allTestValues['flutter.Double']); expect( values['flutter.StringList'], allTestValues['flutter.StringList']); }); testWidgets('clearWithNoPrefix', (WidgetTester _) async { await preferences.clearWithParameters( ClearParameters( filter: PreferencesFilter(prefix: ''), ), ); final Map<String, Object> values = await preferences.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: ''), ), ); expect(values['String'], null); expect(values['Bool'], null); expect(values['Int'], null); expect(values['Double'], null); expect(values['StringList'], null); expect(values['flutter.String'], null); expect(values['flutter.Bool'], null); expect(values['flutter.Int'], null); expect(values['flutter.Double'], null); expect(values['flutter.StringList'], null); }); }); }); }
packages/packages/shared_preferences/shared_preferences_linux/example/integration_test/shared_preferences_test.dart/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences_linux/example/integration_test/shared_preferences_test.dart", "repo_id": "packages", "token_count": 5724 }
1,114
// 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 file exists solely to host compiled excerpts for README.md, and is not // intended for use as an actual example application. // ignore_for_file: avoid_print import 'dart:typed_data'; import 'package:standard_message_codec/standard_message_codec.dart'; // #docregion Encoding void main() { final ByteData? data = const StandardMessageCodec().encodeMessage(<Object, Object>{ 'foo': true, 3: 'fizz', }); print('The encoded message is $data'); } // #enddocregion Encoding
packages/packages/standard_message_codec/example/lib/readme_excerpts.dart/0
{ "file_path": "packages/packages/standard_message_codec/example/lib/readme_excerpts.dart", "repo_id": "packages", "token_count": 204 }
1,115
## 6.2.5 * Removes use of deprecated `renderView` API. ## 6.2.4 * Updates support matrix in README to indicate that iOS 11 is no longer supported. * Clients on versions of Flutter that still support iOS 11 can continue to use this package with iOS 11, but will not receive any further updates to the iOS implementation. * Fixes a grammar error in the comments of `launchUrl` method. ## 6.2.3 * Updates minimum required plugin_platform_interface version to 2.1.7. ## 6.2.2 * Adds a link about web limitations to the `url_launcher_web` package in the `url_launcher` `README.md` and `launchUrl` method. ## 6.2.1 * Fixes incorrect types in `supportsLaunchMode` and `supportsCloseForLaunchMode`. ## 6.2.0 _Retracted due to incorrect types in new APIs._ * Adds `supportsLaunchMode` for checking whether the current platform supports a given launch mode, to allow clients that will only work with specific modes to avoid fallback to a different mode. * Adds `supportsCloseForLaunchMode` to allow checking programatically if a launched URL will be able to be closed. Previously the documented behvaior was that it worked only with the `inAppWebView` launch mode, but this is no longer true on all platforms with the addition of `inAppBrowserView`. * Updates the documention for `launchUrl` to clarify that clients should not rely on any specific behavior of the `platformDefault` launch mode. Changes to the handling of `platformDefault`, such as Android's recent change from `inAppWebView` to the new `inAppBrowserView`, are not considered breaking. * Updates minimum supported SDK version to Flutter 3.13. ## 6.1.14 * Updates documentation to mention support for Android Custom Tabs. ## 6.1.13 * Adds pub topics to package metadata. * Updates minimum supported SDK version to Flutter 3.7/Dart 2.19. ## 6.1.12 * Removes the use of `canLaunchUrl` in `Link`, to avoid issues on platforms where `canLaunchUrl` is unreliable or requires permissions. * Updates minimum supported macOS version to 10.14. * Fixes stale ignore: prefer_const_constructors. * Updates minimum supported SDK version to Flutter 3.10/Dart 3.0. ## 6.1.11 * Fixes some url_launcher docs that were missing the null operator (?). * Updates minimum Flutter version to 3.3. * Aligns Dart and Flutter SDK constraints. ## 6.1.10 * Updates links for the merge of flutter/plugins into flutter/packages. ## 6.1.9 * Updates minimum Flutter version to 3.0. * Updates iOS minimum version in README. ## 6.1.8 * Updates code for stricter lint checks. ## 6.1.7 * Updates code for new analysis options. ## 6.1.6 * Updates imports for `prefer_relative_imports`. * Updates minimum Flutter version to 2.10. * Fixes avoid_redundant_argument_values lint warnings and minor typos. ## 6.1.5 * Migrates `README.md` examples to the [`code-excerpt` system](https://github.com/flutter/flutter/wiki/Contributing-to-Plugins-and-Packages#readme-code). ## 6.1.4 * Adopts new platform interface method for launching URLs. * Ignores unnecessary import warnings in preparation for [upcoming Flutter changes](https://github.com/flutter/flutter/pull/105648). ## 6.1.3 * Updates README section about query permissions to better reflect changes to `canLaunchUrl` recommendations. ## 6.1.2 * Minor fixes for new analysis options. ## 6.1.1 * Removes unnecessary imports. * Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors lint warnings. ## 6.1.0 * Introduces new `launchUrl` and `canLaunchUrl` APIs; `launch` and `canLaunch` are now deprecated. These new APIs: * replace the `String` URL argument with a `Uri`, to prevent common issues with providing invalid URL strings. * replace `forceSafariVC` and `forceWebView` with `LaunchMode`, which makes the API platform-neutral, and standardizes the default behavior between Android and iOS. * move web view configuration options into a new `WebViewConfiguration` object. The default behavior for JavaScript and DOM storage is now enabled rather than disabled. * Also deprecates `closeWebView` in favor of `closeInAppWebView` to clarify that it is specific to the in-app web view launch option. * Adds OS version support information to README. * Reorganizes and clarifies README. ## 6.0.20 * Fixes a typo in `default_package` registration for Windows, macOS, and Linux. ## 6.0.19 * Updates README: * Adds description for `file` scheme usage. * Updates `Uri` class link to SDK documentation. ## 6.0.18 * Removes dependency on `meta`. ## 6.0.17 * Updates code for new analysis options. ## 6.0.16 * Moves Android and iOS implementations to federated packages. ## 6.0.15 * Updates README: * Improves organization. * Clarifies how `canLaunch` should be used. * Updates example application to demonstrate intended use of `canLaunch`. ## 6.0.14 * Updates readme to indicate that sending SMS messages on Android 11 requires to add a query to AndroidManifest.xml. * Fixes integration tests. * Updates example app Android compileSdkVersion to 31. ## 6.0.13 * Fixed extracting browser headers when they are null error. ## 6.0.12 * Fixed an error where 'launch' method of url_launcher would cause an error if the provided URL was not valid by RFC 3986. ## 6.0.11 * Update minimum Flutter SDK to 2.5 and iOS deployment target to 9.0. * Updated Android lint settings. ## 6.0.10 * Remove references to the Android v1 embedding. ## 6.0.9 * Silenced warnings that may occur during build when using a very recent version of Flutter relating to null safety. ## 6.0.8 * Adding API level 30 required package visibility configuration to the example's AndroidManifest.xml and README * Fix test button check for iOS 15. ## 6.0.7 * Update the README to describe a workaround to the `Uri` query encoding bug. ## 6.0.6 * Require `url_launcher_platform_interface` 2.0.3. This fixes an issue where 6.0.5 could fail to compile in some projects due to internal changes in that version that were not compatible with earlier versions of `url_launcher_platform_interface`. ## 6.0.5 * Add iOS unit and UI integration test targets. * Add a `Link` widget to the example app. ## 6.0.4 * Migrate maven repository from jcenter to mavenCentral. ## 6.0.3 * Update README notes about URL schemes on iOS ## 6.0.2 * Update platform_plugin_interface version requirement. ## 6.0.1 * Update result to `True` on iOS when the url was loaded successfully. * Added a README note about required applications. ## 6.0.0 * Migrate to null safety. * Fix outdated links across a number of markdown files ([#3276](https://github.com/flutter/plugins/pull/3276)) * Update the example app: remove the deprecated `RaisedButton` and `FlatButton` widgets. * Correct statement in description about which platforms url_launcher supports. ## 5.7.13 * Update Flutter SDK constraint. ## 5.7.12 * Updated code sample in `README.md` ## 5.7.11 * Update integration test examples to use `testWidgets` instead of `test`. ## 5.7.10 * Update Dart SDK constraint in example. ## 5.7.9 * Check in windows/ directory for example/ ## 5.7.8 * Fixed a situation where an app would crash if the url_launcher’s `launch` method can’t find an app to open the provided url. It will now throw a clear Dart PlatformException. ## 5.7.7 * Introduce the Link widget with an implementation for native platforms. ## 5.7.6 * Suppress deprecation warning on the `shouldOverrideUrlLoading` method on Android of the `FlutterWebChromeClient` class. ## 5.7.5 * Improved documentation of the `headers` parameter. ## 5.7.4 * Update android compileSdkVersion to 29. ## 5.7.3 * Check in linux/ directory for example/ ## 5.7.2 * Add API documentation explaining the [canLaunch] method returns `false` if package visibility (Android API 30) is not managed correctly. ## 5.7.1 * Keep handling deprecated Android v1 classes for backward compatibility. ## 5.7.0 * Handle WebView multi-window support. ## 5.6.0 * Support Windows by default. ## 5.5.3 * Suppress deprecation warning on the `shouldOverrideUrlLoading` method on Android. ## 5.5.2 * Depend explicitly on the `platform_interface` package that adds the `webOnlyWindowName` parameter. ## 5.5.1 * Added webOnlyWindowName parameter to launch() ## 5.5.0 * Support Linux by default. ## 5.4.11 * Add documentation in README suggesting how to properly encode urls with special characters. ## 5.4.10 * Post-v2 Android embedding cleanups. ## 5.4.9 * Update README. ## 5.4.8 * Initialize `previousAutomaticSystemUiAdjustment` in launch method. ## 5.4.7 * Update lower bound of dart dependency to 2.1.0. ## 5.4.6 * Add `web` to the example app. ## 5.4.5 * Remove Android dependencies fallback. * Require Flutter SDK 1.12.13+hotfix.5 or greater. * Fix CocoaPods podspec lint warnings. ## 5.4.4 * Replace deprecated `getFlutterEngine` call on Android. ## 5.4.3 * Fixed the launchUniversalLinkIos method. ## 5.4.2 * Make the pedantic dev_dependency explicit. ## 5.4.1 * Update unit tests to work with the PlatformInterface from package `plugin_platform_interface`. ## 5.4.0 * Support macOS by default. ## 5.3.0 * Support web by default. * Use the new plugins pubspec schema. ## 5.2.7 * Minor unit test changes and added a lint for public DartDocs. ## 5.2.6 * Remove AndroidX warnings. ## 5.2.5 * Include lifecycle dependency as a compileOnly one on Android to resolve potential version conflicts with other transitive libraries. ## 5.2.4 * Use `package:url_launcher_platform_interface` to get the platform-specific implementation. ## 5.2.3 * Android: Use android.arch.lifecycle instead of androidx.lifecycle:lifecycle in `build.gradle` to support apps that has not been migrated to AndroidX. ## 5.2.2 * Re-land embedder v2 support with correct Flutter SDK constraints. ## 5.2.1 * Revert the migration since the Flutter dependency was too low. ## 5.2.0 * Migrate the plugin to use the V2 Android engine embedding. This shouldn't affect existing functionality. Plugin authors who use the V2 embedding can now instantiate the plugin and expect that it correctly responds to app lifecycle changes. ## 5.1.7 * Define clang module for iOS. ## 5.1.6 * Fixes bug where androidx app won't build with this plugin by enabling androidx and jetifier in the android `gradle.properties`. ## 5.1.5 * Update homepage url after moving to federated directory. ## 5.1.4 * Update and migrate iOS example project. ## 5.1.3 * Always launch url from the top most UIViewController in iOS. ## 5.1.2 * Update AGP and gradle. * Split plugin and WebViewActivity class files. ## 5.1.1 * Suppress a handled deprecation warning on iOS ## 5.1.0 * Add `headers` field to enable headers in the Android implementation. ## 5.0.5 * Add `enableDomStorage` field to `launch` to enable DOM storage in Android WebView. ## 5.0.4 * Update Dart code to conform to current Dart formatter. ## 5.0.3 * Add missing template type parameter to `invokeMethod` calls. * Bump minimum Flutter version to 1.5.0. * Replace invokeMethod with invokeMapMethod wherever necessary. ## 5.0.2 * Fixes `closeWebView` failure on iOS. ## 5.0.1 * Log a more detailed warning at build time about the previous AndroidX migration. ## 5.0.0 * **Breaking change**. Migrate from the deprecated original Android Support Library to AndroidX. This shouldn't result in any functional changes, but it requires any Android apps using this plugin to [also migrate](https://developer.android.com/jetpack/androidx/migrate) if they're using the original support library. This was originally incorrectly pushed in the `4.2.0` update. ## 4.2.0+3 * **Revert the breaking 4.2.0 update**. 4.2.0 was known to be breaking and should have incremented the major version number instead of the minor. This revert is in and of itself breaking for anyone that has already migrated however. Anyone who has already migrated their app to AndroidX should immediately update to `5.0.0` instead. That's the correctly versioned new push of `4.2.0`. ## 4.2.0+2 * Updated `launch` to use async and await, fixed the incorrect return value by `launch` method. ## 4.2.0+1 * Refactored the Java and Objective-C code. Replaced instance variables with properties in Objective-C. ## 4.2.0 * **BAD**. This was a breaking change that was incorrectly published on a minor version upgrade, should never have happened. Reverted by 4.2.0+3. * **Breaking change**. Migrate from the deprecated original Android Support Library to AndroidX. This shouldn't result in any functional changes, but it requires any Android apps using this plugin to [also migrate](https://developer.android.com/jetpack/androidx/migrate) if they're using the original support library. ## 4.1.0+1 * This is just a version bump to republish as 4.1.0 was published with some dirty local state. ## 4.1.0 * Added `universalLinksOnly` setting. * Updated `launch` to return `Future<bool>`. ## 4.0.3 * Fixed launch url fail for Android: `launch` now assert activity not null and using activity to startActivity. * Fixed `WebViewActivity has leaked IntentReceiver` for Android. ## 4.0.2 * Added `closeWebView` function to programmatically close the current WebView. ## 4.0.1 * Added enableJavaScript field to `launch` to enable javascript in Android WebView. ## 4.0.0 * **Breaking change** Now requires a minimum Flutter version of 0.5.6. * Update to statusBarBrightness field so that the logic runs on the Flutter side. * **Breaking change** statusBarBrightness no longer has a default value. ## 3.0.3 * Added statusBarBrightness field to `launch` to set iOS status bar brightness. ## 3.0.2 * Updated Gradle tooling to match Android Studio 3.1.2. ## 3.0.1 * Fix a crash during Safari view controller dismiss. ## 3.0.0 * **Breaking change**. Set SDK constraints to match the Flutter beta release. ## 2.0.2 * Fixed Dart 2 issue: `launch` now returns `Future<void>` instead of `Future<Null>`. ## 2.0.1 * Simplified and upgraded Android project template to Android SDK 27. * Updated package description. ## 2.0.0 * **Breaking change**. Upgraded to Gradle 4.1 and Android Studio Gradle plugin 3.0.1. Older Flutter projects need to upgrade their Gradle setup as well in order to use this version of the plugin. Instructions can be found [here](https://github.com/flutter/flutter/wiki/Updating-Flutter-projects-to-Gradle-4.1-and-Android-Studio-Gradle-plugin-3.0.1). ## 1.0.3 * Add FLT prefix to iOS types. ## 1.0.2 * Fix handling of URLs in Android WebView. ## 1.0.1 * Support option to launch default browser in iOS. * Parse incoming url and decide on what to open based on scheme. * Support WebView on Android. ## 1.0.0 * iOS plugin presents a Safari view controller instead of switching to the Safari app. ## 0.4.2+5 * Aligned author name with rest of repo. ## 0.4.2+2, 0.4.2+3, 0.4.2+4 * Updated README. ## 0.4.2+1 * Updated README. ## 0.4.2 * Change to README.md. ## 0.4.1 * Upgrade Android SDK Build Tools to 25.0.3. ## 0.4.0 * Upgrade to new plugin registration. ## 0.3.6 * Fix workaround for failing dynamic check in Xcode 7/sdk version 9. ## 0.3.5 * Workaround for failing dynamic check in Xcode 7/sdk version 9. ## 0.3.4 * Add test. ## 0.3.3 * Change to buildToolsVersion. ## 0.3.2 * Change to README.md. ## 0.3.1 * Change to README.md. ## 0.3.0 * Add `canLaunch` method. ## 0.2.0 * Change `launch` to a top-level method instead of a static method in a class. ## 0.1.1 * Change to README.md. ## 0.1.0 * Initial Open Source release.
packages/packages/url_launcher/url_launcher/CHANGELOG.md/0
{ "file_path": "packages/packages/url_launcher/url_launcher/CHANGELOG.md", "repo_id": "packages", "token_count": 4794 }
1,116
org.gradle.jvmargs=-Xmx4G android.useAndroidX=true android.enableJetifier=true
packages/packages/url_launcher/url_launcher/example/android/gradle.properties/0
{ "file_path": "packages/packages/url_launcher/url_launcher/example/android/gradle.properties", "repo_id": "packages", "token_count": 30 }
1,117
#include "../../Flutter/Flutter-Release.xcconfig" #include "Warnings.xcconfig"
packages/packages/url_launcher/url_launcher/example/macos/Runner/Configs/Release.xcconfig/0
{ "file_path": "packages/packages/url_launcher/url_launcher/example/macos/Runner/Configs/Release.xcconfig", "repo_id": "packages", "token_count": 32 }
1,118
// 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:ui'; import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart'; /// Parses the specified URL string and delegates handling of it to the /// underlying platform. /// /// The returned future completes with a [PlatformException] on invalid URLs and /// schemes which cannot be handled, that is when [canLaunch] would complete /// with false. /// /// By default when [forceSafariVC] is unset, the launcher /// opens web URLs in the Safari View Controller, anything else is opened /// using the default handler on the platform. If set to true, it opens the /// URL in the Safari View Controller. If false, the URL is opened in the /// default browser of the phone. Note that to work with universal links on iOS, /// this must be set to false to let the platform's system handle the URL. /// Set this to false if you want to use the cookies/context of the main browser /// of the app (such as SSO flows). This setting will nullify [universalLinksOnly] /// and will always launch a web content in the built-in Safari View Controller regardless /// if the url is a universal link or not. /// /// [universalLinksOnly] is only used in iOS with iOS version >= 10.0. This setting is only validated /// when [forceSafariVC] is set to false. The default value of this setting is false. /// By default (when unset), the launcher will either launch the url in a browser (when the /// url is not a universal link), or launch the respective native app content (when /// the url is a universal link). When set to true, the launcher will only launch /// the content if the url is a universal link and the respective app for the universal /// link is installed on the user's device; otherwise throw a [PlatformException]. /// /// [forceWebView] is an Android only setting. If null or false, the URL is /// always launched with the default browser on device. If set to true, the URL /// is launched in a WebView. Unlike iOS, browser context is shared across /// WebViews. /// [enableJavaScript] is an Android only setting. If true, WebView enable /// javascript. /// [enableDomStorage] is an Android only setting. If true, WebView enable /// DOM storage. /// [headers] is an Android only setting that adds headers to the WebView. /// When not using a WebView, the header information is passed to the browser, /// some Android browsers do not support the [Browser.EXTRA_HEADERS](https://developer.android.com/reference/android/provider/Browser#EXTRA_HEADERS) /// intent extra and the header information will be lost. /// [webOnlyWindowName] is an Web only setting . _blank opens the new url in new tab , /// _self opens the new url in current tab. /// Default behaviour is to open the url in new tab. /// /// Note that if any of the above are set to true but the URL is not a web URL, /// this will throw a [PlatformException]. /// /// [statusBarBrightness] Sets the status bar brightness of the application /// after opening a link on iOS. Does nothing if no value is passed. This does /// not handle resetting the previous status bar style. /// /// Returns true if launch url is successful; false is only returned when [universalLinksOnly] /// is set to true and the universal link failed to launch. @Deprecated('Use launchUrl instead') Future<bool> launch( String urlString, { bool? forceSafariVC, bool forceWebView = false, bool enableJavaScript = false, bool enableDomStorage = false, bool universalLinksOnly = false, Map<String, String> headers = const <String, String>{}, Brightness? statusBarBrightness, String? webOnlyWindowName, }) async { final Uri? url = Uri.tryParse(urlString.trimLeft()); final bool isWebURL = url != null && (url.scheme == 'http' || url.scheme == 'https'); if ((forceSafariVC ?? false || forceWebView) && !isWebURL) { throw PlatformException( code: 'NOT_A_WEB_SCHEME', message: 'To use webview or safariVC, you need to pass ' 'in a web URL. This $urlString is not a web URL.'); } /// [true] so that ui is automatically computed if [statusBarBrightness] is set. bool previousAutomaticSystemUiAdjustment = true; final RenderView? renderViewToAdjust = statusBarBrightness != null && defaultTargetPlatform == TargetPlatform.iOS ? _findImplicitRenderView() : null; if (renderViewToAdjust != null) { previousAutomaticSystemUiAdjustment = renderViewToAdjust.automaticSystemUiAdjustment; renderViewToAdjust.automaticSystemUiAdjustment = false; SystemChrome.setSystemUIOverlayStyle(statusBarBrightness == Brightness.light ? SystemUiOverlayStyle.dark : SystemUiOverlayStyle.light); } final bool result = await UrlLauncherPlatform.instance.launch( urlString, useSafariVC: forceSafariVC ?? isWebURL, useWebView: forceWebView, enableJavaScript: enableJavaScript, enableDomStorage: enableDomStorage, universalLinksOnly: universalLinksOnly, headers: headers, webOnlyWindowName: webOnlyWindowName, ); if (renderViewToAdjust != null) { renderViewToAdjust.automaticSystemUiAdjustment = previousAutomaticSystemUiAdjustment; } return result; } /// Checks whether the specified URL can be handled by some app installed on the /// device. /// /// On some systems, such as recent versions of Android and iOS, this will /// always return false unless the application has been configuration to allow /// querying the system for launch support. See /// [the README](https://pub.dev/packages/url_launcher#configuration) for /// details. @Deprecated('Use canLaunchUrl instead') Future<bool> canLaunch(String urlString) async { return UrlLauncherPlatform.instance.canLaunch(urlString); } /// Closes the current WebView, if one was previously opened via a call to [launch]. /// /// If [launch] was never called, then this call will not have any effect. /// /// On Android systems, if [launch] was called without `forceWebView` being set to `true` /// Or on IOS systems, if [launch] was called without `forceSafariVC` being set to `true`, /// this call will not do anything either, simply because there is no /// WebView/SafariViewController available to be closed. @Deprecated('Use closeInAppWebView instead') Future<void> closeWebView() async { return UrlLauncherPlatform.instance.closeWebView(); } /// Returns the [RenderView] associated with the implicit [FlutterView], if any. /// /// [launch] predates multi-window support, and it doesn't have enough context /// to get the right render view, so this assumes anyone still trying to use /// the deprecated API with `statusBarBrightness` is in a single-view scenario. /// This allows a best-effort implementation of the deprecated API for as long /// as it continues to exist, without depending on deprecated Flutter APIs (and /// therefore keeping url_launcher forward-compatible with future versions of /// Flutter for longer). RenderView? _findImplicitRenderView() { final FlutterView? implicitFlutterView = WidgetsBinding.instance.platformDispatcher.implicitView; if (implicitFlutterView == null) { return null; } return WidgetsBinding.instance.renderViews .where((RenderView v) => v.flutterView == implicitFlutterView) .firstOrNull; }
packages/packages/url_launcher/url_launcher/lib/src/legacy_api.dart/0
{ "file_path": "packages/packages/url_launcher/url_launcher/lib/src/legacy_api.dart", "repo_id": "packages", "token_count": 2128 }
1,119
// 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' show visibleForTesting; import 'package:flutter/services.dart'; import 'package:url_launcher_platform_interface/link.dart'; import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart'; import 'src/messages.g.dart'; /// An implementation of [UrlLauncherPlatform] for Android. class UrlLauncherAndroid extends UrlLauncherPlatform { /// Creates a new plugin implementation instance. UrlLauncherAndroid({ @visibleForTesting UrlLauncherApi? api, }) : _hostApi = api ?? UrlLauncherApi(); final UrlLauncherApi _hostApi; /// Registers this class as the default instance of [UrlLauncherPlatform]. static void registerWith() { UrlLauncherPlatform.instance = UrlLauncherAndroid(); } @override final LinkDelegate? linkDelegate = null; @override Future<bool> canLaunch(String url) async { final bool canLaunchSpecificUrl = await _hostApi.canLaunchUrl(url); if (!canLaunchSpecificUrl) { final String scheme = _getUrlScheme(url); // canLaunch can return false when a custom application is registered to // handle a web URL, but the caller doesn't have permission to see what // that handler is. If that happens, try a web URL (with the same scheme // variant, to be safe) that should not have a custom handler. If that // returns true, then there is a browser, which means that there is // at least one handler for the original URL. if (scheme == 'http' || scheme == 'https') { return _hostApi.canLaunchUrl('$scheme://flutter.dev'); } } return canLaunchSpecificUrl; } @override Future<void> closeWebView() { return _hostApi.closeWebView(); } @override Future<bool> launch( String url, { required bool useSafariVC, required bool useWebView, required bool enableJavaScript, required bool enableDomStorage, required bool universalLinksOnly, required Map<String, String> headers, String? webOnlyWindowName, }) async { return launchUrl( url, LaunchOptions( mode: useWebView ? PreferredLaunchMode.inAppWebView : PreferredLaunchMode.externalApplication, webViewConfiguration: InAppWebViewConfiguration( enableDomStorage: enableDomStorage, enableJavaScript: enableJavaScript, headers: headers))); } @override Future<bool> launchUrl(String url, LaunchOptions options) async { final bool inApp; switch (options.mode) { case PreferredLaunchMode.inAppWebView: case PreferredLaunchMode.inAppBrowserView: inApp = true; case PreferredLaunchMode.externalApplication: case PreferredLaunchMode.externalNonBrowserApplication: // TODO(stuartmorgan): Add full support for // externalNonBrowsingApplication; see // https://github.com/flutter/flutter/issues/66721. // Currently it's treated the same as externalApplication. inApp = false; case PreferredLaunchMode.platformDefault: // Intentionally treat any new values as platformDefault; see comment in // supportsMode. // ignore: no_default_cases default: // By default, open web URLs in the application. inApp = url.startsWith('http:') || url.startsWith('https:'); break; } final bool succeeded; if (inApp) { succeeded = await _hostApi.openUrlInApp( url, // Prefer custom tabs unless a webview was specifically requested. options.mode != PreferredLaunchMode.inAppWebView, WebViewOptions( enableJavaScript: options.webViewConfiguration.enableJavaScript, enableDomStorage: options.webViewConfiguration.enableDomStorage, headers: options.webViewConfiguration.headers, ), BrowserOptions( showTitle: options.browserConfiguration.showTitle, ), ); } else { succeeded = await _hostApi.launchUrl(url, options.webViewConfiguration.headers); } // TODO(stuartmorgan): Remove this special handling as part of a // breaking change to rework failure handling across all platform. The // current behavior is backwards compatible with the previous Java error. if (!succeeded) { throw PlatformException( code: 'ACTIVITY_NOT_FOUND', message: 'No Activity found to handle intent { $url }'); } return succeeded; } @override Future<bool> supportsMode(PreferredLaunchMode mode) async { switch (mode) { case PreferredLaunchMode.platformDefault: case PreferredLaunchMode.inAppWebView: case PreferredLaunchMode.externalApplication: return true; case PreferredLaunchMode.inAppBrowserView: return _hostApi.supportsCustomTabs(); // Default is a desired behavior here since support for new modes is // always opt-in, and the enum lives in a different package, so silently // adding "false" for new values is the correct behavior. // ignore: no_default_cases default: return false; } } @override Future<bool> supportsCloseForMode(PreferredLaunchMode mode) async { return mode == PreferredLaunchMode.inAppWebView; } // Returns the part of [url] up to the first ':', or an empty string if there // is no ':'. This deliberately does not use [Uri] to extract the scheme // so that it works on strings that aren't actually valid URLs, since Android // is very lenient about what it accepts for launching. String _getUrlScheme(String url) { final int schemeEnd = url.indexOf(':'); if (schemeEnd == -1) { return ''; } return url.substring(0, schemeEnd); } }
packages/packages/url_launcher/url_launcher_android/lib/url_launcher_android.dart/0
{ "file_path": "packages/packages/url_launcher/url_launcher_android/lib/url_launcher_android.dart", "repo_id": "packages", "token_count": 2065 }
1,120
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import FlutterMacOS import Foundation /// A handler that can launch other apps, check if any app is able to open the URL. public protocol SystemURLHandler { /// Opens the location at the specified URL. /// /// - Parameters: /// - url: A URL specifying the location to open. /// - Returns: true if the location was successfully opened; otherwise, false. func open(_ url: URL) -> Bool /// Returns the URL to the default app that would be opened. /// /// - Parameters: /// - toOpen: The URL of the file to open. /// - Returns: The URL of the default app that would open the specified url. /// Returns nil if no app is able to open the URL, or if the file URL does not exist. func urlForApplication(toOpen: URL) -> URL? } extension NSWorkspace: SystemURLHandler {} public class UrlLauncherPlugin: NSObject, FlutterPlugin, UrlLauncherApi { private var workspace: SystemURLHandler public init(_ workspace: SystemURLHandler = NSWorkspace.shared) { self.workspace = workspace } public static func register(with registrar: FlutterPluginRegistrar) { let instance = UrlLauncherPlugin() UrlLauncherApiSetup.setUp(binaryMessenger: registrar.messenger, api: instance) } func canLaunch(url: String) throws -> UrlLauncherBoolResult { guard let nsurl = URL.init(string: url) else { return UrlLauncherBoolResult(value: false, error: .invalidUrl) } let canOpen = workspace.urlForApplication(toOpen: nsurl) != nil return UrlLauncherBoolResult(value: canOpen, error: nil) } func launch(url: String) throws -> UrlLauncherBoolResult { guard let nsurl = URL.init(string: url) else { return UrlLauncherBoolResult(value: false, error: .invalidUrl) } let success = workspace.open(nsurl) return UrlLauncherBoolResult(value: success, error: nil) } }
packages/packages/url_launcher/url_launcher_macos/macos/Classes/UrlLauncherPlugin.swift/0
{ "file_path": "packages/packages/url_launcher/url_launcher_macos/macos/Classes/UrlLauncherPlugin.swift", "repo_id": "packages", "token_count": 616 }
1,121
name: url_launcher_platform_interface description: A common platform interface for the url_launcher plugin. repository: https://github.com/flutter/packages/tree/main/packages/url_launcher/url_launcher_platform_interface issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+url_launcher%22 # NOTE: We strongly prefer non-breaking changes, even at the expense of a # less-clean API. See https://flutter.dev/go/platform-interface-breaking-changes version: 2.3.2 environment: sdk: ^3.1.0 flutter: ">=3.13.0" dependencies: flutter: sdk: flutter plugin_platform_interface: ^2.1.7 dev_dependencies: flutter_test: sdk: flutter mockito: 5.4.4 topics: - links - os-integration - url-launcher - urls
packages/packages/url_launcher/url_launcher_platform_interface/pubspec.yaml/0
{ "file_path": "packages/packages/url_launcher/url_launcher_platform_interface/pubspec.yaml", "repo_id": "packages", "token_count": 285 }
1,122
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "system_apis.h" #include <windows.h> namespace url_launcher_windows { SystemApis::SystemApis() {} SystemApis::~SystemApis() {} SystemApisImpl::SystemApisImpl() {} SystemApisImpl::~SystemApisImpl() {} LSTATUS SystemApisImpl::RegCloseKey(HKEY key) { return ::RegCloseKey(key); } LSTATUS SystemApisImpl::RegOpenKeyExW(HKEY key, LPCWSTR sub_key, DWORD options, REGSAM desired, PHKEY result) { return ::RegOpenKeyExW(key, sub_key, options, desired, result); } LSTATUS SystemApisImpl::RegQueryValueExW(HKEY key, LPCWSTR value_name, LPDWORD type, LPBYTE data, LPDWORD data_size) { return ::RegQueryValueExW(key, value_name, nullptr, type, data, data_size); } HINSTANCE SystemApisImpl::ShellExecuteW(HWND hwnd, LPCWSTR operation, LPCWSTR file, LPCWSTR parameters, LPCWSTR directory, int show_flags) { return ::ShellExecuteW(hwnd, operation, file, parameters, directory, show_flags); } } // namespace url_launcher_windows
packages/packages/url_launcher/url_launcher_windows/windows/system_apis.cpp/0
{ "file_path": "packages/packages/url_launcher/url_launcher_windows/windows/system_apis.cpp", "repo_id": "packages", "token_count": 608 }
1,123
// 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/src/closed_caption_file.dart'; void main() { group('ClosedCaptionFile', () { test('toString()', () { const Caption caption = Caption( number: 1, start: Duration(seconds: 1), end: Duration(seconds: 2), text: 'caption', ); expect( caption.toString(), 'Caption(' 'number: 1, ' 'start: 0:00:01.000000, ' 'end: 0:00:02.000000, ' 'text: caption)'); }); }); }
packages/packages/video_player/video_player/test/closed_caption_file_test.dart/0
{ "file_path": "packages/packages/video_player/video_player/test/closed_caption_file_test.dart", "repo_id": "packages", "token_count": 311 }
1,124
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.videoplayer; import static com.google.android.exoplayer2.Player.REPEAT_MODE_ALL; import static com.google.android.exoplayer2.Player.REPEAT_MODE_OFF; import android.content.Context; import android.net.Uri; import android.view.Surface; import androidx.annotation.NonNull; import androidx.annotation.VisibleForTesting; import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.ExoPlayer; import com.google.android.exoplayer2.Format; import com.google.android.exoplayer2.MediaItem; import com.google.android.exoplayer2.PlaybackException; import com.google.android.exoplayer2.PlaybackParameters; import com.google.android.exoplayer2.Player; import com.google.android.exoplayer2.Player.Listener; import com.google.android.exoplayer2.audio.AudioAttributes; import com.google.android.exoplayer2.source.MediaSource; import com.google.android.exoplayer2.source.ProgressiveMediaSource; import com.google.android.exoplayer2.source.dash.DashMediaSource; import com.google.android.exoplayer2.source.dash.DefaultDashChunkSource; import com.google.android.exoplayer2.source.hls.HlsMediaSource; import com.google.android.exoplayer2.source.smoothstreaming.DefaultSsChunkSource; import com.google.android.exoplayer2.source.smoothstreaming.SsMediaSource; import com.google.android.exoplayer2.upstream.DataSource; import com.google.android.exoplayer2.upstream.DefaultDataSource; import com.google.android.exoplayer2.upstream.DefaultHttpDataSource; import com.google.android.exoplayer2.util.Util; import io.flutter.plugin.common.EventChannel; import io.flutter.view.TextureRegistry; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; final class VideoPlayer { private static final String FORMAT_SS = "ss"; private static final String FORMAT_DASH = "dash"; private static final String FORMAT_HLS = "hls"; private static final String FORMAT_OTHER = "other"; private ExoPlayer exoPlayer; private Surface surface; private final TextureRegistry.SurfaceTextureEntry textureEntry; private QueuingEventSink eventSink; private final EventChannel eventChannel; private static final String USER_AGENT = "User-Agent"; @VisibleForTesting boolean isInitialized = false; private final VideoPlayerOptions options; private DefaultHttpDataSource.Factory httpDataSourceFactory = new DefaultHttpDataSource.Factory(); VideoPlayer( Context context, EventChannel eventChannel, TextureRegistry.SurfaceTextureEntry textureEntry, String dataSource, String formatHint, @NonNull Map<String, String> httpHeaders, VideoPlayerOptions options) { this.eventChannel = eventChannel; this.textureEntry = textureEntry; this.options = options; ExoPlayer exoPlayer = new ExoPlayer.Builder(context).build(); Uri uri = Uri.parse(dataSource); buildHttpDataSourceFactory(httpHeaders); DataSource.Factory dataSourceFactory = new DefaultDataSource.Factory(context, httpDataSourceFactory); MediaSource mediaSource = buildMediaSource(uri, dataSourceFactory, formatHint); exoPlayer.setMediaSource(mediaSource); exoPlayer.prepare(); setUpVideoPlayer(exoPlayer, new QueuingEventSink()); } // Constructor used to directly test members of this class. @VisibleForTesting VideoPlayer( ExoPlayer exoPlayer, EventChannel eventChannel, TextureRegistry.SurfaceTextureEntry textureEntry, VideoPlayerOptions options, QueuingEventSink eventSink, DefaultHttpDataSource.Factory httpDataSourceFactory) { this.eventChannel = eventChannel; this.textureEntry = textureEntry; this.options = options; this.httpDataSourceFactory = httpDataSourceFactory; setUpVideoPlayer(exoPlayer, eventSink); } @VisibleForTesting public void buildHttpDataSourceFactory(@NonNull Map<String, String> httpHeaders) { final boolean httpHeadersNotEmpty = !httpHeaders.isEmpty(); final String userAgent = httpHeadersNotEmpty && httpHeaders.containsKey(USER_AGENT) ? httpHeaders.get(USER_AGENT) : "ExoPlayer"; httpDataSourceFactory.setUserAgent(userAgent).setAllowCrossProtocolRedirects(true); if (httpHeadersNotEmpty) { httpDataSourceFactory.setDefaultRequestProperties(httpHeaders); } } private MediaSource buildMediaSource( Uri uri, DataSource.Factory mediaDataSourceFactory, String formatHint) { int type; if (formatHint == null) { type = Util.inferContentType(uri); } else { switch (formatHint) { case FORMAT_SS: type = C.CONTENT_TYPE_SS; break; case FORMAT_DASH: type = C.CONTENT_TYPE_DASH; break; case FORMAT_HLS: type = C.CONTENT_TYPE_HLS; break; case FORMAT_OTHER: type = C.CONTENT_TYPE_OTHER; break; default: type = -1; break; } } switch (type) { case C.CONTENT_TYPE_SS: return new SsMediaSource.Factory( new DefaultSsChunkSource.Factory(mediaDataSourceFactory), mediaDataSourceFactory) .createMediaSource(MediaItem.fromUri(uri)); case C.CONTENT_TYPE_DASH: return new DashMediaSource.Factory( new DefaultDashChunkSource.Factory(mediaDataSourceFactory), mediaDataSourceFactory) .createMediaSource(MediaItem.fromUri(uri)); case C.CONTENT_TYPE_HLS: return new HlsMediaSource.Factory(mediaDataSourceFactory) .createMediaSource(MediaItem.fromUri(uri)); case C.CONTENT_TYPE_OTHER: return new ProgressiveMediaSource.Factory(mediaDataSourceFactory) .createMediaSource(MediaItem.fromUri(uri)); default: { throw new IllegalStateException("Unsupported type: " + type); } } } private void setUpVideoPlayer(ExoPlayer exoPlayer, QueuingEventSink eventSink) { this.exoPlayer = exoPlayer; this.eventSink = eventSink; eventChannel.setStreamHandler( new EventChannel.StreamHandler() { @Override public void onListen(Object o, EventChannel.EventSink sink) { eventSink.setDelegate(sink); } @Override public void onCancel(Object o) { eventSink.setDelegate(null); } }); surface = new Surface(textureEntry.surfaceTexture()); exoPlayer.setVideoSurface(surface); setAudioAttributes(exoPlayer, options.mixWithOthers); exoPlayer.addListener( new Listener() { private boolean isBuffering = false; public void setBuffering(boolean buffering) { if (isBuffering != buffering) { isBuffering = buffering; Map<String, Object> event = new HashMap<>(); event.put("event", isBuffering ? "bufferingStart" : "bufferingEnd"); eventSink.success(event); } } @Override public void onPlaybackStateChanged(final int playbackState) { if (playbackState == Player.STATE_BUFFERING) { setBuffering(true); sendBufferingUpdate(); } else if (playbackState == Player.STATE_READY) { if (!isInitialized) { isInitialized = true; sendInitialized(); } } else if (playbackState == Player.STATE_ENDED) { Map<String, Object> event = new HashMap<>(); event.put("event", "completed"); eventSink.success(event); } if (playbackState != Player.STATE_BUFFERING) { setBuffering(false); } } @Override public void onPlayerError(@NonNull final PlaybackException error) { setBuffering(false); if (error.errorCode == PlaybackException.ERROR_CODE_BEHIND_LIVE_WINDOW) { // See https://exoplayer.dev/live-streaming.html#behindlivewindowexception-and-error_code_behind_live_window exoPlayer.seekToDefaultPosition(); exoPlayer.prepare(); } else if (eventSink != null) { eventSink.error("VideoError", "Video player had error " + error, null); } } @Override public void onIsPlayingChanged(boolean isPlaying) { if (eventSink != null) { Map<String, Object> event = new HashMap<>(); event.put("event", "isPlayingStateUpdate"); event.put("isPlaying", isPlaying); eventSink.success(event); } } }); } void sendBufferingUpdate() { Map<String, Object> event = new HashMap<>(); event.put("event", "bufferingUpdate"); List<? extends Number> range = Arrays.asList(0, exoPlayer.getBufferedPosition()); // iOS supports a list of buffered ranges, so here is a list with a single range. event.put("values", Collections.singletonList(range)); eventSink.success(event); } private static void setAudioAttributes(ExoPlayer exoPlayer, boolean isMixMode) { exoPlayer.setAudioAttributes( new AudioAttributes.Builder().setContentType(C.AUDIO_CONTENT_TYPE_MOVIE).build(), !isMixMode); } void play() { exoPlayer.setPlayWhenReady(true); } void pause() { exoPlayer.setPlayWhenReady(false); } void setLooping(boolean value) { exoPlayer.setRepeatMode(value ? REPEAT_MODE_ALL : REPEAT_MODE_OFF); } void setVolume(double value) { float bracketedValue = (float) Math.max(0.0, Math.min(1.0, value)); exoPlayer.setVolume(bracketedValue); } void setPlaybackSpeed(double value) { // We do not need to consider pitch and skipSilence for now as we do not handle them and // therefore never diverge from the default values. final PlaybackParameters playbackParameters = new PlaybackParameters(((float) value)); exoPlayer.setPlaybackParameters(playbackParameters); } void seekTo(int location) { exoPlayer.seekTo(location); } long getPosition() { return exoPlayer.getCurrentPosition(); } @SuppressWarnings("SuspiciousNameCombination") @VisibleForTesting void sendInitialized() { if (isInitialized) { Map<String, Object> event = new HashMap<>(); event.put("event", "initialized"); event.put("duration", exoPlayer.getDuration()); if (exoPlayer.getVideoFormat() != null) { Format videoFormat = exoPlayer.getVideoFormat(); int width = videoFormat.width; int height = videoFormat.height; int rotationDegrees = videoFormat.rotationDegrees; // Switch the width/height if video was taken in portrait mode if (rotationDegrees == 90 || rotationDegrees == 270) { width = exoPlayer.getVideoFormat().height; height = exoPlayer.getVideoFormat().width; } event.put("width", width); event.put("height", height); // Rotating the video with ExoPlayer does not seem to be possible with a Surface, // so inform the Flutter code that the widget needs to be rotated to prevent // upside-down playback for videos with rotationDegrees of 180 (other orientations work // correctly without correction). if (rotationDegrees == 180) { event.put("rotationCorrection", rotationDegrees); } } eventSink.success(event); } } void dispose() { if (isInitialized) { exoPlayer.stop(); } textureEntry.release(); eventChannel.setStreamHandler(null); if (surface != null) { surface.release(); } if (exoPlayer != null) { exoPlayer.release(); } } }
packages/packages/video_player/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/VideoPlayer.java/0
{ "file_path": "packages/packages/video_player/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/VideoPlayer.java", "repo_id": "packages", "token_count": 4622 }
1,125
// 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 <AVFoundation/AVFoundation.h> CGAffineTransform FVPGetStandardizedTransformForTrack(AVAssetTrack *track) { CGAffineTransform t = track.preferredTransform; CGSize size = track.naturalSize; // Each case of control flows corresponds to a specific // `UIImageOrientation`, with 8 cases in total. if (t.a == 1 && t.b == 0 && t.c == 0 && t.d == 1) { // UIImageOrientationUp t.tx = 0; t.ty = 0; } else if (t.a == -1 && t.b == 0 && t.c == 0 && t.d == -1) { // UIImageOrientationDown t.tx = size.width; t.ty = size.height; } else if (t.a == 0 && t.b == -1 && t.c == 1 && t.d == 0) { // UIImageOrientationLeft t.tx = 0; t.ty = size.width; } else if (t.a == 0 && t.b == 1 && t.c == -1 && t.d == 0) { // UIImageOrientationRight t.tx = size.height; t.ty = 0; } else if (t.a == -1 && t.b == 0 && t.c == 0 && t.d == 1) { // UIImageOrientationUpMirrored t.tx = size.width; t.ty = 0; } else if (t.a == 1 && t.b == 0 && t.c == 0 && t.d == -1) { // UIImageOrientationDownMirrored t.tx = 0; t.ty = size.height; } else if (t.a == 0 && t.b == -1 && t.c == -1 && t.d == 0) { // UIImageOrientationLeftMirrored t.tx = size.height; t.ty = size.width; } else if (t.a == 0 && t.b == 1 && t.c == 1 && t.d == 0) { // UIImageOrientationRightMirrored t.tx = 0; t.ty = 0; } return t; }
packages/packages/video_player/video_player_avfoundation/darwin/Classes/AVAssetTrackUtils.m/0
{ "file_path": "packages/packages/video_player/video_player_avfoundation/darwin/Classes/AVAssetTrackUtils.m", "repo_id": "packages", "token_count": 669 }
1,126
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:io'; import 'dart:typed_data'; import 'package:flutter/services.dart' show rootBundle; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import 'package:path_provider/path_provider.dart'; import 'package:video_player_avfoundation/video_player_avfoundation.dart'; // TODO(stuartmorgan): Remove the use of MiniController in tests, as that is // testing test code; tests should instead be written directly against the // platform interface. (These tests were copied from the app-facing package // during federation and minimally modified, which is why they currently use the // controller.) import 'package:video_player_example/mini_controller.dart'; import 'package:video_player_platform_interface/video_player_platform_interface.dart'; const Duration _playDuration = Duration(seconds: 1); const String _videoAssetKey = 'assets/Butterfly-209.mp4'; // Returns the URL to load an asset from this example app as a network source. // // TODO(stuartmorgan): Convert this to a local `HttpServer` that vends the // assets directly, https://github.com/flutter/flutter/issues/95420 String getUrlForAssetAsNetworkSource(String assetKey) { return 'https://github.com/flutter/packages/blob/' // This hash can be rolled forward to pick up newly-added assets. '2e1673307ff7454aff40b47024eaed49a9e77e81' '/packages/video_player/video_player/example/' '$assetKey' '?raw=true'; } void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); late MiniController controller; tearDown(() async => controller.dispose()); group('asset videos', () { setUp(() { controller = MiniController.asset(_videoAssetKey); }); testWidgets('registers expected implementation', (WidgetTester tester) async { AVFoundationVideoPlayer.registerWith(); expect(VideoPlayerPlatform.instance, isA<AVFoundationVideoPlayer>()); }); testWidgets('can be initialized', (WidgetTester tester) async { await controller.initialize(); expect(controller.value.isInitialized, true); expect(await controller.position, Duration.zero); expect(controller.value.duration, const Duration(seconds: 7, milliseconds: 540)); }); testWidgets('can be played', (WidgetTester tester) async { await controller.initialize(); await controller.play(); await tester.pumpAndSettle(_playDuration); expect(await controller.position, greaterThan(Duration.zero)); }); testWidgets( 'can seek', (WidgetTester tester) async { await controller.initialize(); await controller.seekTo(const Duration(seconds: 3)); expect(controller.value.position, const Duration(seconds: 3)); }, ); testWidgets( 'can seek to end', (WidgetTester tester) async { await controller.initialize(); await controller.seekTo(controller.value.duration); expect(controller.value.duration, controller.value.position); }, ); testWidgets('can be paused', (WidgetTester tester) async { await controller.initialize(); // Play for a second, then pause, and then wait a second. await controller.play(); await tester.pumpAndSettle(_playDuration); await controller.pause(); final Duration pausedPosition = (await controller.position)!; await tester.pumpAndSettle(_playDuration); // Verify that we stopped playing after the pause. // TODO(stuartmorgan): Investigate why this has a slight discrepency, and // fix it if possible. Is AVPlayer's pause method internally async? const Duration allowableDelta = Duration(milliseconds: 10); expect( await controller.position, lessThan(pausedPosition + allowableDelta)); }); }); group('file-based videos', () { setUp(() async { // Load the data from the asset. final String tempDir = (await getTemporaryDirectory()).path; final ByteData bytes = await rootBundle.load(_videoAssetKey); // Write it to a file to use as a source. final String filename = _videoAssetKey.split('/').last; final File file = File('$tempDir/$filename'); await file.writeAsBytes(bytes.buffer.asInt8List()); controller = MiniController.file(file); }); testWidgets('test video player using static file() method as constructor', (WidgetTester tester) async { await controller.initialize(); await controller.play(); await tester.pumpAndSettle(_playDuration); expect(await controller.position, greaterThan(Duration.zero)); }); }); group('network videos', () { setUp(() { final String videoUrl = getUrlForAssetAsNetworkSource(_videoAssetKey); controller = MiniController.network(videoUrl); }); testWidgets('reports buffering status', (WidgetTester tester) async { await controller.initialize(); final Completer<void> started = Completer<void>(); final Completer<void> ended = Completer<void>(); controller.addListener(() { if (!started.isCompleted && controller.value.isBuffering) { started.complete(); } if (started.isCompleted && !controller.value.isBuffering && !ended.isCompleted) { ended.complete(); } }); await controller.play(); await controller.seekTo(const Duration(seconds: 5)); await tester.pumpAndSettle(_playDuration); await controller.pause(); // TODO(stuartmorgan): Switch to _controller.position once seekTo is // fixed on the native side to wait for completion, so this is testing // the native code rather than the MiniController position cache. expect(controller.value.position, greaterThan(Duration.zero)); await expectLater(started.future, completes); await expectLater(ended.future, completes); }, // TODO(stuartmorgan): Skipped on iOS without explanation in main // package. Needs investigation. skip: true); testWidgets('live stream duration != 0', (WidgetTester tester) async { final MiniController livestreamController = MiniController.network( 'https://flutter.github.io/assets-for-api-docs/assets/videos/hls/bee.m3u8', ); await livestreamController.initialize(); expect(livestreamController.value.isInitialized, true); // Live streams should have either a positive duration or C.TIME_UNSET if the duration is unknown // See https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/Player.html#getDuration-- expect(livestreamController.value.duration, (Duration duration) => duration != Duration.zero); }); testWidgets('rotated m3u8 has correct aspect ratio', (WidgetTester tester) async { // Some m3u8 files contain rotation data that may incorrectly invert the aspect ratio. // More info [here](https://github.com/flutter/flutter/issues/109116). final MiniController livestreamController = MiniController.network( 'https://flutter.github.io/assets-for-api-docs/assets/videos/hls/rotated_nail_manifest.m3u8', ); await livestreamController.initialize(); expect(livestreamController.value.isInitialized, true); expect(livestreamController.value.size.width, lessThan(livestreamController.value.size.height)); }); }); }
packages/packages/video_player/video_player_avfoundation/example/integration_test/video_player_test.dart/0
{ "file_path": "packages/packages/video_player/video_player_avfoundation/example/integration_test/video_player_test.dart", "repo_id": "packages", "token_count": 2620 }
1,127
// 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_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import 'package:video_player_platform_interface/video_player_platform_interface.dart'; import 'package:video_player_web/src/duration_utils.dart'; import 'package:video_player_web/src/video_player.dart'; import 'package:web/web.dart' as web; import 'pkg_web_tweaks.dart'; import 'utils.dart'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); group('VideoPlayer', () { late web.HTMLVideoElement video; setUp(() { // Never set "src" on the video, so this test doesn't hit the network! video = web.HTMLVideoElement() ..controls = true ..playsInline = false; }); testWidgets('fixes critical video element config', (WidgetTester _) async { VideoPlayer(videoElement: video).initialize(); expect(video.controls, isFalse, reason: 'Video is controlled through code'); expect(video.autoplay, isFalse, reason: 'autoplay attribute on HTMLVideoElement MUST be false'); // see: https://developer.mozilla.org/en-US/docs/Glossary/Boolean/HTML expect(video.getAttribute('autoplay'), isNull, reason: 'autoplay attribute on video tag must NOT be set'); expect(video.playsInline, true, reason: 'Needed by safari iOS'); }); testWidgets('setVolume', (WidgetTester tester) async { final VideoPlayer player = VideoPlayer(videoElement: video)..initialize(); player.setVolume(0); expect(video.volume, isZero, reason: 'Volume should be zero'); expect(video.muted, isTrue, reason: 'muted attribute should be true'); expect(() { player.setVolume(-0.0001); }, throwsAssertionError, reason: 'Volume cannot be < 0'); expect(() { player.setVolume(1.0001); }, throwsAssertionError, reason: 'Volume cannot be > 1'); }); testWidgets('setPlaybackSpeed', (WidgetTester tester) async { final VideoPlayer player = VideoPlayer(videoElement: video)..initialize(); expect(() { player.setPlaybackSpeed(-1); }, throwsAssertionError, reason: 'Playback speed cannot be < 0'); expect(() { player.setPlaybackSpeed(0); }, throwsAssertionError, reason: 'Playback speed cannot be == 0'); }); group('seekTo', () { testWidgets('negative time - throws assert', (WidgetTester tester) async { final VideoPlayer player = VideoPlayer(videoElement: video) ..initialize(); expect(() { player.seekTo(const Duration(seconds: -1)); }, throwsAssertionError, reason: 'Cannot seek into negative numbers'); }); testWidgets('setting currentTime to its current value - noop', (WidgetTester tester) async { makeSetCurrentTimeThrow(video); final VideoPlayer player = VideoPlayer(videoElement: video) ..initialize(); expect(() { // Self-test... video.currentTime = 123; }, throwsException, reason: 'Setting currentTime must throw!'); expect(() { // Should not set currentTime (and throw) when seekTo current time. player.seekTo(Duration(seconds: video.currentTime.toInt())); }, returnsNormally); }); }); // The events tested in this group do *not* represent the actual sequence // of events from a real "video" element. They're crafted to test the // behavior of the VideoPlayer in different states with different events. group('events', () { late StreamController<VideoEvent> streamController; late VideoPlayer player; late Stream<VideoEvent> timedStream; final Set<VideoEventType> bufferingEvents = <VideoEventType>{ VideoEventType.bufferingStart, VideoEventType.bufferingEnd, }; setUp(() { streamController = StreamController<VideoEvent>(); player = VideoPlayer(videoElement: video, eventController: streamController) ..initialize(); // This stream will automatically close after 100 ms without seeing any events timedStream = streamController.stream.timeout( const Duration(milliseconds: 100), onTimeout: (EventSink<VideoEvent> sink) { sink.close(); }, ); }); testWidgets('buffering dispatches only when it changes', (WidgetTester tester) async { // Take all the "buffering" events that we see during the next few seconds final Future<List<bool>> stream = timedStream .where( (VideoEvent event) => bufferingEvents.contains(event.eventType)) .map((VideoEvent event) => event.eventType == VideoEventType.bufferingStart) .toList(); // Simulate some events coming from the player... player.setBuffering(true); player.setBuffering(true); player.setBuffering(true); player.setBuffering(false); player.setBuffering(false); player.setBuffering(true); player.setBuffering(false); player.setBuffering(true); player.setBuffering(false); final List<bool> events = await stream; expect(events, hasLength(6)); expect(events, <bool>[true, false, true, false, true, false]); }); testWidgets('canplay event does not change buffering state', (WidgetTester tester) async { // Take all the "buffering" events that we see during the next few seconds final Future<List<bool>> stream = timedStream .where( (VideoEvent event) => bufferingEvents.contains(event.eventType)) .map((VideoEvent event) => event.eventType == VideoEventType.bufferingStart) .toList(); player.setBuffering(true); // Simulate "canplay" event... video.dispatchEvent(web.Event('canplay')); final List<bool> events = await stream; expect(events, hasLength(1)); expect(events, <bool>[true]); }); testWidgets('canplaythrough event does change buffering state', (WidgetTester tester) async { // Take all the "buffering" events that we see during the next few seconds final Future<List<bool>> stream = timedStream .where( (VideoEvent event) => bufferingEvents.contains(event.eventType)) .map((VideoEvent event) => event.eventType == VideoEventType.bufferingStart) .toList(); player.setBuffering(true); // Simulate "canplaythrough" event... video.dispatchEvent(web.Event('canplaythrough')); final List<bool> events = await stream; expect(events, hasLength(2)); expect(events, <bool>[true, false]); }); testWidgets('initialized dispatches only once', (WidgetTester tester) async { // Dispatch some bogus "canplay" events from the video object video.dispatchEvent(web.Event('canplay')); video.dispatchEvent(web.Event('canplay')); video.dispatchEvent(web.Event('canplay')); // Take all the "initialized" events that we see during the next few seconds final Future<List<VideoEvent>> stream = timedStream .where((VideoEvent event) => event.eventType == VideoEventType.initialized) .toList(); video.dispatchEvent(web.Event('canplay')); video.dispatchEvent(web.Event('canplay')); video.dispatchEvent(web.Event('canplay')); final List<VideoEvent> events = await stream; expect(events, hasLength(1)); expect(events[0].eventType, VideoEventType.initialized); }); // Issue: https://github.com/flutter/flutter/issues/137023 testWidgets('loadedmetadata dispatches initialized', (WidgetTester tester) async { video.dispatchEvent(web.Event('loadedmetadata')); video.dispatchEvent(web.Event('loadedmetadata')); final Future<List<VideoEvent>> stream = timedStream .where((VideoEvent event) => event.eventType == VideoEventType.initialized) .toList(); final List<VideoEvent> events = await stream; expect(events, hasLength(1)); expect(events[0].eventType, VideoEventType.initialized); }); // Issue: https://github.com/flutter/flutter/issues/105649 testWidgets('supports `Infinity` duration', (WidgetTester _) async { setInfinityDuration(video); expect(video.duration.isInfinite, isTrue); final Future<List<VideoEvent>> stream = timedStream .where((VideoEvent event) => event.eventType == VideoEventType.initialized) .toList(); video.dispatchEvent(web.Event('canplay')); final List<VideoEvent> events = await stream; expect(events, hasLength(1)); expect(events[0].eventType, VideoEventType.initialized); expect(events[0].duration, equals(jsCompatibleTimeUnset)); }); }); group('VideoPlayerWebOptions', () { late VideoPlayer player; setUp(() { video = web.HTMLVideoElement(); player = VideoPlayer(videoElement: video)..initialize(); }); group('VideoPlayerWebOptionsControls', () { testWidgets('when disabled expect no controls', (WidgetTester tester) async { await player.setOptions( const VideoPlayerWebOptions( // ignore: avoid_redundant_argument_values controls: VideoPlayerWebOptionsControls.disabled(), ), ); expect(video.controls, isFalse); expect(video.controlsList, isNotNull); expect(video.controlsList?.length, isZero); }); group('when enabled', () { testWidgets('expect controls', (WidgetTester tester) async { await player.setOptions( const VideoPlayerWebOptions( controls: VideoPlayerWebOptionsControls.enabled(), ), ); expect(video.controls, isTrue); expect(video.controlsList, isNotNull); expect(video.controlsList?.length, isZero); expect(video.controlsList?.contains('nodownload'), isFalse); expect(video.controlsList?.contains('nofullscreen'), isFalse); expect(video.controlsList?.contains('noplaybackrate'), isFalse); expect(video.disablePictureInPicture, isFalse); }); testWidgets('and no download expect correct controls', (WidgetTester tester) async { await player.setOptions( const VideoPlayerWebOptions( controls: VideoPlayerWebOptionsControls.enabled( allowDownload: false, ), ), ); expect(video.controls, isTrue); expect(video.controlsList, isNotNull); expect(video.controlsList?.length, 1); expect(video.controlsList?.contains('nodownload'), isTrue); expect(video.controlsList?.contains('nofullscreen'), isFalse); expect(video.controlsList?.contains('noplaybackrate'), isFalse); expect(video.disablePictureInPicture, isFalse); }); testWidgets('and no fullscreen expect correct controls', (WidgetTester tester) async { await player.setOptions( const VideoPlayerWebOptions( controls: VideoPlayerWebOptionsControls.enabled( allowFullscreen: false, ), ), ); expect(video.controls, isTrue); expect(video.controlsList, isNotNull); expect(video.controlsList?.length, 1); expect(video.controlsList?.contains('nodownload'), isFalse); expect(video.controlsList?.contains('nofullscreen'), isTrue); expect(video.controlsList?.contains('noplaybackrate'), isFalse); expect(video.disablePictureInPicture, isFalse); }); testWidgets('and no playback rate expect correct controls', (WidgetTester tester) async { await player.setOptions( const VideoPlayerWebOptions( controls: VideoPlayerWebOptionsControls.enabled( allowPlaybackRate: false, ), ), ); expect(video.controls, isTrue); expect(video.controlsList, isNotNull); expect(video.controlsList?.length, 1); expect(video.controlsList?.contains('nodownload'), isFalse); expect(video.controlsList?.contains('nofullscreen'), isFalse); expect(video.controlsList?.contains('noplaybackrate'), isTrue); expect(video.disablePictureInPicture, isFalse); }); testWidgets('and no picture in picture expect correct controls', (WidgetTester tester) async { await player.setOptions( const VideoPlayerWebOptions( controls: VideoPlayerWebOptionsControls.enabled( allowPictureInPicture: false, ), ), ); expect(video.controls, isTrue); expect(video.controlsList, isNotNull); expect(video.controlsList?.length, 0); expect(video.controlsList?.contains('nodownload'), isFalse); expect(video.controlsList?.contains('nofullscreen'), isFalse); expect(video.controlsList?.contains('noplaybackrate'), isFalse); expect(video.disablePictureInPicture, isTrue); }); }); }); group('allowRemotePlayback', () { testWidgets('when enabled expect no attribute', (WidgetTester tester) async { await player.setOptions( const VideoPlayerWebOptions( // ignore: avoid_redundant_argument_values allowRemotePlayback: true, ), ); expect(video.disableRemotePlayback, isFalse); }); testWidgets('when disabled expect attribute', (WidgetTester tester) async { await player.setOptions( const VideoPlayerWebOptions( allowRemotePlayback: false, ), ); expect(video.disableRemotePlayback, isTrue); }); }); group('when called first time', () { testWidgets('expect correct options', (WidgetTester tester) async { await player.setOptions( const VideoPlayerWebOptions( controls: VideoPlayerWebOptionsControls.enabled( allowDownload: false, allowFullscreen: false, allowPlaybackRate: false, allowPictureInPicture: false, ), allowContextMenu: false, allowRemotePlayback: false, ), ); expect(video.controls, isTrue); expect(video.controlsList, isNotNull); expect(video.controlsList?.length, 3); expect(video.controlsList?.contains('nodownload'), isTrue); expect(video.controlsList?.contains('nofullscreen'), isTrue); expect(video.controlsList?.contains('noplaybackrate'), isTrue); expect(video.disablePictureInPicture, isTrue); expect(video.disableRemotePlayback, isTrue); }); group('when called once more', () { testWidgets('expect correct options', (WidgetTester tester) async { await player.setOptions( const VideoPlayerWebOptions( // ignore: avoid_redundant_argument_values controls: VideoPlayerWebOptionsControls.disabled(), // ignore: avoid_redundant_argument_values allowContextMenu: true, // ignore: avoid_redundant_argument_values allowRemotePlayback: true, ), ); expect(video.controls, isFalse); expect(video.controlsList, isNotNull); expect(video.controlsList?.length, 0); expect(video.controlsList?.contains('nodownload'), isFalse); expect(video.controlsList?.contains('nofullscreen'), isFalse); expect(video.controlsList?.contains('noplaybackrate'), isFalse); expect(video.disablePictureInPicture, isFalse); expect(video.disableRemotePlayback, isFalse); }); }); }); }); }); }
packages/packages/video_player/video_player_web/example/integration_test/video_player_test.dart/0
{ "file_path": "packages/packages/video_player/video_player_web/example/integration_test/video_player_test.dart", "repo_id": "packages", "token_count": 7187 }
1,128
# web_benchmarks A benchmark harness for Flutter Web apps. Currently only supports running benchmarks in Chrome. # Writing a benchmark An example benchmark can be found in [testing/web_benchmark_test.dart][1]. A web benchmark is made of two parts: a client and a server. The client is code that runs in the browser together with the benchmark code. The server serves the app's code and assets. Additionally, the server communicates with the browser to extract the performance traces. [1]: https://github.com/flutter/packages/blob/master/packages/web_benchmarks/testing/web_benchmarks_test.dart # Analyzing benchmark results After running web benchmarks, you may want to analyze the results or compare with the results from other benchmark runs. The `web_benchmarks` package supports the following analysis operations: * compute the delta between two benchmark results * compute the average of a set of benchmark results <?code-excerpt "example/analyze_example.dart (analyze)"?> ```dart import 'dart:convert'; import 'dart:io'; import 'package:web_benchmarks/analysis.dart'; void main() { final BenchmarkResults baselineResults = _benchmarkResultsFromFile('/path/to/benchmark_baseline.json'); final BenchmarkResults testResults1 = _benchmarkResultsFromFile('/path/to/benchmark_test_1.json'); final BenchmarkResults testResults2 = _benchmarkResultsFromFile('/path/to/benchmark_test_2.json'); // Compute the delta between [baselineResults] and [testResults1]. final BenchmarkResults delta = computeDelta(baselineResults, testResults1); stdout.writeln(delta.toJson()); // Compute the average of [testResults] and [testResults2]. final BenchmarkResults average = computeAverage(<BenchmarkResults>[testResults1, testResults2]); stdout.writeln(average.toJson()); } BenchmarkResults _benchmarkResultsFromFile(String path) { final File file = File.fromUri(Uri.parse(path)); final Map<String, Object?> fileContentAsJson = jsonDecode(file.readAsStringSync()) as Map<String, Object?>; return BenchmarkResults.parse(fileContentAsJson); } ```
packages/packages/web_benchmarks/README.md/0
{ "file_path": "packages/packages/web_benchmarks/README.md", "repo_id": "packages", "token_count": 615 }
1,129
// 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' show jsonDecode; // JSON Event samples taken from running an instrumented version of the // integration tests of this package that dumped all the data as captured. /// To test isBeginFrame. (Sampled from Chrome 89+) final Map<String, dynamic> beginMainFrameJson_89plus = jsonDecode(''' { "args": { "frameTime": 2338687248768 }, "cat": "blink", "dur": 6836, "name": "WebFrameWidgetImpl::BeginMainFrame", "ph": "X", "pid": 1367081, "tdur": 393, "tid": 1, "ts": 2338687258440, "tts": 375499 } ''') as Map<String, dynamic>; /// To test isUpdateAllLifecyclePhases. (Sampled from Chrome 89+) final Map<String, dynamic> updateLifecycleJson_89plus = jsonDecode(''' { "args": {}, "cat": "blink", "dur": 103, "name": "WebFrameWidgetImpl::UpdateLifecycle", "ph": "X", "pid": 1367081, "tdur": 102, "tid": 1, "ts": 2338687265284, "tts": 375900 } ''') as Map<String, dynamic>; /// To test isBeginMeasuredFrame. (Sampled from Chrome 89+) final Map<String, dynamic> beginMeasuredFrameJson_89plus = jsonDecode(''' { "args": {}, "cat": "blink.user_timing", "id": "0xea2a8b45", "name": "measured_frame", "ph": "b", "pid": 1367081, "scope": "blink.user_timing", "tid": 1, "ts": 2338687265932 } ''') as Map<String, dynamic>; /// To test isEndMeasuredFrame. (Sampled from Chrome 89+) final Map<String, dynamic> endMeasuredFrameJson_89plus = jsonDecode(''' { "args": {}, "cat": "blink.user_timing", "id": "0xea2a8b45", "name": "measured_frame", "ph": "e", "pid": 1367081, "scope": "blink.user_timing", "tid": 1, "ts": 2338687440485 } ''') as Map<String, dynamic>; /// An unrelated data frame to test negative cases. final Map<String, dynamic> unrelatedPhXJson = jsonDecode(''' { "args": {}, "cat": "blink,rail", "dur": 2, "name": "PageAnimator::serviceScriptedAnimations", "ph": "X", "pid": 1367081, "tdur": 2, "tid": 1, "ts": 2338691143317, "tts": 1685405 } ''') as Map<String, dynamic>; /// Another unrelated data frame to test negative cases. final Map<String, dynamic> anotherUnrelatedJson = jsonDecode(''' { "args": { "sort_index": -1 }, "cat": "__metadata", "name": "thread_sort_index", "ph": "M", "pid": 1367081, "tid": 1, "ts": 2338692906482 } ''') as Map<String, dynamic>;
packages/packages/web_benchmarks/test/src/browser_test_json_samples.dart/0
{ "file_path": "packages/packages/web_benchmarks/test/src/browser_test_json_samples.dart", "repo_id": "packages", "token_count": 1099 }
1,130
<!DOCTYPE html> <!-- 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. --> <html> <head> <meta charset="UTF-8"> <meta content="IE=Edge" http-equiv="X-UA-Compatible"> <meta name="description" content="A new Flutter project."> <!-- iOS meta tags & icons --> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="black"> <meta name="apple-mobile-web-app-title" content="test_app"> <link rel="apple-touch-icon" href="icons/Icon-192.png"> <!-- Favicon --> <link rel="icon" type="image/png" href="favicon.png"/> <title>test_app</title> <link rel="manifest" href="manifest.json"> </head> <body> <!-- This script installs service_worker.js to provide PWA functionality to application. For more information, see: https://developers.google.com/web/fundamentals/primers/service-workers --> <script> if ('serviceWorker' in navigator) { window.addEventListener('load', function () { navigator.serviceWorker.register('flutter_service_worker.js'); }); } </script> <script src="main.dart.js" type="application/javascript"></script> </body> </html>
packages/packages/web_benchmarks/testing/test_app/web/index.html/0
{ "file_path": "packages/packages/web_benchmarks/testing/test_app/web/index.html", "repo_id": "packages", "token_count": 439 }
1,131
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="io.flutter.plugins.webviewflutterexample"> <application android:usesCleartextTraffic="true" android:icon="@mipmap/ic_launcher" android:label="webview_flutter_example"> <meta-data android:name="flutterEmbedding" android:value="2" /> <activity android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode" android:hardwareAccelerated="true" android:launchMode="singleTop" android:name="io.flutter.embedding.android.FlutterActivity" android:theme="@style/LaunchTheme" android:windowSoftInputMode="adjustResize"> <!-- This keeps the window background of the activity showing until Flutter renders its first frame. It can be removed if there is no splash screen (such as the default splash screen defined in @style/LaunchTheme). --> <meta-data android:name="io.flutter.app.android.SplashScreenUntilFirstFrame" android:value="true"/> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> </application> <!-- The INTERNET permission is required for development. Specifically, flutter needs it to communicate with the running application to allow setting breakpoints, to provide hot reload, etc. --> <uses-permission android:name="android.permission.INTERNET"/> <!-- When tests are ran on Firebase Test Lab, a wake lock permission failure prevents tests from running. --> <uses-permission android:name="android.permission.WAKE_LOCK" /> </manifest>
packages/packages/webview_flutter/webview_flutter/example/android/app/src/main/AndroidManifest.xml/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter/example/android/app/src/main/AndroidManifest.xml", "repo_id": "packages", "token_count": 623 }
1,132
h1 { color: blue; }
packages/packages/webview_flutter/webview_flutter/example/assets/www/styles/style.css/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter/example/assets/www/styles/style.css", "repo_id": "packages", "token_count": 13 }
1,133
// 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:webview_flutter_platform_interface/webview_flutter_platform_interface.dart'; /// Manages cookies pertaining to all WebViews. /// /// ## Platform-Specific Features /// This class contains an underlying implementation provided by the current /// platform. Once a platform implementation is imported, the examples below /// can be followed to use features provided by a platform's implementation. /// /// {@macro webview_flutter.WebViewCookieManager.fromPlatformCreationParams} /// /// Below is an example of accessing the platform-specific implementation for /// iOS and Android: /// /// ```dart /// final WebViewCookieManager cookieManager = WebViewCookieManager(); /// /// if (WebViewPlatform.instance is WebKitWebViewPlatform) { /// final WebKitWebViewCookieManager webKitManager = /// cookieManager.platform as WebKitWebViewCookieManager; /// } else if (WebViewPlatform.instance is AndroidWebViewPlatform) { /// final AndroidWebViewCookieManager androidManager = /// cookieManager.platform as AndroidWebViewCookieManager; /// } /// ``` class WebViewCookieManager { /// Constructs a [WebViewCookieManager]. /// /// See [WebViewCookieManager.fromPlatformCreationParams] for setting /// parameters for a specific platform. WebViewCookieManager() : this.fromPlatformCreationParams( const PlatformWebViewCookieManagerCreationParams(), ); /// Constructs a [WebViewCookieManager] from creation params for a specific /// platform. /// /// {@template webview_flutter.WebViewCookieManager.fromPlatformCreationParams} /// Below is an example of setting platform-specific creation parameters for /// iOS and Android: /// /// ```dart /// PlatformWebViewCookieManagerCreationParams params = /// const PlatformWebViewCookieManagerCreationParams(); /// /// if (WebViewPlatform.instance is WebKitWebViewPlatform) { /// params = WebKitWebViewCookieManagerCreationParams /// .fromPlatformWebViewCookieManagerCreationParams( /// params, /// ); /// } else if (WebViewPlatform.instance is AndroidWebViewPlatform) { /// params = AndroidWebViewCookieManagerCreationParams /// .fromPlatformWebViewCookieManagerCreationParams( /// params, /// ); /// } /// /// final WebViewCookieManager webViewCookieManager = /// WebViewCookieManager.fromPlatformCreationParams( /// params, /// ); /// ``` /// {@endtemplate} WebViewCookieManager.fromPlatformCreationParams( PlatformWebViewCookieManagerCreationParams params, ) : this.fromPlatform(PlatformWebViewCookieManager(params)); /// Constructs a [WebViewCookieManager] from a specific platform /// implementation. WebViewCookieManager.fromPlatform(this.platform); /// Implementation of [PlatformWebViewCookieManager] for the current platform. final PlatformWebViewCookieManager platform; /// Clears all cookies for all WebViews. /// /// Returns true if cookies were present before clearing, else false. Future<bool> clearCookies() => platform.clearCookies(); /// Sets a cookie for all WebView instances. /// /// This is a no op on iOS versions below 11. Future<void> setCookie(WebViewCookie cookie) => platform.setCookie(cookie); }
packages/packages/webview_flutter/webview_flutter/lib/src/webview_cookie_manager.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter/lib/src/webview_cookie_manager.dart", "repo_id": "packages", "token_count": 982 }
1,134
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.webviewflutter; import android.content.Context; import android.view.View; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.flutter.plugin.common.StandardMessageCodec; import io.flutter.plugin.platform.PlatformView; import io.flutter.plugin.platform.PlatformViewFactory; class FlutterViewFactory extends PlatformViewFactory { private final InstanceManager instanceManager; FlutterViewFactory(InstanceManager instanceManager) { super(StandardMessageCodec.INSTANCE); this.instanceManager = instanceManager; } @NonNull @Override public PlatformView create(Context context, int viewId, @Nullable Object args) { final Integer identifier = (Integer) args; if (identifier == null) { throw new IllegalStateException("An identifier is required to retrieve a View instance."); } final Object instance = instanceManager.getInstance(identifier); if (instance instanceof PlatformView) { return (PlatformView) instance; } else if (instance instanceof View) { return new PlatformView() { @Override public View getView() { return (View) instance; } @Override public void dispose() {} }; } throw new IllegalStateException( "Unable to find a PlatformView or View instance: " + args + ", " + instance); } }
packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/FlutterViewFactory.java/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/FlutterViewFactory.java", "repo_id": "packages", "token_count": 484 }
1,135
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.webviewflutter; import android.webkit.WebSettings; import android.webkit.WebView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.WebSettingsHostApi; import java.util.Objects; /** * Host api implementation for {@link WebSettings}. * * <p>Handles creating {@link WebSettings}s that intercommunicate with a paired Dart object. */ public class WebSettingsHostApiImpl implements WebSettingsHostApi { private final InstanceManager instanceManager; private final WebSettingsCreator webSettingsCreator; /** Handles creating {@link WebSettings} for a {@link WebSettingsHostApiImpl}. */ public static class WebSettingsCreator { /** * Creates a {@link WebSettings}. * * @param webView the {@link WebView} which the settings affect * @return the created {@link WebSettings} */ @NonNull public WebSettings createWebSettings(@NonNull WebView webView) { return webView.getSettings(); } } /** * Creates a host API that handles creating {@link WebSettings} and invoke its methods. * * @param instanceManager maintains instances stored to communicate with Dart objects * @param webSettingsCreator handles creating {@link WebSettings}s */ public WebSettingsHostApiImpl( @NonNull InstanceManager instanceManager, @NonNull WebSettingsCreator webSettingsCreator) { this.instanceManager = instanceManager; this.webSettingsCreator = webSettingsCreator; } @Override public void create(@NonNull Long instanceId, @NonNull Long webViewInstanceId) { final WebView webView = Objects.requireNonNull(instanceManager.getInstance(webViewInstanceId)); instanceManager.addDartCreatedInstance( webSettingsCreator.createWebSettings(webView), instanceId); } @Override public void setDomStorageEnabled(@NonNull Long instanceId, @NonNull Boolean flag) { final WebSettings webSettings = Objects.requireNonNull(instanceManager.getInstance(instanceId)); webSettings.setDomStorageEnabled(flag); } @Override public void setJavaScriptCanOpenWindowsAutomatically( @NonNull Long instanceId, @NonNull Boolean flag) { final WebSettings webSettings = Objects.requireNonNull(instanceManager.getInstance(instanceId)); webSettings.setJavaScriptCanOpenWindowsAutomatically(flag); } @Override public void setSupportMultipleWindows(@NonNull Long instanceId, @NonNull Boolean support) { final WebSettings webSettings = Objects.requireNonNull(instanceManager.getInstance(instanceId)); webSettings.setSupportMultipleWindows(support); } @Override public void setJavaScriptEnabled(@NonNull Long instanceId, @NonNull Boolean flag) { final WebSettings webSettings = Objects.requireNonNull(instanceManager.getInstance(instanceId)); webSettings.setJavaScriptEnabled(flag); } @Override public void setUserAgentString(@NonNull Long instanceId, @Nullable String userAgentString) { final WebSettings webSettings = Objects.requireNonNull(instanceManager.getInstance(instanceId)); webSettings.setUserAgentString(userAgentString); } @Override public void setMediaPlaybackRequiresUserGesture( @NonNull Long instanceId, @NonNull Boolean require) { final WebSettings webSettings = Objects.requireNonNull(instanceManager.getInstance(instanceId)); webSettings.setMediaPlaybackRequiresUserGesture(require); } @Override public void setSupportZoom(@NonNull Long instanceId, @NonNull Boolean support) { final WebSettings webSettings = Objects.requireNonNull(instanceManager.getInstance(instanceId)); webSettings.setSupportZoom(support); } @Override public void setLoadWithOverviewMode(@NonNull Long instanceId, @NonNull Boolean overview) { final WebSettings webSettings = Objects.requireNonNull(instanceManager.getInstance(instanceId)); webSettings.setLoadWithOverviewMode(overview); } @Override public void setUseWideViewPort(@NonNull Long instanceId, @NonNull Boolean use) { final WebSettings webSettings = Objects.requireNonNull(instanceManager.getInstance(instanceId)); webSettings.setUseWideViewPort(use); } @Override public void setDisplayZoomControls(@NonNull Long instanceId, @NonNull Boolean enabled) { final WebSettings webSettings = Objects.requireNonNull(instanceManager.getInstance(instanceId)); webSettings.setDisplayZoomControls(enabled); } @Override public void setBuiltInZoomControls(@NonNull Long instanceId, @NonNull Boolean enabled) { final WebSettings webSettings = Objects.requireNonNull(instanceManager.getInstance(instanceId)); webSettings.setBuiltInZoomControls(enabled); } @Override public void setAllowFileAccess(@NonNull Long instanceId, @NonNull Boolean enabled) { final WebSettings webSettings = Objects.requireNonNull(instanceManager.getInstance(instanceId)); webSettings.setAllowFileAccess(enabled); } @Override public void setTextZoom(@NonNull Long instanceId, @NonNull Long textZoom) { final WebSettings webSettings = Objects.requireNonNull(instanceManager.getInstance(instanceId)); webSettings.setTextZoom(textZoom.intValue()); } @NonNull @Override public String getUserAgentString(@NonNull Long instanceId) { final WebSettings webSettings = Objects.requireNonNull(instanceManager.getInstance(instanceId)); return webSettings.getUserAgentString(); } }
packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/WebSettingsHostApiImpl.java/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/WebSettingsHostApiImpl.java", "repo_id": "packages", "token_count": 1620 }
1,136
name: webview_flutter_android_example description: Demonstrates how to use the webview_flutter_android plugin. publish_to: none environment: sdk: ^3.1.0 flutter: ">=3.13.0" dependencies: flutter: sdk: flutter path_provider: ^2.0.6 webview_flutter_android: # When depending on this package from a real application you should use: # webview_flutter: ^x.y.z # See https://dart.dev/tools/pub/dependencies#version-constraints # The example app is bundled with the plugin so we use a path dependency on # the parent directory to use the current plugin's version. path: ../ webview_flutter_platform_interface: ^2.10.0 dev_dependencies: espresso: ^0.2.0 flutter_test: sdk: flutter integration_test: sdk: flutter flutter: uses-material-design: true assets: - assets/sample_audio.ogg - assets/sample_video.mp4 - assets/www/index.html - assets/www/styles/style.css
packages/packages/webview_flutter/webview_flutter_android/example/pubspec.yaml/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_android/example/pubspec.yaml", "repo_id": "packages", "token_count": 350 }
1,137
// Mocks generated by Mockito 5.4.4 from annotations // in webview_flutter_android/test/legacy/webview_android_cookie_manager_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i3; import 'package:mockito/mockito.dart' as _i1; import 'package:webview_flutter_android/src/android_webview.dart' as _i2; // 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 _FakeCookieManager_0 extends _i1.SmartFake implements _i2.CookieManager { _FakeCookieManager_0( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } /// A class which mocks [CookieManager]. /// /// See the documentation for Mockito's code generation for more information. class MockCookieManager extends _i1.Mock implements _i2.CookieManager { MockCookieManager() { _i1.throwOnMissingStub(this); } @override _i3.Future<void> setCookie( String? url, String? value, ) => (super.noSuchMethod( Invocation.method( #setCookie, [ url, value, ], ), returnValue: _i3.Future<void>.value(), returnValueForMissingStub: _i3.Future<void>.value(), ) as _i3.Future<void>); @override _i3.Future<bool> removeAllCookies() => (super.noSuchMethod( Invocation.method( #removeAllCookies, [], ), returnValue: _i3.Future<bool>.value(false), ) as _i3.Future<bool>); @override _i3.Future<void> setAcceptThirdPartyCookies( _i2.WebView? webView, bool? accept, ) => (super.noSuchMethod( Invocation.method( #setAcceptThirdPartyCookies, [ webView, accept, ], ), returnValue: _i3.Future<void>.value(), returnValueForMissingStub: _i3.Future<void>.value(), ) as _i3.Future<void>); @override _i2.CookieManager copy() => (super.noSuchMethod( Invocation.method( #copy, [], ), returnValue: _FakeCookieManager_0( this, Invocation.method( #copy, [], ), ), ) as _i2.CookieManager); }
packages/packages/webview_flutter/webview_flutter_android/test/legacy/webview_android_cookie_manager_test.mocks.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_android/test/legacy/webview_android_cookie_manager_test.mocks.dart", "repo_id": "packages", "token_count": 1215 }
1,138
// 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 'javascript_message.dart'; /// Callback type for handling messages sent from JavaScript running in a web view. typedef JavascriptMessageHandler = void Function(JavascriptMessage message); final RegExp _validChannelNames = RegExp(r'^[a-zA-Z_][a-zA-Z0-9_]*$'); /// A named channel for receiving messaged from JavaScript code running inside a web view. class JavascriptChannel { /// Constructs a JavaScript channel. /// /// The parameters `name` and `onMessageReceived` must not be null. JavascriptChannel({ required this.name, required this.onMessageReceived, }) : assert(_validChannelNames.hasMatch(name)); /// The channel's name. /// /// Passing this channel object as part of a [WebView.javascriptChannels] adds a channel object to /// the JavaScript window object's property named `name`. /// /// The name must start with a letter or underscore(_), followed by any combination of those /// characters plus digits. /// /// Note that any JavaScript existing `window` property with this name will be overridden. /// /// See also [WebView.javascriptChannels] for more details on the channel registration mechanism. final String name; /// A callback that's invoked when a message is received through the channel. final JavascriptMessageHandler onMessageReceived; }
packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/types/javascript_channel.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/types/javascript_channel.dart", "repo_id": "packages", "token_count": 384 }
1,139
// 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'; /// Defines the parameters that support `PlatformWebViewController.setOnJavaScriptAlertDialog`. @immutable class JavaScriptAlertDialogRequest { /// Creates a [JavaScriptAlertDialogRequest]. const JavaScriptAlertDialogRequest({ required this.message, required this.url, }); /// The message to be displayed in the window. final String message; /// The URL of the page requesting the dialog. final String url; } /// Defines the parameters that support `PlatformWebViewController.setOnJavaScriptConfirmDialog`. @immutable class JavaScriptConfirmDialogRequest { /// Creates a [JavaScriptConfirmDialogRequest]. const JavaScriptConfirmDialogRequest({ required this.message, required this.url, }); /// The message to be displayed in the window. final String message; /// The URL of the page requesting the dialog. final String url; } /// Defines the parameters that support `PlatformWebViewController.setOnJavaScriptTextInputDialog`. @immutable class JavaScriptTextInputDialogRequest { /// Creates a [JavaScriptAlertDialogRequest]. const JavaScriptTextInputDialogRequest({ required this.message, required this.url, required this.defaultText, }); /// The message to be displayed in the window. final String message; /// The URL of the page requesting the dialog. final String url; /// The initial text to display in the text entry field. final String? defaultText; }
packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/javascript_dialog_request.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/javascript_dialog_request.dart", "repo_id": "packages", "token_count": 433 }
1,140
// 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'; /// Defines the parameters of the web resource request from the associated request. /// /// Platform specific implementations can add additional fields by extending /// this class. /// /// This example demonstrates how to extend the [WebResourceRequest] to /// provide additional platform specific parameters. /// /// When extending [WebResourceRequest] additional parameters should always /// accept `null` or have a default value to prevent breaking changes. /// /// ```dart /// class AndroidWebResourceRequest extends WebResourceRequest { /// WebResourceRequest._({ /// required WebResourceRequest request, /// }) : super( /// uri: request.uri, /// ); /// /// factory AndroidWebResourceRequest.fromWebResourceRequest( /// WebResourceRequest request, { /// Map<String, String> headers, /// }) { /// return AndroidWebResourceRequest._(request, headers: headers); /// } /// /// final Map<String, String> headers; /// } /// ``` @immutable class WebResourceRequest { /// Used by the platform implementation to create a new [WebResourceRequest]. const WebResourceRequest({required this.uri}); /// URI for the request. final Uri uri; }
packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/web_resource_request.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/web_resource_request.dart", "repo_id": "packages", "token_count": 364 }
1,141
// 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'; import 'dart:typed_data'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'package:webview_flutter_platform_interface/src/webview_flutter_platform_interface_legacy.dart'; import 'package:webview_flutter_web/src/http_request_factory.dart'; import 'package:webview_flutter_web/src/webview_flutter_web_legacy.dart'; import 'webview_flutter_web_test.mocks.dart'; @GenerateMocks(<Type>[ IFrameElement, BuildContext, CreationParams, WebViewPlatformCallbacksHandler, HttpRequestFactory, HttpRequest, ]) void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('WebWebViewPlatform', () { test('build returns a HtmlElementView', () { // Setup final WebWebViewPlatform platform = WebWebViewPlatform(); // Run final Widget widget = platform.build( context: MockBuildContext(), creationParams: CreationParams(), webViewPlatformCallbacksHandler: MockWebViewPlatformCallbacksHandler(), javascriptChannelRegistry: null, ); // Verify expect(widget, isA<HtmlElementView>()); }); }); group('WebWebViewPlatformController', () { test('loadUrl sets url on iframe src attribute', () { // Setup final MockIFrameElement mockElement = MockIFrameElement(); final WebWebViewPlatformController controller = WebWebViewPlatformController( mockElement, ); // Run controller.loadUrl('test url', null); // Verify verify(mockElement.src = 'test url'); }); group('loadHtmlString', () { test('loadHtmlString loads html into iframe', () { // Setup final MockIFrameElement mockElement = MockIFrameElement(); final WebWebViewPlatformController controller = WebWebViewPlatformController( mockElement, ); // Run controller.loadHtmlString('test html'); // Verify verify(mockElement.src = 'data:text/html;charset=utf-8,${Uri.encodeFull('test html')}'); }); test('loadHtmlString escapes "#" correctly', () { // Setup final MockIFrameElement mockElement = MockIFrameElement(); final WebWebViewPlatformController controller = WebWebViewPlatformController( mockElement, ); // Run controller.loadHtmlString('#'); // Verify verify(mockElement.src = argThat(contains('%23'))); }); }); group('loadRequest', () { test('loadRequest throws ArgumentError on missing scheme', () { // Setup final MockIFrameElement mockElement = MockIFrameElement(); final WebWebViewPlatformController controller = WebWebViewPlatformController( mockElement, ); // Run & Verify expect( () async => controller.loadRequest( WebViewRequest( uri: Uri.parse('flutter.dev'), method: WebViewRequestMethod.get, ), ), throwsA(const TypeMatcher<ArgumentError>())); }); test('loadRequest makes request and loads response into iframe', () async { // Setup final MockIFrameElement mockElement = MockIFrameElement(); final WebWebViewPlatformController controller = WebWebViewPlatformController( mockElement, ); final MockHttpRequest mockHttpRequest = MockHttpRequest(); when(mockHttpRequest.getResponseHeader('content-type')) .thenReturn('text/plain'); when(mockHttpRequest.responseText).thenReturn('test data'); final MockHttpRequestFactory mockHttpRequestFactory = MockHttpRequestFactory(); when(mockHttpRequestFactory.request( any, method: anyNamed('method'), requestHeaders: anyNamed('requestHeaders'), sendData: anyNamed('sendData'), )).thenAnswer((_) => Future<HttpRequest>.value(mockHttpRequest)); controller.httpRequestFactory = mockHttpRequestFactory; // Run await controller.loadRequest( WebViewRequest( uri: Uri.parse('https://flutter.dev'), method: WebViewRequestMethod.post, body: Uint8List.fromList('test body'.codeUnits), headers: <String, String>{'Foo': 'Bar'}), ); // Verify verify(mockHttpRequestFactory.request( 'https://flutter.dev', method: 'post', requestHeaders: <String, String>{'Foo': 'Bar'}, sendData: Uint8List.fromList('test body'.codeUnits), )); verify(mockElement.src = 'data:;charset=utf-8,${Uri.encodeFull('test data')}'); }); test('loadRequest escapes "#" correctly', () async { // Setup final MockIFrameElement mockElement = MockIFrameElement(); final WebWebViewPlatformController controller = WebWebViewPlatformController( mockElement, ); final MockHttpRequest mockHttpRequest = MockHttpRequest(); when(mockHttpRequest.getResponseHeader('content-type')) .thenReturn('text/html'); when(mockHttpRequest.responseText).thenReturn('#'); final MockHttpRequestFactory mockHttpRequestFactory = MockHttpRequestFactory(); when(mockHttpRequestFactory.request( any, method: anyNamed('method'), requestHeaders: anyNamed('requestHeaders'), sendData: anyNamed('sendData'), )).thenAnswer((_) => Future<HttpRequest>.value(mockHttpRequest)); controller.httpRequestFactory = mockHttpRequestFactory; // Run await controller.loadRequest( WebViewRequest( uri: Uri.parse('https://flutter.dev'), method: WebViewRequestMethod.post, body: Uint8List.fromList('test body'.codeUnits), headers: <String, String>{'Foo': 'Bar'}), ); // Verify verify(mockElement.src = argThat(contains('%23'))); }); }); }); }
packages/packages/webview_flutter/webview_flutter_web/test/legacy/webview_flutter_web_test.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_web/test/legacy/webview_flutter_web_test.dart", "repo_id": "packages", "token_count": 2666 }
1,142
// 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 test is run using `flutter drive` by the CI (see /script/tool/README.md // in this repository for details on driving that tooling manually), but can // also be run using `flutter test` directly during development. import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import 'package:webview_flutter_platform_interface/src/webview_flutter_platform_interface_legacy.dart'; import 'package:webview_flutter_wkwebview/src/common/instance_manager.dart'; import 'package:webview_flutter_wkwebview/src/common/weak_reference_utils.dart'; import 'package:webview_flutter_wkwebview_example/legacy/navigation_decision.dart'; import 'package:webview_flutter_wkwebview_example/legacy/navigation_request.dart'; import 'package:webview_flutter_wkwebview_example/legacy/web_view.dart'; Future<void> main() async { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); final HttpServer server = await HttpServer.bind(InternetAddress.anyIPv4, 0); unawaited(server.forEach((HttpRequest request) { if (request.uri.path == '/hello.txt') { request.response.writeln('Hello, world.'); } else if (request.uri.path == '/secondary.txt') { request.response.writeln('How are you today?'); } else if (request.uri.path == '/headers') { request.response.writeln('${request.headers}'); } else if (request.uri.path == '/favicon.ico') { request.response.statusCode = HttpStatus.notFound; } else { fail('unexpected request: ${request.method} ${request.uri}'); } request.response.close(); })); final String prefixUrl = 'http://${server.address.address}:${server.port}'; final String primaryUrl = '$prefixUrl/hello.txt'; final String secondaryUrl = '$prefixUrl/secondary.txt'; final String headersUrl = '$prefixUrl/headers'; testWidgets('initialUrl', (WidgetTester tester) async { final Completer<WebViewController> controllerCompleter = Completer<WebViewController>(); final Completer<void> pageFinishedCompleter = Completer<void>(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WebView( key: GlobalKey(), initialUrl: primaryUrl, onWebViewCreated: (WebViewController controller) { controllerCompleter.complete(controller); }, onPageFinished: pageFinishedCompleter.complete, ), ), ); final WebViewController controller = await controllerCompleter.future; await pageFinishedCompleter.future; final String? currentUrl = await controller.currentUrl(); expect(currentUrl, primaryUrl); }); testWidgets( 'withWeakRefenceTo allows encapsulating class to be garbage collected', (WidgetTester tester) async { final Completer<int> gcCompleter = Completer<int>(); final InstanceManager instanceManager = InstanceManager( onWeakReferenceRemoved: gcCompleter.complete, ); ClassWithCallbackClass? instance = ClassWithCallbackClass(); instanceManager.addHostCreatedInstance(instance.callbackClass, 0); instance = null; // Force garbage collection. await IntegrationTestWidgetsFlutterBinding.instance .watchPerformance(() async { await tester.pumpAndSettle(); }); final int gcIdentifier = await gcCompleter.future; expect(gcIdentifier, 0); }, timeout: const Timeout(Duration(seconds: 10))); testWidgets('loadUrl', (WidgetTester tester) async { final Completer<WebViewController> controllerCompleter = Completer<WebViewController>(); final StreamController<String> pageLoads = StreamController<String>(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WebView( key: GlobalKey(), initialUrl: primaryUrl, onWebViewCreated: (WebViewController controller) { controllerCompleter.complete(controller); }, onPageFinished: (String url) { pageLoads.add(url); }, ), ), ); final WebViewController controller = await controllerCompleter.future; await controller.loadUrl(secondaryUrl); await expectLater( pageLoads.stream.firstWhere((String url) => url == secondaryUrl), completion(secondaryUrl), ); }); testWidgets('evaluateJavascript', (WidgetTester tester) async { final Completer<WebViewController> controllerCompleter = Completer<WebViewController>(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WebView( key: GlobalKey(), initialUrl: primaryUrl, onWebViewCreated: (WebViewController controller) { controllerCompleter.complete(controller); }, javascriptMode: JavascriptMode.unrestricted, ), ), ); final WebViewController controller = await controllerCompleter.future; final String result = await controller.evaluateJavascript('1 + 1'); expect(result, equals('2')); }); testWidgets('loadUrl with headers', (WidgetTester tester) async { final Completer<WebViewController> controllerCompleter = Completer<WebViewController>(); final StreamController<String> pageStarts = StreamController<String>(); final StreamController<String> pageLoads = StreamController<String>(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WebView( key: GlobalKey(), initialUrl: primaryUrl, onWebViewCreated: (WebViewController controller) { controllerCompleter.complete(controller); }, javascriptMode: JavascriptMode.unrestricted, onPageStarted: (String url) { pageStarts.add(url); }, onPageFinished: (String url) { pageLoads.add(url); }, ), ), ); final WebViewController controller = await controllerCompleter.future; final Map<String, String> headers = <String, String>{ 'test_header': 'flutter_test_header' }; await controller.loadUrl(headersUrl, headers: headers); await pageStarts.stream.firstWhere((String url) => url == headersUrl); await pageLoads.stream.firstWhere((String url) => url == headersUrl); final String content = await controller .runJavascriptReturningResult('document.documentElement.innerText'); expect(content.contains('flutter_test_header'), isTrue); }); testWidgets('JavascriptChannel', (WidgetTester tester) async { final Completer<WebViewController> controllerCompleter = Completer<WebViewController>(); final Completer<void> pageStarted = Completer<void>(); final Completer<void> pageLoaded = Completer<void>(); final Completer<String> channelCompleter = Completer<String>(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WebView( key: GlobalKey(), // This is the data URL for: '<!DOCTYPE html>' initialUrl: 'data:text/html;charset=utf-8;base64,PCFET0NUWVBFIGh0bWw+', onWebViewCreated: (WebViewController controller) { controllerCompleter.complete(controller); }, javascriptMode: JavascriptMode.unrestricted, javascriptChannels: <JavascriptChannel>{ JavascriptChannel( name: 'Echo', onMessageReceived: (JavascriptMessage message) { channelCompleter.complete(message.message); }, ), }, onPageStarted: (String url) { pageStarted.complete(null); }, onPageFinished: (String url) { pageLoaded.complete(null); }, ), ), ); final WebViewController controller = await controllerCompleter.future; await pageStarted.future; await pageLoaded.future; expect(channelCompleter.isCompleted, isFalse); await controller.runJavascript('Echo.postMessage("hello");'); await expectLater(channelCompleter.future, completion('hello')); }); testWidgets('resize webview', (WidgetTester tester) async { final Completer<void> buttonTapResizeCompleter = Completer<void>(); final Completer<void> onPageFinished = Completer<void>(); bool resizeButtonTapped = false; await tester.pumpWidget(ResizableWebView( onResize: (_) { if (resizeButtonTapped) { buttonTapResizeCompleter.complete(); } }, onPageFinished: () => onPageFinished.complete(), )); await onPageFinished.future; resizeButtonTapped = true; await tester.tap(find.byKey(const ValueKey<String>('resizeButton'))); await tester.pumpAndSettle(); expect(buttonTapResizeCompleter.future, completes); }); testWidgets('set custom userAgent', (WidgetTester tester) async { final Completer<WebViewController> controllerCompleter1 = Completer<WebViewController>(); final GlobalKey globalKey = GlobalKey(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WebView( key: globalKey, initialUrl: 'about:blank', javascriptMode: JavascriptMode.unrestricted, userAgent: 'Custom_User_Agent1', onWebViewCreated: (WebViewController controller) { controllerCompleter1.complete(controller); }, ), ), ); final WebViewController controller1 = await controllerCompleter1.future; final String customUserAgent1 = await _getUserAgent(controller1); expect(customUserAgent1, 'Custom_User_Agent1'); // rebuild the WebView with a different user agent. await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WebView( key: globalKey, initialUrl: 'about:blank', javascriptMode: JavascriptMode.unrestricted, userAgent: 'Custom_User_Agent2', ), ), ); final String customUserAgent2 = await _getUserAgent(controller1); expect(customUserAgent2, 'Custom_User_Agent2'); }); testWidgets('use default platform userAgent after webView is rebuilt', (WidgetTester tester) async { final Completer<WebViewController> controllerCompleter = Completer<WebViewController>(); final GlobalKey globalKey = GlobalKey(); // Build the webView with no user agent to get the default platform user agent. await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WebView( key: globalKey, initialUrl: primaryUrl, javascriptMode: JavascriptMode.unrestricted, onWebViewCreated: (WebViewController controller) { controllerCompleter.complete(controller); }, ), ), ); final WebViewController controller = await controllerCompleter.future; final String defaultPlatformUserAgent = await _getUserAgent(controller); // rebuild the WebView with a custom user agent. await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WebView( key: globalKey, initialUrl: 'about:blank', javascriptMode: JavascriptMode.unrestricted, userAgent: 'Custom_User_Agent', ), ), ); final String customUserAgent = await _getUserAgent(controller); expect(customUserAgent, 'Custom_User_Agent'); // rebuilds the WebView with no user agent. await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WebView( key: globalKey, initialUrl: 'about:blank', javascriptMode: JavascriptMode.unrestricted, ), ), ); final String customUserAgent2 = await _getUserAgent(controller); expect(customUserAgent2, defaultPlatformUserAgent); }); group('Video playback policy', () { late String videoTestBase64; setUpAll(() async { final ByteData videoData = await rootBundle.load('assets/sample_video.mp4'); final String base64VideoData = base64Encode(Uint8List.view(videoData.buffer)); final String videoTest = ''' <!DOCTYPE html><html> <head><title>Video auto play</title> <script type="text/javascript"> function play() { var video = document.getElementById("video"); video.play(); video.addEventListener('timeupdate', videoTimeUpdateHandler, false); } function videoTimeUpdateHandler(e) { var video = document.getElementById("video"); VideoTestTime.postMessage(video.currentTime); } function isPaused() { var video = document.getElementById("video"); return video.paused; } function isFullScreen() { var video = document.getElementById("video"); return video.webkitDisplayingFullscreen; } </script> </head> <body onload="play();"> <video controls playsinline autoplay id="video"> <source src="data:video/mp4;charset=utf-8;base64,$base64VideoData"> </video> </body> </html> '''; videoTestBase64 = base64Encode(const Utf8Encoder().convert(videoTest)); }); testWidgets('Auto media playback', (WidgetTester tester) async { Completer<WebViewController> controllerCompleter = Completer<WebViewController>(); Completer<void> pageLoaded = Completer<void>(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WebView( key: GlobalKey(), initialUrl: 'data:text/html;charset=utf-8;base64,$videoTestBase64', onWebViewCreated: (WebViewController controller) { controllerCompleter.complete(controller); }, javascriptMode: JavascriptMode.unrestricted, onPageFinished: (String url) { pageLoaded.complete(null); }, initialMediaPlaybackPolicy: AutoMediaPlaybackPolicy.always_allow, ), ), ); WebViewController controller = await controllerCompleter.future; await pageLoaded.future; String isPaused = await controller.runJavascriptReturningResult('isPaused();'); expect(isPaused, _webviewBool(false)); controllerCompleter = Completer<WebViewController>(); pageLoaded = Completer<void>(); // We change the key to re-create a new webview as we change the initialMediaPlaybackPolicy await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WebView( key: GlobalKey(), initialUrl: 'data:text/html;charset=utf-8;base64,$videoTestBase64', onWebViewCreated: (WebViewController controller) { controllerCompleter.complete(controller); }, javascriptMode: JavascriptMode.unrestricted, onPageFinished: (String url) { pageLoaded.complete(null); }, ), ), ); controller = await controllerCompleter.future; await pageLoaded.future; isPaused = await controller.runJavascriptReturningResult('isPaused();'); expect(isPaused, _webviewBool(true)); }); testWidgets('Changes to initialMediaPlaybackPolicy are ignored', (WidgetTester tester) async { final Completer<WebViewController> controllerCompleter = Completer<WebViewController>(); Completer<void> pageLoaded = Completer<void>(); final GlobalKey key = GlobalKey(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WebView( key: key, initialUrl: 'data:text/html;charset=utf-8;base64,$videoTestBase64', onWebViewCreated: (WebViewController controller) { controllerCompleter.complete(controller); }, javascriptMode: JavascriptMode.unrestricted, onPageFinished: (String url) { pageLoaded.complete(null); }, initialMediaPlaybackPolicy: AutoMediaPlaybackPolicy.always_allow, ), ), ); final WebViewController controller = await controllerCompleter.future; await pageLoaded.future; String isPaused = await controller.runJavascriptReturningResult('isPaused();'); expect(isPaused, _webviewBool(false)); pageLoaded = Completer<void>(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WebView( key: key, initialUrl: 'data:text/html;charset=utf-8;base64,$videoTestBase64', onWebViewCreated: (WebViewController controller) { controllerCompleter.complete(controller); }, javascriptMode: JavascriptMode.unrestricted, onPageFinished: (String url) { pageLoaded.complete(null); }, ), ), ); await controller.reload(); await pageLoaded.future; isPaused = await controller.runJavascriptReturningResult('isPaused();'); expect(isPaused, _webviewBool(false)); }); testWidgets('Video plays inline when allowsInlineMediaPlayback is true', (WidgetTester tester) async { final Completer<WebViewController> controllerCompleter = Completer<WebViewController>(); final Completer<void> pageLoaded = Completer<void>(); final Completer<void> videoPlaying = Completer<void>(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WebView( initialUrl: 'data:text/html;charset=utf-8;base64,$videoTestBase64', onWebViewCreated: (WebViewController controller) { controllerCompleter.complete(controller); }, javascriptMode: JavascriptMode.unrestricted, javascriptChannels: <JavascriptChannel>{ JavascriptChannel( name: 'VideoTestTime', onMessageReceived: (JavascriptMessage message) { final double currentTime = double.parse(message.message); // Let it play for at least 1 second to make sure the related video's properties are set. if (currentTime > 1 && !videoPlaying.isCompleted) { videoPlaying.complete(null); } }, ), }, onPageFinished: (String url) { pageLoaded.complete(null); }, initialMediaPlaybackPolicy: AutoMediaPlaybackPolicy.always_allow, allowsInlineMediaPlayback: true, ), ), ); final WebViewController controller = await controllerCompleter.future; await pageLoaded.future; // Pump once to trigger the video play. await tester.pump(); // Makes sure we get the correct event that indicates the video is actually playing. await videoPlaying.future; final String fullScreen = await controller.runJavascriptReturningResult('isFullScreen();'); expect(fullScreen, _webviewBool(false)); }); testWidgets( 'Video plays full screen when allowsInlineMediaPlayback is false', (WidgetTester tester) async { final Completer<WebViewController> controllerCompleter = Completer<WebViewController>(); final Completer<void> pageLoaded = Completer<void>(); final Completer<void> videoPlaying = Completer<void>(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WebView( initialUrl: 'data:text/html;charset=utf-8;base64,$videoTestBase64', onWebViewCreated: (WebViewController controller) { controllerCompleter.complete(controller); }, javascriptMode: JavascriptMode.unrestricted, javascriptChannels: <JavascriptChannel>{ JavascriptChannel( name: 'VideoTestTime', onMessageReceived: (JavascriptMessage message) { final double currentTime = double.parse(message.message); // Let it play for at least 1 second to make sure the related video's properties are set. if (currentTime > 1 && !videoPlaying.isCompleted) { videoPlaying.complete(null); } }, ), }, onPageFinished: (String url) { pageLoaded.complete(null); }, initialMediaPlaybackPolicy: AutoMediaPlaybackPolicy.always_allow, ), ), ); final WebViewController controller = await controllerCompleter.future; await pageLoaded.future; // Pump once to trigger the video play. await tester.pump(); // Makes sure we get the correct event that indicates the video is actually playing. await videoPlaying.future; final String fullScreen = await controller.runJavascriptReturningResult('isFullScreen();'); expect(fullScreen, _webviewBool(true)); }); }); group('Audio playback policy', () { late String audioTestBase64; setUpAll(() async { final ByteData audioData = await rootBundle.load('assets/sample_audio.ogg'); final String base64AudioData = base64Encode(Uint8List.view(audioData.buffer)); final String audioTest = ''' <!DOCTYPE html><html> <head><title>Audio auto play</title> <script type="text/javascript"> function play() { var audio = document.getElementById("audio"); audio.play(); } function isPaused() { var audio = document.getElementById("audio"); return audio.paused; } </script> </head> <body onload="play();"> <audio controls id="audio"> <source src="data:audio/ogg;charset=utf-8;base64,$base64AudioData"> </audio> </body> </html> '''; audioTestBase64 = base64Encode(const Utf8Encoder().convert(audioTest)); }); testWidgets('Auto media playback', (WidgetTester tester) async { Completer<WebViewController> controllerCompleter = Completer<WebViewController>(); Completer<void> pageStarted = Completer<void>(); Completer<void> pageLoaded = Completer<void>(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WebView( key: GlobalKey(), initialUrl: 'data:text/html;charset=utf-8;base64,$audioTestBase64', onWebViewCreated: (WebViewController controller) { controllerCompleter.complete(controller); }, javascriptMode: JavascriptMode.unrestricted, onPageStarted: (String url) { pageStarted.complete(null); }, onPageFinished: (String url) { pageLoaded.complete(null); }, initialMediaPlaybackPolicy: AutoMediaPlaybackPolicy.always_allow, ), ), ); WebViewController controller = await controllerCompleter.future; await pageStarted.future; await pageLoaded.future; String isPaused = await controller.runJavascriptReturningResult('isPaused();'); expect(isPaused, _webviewBool(false)); controllerCompleter = Completer<WebViewController>(); pageStarted = Completer<void>(); pageLoaded = Completer<void>(); // We change the key to re-create a new webview as we change the initialMediaPlaybackPolicy await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WebView( key: GlobalKey(), initialUrl: 'data:text/html;charset=utf-8;base64,$audioTestBase64', onWebViewCreated: (WebViewController controller) { controllerCompleter.complete(controller); }, javascriptMode: JavascriptMode.unrestricted, onPageStarted: (String url) { pageStarted.complete(null); }, onPageFinished: (String url) { pageLoaded.complete(null); }, ), ), ); controller = await controllerCompleter.future; await pageStarted.future; await pageLoaded.future; isPaused = await controller.runJavascriptReturningResult('isPaused();'); expect(isPaused, _webviewBool(true)); }); testWidgets('Changes to initialMediaPlaybackPolicy are ignored', (WidgetTester tester) async { final Completer<WebViewController> controllerCompleter = Completer<WebViewController>(); Completer<void> pageStarted = Completer<void>(); Completer<void> pageLoaded = Completer<void>(); final GlobalKey key = GlobalKey(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WebView( key: key, initialUrl: 'data:text/html;charset=utf-8;base64,$audioTestBase64', onWebViewCreated: (WebViewController controller) { controllerCompleter.complete(controller); }, javascriptMode: JavascriptMode.unrestricted, onPageStarted: (String url) { pageStarted.complete(null); }, onPageFinished: (String url) { pageLoaded.complete(null); }, initialMediaPlaybackPolicy: AutoMediaPlaybackPolicy.always_allow, ), ), ); final WebViewController controller = await controllerCompleter.future; await pageStarted.future; await pageLoaded.future; String isPaused = await controller.runJavascriptReturningResult('isPaused();'); expect(isPaused, _webviewBool(false)); pageStarted = Completer<void>(); pageLoaded = Completer<void>(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WebView( key: key, initialUrl: 'data:text/html;charset=utf-8;base64,$audioTestBase64', onWebViewCreated: (WebViewController controller) { controllerCompleter.complete(controller); }, javascriptMode: JavascriptMode.unrestricted, onPageStarted: (String url) { pageStarted.complete(null); }, onPageFinished: (String url) { pageLoaded.complete(null); }, ), ), ); await controller.reload(); await pageStarted.future; await pageLoaded.future; isPaused = await controller.runJavascriptReturningResult('isPaused();'); expect(isPaused, _webviewBool(false)); }); }); testWidgets('getTitle', (WidgetTester tester) async { const String getTitleTest = ''' <!DOCTYPE html><html> <head><title>Some title</title> </head> <body> </body> </html> '''; final String getTitleTestBase64 = base64Encode(const Utf8Encoder().convert(getTitleTest)); final Completer<void> pageStarted = Completer<void>(); final Completer<void> pageLoaded = Completer<void>(); final Completer<WebViewController> controllerCompleter = Completer<WebViewController>(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WebView( initialUrl: 'data:text/html;charset=utf-8;base64,$getTitleTestBase64', javascriptMode: JavascriptMode.unrestricted, onWebViewCreated: (WebViewController controller) { controllerCompleter.complete(controller); }, onPageStarted: (String url) { pageStarted.complete(null); }, onPageFinished: (String url) { pageLoaded.complete(null); }, ), ), ); final WebViewController controller = await controllerCompleter.future; await pageStarted.future; await pageLoaded.future; // On at least iOS, it does not appear to be guaranteed that the native // code has the title when the page load completes. Execute some JavaScript // before checking the title to ensure that the page has been fully parsed // and processed. await controller.runJavascript('1;'); final String? title = await controller.getTitle(); expect(title, 'Some title'); }); group('Programmatic Scroll', () { testWidgets('setAndGetScrollPosition', (WidgetTester tester) async { const String scrollTestPage = ''' <!DOCTYPE html> <html> <head> <style> body { height: 100%; width: 100%; } #container{ width:5000px; height:5000px; } </style> </head> <body> <div id="container"/> </body> </html> '''; final String scrollTestPageBase64 = base64Encode(const Utf8Encoder().convert(scrollTestPage)); final Completer<void> pageLoaded = Completer<void>(); final Completer<WebViewController> controllerCompleter = Completer<WebViewController>(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WebView( initialUrl: 'data:text/html;charset=utf-8;base64,$scrollTestPageBase64', onWebViewCreated: (WebViewController controller) { controllerCompleter.complete(controller); }, onPageFinished: (String url) { pageLoaded.complete(null); }, ), ), ); final WebViewController controller = await controllerCompleter.future; await pageLoaded.future; await tester.pumpAndSettle(const Duration(seconds: 3)); int scrollPosX = await controller.getScrollX(); int scrollPosY = await controller.getScrollY(); // Check scrollTo() const int X_SCROLL = 123; const int Y_SCROLL = 321; // Get the initial position; this ensures that scrollTo is actually // changing something, but also gives the native view's scroll position // time to settle. expect(scrollPosX, isNot(X_SCROLL)); expect(scrollPosX, isNot(Y_SCROLL)); await controller.scrollTo(X_SCROLL, Y_SCROLL); scrollPosX = await controller.getScrollX(); scrollPosY = await controller.getScrollY(); expect(scrollPosX, X_SCROLL); expect(scrollPosY, Y_SCROLL); // Check scrollBy() (on top of scrollTo()) await controller.scrollBy(X_SCROLL, Y_SCROLL); scrollPosX = await controller.getScrollX(); scrollPosY = await controller.getScrollY(); expect(scrollPosX, X_SCROLL * 2); expect(scrollPosY, Y_SCROLL * 2); }); }); group('NavigationDelegate', () { const String blankPage = '<!DOCTYPE html><head></head><body></body></html>'; final String blankPageEncoded = 'data:text/html;charset=utf-8;base64,' '${base64Encode(const Utf8Encoder().convert(blankPage))}'; testWidgets('can allow requests', (WidgetTester tester) async { final Completer<WebViewController> controllerCompleter = Completer<WebViewController>(); final StreamController<String> pageLoads = StreamController<String>.broadcast(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WebView( key: GlobalKey(), initialUrl: blankPageEncoded, onWebViewCreated: (WebViewController controller) { controllerCompleter.complete(controller); }, javascriptMode: JavascriptMode.unrestricted, navigationDelegate: (NavigationRequest request) { return (request.url.contains('youtube.com')) ? NavigationDecision.prevent : NavigationDecision.navigate; }, onPageFinished: (String url) => pageLoads.add(url), ), ), ); await pageLoads.stream.first; // Wait for initial page load. final WebViewController controller = await controllerCompleter.future; await controller.runJavascript('location.href = "$secondaryUrl"'); await pageLoads.stream.first; // Wait for the next page load. final String? currentUrl = await controller.currentUrl(); expect(currentUrl, secondaryUrl); }); testWidgets('onWebResourceError', (WidgetTester tester) async { final Completer<WebResourceError> errorCompleter = Completer<WebResourceError>(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WebView( key: GlobalKey(), initialUrl: 'https://www.notawebsite..com', onWebResourceError: (WebResourceError error) { errorCompleter.complete(error); }, ), ), ); final WebResourceError error = await errorCompleter.future; expect(error, isNotNull); if (Platform.isIOS) { expect(error.domain, isNotNull); expect(error.failingUrl, isNull); } else if (Platform.isAndroid) { expect(error.errorType, isNotNull); expect(error.failingUrl?.startsWith('https://www.notawebsite..com'), isTrue); } }); testWidgets('onWebResourceError is not called with valid url', (WidgetTester tester) async { final Completer<WebResourceError> errorCompleter = Completer<WebResourceError>(); final Completer<void> pageFinishCompleter = Completer<void>(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WebView( key: GlobalKey(), initialUrl: 'data:text/html;charset=utf-8;base64,PCFET0NUWVBFIGh0bWw+', onWebResourceError: (WebResourceError error) { errorCompleter.complete(error); }, onPageFinished: (_) => pageFinishCompleter.complete(), ), ), ); expect(errorCompleter.future, doesNotComplete); await pageFinishCompleter.future; }); testWidgets( 'onWebResourceError only called for main frame', (WidgetTester tester) async { const String iframeTest = ''' <!DOCTYPE html> <html> <head> <title>WebResourceError test</title> </head> <body> <iframe src="https://notawebsite..com"></iframe> </body> </html> '''; final String iframeTestBase64 = base64Encode(const Utf8Encoder().convert(iframeTest)); final Completer<WebResourceError> errorCompleter = Completer<WebResourceError>(); final Completer<void> pageFinishCompleter = Completer<void>(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WebView( key: GlobalKey(), initialUrl: 'data:text/html;charset=utf-8;base64,$iframeTestBase64', onWebResourceError: (WebResourceError error) { errorCompleter.complete(error); }, onPageFinished: (_) => pageFinishCompleter.complete(), ), ), ); expect(errorCompleter.future, doesNotComplete); await pageFinishCompleter.future; }, ); testWidgets('can block requests', (WidgetTester tester) async { final Completer<WebViewController> controllerCompleter = Completer<WebViewController>(); final StreamController<String> pageLoads = StreamController<String>.broadcast(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WebView( key: GlobalKey(), initialUrl: blankPageEncoded, onWebViewCreated: (WebViewController controller) { controllerCompleter.complete(controller); }, javascriptMode: JavascriptMode.unrestricted, navigationDelegate: (NavigationRequest request) { return (request.url.contains('youtube.com')) ? NavigationDecision.prevent : NavigationDecision.navigate; }, onPageFinished: (String url) => pageLoads.add(url), ), ), ); await pageLoads.stream.first; // Wait for initial page load. final WebViewController controller = await controllerCompleter.future; await controller .runJavascript('location.href = "https://www.youtube.com/"'); // There should never be any second page load, since our new URL is // blocked. Still wait for a potential page change for some time in order // to give the test a chance to fail. await pageLoads.stream.first .timeout(const Duration(milliseconds: 500), onTimeout: () => ''); final String? currentUrl = await controller.currentUrl(); expect(currentUrl, isNot(contains('youtube.com'))); }); testWidgets('supports asynchronous decisions', (WidgetTester tester) async { final Completer<WebViewController> controllerCompleter = Completer<WebViewController>(); final StreamController<String> pageLoads = StreamController<String>.broadcast(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WebView( key: GlobalKey(), initialUrl: blankPageEncoded, onWebViewCreated: (WebViewController controller) { controllerCompleter.complete(controller); }, javascriptMode: JavascriptMode.unrestricted, navigationDelegate: (NavigationRequest request) async { NavigationDecision decision = NavigationDecision.prevent; decision = await Future<NavigationDecision>.delayed( const Duration(milliseconds: 10), () => NavigationDecision.navigate); return decision; }, onPageFinished: (String url) => pageLoads.add(url), ), ), ); await pageLoads.stream.first; // Wait for initial page load. final WebViewController controller = await controllerCompleter.future; await controller.runJavascript('location.href = "$secondaryUrl"'); await pageLoads.stream.first; // Wait for second page to load. final String? currentUrl = await controller.currentUrl(); expect(currentUrl, secondaryUrl); }); }); testWidgets('launches with gestureNavigationEnabled on iOS', (WidgetTester tester) async { final Completer<WebViewController> controllerCompleter = Completer<WebViewController>(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: SizedBox( width: 400, height: 300, child: WebView( key: GlobalKey(), initialUrl: primaryUrl, gestureNavigationEnabled: true, onWebViewCreated: (WebViewController controller) { controllerCompleter.complete(controller); }, ), ), ), ); final WebViewController controller = await controllerCompleter.future; final String? currentUrl = await controller.currentUrl(); expect(currentUrl, primaryUrl); }); testWidgets('target _blank opens in same window', (WidgetTester tester) async { final Completer<WebViewController> controllerCompleter = Completer<WebViewController>(); final Completer<void> pageLoaded = Completer<void>(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WebView( key: GlobalKey(), onWebViewCreated: (WebViewController controller) { controllerCompleter.complete(controller); }, javascriptMode: JavascriptMode.unrestricted, onPageFinished: (String url) { pageLoaded.complete(null); }, ), ), ); final WebViewController controller = await controllerCompleter.future; await controller.runJavascript('window.open("$primaryUrl", "_blank")'); await pageLoaded.future; final String? currentUrl = await controller.currentUrl(); expect(currentUrl, primaryUrl); }); testWidgets( 'can open new window and go back', (WidgetTester tester) async { final Completer<WebViewController> controllerCompleter = Completer<WebViewController>(); Completer<void> pageLoaded = Completer<void>(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WebView( key: GlobalKey(), onWebViewCreated: (WebViewController controller) { controllerCompleter.complete(controller); }, javascriptMode: JavascriptMode.unrestricted, onPageFinished: (String url) { pageLoaded.complete(); }, initialUrl: primaryUrl, ), ), ); final WebViewController controller = await controllerCompleter.future; expect(controller.currentUrl(), completion(primaryUrl)); await pageLoaded.future; pageLoaded = Completer<void>(); await controller.runJavascript('window.open("$secondaryUrl")'); await pageLoaded.future; pageLoaded = Completer<void>(); expect(controller.currentUrl(), completion(secondaryUrl)); expect(controller.canGoBack(), completion(true)); await controller.goBack(); await pageLoaded.future; await expectLater(controller.currentUrl(), completion(primaryUrl)); }, ); } // JavaScript booleans evaluate to different string values on Android and iOS. // This utility method returns the string boolean value of the current platform. String _webviewBool(bool value) { if (defaultTargetPlatform == TargetPlatform.iOS) { return value ? '1' : '0'; } return value ? 'true' : 'false'; } /// Returns the value used for the HTTP User-Agent: request header in subsequent HTTP requests. Future<String> _getUserAgent(WebViewController controller) async { return controller.runJavascriptReturningResult('navigator.userAgent;'); } class ResizableWebView extends StatefulWidget { const ResizableWebView( {super.key, required this.onResize, required this.onPageFinished}); final JavascriptMessageHandler onResize; final VoidCallback onPageFinished; @override State<StatefulWidget> createState() => ResizableWebViewState(); } class ResizableWebViewState extends State<ResizableWebView> { double webViewWidth = 200; double webViewHeight = 200; static const String resizePage = ''' <!DOCTYPE html><html> <head><title>Resize test</title> <script type="text/javascript"> function onResize() { Resize.postMessage("resize"); } function onLoad() { window.onresize = onResize; } </script> </head> <body onload="onLoad();" bgColor="blue"> </body> </html> '''; @override Widget build(BuildContext context) { final String resizeTestBase64 = base64Encode(const Utf8Encoder().convert(resizePage)); return Directionality( textDirection: TextDirection.ltr, child: Column( children: <Widget>[ SizedBox( width: webViewWidth, height: webViewHeight, child: WebView( initialUrl: 'data:text/html;charset=utf-8;base64,$resizeTestBase64', javascriptChannels: <JavascriptChannel>{ JavascriptChannel( name: 'Resize', onMessageReceived: widget.onResize, ), }, onPageFinished: (_) => widget.onPageFinished(), javascriptMode: JavascriptMode.unrestricted, ), ), TextButton( key: const Key('resizeButton'), onPressed: () { setState(() { webViewWidth += 100.0; webViewHeight += 100.0; }); }, child: const Text('ResizeButton'), ), ], ), ); } } class CopyableObjectWithCallback with Copyable { CopyableObjectWithCallback(this.callback); final VoidCallback callback; @override CopyableObjectWithCallback copy() { return CopyableObjectWithCallback(callback); } } class ClassWithCallbackClass { ClassWithCallbackClass() { callbackClass = CopyableObjectWithCallback( withWeakReferenceTo( this, (WeakReference<ClassWithCallbackClass> weakReference) { return () { // Weak reference to `this` in callback. // ignore: unnecessary_statements weakReference; }; }, ), ); } late final CopyableObjectWithCallback callbackClass; }
packages/packages/webview_flutter/webview_flutter_wkwebview/example/integration_test/legacy/webview_flutter_test.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/example/integration_test/legacy/webview_flutter_test.dart", "repo_id": "packages", "token_count": 19575 }
1,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 Flutter; @import XCTest; @import webview_flutter_wkwebview; @import webview_flutter_wkwebview.Test; #import <OCMock/OCMock.h> @interface FWFUIDelegateHostApiTests : XCTestCase @end @implementation FWFUIDelegateHostApiTests /** * Creates a partially mocked FWFUIDelegate and adds it to instanceManager. * * @param instanceManager Instance manager to add the delegate to. * @param identifier Identifier for the delegate added to the instanceManager. * * @return A mock FWFUIDelegate. */ - (id)mockDelegateWithManager:(FWFInstanceManager *)instanceManager identifier:(long)identifier { FWFUIDelegate *delegate = [[FWFUIDelegate alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; [instanceManager addDartCreatedInstance:delegate withIdentifier:0]; return OCMPartialMock(delegate); } /** * Creates a mock FWFUIDelegateFlutterApiImpl with instanceManager. * * @param instanceManager Instance manager passed to the Flutter API. * * @return A mock FWFUIDelegateFlutterApiImpl. */ - (id)mockFlutterApiWithManager:(FWFInstanceManager *)instanceManager { FWFUIDelegateFlutterApiImpl *flutterAPI = [[FWFUIDelegateFlutterApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; return OCMPartialMock(flutterAPI); } - (void)testCreateWithIdentifier { FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; FWFUIDelegateHostApiImpl *hostAPI = [[FWFUIDelegateHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; FlutterError *error; [hostAPI createWithIdentifier:0 error:&error]; FWFUIDelegate *delegate = (FWFUIDelegate *)[instanceManager instanceForIdentifier:0]; XCTAssertTrue([delegate conformsToProtocol:@protocol(WKUIDelegate)]); XCTAssertNil(error); } - (void)testOnCreateWebViewForDelegateWithIdentifier { FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; FWFUIDelegate *mockDelegate = [self mockDelegateWithManager:instanceManager identifier:0]; FWFUIDelegateFlutterApiImpl *mockFlutterAPI = [self mockFlutterApiWithManager:instanceManager]; OCMStub([mockDelegate UIDelegateAPI]).andReturn(mockFlutterAPI); WKWebView *mockWebView = OCMClassMock([WKWebView class]); [instanceManager addDartCreatedInstance:mockWebView withIdentifier:1]; WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init]; id mockConfigurationFlutterApi = OCMPartialMock(mockFlutterAPI.webViewConfigurationFlutterApi); OCMStub([mockConfigurationFlutterApi createWithIdentifier:0 completion:OCMOCK_ANY]) .ignoringNonObjectArgs(); WKNavigationAction *mockNavigationAction = OCMClassMock([WKNavigationAction class]); OCMStub([mockNavigationAction request]) .andReturn([NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.flutter.dev"]]); WKFrameInfo *mockFrameInfo = OCMClassMock([WKFrameInfo class]); OCMStub([mockFrameInfo isMainFrame]).andReturn(YES); OCMStub([mockNavigationAction targetFrame]).andReturn(mockFrameInfo); // Creating the webview will create a configuration on the host side, using the next available // identifier, so save that for checking against later. NSInteger configurationIdentifier = instanceManager.nextIdentifier; [mockDelegate webView:mockWebView createWebViewWithConfiguration:configuration forNavigationAction:mockNavigationAction windowFeatures:OCMClassMock([WKWindowFeatures class])]; OCMVerify([mockFlutterAPI onCreateWebViewForDelegateWithIdentifier:0 webViewIdentifier:1 configurationIdentifier:configurationIdentifier navigationAction:[OCMArg isKindOfClass:[FWFWKNavigationActionData class]] completion:OCMOCK_ANY]); } - (void)testRequestMediaCapturePermissionForOrigin API_AVAILABLE(ios(15.0)) { FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; FWFUIDelegate *mockDelegate = [self mockDelegateWithManager:instanceManager identifier:0]; FWFUIDelegateFlutterApiImpl *mockFlutterAPI = [self mockFlutterApiWithManager:instanceManager]; OCMStub([mockDelegate UIDelegateAPI]).andReturn(mockFlutterAPI); WKWebView *mockWebView = OCMClassMock([WKWebView class]); [instanceManager addDartCreatedInstance:mockWebView withIdentifier:1]; WKSecurityOrigin *mockSecurityOrigin = OCMClassMock([WKSecurityOrigin class]); OCMStub([mockSecurityOrigin host]).andReturn(@""); OCMStub([mockSecurityOrigin port]).andReturn(0); OCMStub([mockSecurityOrigin protocol]).andReturn(@""); WKFrameInfo *mockFrameInfo = OCMClassMock([WKFrameInfo class]); OCMStub([mockFrameInfo isMainFrame]).andReturn(YES); [mockDelegate webView:mockWebView requestMediaCapturePermissionForOrigin:mockSecurityOrigin initiatedByFrame:mockFrameInfo type:WKMediaCaptureTypeMicrophone decisionHandler:^(WKPermissionDecision decision){ }]; OCMVerify([mockFlutterAPI requestMediaCapturePermissionForDelegateWithIdentifier:0 webViewIdentifier:1 origin:[OCMArg isKindOfClass: [FWFWKSecurityOriginData class]] frame:[OCMArg isKindOfClass:[FWFWKFrameInfoData class]] type:[OCMArg isKindOfClass: [FWFWKMediaCaptureTypeData class]] completion:OCMOCK_ANY]); } @end
packages/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerTests/FWFUIDelegateHostApiTests.m/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerTests/FWFUIDelegateHostApiTests.m", "repo_id": "packages", "token_count": 2807 }
1,144
// 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 <Flutter/Flutter.h> #import <Foundation/Foundation.h> #import <WebKit/WebKit.h> #import "FWFGeneratedWebKitApis.h" #import "FWFInstanceManager.h" #import "FWFObjectHostApi.h" NS_ASSUME_NONNULL_BEGIN /// Flutter api implementation for WKNavigationDelegate. /// /// Handles making callbacks to Dart for a WKNavigationDelegate. @interface FWFNavigationDelegateFlutterApiImpl : FWFWKNavigationDelegateFlutterApi - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger instanceManager:(FWFInstanceManager *)instanceManager; @end /// Implementation of WKNavigationDelegate for FWFNavigationDelegateHostApiImpl. @interface FWFNavigationDelegate : FWFObject <WKNavigationDelegate> @property(readonly, nonnull, nonatomic) FWFNavigationDelegateFlutterApiImpl *navigationDelegateAPI; - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger instanceManager:(FWFInstanceManager *)instanceManager; @end /// Host api implementation for WKNavigationDelegate. /// /// Handles creating WKNavigationDelegate that intercommunicate with a paired Dart object. @interface FWFNavigationDelegateHostApiImpl : NSObject <FWFWKNavigationDelegateHostApi> - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger instanceManager:(FWFInstanceManager *)instanceManager; @end NS_ASSUME_NONNULL_END
packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFNavigationDelegateHostApi.h/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFNavigationDelegateHostApi.h", "repo_id": "packages", "token_count": 540 }
1,145
// 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 <Flutter/Flutter.h> #import <Foundation/Foundation.h> #import "FWFGeneratedWebKitApis.h" #import "FWFInstanceManager.h" NS_ASSUME_NONNULL_BEGIN /// Flutter API implementation for `NSURLAuthenticationChallenge`. /// /// This class may handle instantiating and adding Dart instances that are attached to a native /// instance or sending callback methods from an overridden native class. @interface FWFURLAuthenticationChallengeFlutterApiImpl : NSObject /// The Flutter API used to send messages back to Dart. @property FWFNSUrlAuthenticationChallengeFlutterApi *api; - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger instanceManager:(FWFInstanceManager *)instanceManager; /// Sends a message to Dart to create a new Dart instance and add it to the `InstanceManager`. - (void)createWithInstance:(NSURLAuthenticationChallenge *)instance protectionSpace:(NSURLProtectionSpace *)protectionSpace completion:(void (^)(FlutterError *_Nullable))completion; @end NS_ASSUME_NONNULL_END
packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFURLAuthenticationChallengeHostApi.h/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFURLAuthenticationChallengeHostApi.h", "repo_id": "packages", "token_count": 383 }
1,146
// 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 <Flutter/Flutter.h> #import <WebKit/WebKit.h> #import "FWFGeneratedWebKitApis.h" #import "FWFInstanceManager.h" NS_ASSUME_NONNULL_BEGIN /// Host api implementation for WKWebsiteDataStore. /// /// Handles creating WKWebsiteDataStore that intercommunicate with a paired Dart object. @interface FWFWebsiteDataStoreHostApiImpl : NSObject <FWFWKWebsiteDataStoreHostApi> - (instancetype)initWithInstanceManager:(FWFInstanceManager *)instanceManager; @end NS_ASSUME_NONNULL_END
packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFWebsiteDataStoreHostApi.h/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFWebsiteDataStoreHostApi.h", "repo_id": "packages", "token_count": 203 }
1,147
// 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. // Autogenerated from Pigeon (v13.0.0), do not edit directly. // See also: https://pub.dev/packages/pigeon // ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, unnecessary_import // ignore_for_file: avoid_relative_lib_imports import 'dart:async'; import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:webview_flutter_wkwebview/src/common/web_kit.g.dart'; class _TestWKWebsiteDataStoreHostApiCodec extends StandardMessageCodec { const _TestWKWebsiteDataStoreHostApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { if (value is WKWebsiteDataTypeEnumData) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } } @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: return WKWebsiteDataTypeEnumData.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } } } /// Mirror of WKWebsiteDataStore. /// /// See https://developer.apple.com/documentation/webkit/wkwebsitedatastore?language=objc. abstract class TestWKWebsiteDataStoreHostApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = _TestWKWebsiteDataStoreHostApiCodec(); void createFromWebViewConfiguration( int identifier, int configurationIdentifier); void createDefaultDataStore(int identifier); Future<bool> removeDataOfTypes( int identifier, List<WKWebsiteDataTypeEnumData?> dataTypes, double modificationTimeInSecondsSinceEpoch); static void setup(TestWKWebsiteDataStoreHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebsiteDataStoreHostApi.createFromWebViewConfiguration', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebsiteDataStoreHostApi.createFromWebViewConfiguration was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebsiteDataStoreHostApi.createFromWebViewConfiguration was null, expected non-null int.'); final int? arg_configurationIdentifier = (args[1] as int?); assert(arg_configurationIdentifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebsiteDataStoreHostApi.createFromWebViewConfiguration was null, expected non-null int.'); try { api.createFromWebViewConfiguration( arg_identifier!, arg_configurationIdentifier!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebsiteDataStoreHostApi.createDefaultDataStore', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebsiteDataStoreHostApi.createDefaultDataStore was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebsiteDataStoreHostApi.createDefaultDataStore was null, expected non-null int.'); try { api.createDefaultDataStore(arg_identifier!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebsiteDataStoreHostApi.removeDataOfTypes', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebsiteDataStoreHostApi.removeDataOfTypes was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebsiteDataStoreHostApi.removeDataOfTypes was null, expected non-null int.'); final List<WKWebsiteDataTypeEnumData?>? arg_dataTypes = (args[1] as List<Object?>?)?.cast<WKWebsiteDataTypeEnumData?>(); assert(arg_dataTypes != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebsiteDataStoreHostApi.removeDataOfTypes was null, expected non-null List<WKWebsiteDataTypeEnumData?>.'); final double? arg_modificationTimeInSecondsSinceEpoch = (args[2] as double?); assert(arg_modificationTimeInSecondsSinceEpoch != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebsiteDataStoreHostApi.removeDataOfTypes was null, expected non-null double.'); try { final bool output = await api.removeDataOfTypes(arg_identifier!, arg_dataTypes!, arg_modificationTimeInSecondsSinceEpoch!); return <Object?>[output]; } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } } } /// Mirror of UIView. /// /// See https://developer.apple.com/documentation/uikit/uiview?language=objc. abstract class TestUIViewHostApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = StandardMessageCodec(); void setBackgroundColor(int identifier, int? value); void setOpaque(int identifier, bool opaque); static void setup(TestUIViewHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.UIViewHostApi.setBackgroundColor', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.UIViewHostApi.setBackgroundColor was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.UIViewHostApi.setBackgroundColor was null, expected non-null int.'); final int? arg_value = (args[1] as int?); try { api.setBackgroundColor(arg_identifier!, arg_value); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.UIViewHostApi.setOpaque', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.UIViewHostApi.setOpaque was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.UIViewHostApi.setOpaque was null, expected non-null int.'); final bool? arg_opaque = (args[1] as bool?); assert(arg_opaque != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.UIViewHostApi.setOpaque was null, expected non-null bool.'); try { api.setOpaque(arg_identifier!, arg_opaque!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } } } /// Mirror of UIScrollView. /// /// See https://developer.apple.com/documentation/uikit/uiscrollview?language=objc. abstract class TestUIScrollViewHostApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = StandardMessageCodec(); void createFromWebView(int identifier, int webViewIdentifier); List<double?> getContentOffset(int identifier); void scrollBy(int identifier, double x, double y); void setContentOffset(int identifier, double x, double y); void setDelegate(int identifier, int? uiScrollViewDelegateIdentifier); static void setup(TestUIScrollViewHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.UIScrollViewHostApi.createFromWebView', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.UIScrollViewHostApi.createFromWebView was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.UIScrollViewHostApi.createFromWebView was null, expected non-null int.'); final int? arg_webViewIdentifier = (args[1] as int?); assert(arg_webViewIdentifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.UIScrollViewHostApi.createFromWebView was null, expected non-null int.'); try { api.createFromWebView(arg_identifier!, arg_webViewIdentifier!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.UIScrollViewHostApi.getContentOffset', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.UIScrollViewHostApi.getContentOffset was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.UIScrollViewHostApi.getContentOffset was null, expected non-null int.'); try { final List<double?> output = api.getContentOffset(arg_identifier!); return <Object?>[output]; } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.UIScrollViewHostApi.scrollBy', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.UIScrollViewHostApi.scrollBy was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.UIScrollViewHostApi.scrollBy was null, expected non-null int.'); final double? arg_x = (args[1] as double?); assert(arg_x != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.UIScrollViewHostApi.scrollBy was null, expected non-null double.'); final double? arg_y = (args[2] as double?); assert(arg_y != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.UIScrollViewHostApi.scrollBy was null, expected non-null double.'); try { api.scrollBy(arg_identifier!, arg_x!, arg_y!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.UIScrollViewHostApi.setContentOffset', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.UIScrollViewHostApi.setContentOffset was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.UIScrollViewHostApi.setContentOffset was null, expected non-null int.'); final double? arg_x = (args[1] as double?); assert(arg_x != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.UIScrollViewHostApi.setContentOffset was null, expected non-null double.'); final double? arg_y = (args[2] as double?); assert(arg_y != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.UIScrollViewHostApi.setContentOffset was null, expected non-null double.'); try { api.setContentOffset(arg_identifier!, arg_x!, arg_y!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.UIScrollViewHostApi.setDelegate', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.UIScrollViewHostApi.setDelegate was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.UIScrollViewHostApi.setDelegate was null, expected non-null int.'); final int? arg_uiScrollViewDelegateIdentifier = (args[1] as int?); try { api.setDelegate( arg_identifier!, arg_uiScrollViewDelegateIdentifier); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } } } class _TestWKWebViewConfigurationHostApiCodec extends StandardMessageCodec { const _TestWKWebViewConfigurationHostApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { if (value is WKAudiovisualMediaTypeEnumData) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } } @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: return WKAudiovisualMediaTypeEnumData.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } } } /// Mirror of WKWebViewConfiguration. /// /// See https://developer.apple.com/documentation/webkit/wkwebviewconfiguration?language=objc. abstract class TestWKWebViewConfigurationHostApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = _TestWKWebViewConfigurationHostApiCodec(); void create(int identifier); void createFromWebView(int identifier, int webViewIdentifier); void setAllowsInlineMediaPlayback(int identifier, bool allow); void setLimitsNavigationsToAppBoundDomains(int identifier, bool limit); void setMediaTypesRequiringUserActionForPlayback( int identifier, List<WKAudiovisualMediaTypeEnumData?> types); static void setup(TestWKWebViewConfigurationHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewConfigurationHostApi.create', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewConfigurationHostApi.create was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewConfigurationHostApi.create was null, expected non-null int.'); try { api.create(arg_identifier!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewConfigurationHostApi.createFromWebView', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewConfigurationHostApi.createFromWebView was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewConfigurationHostApi.createFromWebView was null, expected non-null int.'); final int? arg_webViewIdentifier = (args[1] as int?); assert(arg_webViewIdentifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewConfigurationHostApi.createFromWebView was null, expected non-null int.'); try { api.createFromWebView(arg_identifier!, arg_webViewIdentifier!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewConfigurationHostApi.setAllowsInlineMediaPlayback', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewConfigurationHostApi.setAllowsInlineMediaPlayback was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewConfigurationHostApi.setAllowsInlineMediaPlayback was null, expected non-null int.'); final bool? arg_allow = (args[1] as bool?); assert(arg_allow != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewConfigurationHostApi.setAllowsInlineMediaPlayback was null, expected non-null bool.'); try { api.setAllowsInlineMediaPlayback(arg_identifier!, arg_allow!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewConfigurationHostApi.setLimitsNavigationsToAppBoundDomains', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewConfigurationHostApi.setLimitsNavigationsToAppBoundDomains was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewConfigurationHostApi.setLimitsNavigationsToAppBoundDomains was null, expected non-null int.'); final bool? arg_limit = (args[1] as bool?); assert(arg_limit != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewConfigurationHostApi.setLimitsNavigationsToAppBoundDomains was null, expected non-null bool.'); try { api.setLimitsNavigationsToAppBoundDomains( arg_identifier!, arg_limit!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewConfigurationHostApi.setMediaTypesRequiringUserActionForPlayback', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewConfigurationHostApi.setMediaTypesRequiringUserActionForPlayback was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewConfigurationHostApi.setMediaTypesRequiringUserActionForPlayback was null, expected non-null int.'); final List<WKAudiovisualMediaTypeEnumData?>? arg_types = (args[1] as List<Object?>?) ?.cast<WKAudiovisualMediaTypeEnumData?>(); assert(arg_types != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewConfigurationHostApi.setMediaTypesRequiringUserActionForPlayback was null, expected non-null List<WKAudiovisualMediaTypeEnumData?>.'); try { api.setMediaTypesRequiringUserActionForPlayback( arg_identifier!, arg_types!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } } } class _TestWKUserContentControllerHostApiCodec extends StandardMessageCodec { const _TestWKUserContentControllerHostApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { if (value is WKUserScriptData) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else if (value is WKUserScriptInjectionTimeEnumData) { buffer.putUint8(129); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } } @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: return WKUserScriptData.decode(readValue(buffer)!); case 129: return WKUserScriptInjectionTimeEnumData.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } } } /// Mirror of WKUserContentController. /// /// See https://developer.apple.com/documentation/webkit/wkusercontentcontroller?language=objc. abstract class TestWKUserContentControllerHostApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = _TestWKUserContentControllerHostApiCodec(); void createFromWebViewConfiguration( int identifier, int configurationIdentifier); void addScriptMessageHandler( int identifier, int handlerIdentifier, String name); void removeScriptMessageHandler(int identifier, String name); void removeAllScriptMessageHandlers(int identifier); void addUserScript(int identifier, WKUserScriptData userScript); void removeAllUserScripts(int identifier); static void setup(TestWKUserContentControllerHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.WKUserContentControllerHostApi.createFromWebViewConfiguration', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKUserContentControllerHostApi.createFromWebViewConfiguration was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKUserContentControllerHostApi.createFromWebViewConfiguration was null, expected non-null int.'); final int? arg_configurationIdentifier = (args[1] as int?); assert(arg_configurationIdentifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKUserContentControllerHostApi.createFromWebViewConfiguration was null, expected non-null int.'); try { api.createFromWebViewConfiguration( arg_identifier!, arg_configurationIdentifier!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.WKUserContentControllerHostApi.addScriptMessageHandler', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKUserContentControllerHostApi.addScriptMessageHandler was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKUserContentControllerHostApi.addScriptMessageHandler was null, expected non-null int.'); final int? arg_handlerIdentifier = (args[1] as int?); assert(arg_handlerIdentifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKUserContentControllerHostApi.addScriptMessageHandler was null, expected non-null int.'); final String? arg_name = (args[2] as String?); assert(arg_name != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKUserContentControllerHostApi.addScriptMessageHandler was null, expected non-null String.'); try { api.addScriptMessageHandler( arg_identifier!, arg_handlerIdentifier!, arg_name!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.WKUserContentControllerHostApi.removeScriptMessageHandler', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKUserContentControllerHostApi.removeScriptMessageHandler was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKUserContentControllerHostApi.removeScriptMessageHandler was null, expected non-null int.'); final String? arg_name = (args[1] as String?); assert(arg_name != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKUserContentControllerHostApi.removeScriptMessageHandler was null, expected non-null String.'); try { api.removeScriptMessageHandler(arg_identifier!, arg_name!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.WKUserContentControllerHostApi.removeAllScriptMessageHandlers', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKUserContentControllerHostApi.removeAllScriptMessageHandlers was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKUserContentControllerHostApi.removeAllScriptMessageHandlers was null, expected non-null int.'); try { api.removeAllScriptMessageHandlers(arg_identifier!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.WKUserContentControllerHostApi.addUserScript', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKUserContentControllerHostApi.addUserScript was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKUserContentControllerHostApi.addUserScript was null, expected non-null int.'); final WKUserScriptData? arg_userScript = (args[1] as WKUserScriptData?); assert(arg_userScript != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKUserContentControllerHostApi.addUserScript was null, expected non-null WKUserScriptData.'); try { api.addUserScript(arg_identifier!, arg_userScript!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.WKUserContentControllerHostApi.removeAllUserScripts', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKUserContentControllerHostApi.removeAllUserScripts was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKUserContentControllerHostApi.removeAllUserScripts was null, expected non-null int.'); try { api.removeAllUserScripts(arg_identifier!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } } } /// Mirror of WKUserPreferences. /// /// See https://developer.apple.com/documentation/webkit/wkpreferences?language=objc. abstract class TestWKPreferencesHostApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = StandardMessageCodec(); void createFromWebViewConfiguration( int identifier, int configurationIdentifier); void setJavaScriptEnabled(int identifier, bool enabled); static void setup(TestWKPreferencesHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.WKPreferencesHostApi.createFromWebViewConfiguration', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKPreferencesHostApi.createFromWebViewConfiguration was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKPreferencesHostApi.createFromWebViewConfiguration was null, expected non-null int.'); final int? arg_configurationIdentifier = (args[1] as int?); assert(arg_configurationIdentifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKPreferencesHostApi.createFromWebViewConfiguration was null, expected non-null int.'); try { api.createFromWebViewConfiguration( arg_identifier!, arg_configurationIdentifier!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.WKPreferencesHostApi.setJavaScriptEnabled', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKPreferencesHostApi.setJavaScriptEnabled was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKPreferencesHostApi.setJavaScriptEnabled was null, expected non-null int.'); final bool? arg_enabled = (args[1] as bool?); assert(arg_enabled != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKPreferencesHostApi.setJavaScriptEnabled was null, expected non-null bool.'); try { api.setJavaScriptEnabled(arg_identifier!, arg_enabled!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } } } /// Mirror of WKScriptMessageHandler. /// /// See https://developer.apple.com/documentation/webkit/wkscriptmessagehandler?language=objc. abstract class TestWKScriptMessageHandlerHostApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = StandardMessageCodec(); void create(int identifier); static void setup(TestWKScriptMessageHandlerHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.WKScriptMessageHandlerHostApi.create', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKScriptMessageHandlerHostApi.create was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKScriptMessageHandlerHostApi.create was null, expected non-null int.'); try { api.create(arg_identifier!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } } } /// Mirror of WKNavigationDelegate. /// /// See https://developer.apple.com/documentation/webkit/wknavigationdelegate?language=objc. abstract class TestWKNavigationDelegateHostApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = StandardMessageCodec(); void create(int identifier); static void setup(TestWKNavigationDelegateHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.WKNavigationDelegateHostApi.create', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKNavigationDelegateHostApi.create was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKNavigationDelegateHostApi.create was null, expected non-null int.'); try { api.create(arg_identifier!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } } } class _TestNSObjectHostApiCodec extends StandardMessageCodec { const _TestNSObjectHostApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { if (value is NSKeyValueObservingOptionsEnumData) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } } @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: return NSKeyValueObservingOptionsEnumData.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } } } /// Mirror of NSObject. /// /// See https://developer.apple.com/documentation/objectivec/nsobject. abstract class TestNSObjectHostApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = _TestNSObjectHostApiCodec(); void dispose(int identifier); void addObserver(int identifier, int observerIdentifier, String keyPath, List<NSKeyValueObservingOptionsEnumData?> options); void removeObserver(int identifier, int observerIdentifier, String keyPath); static void setup(TestNSObjectHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.NSObjectHostApi.dispose', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.NSObjectHostApi.dispose was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.NSObjectHostApi.dispose was null, expected non-null int.'); try { api.dispose(arg_identifier!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.NSObjectHostApi.addObserver', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.NSObjectHostApi.addObserver was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.NSObjectHostApi.addObserver was null, expected non-null int.'); final int? arg_observerIdentifier = (args[1] as int?); assert(arg_observerIdentifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.NSObjectHostApi.addObserver was null, expected non-null int.'); final String? arg_keyPath = (args[2] as String?); assert(arg_keyPath != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.NSObjectHostApi.addObserver was null, expected non-null String.'); final List<NSKeyValueObservingOptionsEnumData?>? arg_options = (args[3] as List<Object?>?) ?.cast<NSKeyValueObservingOptionsEnumData?>(); assert(arg_options != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.NSObjectHostApi.addObserver was null, expected non-null List<NSKeyValueObservingOptionsEnumData?>.'); try { api.addObserver(arg_identifier!, arg_observerIdentifier!, arg_keyPath!, arg_options!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.NSObjectHostApi.removeObserver', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.NSObjectHostApi.removeObserver was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.NSObjectHostApi.removeObserver was null, expected non-null int.'); final int? arg_observerIdentifier = (args[1] as int?); assert(arg_observerIdentifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.NSObjectHostApi.removeObserver was null, expected non-null int.'); final String? arg_keyPath = (args[2] as String?); assert(arg_keyPath != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.NSObjectHostApi.removeObserver was null, expected non-null String.'); try { api.removeObserver( arg_identifier!, arg_observerIdentifier!, arg_keyPath!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } } } class _TestWKWebViewHostApiCodec extends StandardMessageCodec { const _TestWKWebViewHostApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { if (value is AuthenticationChallengeResponse) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else if (value is NSErrorData) { buffer.putUint8(129); writeValue(buffer, value.encode()); } else if (value is NSHttpCookieData) { buffer.putUint8(130); writeValue(buffer, value.encode()); } else if (value is NSHttpCookiePropertyKeyEnumData) { buffer.putUint8(131); writeValue(buffer, value.encode()); } else if (value is NSHttpUrlResponseData) { buffer.putUint8(132); writeValue(buffer, value.encode()); } else if (value is NSKeyValueChangeKeyEnumData) { buffer.putUint8(133); writeValue(buffer, value.encode()); } else if (value is NSKeyValueObservingOptionsEnumData) { buffer.putUint8(134); writeValue(buffer, value.encode()); } else if (value is NSUrlRequestData) { buffer.putUint8(135); writeValue(buffer, value.encode()); } else if (value is ObjectOrIdentifier) { buffer.putUint8(136); writeValue(buffer, value.encode()); } else if (value is WKAudiovisualMediaTypeEnumData) { buffer.putUint8(137); writeValue(buffer, value.encode()); } else if (value is WKFrameInfoData) { buffer.putUint8(138); writeValue(buffer, value.encode()); } else if (value is WKMediaCaptureTypeData) { buffer.putUint8(139); writeValue(buffer, value.encode()); } else if (value is WKNavigationActionData) { buffer.putUint8(140); writeValue(buffer, value.encode()); } else if (value is WKNavigationActionPolicyEnumData) { buffer.putUint8(141); writeValue(buffer, value.encode()); } else if (value is WKNavigationResponseData) { buffer.putUint8(142); writeValue(buffer, value.encode()); } else if (value is WKPermissionDecisionData) { buffer.putUint8(143); writeValue(buffer, value.encode()); } else if (value is WKScriptMessageData) { buffer.putUint8(144); writeValue(buffer, value.encode()); } else if (value is WKSecurityOriginData) { buffer.putUint8(145); writeValue(buffer, value.encode()); } else if (value is WKUserScriptData) { buffer.putUint8(146); writeValue(buffer, value.encode()); } else if (value is WKUserScriptInjectionTimeEnumData) { buffer.putUint8(147); writeValue(buffer, value.encode()); } else if (value is WKWebsiteDataTypeEnumData) { buffer.putUint8(148); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } } @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: return AuthenticationChallengeResponse.decode(readValue(buffer)!); case 129: return NSErrorData.decode(readValue(buffer)!); case 130: return NSHttpCookieData.decode(readValue(buffer)!); case 131: return NSHttpCookiePropertyKeyEnumData.decode(readValue(buffer)!); case 132: return NSHttpUrlResponseData.decode(readValue(buffer)!); case 133: return NSKeyValueChangeKeyEnumData.decode(readValue(buffer)!); case 134: return NSKeyValueObservingOptionsEnumData.decode(readValue(buffer)!); case 135: return NSUrlRequestData.decode(readValue(buffer)!); case 136: return ObjectOrIdentifier.decode(readValue(buffer)!); case 137: return WKAudiovisualMediaTypeEnumData.decode(readValue(buffer)!); case 138: return WKFrameInfoData.decode(readValue(buffer)!); case 139: return WKMediaCaptureTypeData.decode(readValue(buffer)!); case 140: return WKNavigationActionData.decode(readValue(buffer)!); case 141: return WKNavigationActionPolicyEnumData.decode(readValue(buffer)!); case 142: return WKNavigationResponseData.decode(readValue(buffer)!); case 143: return WKPermissionDecisionData.decode(readValue(buffer)!); case 144: return WKScriptMessageData.decode(readValue(buffer)!); case 145: return WKSecurityOriginData.decode(readValue(buffer)!); case 146: return WKUserScriptData.decode(readValue(buffer)!); case 147: return WKUserScriptInjectionTimeEnumData.decode(readValue(buffer)!); case 148: return WKWebsiteDataTypeEnumData.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } } } /// Mirror of WKWebView. /// /// See https://developer.apple.com/documentation/webkit/wkwebview?language=objc. abstract class TestWKWebViewHostApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = _TestWKWebViewHostApiCodec(); void create(int identifier, int configurationIdentifier); void setUIDelegate(int identifier, int? uiDelegateIdentifier); void setNavigationDelegate(int identifier, int? navigationDelegateIdentifier); String? getUrl(int identifier); double getEstimatedProgress(int identifier); void loadRequest(int identifier, NSUrlRequestData request); void loadHtmlString(int identifier, String string, String? baseUrl); void loadFileUrl(int identifier, String url, String readAccessUrl); void loadFlutterAsset(int identifier, String key); bool canGoBack(int identifier); bool canGoForward(int identifier); void goBack(int identifier); void goForward(int identifier); void reload(int identifier); String? getTitle(int identifier); void setAllowsBackForwardNavigationGestures(int identifier, bool allow); void setCustomUserAgent(int identifier, String? userAgent); Future<Object?> evaluateJavaScript(int identifier, String javaScriptString); void setInspectable(int identifier, bool inspectable); String? getCustomUserAgent(int identifier); static void setup(TestWKWebViewHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.create', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.create was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.create was null, expected non-null int.'); final int? arg_configurationIdentifier = (args[1] as int?); assert(arg_configurationIdentifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.create was null, expected non-null int.'); try { api.create(arg_identifier!, arg_configurationIdentifier!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.setUIDelegate', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.setUIDelegate was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.setUIDelegate was null, expected non-null int.'); final int? arg_uiDelegateIdentifier = (args[1] as int?); try { api.setUIDelegate(arg_identifier!, arg_uiDelegateIdentifier); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.setNavigationDelegate', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.setNavigationDelegate was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.setNavigationDelegate was null, expected non-null int.'); final int? arg_navigationDelegateIdentifier = (args[1] as int?); try { api.setNavigationDelegate( arg_identifier!, arg_navigationDelegateIdentifier); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.getUrl', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.getUrl was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.getUrl was null, expected non-null int.'); try { final String? output = api.getUrl(arg_identifier!); return <Object?>[output]; } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.getEstimatedProgress', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.getEstimatedProgress was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.getEstimatedProgress was null, expected non-null int.'); try { final double output = api.getEstimatedProgress(arg_identifier!); return <Object?>[output]; } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.loadRequest', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.loadRequest was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.loadRequest was null, expected non-null int.'); final NSUrlRequestData? arg_request = (args[1] as NSUrlRequestData?); assert(arg_request != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.loadRequest was null, expected non-null NSUrlRequestData.'); try { api.loadRequest(arg_identifier!, arg_request!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.loadHtmlString', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.loadHtmlString was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.loadHtmlString was null, expected non-null int.'); final String? arg_string = (args[1] as String?); assert(arg_string != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.loadHtmlString was null, expected non-null String.'); final String? arg_baseUrl = (args[2] as String?); try { api.loadHtmlString(arg_identifier!, arg_string!, arg_baseUrl); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.loadFileUrl', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.loadFileUrl was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.loadFileUrl was null, expected non-null int.'); final String? arg_url = (args[1] as String?); assert(arg_url != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.loadFileUrl was null, expected non-null String.'); final String? arg_readAccessUrl = (args[2] as String?); assert(arg_readAccessUrl != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.loadFileUrl was null, expected non-null String.'); try { api.loadFileUrl(arg_identifier!, arg_url!, arg_readAccessUrl!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.loadFlutterAsset', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.loadFlutterAsset was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.loadFlutterAsset was null, expected non-null int.'); final String? arg_key = (args[1] as String?); assert(arg_key != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.loadFlutterAsset was null, expected non-null String.'); try { api.loadFlutterAsset(arg_identifier!, arg_key!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.canGoBack', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.canGoBack was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.canGoBack was null, expected non-null int.'); try { final bool output = api.canGoBack(arg_identifier!); return <Object?>[output]; } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.canGoForward', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.canGoForward was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.canGoForward was null, expected non-null int.'); try { final bool output = api.canGoForward(arg_identifier!); return <Object?>[output]; } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.goBack', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.goBack was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.goBack was null, expected non-null int.'); try { api.goBack(arg_identifier!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.goForward', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.goForward was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.goForward was null, expected non-null int.'); try { api.goForward(arg_identifier!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.reload', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.reload was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.reload was null, expected non-null int.'); try { api.reload(arg_identifier!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.getTitle', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.getTitle was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.getTitle was null, expected non-null int.'); try { final String? output = api.getTitle(arg_identifier!); return <Object?>[output]; } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.setAllowsBackForwardNavigationGestures', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.setAllowsBackForwardNavigationGestures was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.setAllowsBackForwardNavigationGestures was null, expected non-null int.'); final bool? arg_allow = (args[1] as bool?); assert(arg_allow != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.setAllowsBackForwardNavigationGestures was null, expected non-null bool.'); try { api.setAllowsBackForwardNavigationGestures( arg_identifier!, arg_allow!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.setCustomUserAgent', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.setCustomUserAgent was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.setCustomUserAgent was null, expected non-null int.'); final String? arg_userAgent = (args[1] as String?); try { api.setCustomUserAgent(arg_identifier!, arg_userAgent); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.evaluateJavaScript', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.evaluateJavaScript was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.evaluateJavaScript was null, expected non-null int.'); final String? arg_javaScriptString = (args[1] as String?); assert(arg_javaScriptString != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.evaluateJavaScript was null, expected non-null String.'); try { final Object? output = await api.evaluateJavaScript( arg_identifier!, arg_javaScriptString!); return <Object?>[output]; } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.setInspectable', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.setInspectable was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.setInspectable was null, expected non-null int.'); final bool? arg_inspectable = (args[1] as bool?); assert(arg_inspectable != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.setInspectable was null, expected non-null bool.'); try { api.setInspectable(arg_identifier!, arg_inspectable!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.getCustomUserAgent', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.getCustomUserAgent was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.getCustomUserAgent was null, expected non-null int.'); try { final String? output = api.getCustomUserAgent(arg_identifier!); return <Object?>[output]; } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } } } /// Mirror of WKUIDelegate. /// /// See https://developer.apple.com/documentation/webkit/wkuidelegate?language=objc. abstract class TestWKUIDelegateHostApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = StandardMessageCodec(); void create(int identifier); static void setup(TestWKUIDelegateHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.WKUIDelegateHostApi.create', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKUIDelegateHostApi.create was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKUIDelegateHostApi.create was null, expected non-null int.'); try { api.create(arg_identifier!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } } } class _TestWKHttpCookieStoreHostApiCodec extends StandardMessageCodec { const _TestWKHttpCookieStoreHostApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { if (value is NSHttpCookieData) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else if (value is NSHttpCookiePropertyKeyEnumData) { buffer.putUint8(129); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } } @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: return NSHttpCookieData.decode(readValue(buffer)!); case 129: return NSHttpCookiePropertyKeyEnumData.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } } } /// Mirror of WKHttpCookieStore. /// /// See https://developer.apple.com/documentation/webkit/wkhttpcookiestore?language=objc. abstract class TestWKHttpCookieStoreHostApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = _TestWKHttpCookieStoreHostApiCodec(); void createFromWebsiteDataStore( int identifier, int websiteDataStoreIdentifier); Future<void> setCookie(int identifier, NSHttpCookieData cookie); static void setup(TestWKHttpCookieStoreHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.WKHttpCookieStoreHostApi.createFromWebsiteDataStore', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKHttpCookieStoreHostApi.createFromWebsiteDataStore was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKHttpCookieStoreHostApi.createFromWebsiteDataStore was null, expected non-null int.'); final int? arg_websiteDataStoreIdentifier = (args[1] as int?); assert(arg_websiteDataStoreIdentifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKHttpCookieStoreHostApi.createFromWebsiteDataStore was null, expected non-null int.'); try { api.createFromWebsiteDataStore( arg_identifier!, arg_websiteDataStoreIdentifier!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.WKHttpCookieStoreHostApi.setCookie', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKHttpCookieStoreHostApi.setCookie was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKHttpCookieStoreHostApi.setCookie was null, expected non-null int.'); final NSHttpCookieData? arg_cookie = (args[1] as NSHttpCookieData?); assert(arg_cookie != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKHttpCookieStoreHostApi.setCookie was null, expected non-null NSHttpCookieData.'); try { await api.setCookie(arg_identifier!, arg_cookie!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } } } /// Host API for `NSUrl`. /// /// This class may handle instantiating and adding native object instances that /// are attached to a Dart instance or method calls on the associated native /// class or an instance of the class. /// /// See https://developer.apple.com/documentation/foundation/nsurl?language=objc. abstract class TestNSUrlHostApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = StandardMessageCodec(); String? getAbsoluteString(int identifier); static void setup(TestNSUrlHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.NSUrlHostApi.getAbsoluteString', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.NSUrlHostApi.getAbsoluteString was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.NSUrlHostApi.getAbsoluteString was null, expected non-null int.'); try { final String? output = api.getAbsoluteString(arg_identifier!); return <Object?>[output]; } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } } } /// Host API for `UIScrollViewDelegate`. /// /// This class may handle instantiating and adding native object instances that /// are attached to a Dart instance or method calls on the associated native /// class or an instance of the class. /// /// See https://developer.apple.com/documentation/uikit/uiscrollviewdelegate?language=objc. abstract class TestUIScrollViewDelegateHostApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = StandardMessageCodec(); void create(int identifier); static void setup(TestUIScrollViewDelegateHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.UIScrollViewDelegateHostApi.create', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.UIScrollViewDelegateHostApi.create was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.UIScrollViewDelegateHostApi.create was null, expected non-null int.'); try { api.create(arg_identifier!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } } } /// Host API for `NSUrlCredential`. /// /// This class may handle instantiating and adding native object instances that /// are attached to a Dart instance or handle method calls on the associated /// native class or an instance of the class. /// /// See https://developer.apple.com/documentation/foundation/nsurlcredential?language=objc. abstract class TestNSUrlCredentialHostApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = StandardMessageCodec(); /// Create a new native instance and add it to the `InstanceManager`. void createWithUser(int identifier, String user, String password, NSUrlCredentialPersistence persistence); static void setup(TestNSUrlCredentialHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.webview_flutter_wkwebview.NSUrlCredentialHostApi.createWithUser', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.NSUrlCredentialHostApi.createWithUser was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_identifier = (args[0] as int?); assert(arg_identifier != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.NSUrlCredentialHostApi.createWithUser was null, expected non-null int.'); final String? arg_user = (args[1] as String?); assert(arg_user != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.NSUrlCredentialHostApi.createWithUser was null, expected non-null String.'); final String? arg_password = (args[2] as String?); assert(arg_password != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.NSUrlCredentialHostApi.createWithUser was null, expected non-null String.'); final NSUrlCredentialPersistence? arg_persistence = args[3] == null ? null : NSUrlCredentialPersistence.values[args[3]! as int]; assert(arg_persistence != null, 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.NSUrlCredentialHostApi.createWithUser was null, expected non-null NSUrlCredentialPersistence.'); try { api.createWithUser( arg_identifier!, arg_user!, arg_password!, arg_persistence!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } } }
packages/packages/webview_flutter/webview_flutter_wkwebview/test/src/common/test_web_kit.g.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/test/src/common/test_web_kit.g.dart", "repo_id": "packages", "token_count": 46704 }
1,148
// 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'; /// Returns a [File] created by appending all but the last item in [components] /// to [base] as subdirectories, then appending the last as a file. /// /// Example: /// childFileWithSubcomponents(rootDir, ['foo', 'bar', 'baz.txt']) /// creates a File representing /rootDir/foo/bar/baz.txt. File childFileWithSubcomponents(Directory base, List<String> components) { final String basename = components.removeLast(); return childDirectoryWithSubcomponents(base, components).childFile(basename); } /// Returns a [Directory] created by appending everything in [components] /// to [base] as subdirectories. /// /// Example: /// childFileWithSubcomponents(rootDir, ['foo', 'bar']) /// creates a File representing /rootDir/foo/bar/. Directory childDirectoryWithSubcomponents( Directory base, List<String> components) { Directory dir = base; for (final String directoryName in components) { dir = dir.childDirectory(directoryName); } return dir; }
packages/script/tool/lib/src/common/file_utils.dart/0
{ "file_path": "packages/script/tool/lib/src/common/file_utils.dart", "repo_id": "packages", "token_count": 337 }
1,149
// 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:yaml/yaml.dart'; import 'common/output_utils.dart'; import 'common/package_looping_command.dart'; import 'common/repository_package.dart'; /// A command to verify Dependabot configuration coverage of packages. class DependabotCheckCommand extends PackageLoopingCommand { /// Creates Dependabot check command instance. DependabotCheckCommand(super.packagesDir, {super.gitDir}) { argParser.addOption(_configPathFlag, help: 'Path to the Dependabot configuration file', defaultsTo: '.github/dependabot.yml'); } static const String _configPathFlag = 'config'; late Directory _repoRoot; // The set of directories covered by "gradle" entries in the config. Set<String> _gradleDirs = const <String>{}; @override final String name = 'dependabot-check'; @override List<String> get aliases => <String>['check-dependabot']; @override final String description = 'Checks that all packages have Dependabot coverage.'; @override final PackageLoopingType packageLoopingType = PackageLoopingType.includeAllSubpackages; @override final bool hasLongOutput = false; @override Future<void> initializeRun() async { _repoRoot = packagesDir.fileSystem.directory((await gitDir).path); final YamlMap config = loadYaml(_repoRoot .childFile(getStringArg(_configPathFlag)) .readAsStringSync()) as YamlMap; final dynamic entries = config['updates']; if (entries is! YamlList) { return; } const String typeKey = 'package-ecosystem'; const String dirKey = 'directory'; _gradleDirs = entries .cast<YamlMap>() .where((YamlMap entry) => entry[typeKey] == 'gradle') .map((YamlMap entry) => entry[dirKey] as String) .toSet(); } @override Future<PackageResult> runForPackage(RepositoryPackage package) async { bool skipped = true; final List<String> errors = <String>[]; final _GradleCoverageResult gradleResult = _validateDependabotGradleCoverage(package); skipped = skipped && gradleResult.runState == RunState.skipped; if (gradleResult.runState == RunState.failed) { printError('${indentation}Missing Gradle coverage.'); print('${indentation}Add a "gradle" entry to ' '${getStringArg(_configPathFlag)} for ${gradleResult.missingPath}'); errors.add('Missing Gradle coverage'); } // TODO(stuartmorgan): Add other ecosystem checks here as more are enabled. if (skipped) { return PackageResult.skip('No supported package ecosystems'); } return errors.isEmpty ? PackageResult.success() : PackageResult.fail(errors); } /// Returns the state for the Dependabot coverage of the Gradle ecosystem for /// [package]: /// - succeeded if it includes gradle and is covered. /// - failed if it includes gradle and is not covered. /// - skipped if it doesn't include gradle. _GradleCoverageResult _validateDependabotGradleCoverage( RepositoryPackage package) { final Directory androidDir = package.platformDirectory(FlutterPlatform.android); final Directory appDir = androidDir.childDirectory('app'); if (appDir.existsSync()) { // It's an app, so only check for the app directory to be covered. final String dependabotPath = '/${getRelativePosixPath(appDir, from: _repoRoot)}'; return _gradleDirs.contains(dependabotPath) ? _GradleCoverageResult(RunState.succeeded) : _GradleCoverageResult(RunState.failed, missingPath: dependabotPath); } else if (androidDir.existsSync()) { // It's a library, so only check for the android directory to be covered. final String dependabotPath = '/${getRelativePosixPath(androidDir, from: _repoRoot)}'; return _gradleDirs.contains(dependabotPath) ? _GradleCoverageResult(RunState.succeeded) : _GradleCoverageResult(RunState.failed, missingPath: dependabotPath); } return _GradleCoverageResult(RunState.skipped); } } class _GradleCoverageResult { _GradleCoverageResult(this.runState, {this.missingPath}); final RunState runState; final String? missingPath; }
packages/script/tool/lib/src/dependabot_check_command.dart/0
{ "file_path": "packages/script/tool/lib/src/dependabot_check_command.dart", "repo_id": "packages", "token_count": 1517 }
1,150
// 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:file/file.dart'; import 'package:git/git.dart'; import 'package:http/http.dart' as http; import 'package:meta/meta.dart'; import 'package:path/path.dart' as p; import 'package:platform/platform.dart'; import 'package:pub_semver/pub_semver.dart'; import 'package:yaml/yaml.dart'; import 'common/core.dart'; import 'common/file_utils.dart'; import 'common/git_version_finder.dart'; import 'common/output_utils.dart'; import 'common/package_command.dart'; import 'common/package_looping_command.dart'; import 'common/pub_version_finder.dart'; import 'common/repository_package.dart'; @immutable class _RemoteInfo { const _RemoteInfo({required this.name, required this.url}); /// The git name for the remote. final String name; /// The remote's URL. final String url; } /// Wraps pub publish with a few niceties used by the flutter/plugin team. /// /// 1. Checks for any modified files in git and refuses to publish if there's an /// issue. /// 2. Tags the release with the format <package-name>-v<package-version>. /// 3. Pushes the release to a remote. /// /// Both 2 and 3 are optional, see `plugin_tools help publish` for full /// usage information. /// /// [processRunner], [print], and [stdin] can be overriden for easier testing. class PublishCommand extends PackageLoopingCommand { /// Creates an instance of the publish command. PublishCommand( super.packagesDir, { super.processRunner, super.platform, io.Stdin? stdinput, super.gitDir, http.Client? httpClient, }) : _pubVersionFinder = PubVersionFinder(httpClient: httpClient ?? http.Client()), _stdin = stdinput ?? io.stdin { argParser.addFlag(_alreadyTaggedFlag, help: 'Instead of tagging, validates that the current checkout is already tagged with the expected version.\n' 'This is primarily intended for use in CI publish steps triggered by tagging.', negatable: false); argParser.addMultiOption(_pubFlagsOption, help: 'A list of options that will be forwarded on to pub. Separate multiple flags with commas.'); argParser.addOption( _remoteOption, help: 'The name of the remote to push the tags to.', // Flutter convention is to use "upstream" for the single source of truth, and "origin" for personal forks. defaultsTo: 'upstream', ); argParser.addFlag( _allChangedFlag, help: 'Release all packages that contains pubspec changes at the current commit compares to the base-sha.\n' 'The --packages option is ignored if this is on.', ); argParser.addFlag( _dryRunFlag, help: 'Skips the real `pub publish` and `git tag` commands and assumes both commands are successful.\n' 'This does not run `pub publish --dry-run`.\n' 'If you want to run the command with `pub publish --dry-run`, use `pub-publish-flags=--dry-run`', ); argParser.addFlag(_skipConfirmationFlag, help: 'Run the command without asking for Y/N inputs.\n' 'This command will add a `--force` flag to the `pub publish` command if it is not added with $_pubFlagsOption\n'); argParser.addFlag(_tagForAutoPublishFlag, help: 'Runs the dry-run publish, and tags if it succeeds, but does not actually publish.\n' 'This is intended for use with a separate publish step that is based on tag push events.', negatable: false); } static const String _alreadyTaggedFlag = 'already-tagged'; static const String _pubFlagsOption = 'pub-publish-flags'; static const String _remoteOption = 'remote'; static const String _allChangedFlag = 'all-changed'; static const String _dryRunFlag = 'dry-run'; static const String _skipConfirmationFlag = 'skip-confirmation'; static const String _tagForAutoPublishFlag = 'tag-for-auto-publish'; static const String _pubCredentialName = 'PUB_CREDENTIALS'; // Version tags should follow <package-name>-v<semantic-version>. For example, // `flutter_plugin_tools-v0.0.24`. static const String _tagFormat = '%PACKAGE%-v%VERSION%'; /// Returns the correct path where the pub credential is stored. @visibleForTesting late final String credentialsPath = _getCredentialsPath(platform: platform, path: path); @override final String name = 'publish'; @override final String description = 'Attempts to publish the given packages and tag the release(s) on GitHub.\n' 'If running this on CI, an environment variable named $_pubCredentialName must be set to a String that represents the pub credential JSON.\n' 'WARNING: Do not check in the content of pub credential JSON, it should only come from secure sources.'; final io.Stdin _stdin; StreamSubscription<String>? _stdinSubscription; final PubVersionFinder _pubVersionFinder; // Tags that already exist in the repository. List<String> _existingGitTags = <String>[]; // The remote to push tags to. late _RemoteInfo _remote; // Flags to pass to `pub publish`. late List<String> _publishFlags; @override String get successSummaryMessage => 'published'; @override String get failureListHeader => 'The following packages had failures during publishing:'; @override Future<void> initializeRun() async { print('Checking local repo...'); // Ensure that the requested remote is present. final String remoteName = getStringArg(_remoteOption); final String? remoteUrl = await _verifyRemote(remoteName); if (remoteUrl == null) { printError('Unable to find URL for remote $remoteName; cannot push tags'); throw ToolExit(1); } _remote = _RemoteInfo(name: remoteName, url: remoteUrl); // Pre-fetch all the repository's tags, to check against when publishing. final GitDir repository = await gitDir; final io.ProcessResult existingTagsResult = await repository.runCommand(<String>['tag', '--sort=-committerdate']); _existingGitTags = (existingTagsResult.stdout as String).split('\n') ..removeWhere((String element) => element.isEmpty); _publishFlags = <String>[ ...getStringListArg(_pubFlagsOption), if (getBoolArg(_skipConfirmationFlag)) '--force', ]; if (getBoolArg(_dryRunFlag)) { print('=============== DRY RUN ==============='); } } @override Stream<PackageEnumerationEntry> getPackagesToProcess() async* { if (getBoolArg(_allChangedFlag)) { final GitVersionFinder gitVersionFinder = await retrieveVersionFinder(); final String baseSha = await gitVersionFinder.getBaseSha(); print( 'Publishing all packages that have changed relative to "$baseSha"\n'); final List<String> changedPubspecs = await gitVersionFinder.getChangedPubSpecs(); for (final String pubspecPath in changedPubspecs) { // git outputs a relativa, Posix-style path. final File pubspecFile = childFileWithSubcomponents( packagesDir.fileSystem.directory((await gitDir).path), p.posix.split(pubspecPath)); yield PackageEnumerationEntry(RepositoryPackage(pubspecFile.parent), excluded: false); } } else { yield* getTargetPackages(filterExcluded: false); } } @override Future<PackageResult> runForPackage(RepositoryPackage package) async { final PackageResult? checkResult = await _checkNeedsRelease(package); if (checkResult != null) { return checkResult; } if (!await _checkGitStatus(package)) { return PackageResult.fail(<String>['uncommitted changes']); } final bool tagOnly = getBoolArg(_tagForAutoPublishFlag); if (!tagOnly) { if (!await _publish(package)) { return PackageResult.fail(<String>['publish failed']); } } final String tag = _getTag(package); if (getBoolArg(_alreadyTaggedFlag)) { if (!(await _getCurrentTags()).contains(tag)) { printError('The current checkout is not already tagged "$tag"'); return PackageResult.fail(<String>['missing tag']); } } else { if (!await _tagRelease(package, tag)) { return PackageResult.fail(<String>['tagging failed']); } } final String action = tagOnly ? 'Tagged' : 'Published'; print('\n$action ${package.directory.basename} successfully!'); return PackageResult.success(); } @override Future<void> completeRun() async { _pubVersionFinder.httpClient.close(); await _stdinSubscription?.cancel(); _stdinSubscription = null; } /// Checks whether [package] needs to be released, printing check status and /// returning one of: /// - PackageResult.fail if the check could not be completed /// - PackageResult.skip if no release is necessary /// - null if releasing should proceed /// /// In cases where a non-null result is returned, that should be returned /// as the final result for the package, without further processing. Future<PackageResult?> _checkNeedsRelease(RepositoryPackage package) async { if (!package.pubspecFile.existsSync()) { logWarning(''' The pubspec file for ${package.displayName} does not exist, so no publishing will happen. Safe to ignore if the package is deleted in this commit. '''); return PackageResult.skip('package deleted'); } final Pubspec pubspec = package.parsePubspec(); if (pubspec.name == 'flutter_plugin_tools') { // Ignore flutter_plugin_tools package when running publishing through flutter_plugin_tools. // TODO(cyanglaz): Make the tool also auto publish flutter_plugin_tools package. // https://github.com/flutter/flutter/issues/85430 return PackageResult.skip( 'publishing flutter_plugin_tools via the tool is not supported'); } if (pubspec.publishTo == 'none') { return PackageResult.skip('publish_to: none'); } if (pubspec.version == null) { printError( 'No version found. A package that intentionally has no version should be marked "publish_to: none"'); return PackageResult.fail(<String>['no version']); } // Check if the package named `packageName` with `version` has already // been published. final Version version = pubspec.version!; final PubVersionFinderResponse pubVersionFinderResponse = await _pubVersionFinder.getPackageVersion(packageName: pubspec.name); if (pubVersionFinderResponse.versions.contains(version)) { final String tagsForPackageWithSameVersion = _existingGitTags.firstWhere( (String tag) => tag.split('-v').first == pubspec.name && tag.split('-v').last == version.toString(), orElse: () => ''); if (tagsForPackageWithSameVersion.isEmpty) { printError( '${pubspec.name} $version has already been published, however ' 'the git release tag (${pubspec.name}-v$version) was not found. ' 'Please manually fix the tag then run the command again.'); return PackageResult.fail(<String>['published but untagged']); } else { print('${pubspec.name} $version has already been published.'); return PackageResult.skip('already published'); } } return null; } // Tag the release with <package-name>-v<version>, and push it to the remote. // // Return `true` if successful, `false` otherwise. Future<bool> _tagRelease(RepositoryPackage package, String tag) async { print('Tagging release $tag...'); if (!getBoolArg(_dryRunFlag)) { final io.ProcessResult result = await (await gitDir).runCommand( <String>['tag', tag], throwOnError: false, ); if (result.exitCode != 0) { return false; } } print('Pushing tag to ${_remote.name}...'); final bool success = await _pushTagToRemote( tag: tag, remote: _remote, ); if (success) { print('Release tagged!'); } return success; } Future<Iterable<String>> _getCurrentTags() async { // git tag --points-at HEAD final io.ProcessResult tagsResult = await (await gitDir).runCommand( <String>['tag', '--points-at', 'HEAD'], throwOnError: false, ); if (tagsResult.exitCode != 0) { return <String>[]; } return (tagsResult.stdout as String) .split('\n') .map((String line) => line.trim()) .where((String line) => line.isNotEmpty); } Future<bool> _checkGitStatus(RepositoryPackage package) async { final io.ProcessResult statusResult = await (await gitDir).runCommand( <String>[ 'status', '--porcelain', '--ignored', package.directory.absolute.path ], throwOnError: false, ); if (statusResult.exitCode != 0) { return false; } final String statusOutput = statusResult.stdout as String; if (statusOutput.isNotEmpty) { printError( "There are files in the package directory that haven't been saved in git. Refusing to publish these files:\n\n" '$statusOutput\n' 'If the directory should be clean, you can run `git clean -xdf && git reset --hard HEAD` to wipe all local changes.'); } return statusOutput.isEmpty; } Future<String?> _verifyRemote(String remote) async { final io.ProcessResult getRemoteUrlResult = await (await gitDir).runCommand( <String>['remote', 'get-url', remote], throwOnError: false, ); if (getRemoteUrlResult.exitCode != 0) { return null; } return getRemoteUrlResult.stdout as String?; } Future<bool> _publish(RepositoryPackage package) async { print('Publishing...'); print('Running `pub publish ${_publishFlags.join(' ')}` in ' '${package.directory.absolute.path}...\n'); if (getBoolArg(_dryRunFlag)) { return true; } if (_publishFlags.contains('--force')) { _ensureValidPubCredential(); } final io.Process publish = await processRunner.start( flutterCommand, <String>['pub', 'publish', ..._publishFlags], workingDirectory: package.directory); publish.stdout.transform(utf8.decoder).listen((String data) => print(data)); publish.stderr.transform(utf8.decoder).listen((String data) => print(data)); _stdinSubscription ??= _stdin .transform(utf8.decoder) .listen((String data) => publish.stdin.writeln(data)); final int result = await publish.exitCode; if (result != 0) { printError('Publishing ${package.directory.basename} failed.'); return false; } print('Package published!'); return true; } String _getTag(RepositoryPackage package) { final File pubspecFile = package.pubspecFile; final YamlMap pubspecYaml = loadYaml(pubspecFile.readAsStringSync()) as YamlMap; final String name = pubspecYaml['name'] as String; final String version = pubspecYaml['version'] as String; // We should have failed to publish if these were unset. assert(name.isNotEmpty && version.isNotEmpty); return _tagFormat .replaceAll('%PACKAGE%', name) .replaceAll('%VERSION%', version); } // Pushes the `tag` to `remote` // // Return `true` if successful, `false` otherwise. Future<bool> _pushTagToRemote({ required String tag, required _RemoteInfo remote, }) async { if (!getBoolArg(_dryRunFlag)) { final io.ProcessResult result = await (await gitDir).runCommand( <String>['push', remote.name, tag], throwOnError: false, ); if (result.exitCode != 0) { return false; } } return true; } void _ensureValidPubCredential() { final File credentialFile = packagesDir.fileSystem.file(credentialsPath); if (credentialFile.existsSync() && credentialFile.readAsStringSync().isNotEmpty) { return; } final String? credential = platform.environment[_pubCredentialName]; if (credential == null) { printError(''' No pub credential available. Please check if `$credentialsPath` is valid. If running this command on CI, you can set the pub credential content in the $_pubCredentialName environment variable. '''); throw ToolExit(1); } credentialFile.createSync(recursive: true); credentialFile.openSync(mode: FileMode.writeOnlyAppend) ..writeStringSync(credential) ..closeSync(); } } /// The path in which pub expects to find its credentials file. String _getCredentialsPath( {required Platform platform, required p.Context path}) { // See https://github.com/dart-lang/pub/blob/master/doc/cache_layout.md#layout String? configDir; if (platform.isLinux) { String? configHome = platform.environment['XDG_CONFIG_HOME']; if (configHome == null) { final String? home = platform.environment['HOME']; if (home == null) { printError('"HOME" environment variable is not set.'); } else { configHome = path.join(home, '.config'); } } if (configHome != null) { configDir = path.join(configHome, 'dart'); } } else if (platform.isWindows) { final String? appData = platform.environment['APPDATA']; if (appData == null) { printError('"APPDATA" environment variable is not set.'); } else { configDir = path.join(appData, 'dart'); } } else if (platform.isMacOS) { final String? home = platform.environment['HOME']; if (home == null) { printError('"HOME" environment variable is not set.'); } else { configDir = path.join(home, 'Library', 'Application Support', 'dart'); } } if (configDir == null) { printError('Unable to determine pub con location'); throw ToolExit(1); } return path.join(configDir, 'pub-credentials.json'); }
packages/script/tool/lib/src/publish_command.dart/0
{ "file_path": "packages/script/tool/lib/src/publish_command.dart", "repo_id": "packages", "token_count": 6393 }
1,151
// 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/gradle.dart'; import 'package:test/test.dart'; import '../mocks.dart'; import '../util.dart'; void main() { late FileSystem fileSystem; late RecordingProcessRunner processRunner; setUp(() { fileSystem = MemoryFileSystem(); processRunner = RecordingProcessRunner(); }); group('isConfigured', () { test('reports true when configured on Windows', () async { final RepositoryPackage plugin = createFakePlugin( 'plugin', fileSystem.directory('/'), extraFiles: <String>['android/gradlew.bat']); final GradleProject project = GradleProject( plugin, processRunner: processRunner, platform: MockPlatform(isWindows: true), ); expect(project.isConfigured(), true); }); test('reports true when configured on non-Windows', () async { final RepositoryPackage plugin = createFakePlugin( 'plugin', fileSystem.directory('/'), extraFiles: <String>['android/gradlew']); final GradleProject project = GradleProject( plugin, processRunner: processRunner, platform: MockPlatform(isMacOS: true), ); expect(project.isConfigured(), true); }); test('reports false when not configured on Windows', () async { final RepositoryPackage plugin = createFakePlugin( 'plugin', fileSystem.directory('/'), extraFiles: <String>['android/foo']); final GradleProject project = GradleProject( plugin, processRunner: processRunner, platform: MockPlatform(isWindows: true), ); expect(project.isConfigured(), false); }); test('reports true when configured on non-Windows', () async { final RepositoryPackage plugin = createFakePlugin( 'plugin', fileSystem.directory('/'), extraFiles: <String>['android/foo']); final GradleProject project = GradleProject( plugin, processRunner: processRunner, platform: MockPlatform(isMacOS: true), ); expect(project.isConfigured(), false); }); }); group('runCommand', () { test('runs without arguments', () async { final RepositoryPackage plugin = createFakePlugin( 'plugin', fileSystem.directory('/'), extraFiles: <String>['android/gradlew']); final GradleProject project = GradleProject( plugin, processRunner: processRunner, platform: MockPlatform(isMacOS: true), ); final int exitCode = await project.runCommand('foo'); expect(exitCode, 0); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( plugin .platformDirectory(FlutterPlatform.android) .childFile('gradlew') .path, const <String>[ 'foo', ], plugin.platformDirectory(FlutterPlatform.android).path), ])); }); test('runs with arguments', () async { final RepositoryPackage plugin = createFakePlugin( 'plugin', fileSystem.directory('/'), extraFiles: <String>['android/gradlew']); final GradleProject project = GradleProject( plugin, processRunner: processRunner, platform: MockPlatform(isMacOS: true), ); final int exitCode = await project.runCommand( 'foo', arguments: <String>['--bar', '--baz'], ); expect(exitCode, 0); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( plugin .platformDirectory(FlutterPlatform.android) .childFile('gradlew') .path, const <String>[ 'foo', '--bar', '--baz', ], plugin.platformDirectory(FlutterPlatform.android).path), ])); }); test('runs with the correct wrapper on Windows', () async { final RepositoryPackage plugin = createFakePlugin( 'plugin', fileSystem.directory('/'), extraFiles: <String>['android/gradlew.bat']); final GradleProject project = GradleProject( plugin, processRunner: processRunner, platform: MockPlatform(isWindows: true), ); final int exitCode = await project.runCommand('foo'); expect(exitCode, 0); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( plugin .platformDirectory(FlutterPlatform.android) .childFile('gradlew.bat') .path, const <String>[ 'foo', ], plugin.platformDirectory(FlutterPlatform.android).path), ])); }); test('returns error codes', () async { final RepositoryPackage plugin = createFakePlugin( 'plugin', fileSystem.directory('/'), extraFiles: <String>['android/gradlew.bat']); final GradleProject project = GradleProject( plugin, processRunner: processRunner, platform: MockPlatform(isWindows: true), ); processRunner.mockProcessesForExecutable[project.gradleWrapper.path] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(exitCode: 1)), ]; final int exitCode = await project.runCommand('foo'); expect(exitCode, 1); }); }); }
packages/script/tool/test/common/gradle_test.dart/0
{ "file_path": "packages/script/tool/test/common/gradle_test.dart", "repo_id": "packages", "token_count": 2487 }
1,152
// 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/federation_safety_check_command.dart'; import 'package:mockito/mockito.dart'; import 'package:test/test.dart'; import 'common/package_command_test.mocks.dart'; import 'mocks.dart'; import 'util.dart'; void main() { FileSystem fileSystem; late MockPlatform mockPlatform; late Directory packagesDir; late CommandRunner<void> runner; late RecordingProcessRunner processRunner; setUp(() { fileSystem = MemoryFileSystem(); mockPlatform = MockPlatform(); packagesDir = createPackagesDirectory(fileSystem: fileSystem); final MockGitDir gitDir = MockGitDir(); when(gitDir.path).thenReturn(packagesDir.parent.path); when(gitDir.runCommand(any, throwOnError: anyNamed('throwOnError'))) .thenAnswer((Invocation invocation) { final List<String> arguments = invocation.positionalArguments[0]! as List<String>; // Route git calls through the process runner, to make mock output // consistent with other processes. Attach the first argument to the // command to make targeting the mock results easier. final String gitCommand = arguments.removeAt(0); return processRunner.run('git-$gitCommand', arguments); }); processRunner = RecordingProcessRunner(); final FederationSafetyCheckCommand command = FederationSafetyCheckCommand( packagesDir, processRunner: processRunner, platform: mockPlatform, gitDir: gitDir); runner = CommandRunner<void>('federation_safety_check_command', 'Test for $FederationSafetyCheckCommand'); runner.addCommand(command); }); test('skips non-plugin packages', () async { final RepositoryPackage package = createFakePackage('foo', packagesDir); final String changedFileOutput = <File>[ package.libDirectory.childFile('foo.dart'), ].map((File file) => file.path).join('\n'); processRunner.mockProcessesForExecutable['git-diff'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(stdout: changedFileOutput)), ]; final List<String> output = await runCapturingPrint(runner, <String>['federation-safety-check']); expect( output, containsAllInOrder(<Matcher>[ contains('Running for foo...'), contains('Not a plugin'), contains('Skipped 1 package(s)'), ]), ); }); test('skips unfederated plugins', () async { final RepositoryPackage package = createFakePlugin('foo', packagesDir); final String changedFileOutput = <File>[ package.libDirectory.childFile('foo.dart'), ].map((File file) => file.path).join('\n'); processRunner.mockProcessesForExecutable['git-diff'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(stdout: changedFileOutput)), ]; final List<String> output = await runCapturingPrint(runner, <String>['federation-safety-check']); expect( output, containsAllInOrder(<Matcher>[ contains('Running for foo...'), contains('Not a federated plugin'), contains('Skipped 1 package(s)'), ]), ); }); test('skips interface packages', () async { final Directory pluginGroupDir = packagesDir.childDirectory('foo'); final RepositoryPackage platformInterface = createFakePlugin('foo_platform_interface', pluginGroupDir); final String changedFileOutput = <File>[ platformInterface.libDirectory.childFile('foo.dart'), ].map((File file) => file.path).join('\n'); processRunner.mockProcessesForExecutable['git-diff'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(stdout: changedFileOutput)), ]; final List<String> output = await runCapturingPrint(runner, <String>['federation-safety-check']); expect( output, containsAllInOrder(<Matcher>[ contains('Running for foo_platform_interface...'), contains('Platform interface changes are not validated.'), contains('Skipped 1 package(s)'), ]), ); }); test('allows changes to just an interface package', () async { final Directory pluginGroupDir = packagesDir.childDirectory('foo'); final RepositoryPackage platformInterface = createFakePlugin('foo_platform_interface', pluginGroupDir); createFakePlugin('foo', pluginGroupDir); createFakePlugin('foo_ios', pluginGroupDir); createFakePlugin('foo_android', pluginGroupDir); final String changedFileOutput = <File>[ platformInterface.libDirectory.childFile('foo.dart'), platformInterface.pubspecFile, ].map((File file) => file.path).join('\n'); processRunner.mockProcessesForExecutable['git-diff'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(stdout: changedFileOutput)), ]; final List<String> output = await runCapturingPrint(runner, <String>['federation-safety-check']); expect( output, containsAllInOrder(<Matcher>[ contains('Running for foo/foo...'), contains('No Dart changes.'), contains('Running for foo_android...'), contains('No Dart changes.'), contains('Running for foo_ios...'), contains('No Dart changes.'), contains('Running for foo_platform_interface...'), contains('Ran for 3 package(s)'), contains('Skipped 1 package(s)'), ]), ); expect( output, isNot(contains(<Matcher>[ contains('No published changes for foo_platform_interface'), ])), ); }); test('allows changes to multiple non-interface packages', () async { final Directory pluginGroupDir = packagesDir.childDirectory('foo'); final RepositoryPackage appFacing = createFakePlugin('foo', pluginGroupDir); final RepositoryPackage implementation = createFakePlugin('foo_bar', pluginGroupDir); createFakePlugin('foo_platform_interface', pluginGroupDir); final String changedFileOutput = <File>[ appFacing.libDirectory.childFile('foo.dart'), implementation.libDirectory.childFile('foo.dart'), ].map((File file) => file.path).join('\n'); processRunner.mockProcessesForExecutable['git-diff'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(stdout: changedFileOutput)), ]; final List<String> output = await runCapturingPrint(runner, <String>['federation-safety-check']); expect( output, containsAllInOrder(<Matcher>[ contains('Running for foo/foo...'), contains('No published changes for foo_platform_interface.'), contains('Running for foo_bar...'), contains('No published changes for foo_platform_interface.'), ]), ); }); test( 'fails on changes to interface and non-interface packages in the same plugin', () async { final Directory pluginGroupDir = packagesDir.childDirectory('foo'); final RepositoryPackage appFacing = createFakePlugin('foo', pluginGroupDir); final RepositoryPackage implementation = createFakePlugin('foo_bar', pluginGroupDir); final RepositoryPackage platformInterface = createFakePlugin('foo_platform_interface', pluginGroupDir); const String appFacingChanges = ''' diff --git a/packages/foo/foo/lib/foo.dart b/packages/foo/foo/lib/foo.dart index abc123..def456 100644 --- a/packages/foo/foo/lib/foo.dart +++ b/packages/foo/foo/lib/foo.dart @@ -51,6 +51,9 @@ Future<bool> launchUrl( return true; } +// This is a new method +bool foo() => true; + // This in an existing method void aMethod() { // Do things. '''; final String changedFileOutput = <File>[ appFacing.libDirectory.childFile('foo.dart'), implementation.libDirectory.childFile('foo.dart'), platformInterface.pubspecFile, platformInterface.libDirectory.childFile('foo.dart'), ].map((File file) => file.path).join('\n'); processRunner.mockProcessesForExecutable['git-diff'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(stdout: changedFileOutput)), // Ensure that a change with both a comment and non-comment addition is // counted, to validate change analysis. FakeProcessInfo(MockProcess(stdout: appFacingChanges), <String>['', 'HEAD', '--', '/packages/foo/foo/lib/foo.dart']), // The others diffs don't need to be specified, since empty diff is also // treated as a non-comment change. ]; Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['federation-safety-check'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('Running for foo/foo...'), contains('Dart changes are not allowed to other packages in foo in the ' 'same PR as changes to public Dart code in foo_platform_interface, ' 'as this can cause accidental breaking changes to be missed by ' 'automated checks. Please split the changes to these two packages ' 'into separate PRs.'), contains('Running for foo_bar...'), contains('Dart changes are not allowed to other packages in foo'), contains('The following packages had errors:'), contains('foo/foo:\n' ' foo_platform_interface changed.'), contains('foo_bar:\n' ' foo_platform_interface changed.'), ]), ); }); test('ignores test-only changes to interface packages', () async { final Directory pluginGroupDir = packagesDir.childDirectory('foo'); final RepositoryPackage appFacing = createFakePlugin('foo', pluginGroupDir); final RepositoryPackage implementation = createFakePlugin('foo_bar', pluginGroupDir); final RepositoryPackage platformInterface = createFakePlugin('foo_platform_interface', pluginGroupDir); final String changedFileOutput = <File>[ appFacing.libDirectory.childFile('foo.dart'), implementation.libDirectory.childFile('foo.dart'), platformInterface.pubspecFile, platformInterface.testDirectory.childFile('foo.dart'), ].map((File file) => file.path).join('\n'); processRunner.mockProcessesForExecutable['git-diff'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(stdout: changedFileOutput)), ]; final List<String> output = await runCapturingPrint(runner, <String>['federation-safety-check']); expect( output, containsAllInOrder(<Matcher>[ contains('Running for foo/foo...'), contains('No public code changes for foo_platform_interface.'), contains('Running for foo_bar...'), contains('No public code changes for foo_platform_interface.'), ]), ); }); test('ignores unpublished changes to interface packages', () async { final Directory pluginGroupDir = packagesDir.childDirectory('foo'); final RepositoryPackage appFacing = createFakePlugin('foo', pluginGroupDir); final RepositoryPackage implementation = createFakePlugin('foo_bar', pluginGroupDir); final RepositoryPackage platformInterface = createFakePlugin('foo_platform_interface', pluginGroupDir); final String changedFileOutput = <File>[ appFacing.libDirectory.childFile('foo.dart'), implementation.libDirectory.childFile('foo.dart'), platformInterface.pubspecFile, platformInterface.libDirectory.childFile('foo.dart'), ].map((File file) => file.path).join('\n'); processRunner.mockProcessesForExecutable['git-diff'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(stdout: changedFileOutput)), ]; // Simulate no change to the version in the interface's pubspec.yaml. processRunner.mockProcessesForExecutable['git-show'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess( stdout: platformInterface.pubspecFile.readAsStringSync())), ]; final List<String> output = await runCapturingPrint(runner, <String>['federation-safety-check']); expect( output, containsAllInOrder(<Matcher>[ contains('Running for foo/foo...'), contains('No published changes for foo_platform_interface.'), contains('Running for foo_bar...'), contains('No published changes for foo_platform_interface.'), ]), ); }); test('ignores comment-only changes in implementation packages', () async { final Directory pluginGroupDir = packagesDir.childDirectory('foo'); final RepositoryPackage implementation = createFakePlugin('foo_bar', pluginGroupDir); final RepositoryPackage platformInterface = createFakePlugin('foo_platform_interface', pluginGroupDir); final String changedFileOutput = <File>[ implementation.libDirectory.childFile('foo.dart'), platformInterface.pubspecFile, platformInterface.libDirectory.childFile('foo.dart'), ].map((File file) => file.path).join('\n'); const String platformInterfaceChanges = ''' diff --git a/packages/foo/foo_platform_interface/lib/foo.dart b/packages/foo/foo_platform_interface/lib/foo.dart index abc123..def456 100644 --- a/packages/foo/foo_platform_interface/lib/foo.dart +++ b/packages/foo/foo_platform_interface/lib/foo.dart @@ -51,6 +51,7 @@ Future<bool> launchUrl( enum Foo { a, b, + c, d, e, } '''; const String implementationChanges = ''' diff --git a/packages/foo/foo_bar/lib/foo.dart b/packages/foo/foo_bar/lib/foo.dart index abc123..def456 100644 --- a/packages/foo/foo_bar/lib/foo.dart +++ b/packages/foo/foo_bar/lib/foo.dart @@ -51,6 +51,7 @@ Future<bool> launchUrl( } void foo() { + // ignore: exhaustive_cases switch(a_foo) { case a: // Do things '''; processRunner.mockProcessesForExecutable['git-diff'] = <FakeProcessInfo>[ FakeProcessInfo( MockProcess(stdout: changedFileOutput), <String>['--name-only']), FakeProcessInfo(MockProcess(stdout: implementationChanges), <String>['', 'HEAD', '--', '/packages/foo/foo_bar/lib/foo.dart']), FakeProcessInfo(MockProcess(stdout: platformInterfaceChanges), <String>[ '', 'HEAD', '--', '/packages/foo/foo_platform_interface/lib/foo.dart' ]), ]; final List<String> output = await runCapturingPrint(runner, <String>['federation-safety-check']); expect( output, containsAllInOrder(<Matcher>[ contains('Running for foo_bar...'), contains('No Dart changes.'), ]), ); }); test('ignores comment-only changes in platform interface packages', () async { final Directory pluginGroupDir = packagesDir.childDirectory('foo'); final RepositoryPackage implementation = createFakePlugin('foo_bar', pluginGroupDir); final RepositoryPackage platformInterface = createFakePlugin('foo_platform_interface', pluginGroupDir); final String changedFileOutput = <File>[ implementation.libDirectory.childFile('foo.dart'), platformInterface.pubspecFile, platformInterface.libDirectory.childFile('foo.dart'), ].map((File file) => file.path).join('\n'); const String platformInterfaceChanges = ''' diff --git a/packages/foo/foo_platform_interface/lib/foo.dart b/packages/foo/foo_platform_interface/lib/foo.dart index abc123..def456 100644 --- a/packages/foo/foo_platform_interface/lib/foo.dart +++ b/packages/foo/foo_platform_interface/lib/foo.dart @@ -51,6 +51,8 @@ Future<bool> launchUrl( // existing comment // existing comment // existing comment + // + // additional comment void foo() { some code; } '''; const String implementationChanges = ''' diff --git a/packages/foo/foo_bar/lib/foo.dart b/packages/foo/foo_bar/lib/foo.dart index abc123..def456 100644 --- a/packages/foo/foo_bar/lib/foo.dart +++ b/packages/foo/foo_bar/lib/foo.dart @@ -51,6 +51,7 @@ Future<bool> launchUrl( } void foo() { + new code; existing code; ... ... '''; processRunner.mockProcessesForExecutable['git-diff'] = <FakeProcessInfo>[ FakeProcessInfo( MockProcess(stdout: changedFileOutput), <String>['--name-only']), FakeProcessInfo(MockProcess(stdout: implementationChanges), <String>['', 'HEAD', '--', '/packages/foo/foo_bar/lib/foo.dart']), FakeProcessInfo(MockProcess(stdout: platformInterfaceChanges), <String>[ '', 'HEAD', '--', '/packages/foo/foo_platform_interface/lib/foo.dart' ]), ]; final List<String> output = await runCapturingPrint(runner, <String>['federation-safety-check']); expect( output, containsAllInOrder(<Matcher>[ contains('Running for foo_bar...'), contains('No public code changes for foo_platform_interface.'), ]), ); }); test('allows things that look like mass changes, with warning', () async { final Directory pluginGroupDir = packagesDir.childDirectory('foo'); final RepositoryPackage appFacing = createFakePlugin('foo', pluginGroupDir); final RepositoryPackage implementation = createFakePlugin('foo_bar', pluginGroupDir); final RepositoryPackage platformInterface = createFakePlugin('foo_platform_interface', pluginGroupDir); final RepositoryPackage otherPlugin1 = createFakePlugin('bar', packagesDir); final RepositoryPackage otherPlugin2 = createFakePlugin('baz', packagesDir); final String changedFileOutput = <File>[ appFacing.libDirectory.childFile('foo.dart'), implementation.libDirectory.childFile('foo.dart'), platformInterface.pubspecFile, platformInterface.libDirectory.childFile('foo.dart'), otherPlugin1.libDirectory.childFile('bar.dart'), otherPlugin2.libDirectory.childFile('baz.dart'), ].map((File file) => file.path).join('\n'); processRunner.mockProcessesForExecutable['git-diff'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(stdout: changedFileOutput)), ]; final List<String> output = await runCapturingPrint(runner, <String>['federation-safety-check']); expect( output, containsAllInOrder(<Matcher>[ contains('Running for foo/foo...'), contains( 'Ignoring potentially dangerous change, as this appears to be a mass change.'), contains('Running for foo_bar...'), contains( 'Ignoring potentially dangerous change, as this appears to be a mass change.'), contains('Ran for 2 package(s) (2 with warnings)'), ]), ); }); test('handles top-level files that match federated package heuristics', () async { final RepositoryPackage plugin = createFakePlugin('foo', packagesDir); final String changedFileOutput = <File>[ // This should be picked up as a change to 'foo', and not crash. plugin.directory.childFile('foo_bar.baz'), ].map((File file) => file.path).join('\n'); processRunner.mockProcessesForExecutable['git-diff'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(stdout: changedFileOutput)), ]; final List<String> output = await runCapturingPrint(runner, <String>['federation-safety-check']); expect( output, containsAllInOrder(<Matcher>[ contains('Running for foo...'), ]), ); }); test('handles deletion of an entire plugin', () async { // Simulate deletion, in the form of diffs for packages that don't exist in // the filesystem. final String changedFileOutput = <File>[ packagesDir.childDirectory('foo').childFile('pubspec.yaml'), packagesDir .childDirectory('foo') .childDirectory('lib') .childFile('foo.dart'), packagesDir .childDirectory('foo_platform_interface') .childFile('pubspec.yaml'), packagesDir .childDirectory('foo_platform_interface') .childDirectory('lib') .childFile('foo.dart'), packagesDir.childDirectory('foo_web').childFile('pubspec.yaml'), packagesDir .childDirectory('foo_web') .childDirectory('lib') .childFile('foo.dart'), ].map((File file) => file.path).join('\n'); processRunner.mockProcessesForExecutable['git-diff'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(stdout: changedFileOutput)), ]; final List<String> output = await runCapturingPrint(runner, <String>['federation-safety-check']); expect( output, containsAllInOrder(<Matcher>[ contains('Ran for 0 package(s)'), ]), ); }); }
packages/script/tool/test/federation_safety_check_command_test.dart/0
{ "file_path": "packages/script/tool/test/federation_safety_check_command_test.dart", "repo_id": "packages", "token_count": 7383 }
1,153
// 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/readme_check_command.dart'; import 'package:test/test.dart'; import 'mocks.dart'; import 'util.dart'; void main() { late CommandRunner<void> runner; late RecordingProcessRunner processRunner; late FileSystem fileSystem; late MockPlatform mockPlatform; late Directory packagesDir; setUp(() { fileSystem = MemoryFileSystem(); mockPlatform = MockPlatform(); packagesDir = fileSystem.currentDirectory.childDirectory('packages'); createPackagesDirectory(parentDir: packagesDir.parent); processRunner = RecordingProcessRunner(); final ReadmeCheckCommand command = ReadmeCheckCommand( packagesDir, processRunner: processRunner, platform: mockPlatform, ); runner = CommandRunner<void>( 'readme_check_command', 'Test for readme_check_command'); runner.addCommand(command); }); test('prints paths of checked READMEs', () async { final RepositoryPackage package = createFakePackage( 'a_package', packagesDir, examples: <String>['example1', 'example2']); for (final RepositoryPackage example in package.getExamples()) { example.readmeFile.writeAsStringSync('A readme'); } getExampleDir(package).childFile('README.md').writeAsStringSync('A readme'); final List<String> output = await runCapturingPrint(runner, <String>['readme-check']); expect( output, containsAll(<Matcher>[ contains(' Checking README.md...'), contains(' Checking example/README.md...'), contains(' Checking example/example1/README.md...'), contains(' Checking example/example2/README.md...'), ]), ); }); test('fails when package README is missing', () async { final RepositoryPackage package = createFakePackage('a_package', packagesDir); package.readmeFile.deleteSync(); Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['readme-check'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('Missing README.md'), ]), ); }); test('passes when example README is missing', () async { createFakePackage('a_package', packagesDir); final List<String> output = await runCapturingPrint(runner, <String>['readme-check']); expect( output, containsAllInOrder(<Matcher>[ contains('No README for example'), ]), ); }); test('does not inculde non-example subpackages', () async { final RepositoryPackage package = createFakePackage('a_package', packagesDir); const String subpackageName = 'special_test'; final RepositoryPackage miscSubpackage = createFakePackage(subpackageName, package.directory); miscSubpackage.readmeFile.deleteSync(); final List<String> output = await runCapturingPrint(runner, <String>['readme-check']); expect(output, isNot(contains(subpackageName))); }); test('fails when README still has plugin template boilerplate', () async { final RepositoryPackage package = createFakePlugin('a_plugin', packagesDir); package.readmeFile.writeAsStringSync(''' ## Getting Started This project is a starting point for a Flutter [plug-in package](https://flutter.dev/developing-packages/), a specialized package that includes platform-specific implementation code for Android and/or iOS. For help getting started with Flutter development, view the [online documentation](https://flutter.dev/docs), which offers tutorials, samples, guidance on mobile development, and a full API reference. '''); Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['readme-check'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('The boilerplate section about getting started with Flutter ' 'should not be left in.'), contains('Contains template boilerplate'), ]), ); }); test('fails when example README still has application template boilerplate', () async { final RepositoryPackage package = createFakePackage('a_package', packagesDir); package.getExamples().first.readmeFile.writeAsStringSync(''' ## Getting Started This project is a starting point for a Flutter application. A few resources to get you started if this is your first Flutter project: - [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab) - [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook) For help getting started with Flutter development, view the [online documentation](https://docs.flutter.dev/), which offers tutorials, samples, guidance on mobile development, and a full API reference. '''); Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['readme-check'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('The boilerplate section about getting started with Flutter ' 'should not be left in.'), contains('Contains template boilerplate'), ]), ); }); test( 'fails when a plugin implementation package example README has the ' 'template boilerplate', () async { final RepositoryPackage package = createFakePlugin( 'a_plugin_ios', packagesDir.childDirectory('a_plugin')); package.getExamples().first.readmeFile.writeAsStringSync(''' # a_plugin_ios_example Demonstrates how to use the a_plugin_ios plugin. '''); Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['readme-check'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('The boilerplate should not be left in for a federated plugin ' "implementation package's example."), contains('Contains template boilerplate'), ]), ); }); test( 'allows the template boilerplate in the example README for packages ' 'other than plugin implementation packages', () async { final RepositoryPackage package = createFakePlugin( 'a_plugin', packagesDir.childDirectory('a_plugin'), platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.inline), }, ); // Write a README with an OS support table so that the main README check // passes. package.readmeFile.writeAsStringSync(''' # a_plugin | | Android | |----------------|---------| | **Support** | SDK 19+ | A great plugin. '''); package.getExamples().first.readmeFile.writeAsStringSync(''' # a_plugin_example Demonstrates how to use the a_plugin plugin. '''); final List<String> output = await runCapturingPrint(runner, <String>['readme-check']); expect( output, containsAll(<Matcher>[ contains(' Checking README.md...'), contains(' Checking example/README.md...'), ]), ); }); test( 'fails when a plugin implementation package example README does not have ' 'the repo-standard message', () async { final RepositoryPackage package = createFakePlugin( 'a_plugin_ios', packagesDir.childDirectory('a_plugin')); package.getExamples().first.readmeFile.writeAsStringSync(''' # a_plugin_ios_example Some random description. '''); Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['readme-check'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('The example README for a platform implementation package ' 'should warn readers about its intended use. Please copy the ' 'example README from another implementation package in this ' 'repository.'), contains('Missing implementation package example warning'), ]), ); }); test('passes for a plugin implementation package with the expected content', () async { final RepositoryPackage package = createFakePlugin( 'a_plugin', packagesDir.childDirectory('a_plugin'), platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.inline), }, ); // Write a README with an OS support table so that the main README check // passes. package.readmeFile.writeAsStringSync(''' # a_plugin | | Android | |----------------|---------| | **Support** | SDK 19+ | A great plugin. '''); package.getExamples().first.readmeFile.writeAsStringSync(''' # Platform Implementation Test App This is a test app for manual testing and automated integration testing of this platform implementation. It is not intended to demonstrate actual use of this package, since the intent is that plugin clients use the app-facing package. Unless you are making changes to this implementation package, this example is very unlikely to be relevant. '''); final List<String> output = await runCapturingPrint(runner, <String>['readme-check']); expect( output, containsAll(<Matcher>[ contains(' Checking README.md...'), contains(' Checking example/README.md...'), ]), ); }); test( 'fails when multi-example top-level example directory README still has ' 'application template boilerplate', () async { final RepositoryPackage package = createFakePackage( 'a_package', packagesDir, examples: <String>['example1', 'example2']); package.directory .childDirectory('example') .childFile('README.md') .writeAsStringSync(''' ## Getting Started This project is a starting point for a Flutter application. A few resources to get you started if this is your first Flutter project: - [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab) - [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook) For help getting started with Flutter development, view the [online documentation](https://docs.flutter.dev/), which offers tutorials, samples, guidance on mobile development, and a full API reference. '''); Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['readme-check'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('The boilerplate section about getting started with Flutter ' 'should not be left in.'), contains('Contains template boilerplate'), ]), ); }); group('plugin OS support', () { test( 'does not check support table for anything other than app-facing plugin packages', () async { const String federatedPluginName = 'a_federated_plugin'; final Directory federatedDir = packagesDir.childDirectory(federatedPluginName); // A non-plugin package. createFakePackage('a_package', packagesDir); // Non-app-facing parts of a federated plugin. createFakePlugin( '${federatedPluginName}_platform_interface', federatedDir); createFakePlugin('${federatedPluginName}_android', federatedDir); final List<String> output = await runCapturingPrint(runner, <String>[ 'readme-check', ]); expect( output, containsAll(<Matcher>[ contains('Running for a_package...'), contains('Running for a_federated_plugin_platform_interface...'), contains('Running for a_federated_plugin_android...'), contains('No issues found!'), ]), ); }); test('fails when non-federated plugin is missing an OS support table', () async { createFakePlugin('a_plugin', packagesDir); Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['readme-check'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('No OS support table found'), ]), ); }); test( 'fails when app-facing part of a federated plugin is missing an OS support table', () async { createFakePlugin('a_plugin', packagesDir.childDirectory('a_plugin')); Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['readme-check'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('No OS support table found'), ]), ); }); test('fails the OS support table is missing the header', () async { final RepositoryPackage plugin = createFakePlugin('a_plugin', packagesDir); plugin.readmeFile.writeAsStringSync(''' A very useful plugin. | **Support** | SDK 21+ | iOS 10+* | [See `camera_web `][1] | '''); Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['readme-check'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('OS support table does not have the expected header format'), ]), ); }); test('fails if the OS support table is missing a supported OS', () async { final RepositoryPackage plugin = createFakePlugin( 'a_plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.inline), platformIOS: const PlatformDetails(PlatformSupport.inline), platformWeb: const PlatformDetails(PlatformSupport.inline), }, ); plugin.readmeFile.writeAsStringSync(''' A very useful plugin. | | Android | iOS | |----------------|---------|----------| | **Support** | SDK 21+ | iOS 10+* | '''); Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['readme-check'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains(' OS support table does not match supported platforms:\n' ' Actual: android, ios, web\n' ' Documented: android, ios'), contains('Incorrect OS support table'), ]), ); }); test('fails if the OS support table lists an extra OS', () async { final RepositoryPackage plugin = createFakePlugin( 'a_plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.inline), platformIOS: const PlatformDetails(PlatformSupport.inline), }, ); plugin.readmeFile.writeAsStringSync(''' A very useful plugin. | | Android | iOS | Web | |----------------|---------|----------|------------------------| | **Support** | SDK 21+ | iOS 10+* | [See `camera_web `][1] | '''); Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['readme-check'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains(' OS support table does not match supported platforms:\n' ' Actual: android, ios\n' ' Documented: android, ios, web'), contains('Incorrect OS support table'), ]), ); }); test('fails if the OS support table has unexpected OS formatting', () async { final RepositoryPackage plugin = createFakePlugin( 'a_plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.inline), platformIOS: const PlatformDetails(PlatformSupport.inline), platformMacOS: const PlatformDetails(PlatformSupport.inline), platformWeb: const PlatformDetails(PlatformSupport.inline), }, ); plugin.readmeFile.writeAsStringSync(''' A very useful plugin. | | android | ios | MacOS | web | |----------------|---------|----------|-------|------------------------| | **Support** | SDK 21+ | iOS 10+* | 10.11 | [See `camera_web `][1] | '''); Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['readme-check'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains(' Incorrect OS capitalization: android, ios, MacOS, web\n' ' Please use standard capitalizations: Android, iOS, macOS, Web\n'), contains('Incorrect OS support formatting'), ]), ); }); }); group('code blocks', () { test('fails on missing info string', () async { final RepositoryPackage package = createFakePackage('a_package', packagesDir); package.readmeFile.writeAsStringSync(''' Example: ``` void main() { // ... } ``` '''); Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['readme-check'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('Code block at line 3 is missing a language identifier.'), contains('Missing language identifier for code block'), ]), ); }); test('allows unknown info strings', () async { final RepositoryPackage package = createFakePackage('a_package', packagesDir); package.readmeFile.writeAsStringSync(''' Example: ```someunknowninfotag A B C ``` '''); final List<String> output = await runCapturingPrint(runner, <String>[ 'readme-check', ]); expect( output, containsAll(<Matcher>[ contains('Running for a_package...'), contains('No issues found!'), ]), ); }); test('allows space around info strings', () async { final RepositoryPackage package = createFakePackage('a_package', packagesDir); package.readmeFile.writeAsStringSync(''' Example: ``` dart A B C ``` '''); final List<String> output = await runCapturingPrint(runner, <String>[ 'readme-check', ]); expect( output, containsAll(<Matcher>[ contains('Running for a_package...'), contains('No issues found!'), ]), ); }); test('passes when excerpt requirement is met', () async { final RepositoryPackage package = createFakePackage( 'a_package', packagesDir, ); package.readmeFile.writeAsStringSync(''' Example: <?code-excerpt "main.dart (SomeSection)"?> ```dart A B C ``` '''); final List<String> output = await runCapturingPrint( runner, <String>['readme-check', '--require-excerpts']); expect( output, containsAll(<Matcher>[ contains('Running for a_package...'), contains('No issues found!'), ]), ); }); test('fails on missing excerpt tag when requested', () async { final RepositoryPackage package = createFakePackage('a_package', packagesDir); package.readmeFile.writeAsStringSync(''' Example: ```dart A B C ``` '''); Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['readme-check', '--require-excerpts'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('Dart code block at line 3 is not managed by code-excerpt.'), // Ensure that the failure message links to instructions. contains( 'https://github.com/flutter/flutter/wiki/Contributing-to-Plugins-and-Packages'), contains('Missing code-excerpt management for code block'), ]), ); }); }); }
packages/script/tool/test/readme_check_command_test.dart/0
{ "file_path": "packages/script/tool/test/readme_check_command_test.dart", "repo_id": "packages", "token_count": 8065 }
1,154
<?code-excerpt path-base="../test"?> This package is used via [`CupertinoIcons`](https://api.flutter.dev/flutter/cupertino/CupertinoIcons-class.html): <?code-excerpt "cupertino_icons_test.dart (CupertinoIcon)"?> ```dart const Icon icon = Icon( CupertinoIcons.heart_fill, color: Colors.pink, size: 24.0, ); ``` For a list of all icons, see [`CupertinoIcons`](https://api.flutter.dev/flutter/cupertino/CupertinoIcons-class.html#constants) [class documentation constants](https://api.flutter.dev/flutter/cupertino/CupertinoIcons-class.html#constants).
packages/third_party/packages/cupertino_icons/example/example.md/0
{ "file_path": "packages/third_party/packages/cupertino_icons/example/example.md", "repo_id": "packages", "token_count": 210 }
1,155
# I/O Photo Booth [![Photo Booth Header][logo]][photo_booth_link] [![io_photobooth][build_status_badge]][workflow_link] ![coverage][coverage_badge] [![style: very good analysis][very_good_analysis_badge]][very_good_analysis_link] [![License: MIT][license_badge]][license_link] A Photo Booth built with [Flutter][flutter_link] and [Firebase][firebase_link] for [Google I/O 2021][google_io_link]. [Try it now][photo_booth_link] and [learn about how it's made][blog_link]. *Built by [Very Good Ventures][very_good_ventures_link] in partnership with Google* *Created using [Very Good CLI][very_good_cli_link] 🤖* --- ## Getting Started 🚀 To run the desired project either use the launch configuration in VSCode/Android Studio or use the following commands: ```sh $ flutter run -d chrome ``` _\*I/O Photo Booth works on Web._ --- ## Running Tests 🧪 To run all unit and widget tests use the following command: ```sh $ flutter test --coverage --test-randomize-ordering-seed random ``` To view the generated coverage report you can use [lcov](https://github.com/linux-test-project/lcov). ```sh # Generate Coverage Report $ genhtml coverage/lcov.info -o coverage/ # Open Coverage Report $ open coverage/index.html ``` --- ## Working with Translations 🌐 This project relies on [flutter_localizations][flutter_localizations_link] and follows the [official internationalization guide for Flutter][internationalization_link]. ### Adding Strings 1. To add a new localizable string, open the `app_en.arb` file at `lib/l10n/arb/app_en.arb`. ```arb { "@@locale": "en", "counterAppBarTitle": "Counter", "@counterAppBarTitle": { "description": "Text shown in the AppBar of the Counter Page" } } ``` 2. Then add a new key/value and description ```arb { "@@locale": "en", "counterAppBarTitle": "Counter", "@counterAppBarTitle": { "description": "Text shown in the AppBar of the Counter Page" }, "helloWorld": "Hello World", "@helloWorld": { "description": "Hello World Text" } } ``` 3. Use the new string ```dart import 'package:io_photobooth/l10n/l10n.dart'; @override Widget build(BuildContext context) { final l10n = context.l10n; return Text(l10n.helloWorld); } ``` ### Adding Translations 1. For each supported locale, add a new ARB file in `lib/l10n/arb`. ``` ├── l10n │ ├── arb │ │ ├── app_en.arb │ │ └── app_es.arb ``` 2. Add the translated strings to each `.arb` file: `app_en.arb` ```arb { "@@locale": "en", "counterAppBarTitle": "Counter", "@counterAppBarTitle": { "description": "Text shown in the AppBar of the Counter Page" } } ``` `app_es.arb` ```arb { "@@locale": "es", "counterAppBarTitle": "Contador", "@counterAppBarTitle": { "description": "Texto mostrado en la AppBar de la página del contador" } } ``` [build_status_badge]: https://github.com/flutter/photobooth/actions/workflows/main.yaml/badge.svg [coverage_badge]: coverage_badge.svg [firebase_link]: https://firebase.google.com/ [flutter_link]: https://flutter.dev [flutter_localizations_link]: https://api.flutter.dev/flutter/flutter_localizations/flutter_localizations-library.html [google_io_link]: https://events.google.com/io/ [blog_link]: https://medium.com/flutter/how-its-made-i-o-photo-booth-3b8355d35883 [internationalization_link]: https://flutter.dev/docs/development/accessibility-and-localization/internationalization [license_badge]: https://img.shields.io/badge/license-MIT-blue.svg [license_link]: https://opensource.org/licenses/MIT [logo]: art/header.png [photo_booth_link]: https://photobooth.flutter.dev [very_good_analysis_badge]: https://img.shields.io/badge/style-very_good_analysis-B22C89.svg [very_good_analysis_link]: https://pub.dev/packages/very_good_analysis [very_good_cli_link]: https://github.com/VeryGoodOpenSource/very_good_cli [very_good_ventures_link]: https://verygood.ventures/ [workflow_link]: https://github.com/flutter/photobooth/actions/workflows/main.yaml
photobooth/README.md/0
{ "file_path": "photobooth/README.md", "repo_id": "photobooth", "token_count": 1477 }
1,156
export default ` html, body { margin: 0; padding: 0; height: 100vh; } body { font-family: "Google Sans", sans-serif; font-size: 12px; background-color: #ddd; display: flex; flex-direction: column; position: relative; } *, ::before, ::after { box-sizing: border-box; } .backdrop { position: fixed; left: 0; top: 0; z-index: -1; height: 100%; width: 100%; background-image: url("{{{assetUrls.bgMobile}}}"); background-repeat: no-repeat; background-position: center; background-size: cover; } .fixed-photos { position: fixed; background-repeat: no-repeat; background-size: contain; z-index: 1; display: none; width: 780px; } main { width: 95%; max-width: 1000px; margin: 0 auto 45px; text-align: center; flex: 1 0 auto; z-index: 10; position: relative; } .share-image { margin: 2rem auto; width: 90%; transform: rotate(-5deg); } .share-image img { width: 100%; box-shadow: -3px 9px 7px 1px rgba(0, 0, 0, 0.3); } .share-image.no-shadow img { box-shadow: none; } h1, h2 { color: white; margin-block-start: 0; margin-block-end: 0; } h1 { line-height: 1.2; font-size: 32px; font-weight: 500; width: 80%; margin: 0 auto 15px; } h2 { line-height: 1.3; font-size: 18px; font-weight: 100; width: 85%; margin: 0 auto 35px; } .share-btn { display: inline-block; font-weight: 400; line-height: 1.5; text-align: center; text-decoration: none; line-height: 1; padding: 16px 0; background-color: #428eff; color: white; font-size: 18px; border-radius: 50px; width: 208px; } footer { width: 100%; color: white; font-size: 14px; font-weight: 100; flex-direction: column; display: flex; justify-content: space-between; align-items: center; padding: 0 5% 1.5rem; text-align: center; position: relative; flex-shrink: 0; z-index: 10; position: relative; } footer a { color: white; text-decoration: none; white-space: nowrap; } footer a:hover { text-decoration: underline; } footer ul { margin: 0; padding: 0; line-height: 2; } footer .left { font-size: 16px; font-weight: 400; margin-bottom: 17px; } footer .left a { text-decoration: underline; } footer li { display: inline; margin-left: 1rem; } @media (min-width: 375px) { h1 { width: 67%; } h2 { width: 75%; } } @media (min-width: 768px) { .backdrop { background-image: url("{{{assetUrls.bg}}}"); } .fixed-photos { display: block; } .fixed-photos.left { top: -151px; left: -550px; } .fixed-photos.right { top: -110px; right: -550px; } .share-image { margin: 4.25rem auto 3rem; position: relative; left: -22px; width: calc(100vh * 0.7); max-width: 740px; } h1, h2 { width: 100%; } h1 { font-size: 44px; } h2 { font-size: 21px; } .share-btn { font-size: 22px; } footer { flex-direction: row; text-align: left; padding-left: 2%; padding-right: 2%; } footer .left { font-size: 18px; margin-bottom: 0; } } @media (min-width: 992px) { .fixed-photos.left { left: -400px; } .fixed-photos.right { right: -400px; } } @media (min-width: 1200px) {} @media (min-width: 1644px) { h1 { font-size: 56px; } h2 { font-size: 24px; } } @media (min-width: 1920px) { .fixed-photos.left { left: -150px; } .fixed-photos.right { right: -150px; } .share-image { margin-top: 9.5rem; margin-bottom: 4rem; } } `;
photobooth/functions/src/share/templates/styles.ts/0
{ "file_path": "photobooth/functions/src/share/templates/styles.ts", "repo_id": "photobooth", "token_count": 1540 }
1,157
{ "@@locale": "fr", "landingPageHeading": "Bienvenue sur I\u2215O Photo Booth", "landingPageSubheading": "Prenez une photo et partagez-la avec la communaut!", "landingPageTakePhotoButtonText": "Démarrer", "footerMadeWithText": "Fait avec ", "footerMadeWithFlutterLinkText": "Flutter", "footerMadeWithFirebaseLinkText": "Firebase", "footerGoogleIOLinkText": "Google I\u2215O", "footerCodelabLinkText": "Codelab", "footerHowItsMadeLinkText": "Comment C'est Fait", "footerTermsOfServiceLinkText": "Conditions d'utilisation", "footerPrivacyPolicyLinkText": "Politique de confidentialité", "sharePageHeading": "Partagez votre photo avec la communauté!", "sharePageSubheading": "Partagez votre photo avec la communauté!", "sharePageSuccessHeading": "Photo Partagée!", "sharePageSuccessSubheading": "Merci d'avoir utilisé notre web application Flutter! Votre photo a été publiée sur cette URL unique", "sharePageSuccessCaption1": "Votre photo sera disponible sur cette URL pendant 30 jours ensuite elle sera automatiquement supprimée. Pour demander une suppression anticipée, contactez ", "sharePageSuccessCaption2": "[email protected]", "sharePageSuccessCaption3": " et assurez-vous d'inclure votre URL unique dans votre demande.", "sharePageRetakeButtonText": "Prendre une nouvelle photo", "sharePageShareButtonText": "Partager", "sharePageDownloadButtonText": "Télécharger", "socialMediaShareLinkText": "J'viens de prendre un selfie au #IOPhotoBooth. On se voit à la #GoogleIO!", "previewPageCameraNotAllowedText": "Vous avez refusé les autorisations de la caméra. Veuillez accorder l'accès afin d'utiliser l'application.", "sharePageSocialMediaShareClarification1": "Si vous choisissez de partager votre photo sur les réseaux sociaux, elle sera disponible sur une URL unique pendant 30 jours, puis automatiquement supprimée. Les photos non-partagées ne sont pas stockées. Pour demander la suppression anticipée de votre photo, veuillez contacter ", "sharePageSocialMediaShareClarification2": "[email protected]", "sharePageSocialMediaShareClarification3": " et assurez-vous d'inclure votre URL unique dans a demande.", "sharePageCopyLinkButton": "Copier", "sharePageLinkedCopiedButton": "Copiée", "sharePageErrorHeading": "Nous rencontrons des difficultés pour traiter votre image", "sharePageErrorSubheading": "Veuillez vous assurer que votre appareil et votre navigateur sont à jour. Si ce problème persiste, veuillez contacter [email protected].", "shareDialogHeading": "Partagez votre photo!", "shareDialogSubheading": "Informez tout le monde que vous êtes à la Google I\u2215O en partageant votre photo et en mettant à jour votre photo de profil pendant l'événement!", "shareErrorDialogHeading": "Oops!", "shareErrorDialogTryAgainButton": "Retourner", "shareErrorDialogSubheading": "Une erreur s'est produite et nous n'avons pas pu charger votre photo.", "sharePageProgressOverlayHeading": "Nous rendons votre photo pixel perfect avec Flutter! ", "sharePageProgressOverlaySubheading": "Veuillez ne pas fermer cet onglet.", "shareDialogTwitterButtonText": "Twitter", "shareDialogFacebookButtonText": "Facebook", "photoBoothCameraAccessDeniedHeadline": "Accès à la camera refusée", "photoBoothCameraAccessDeniedSubheadline": "Pour prendre une photo, vous devez autoriser le navigateur d'accéder à votre camera.", "photoBoothCameraNotFoundHeadline": "Nous n'arrivons à pas trouver votre camera", "photoBoothCameraNotFoundSubheadline1": "On dirait que votre appareil n'a pas de camera ou qu'elle est endommagée.", "photoBoothCameraNotFoundSubheadline2": "Pour prendre une photo, veuillez revisiter I\u2215O Photo Booth à partir d'un appareil ayant une camera.", "photoBoothCameraErrorHeadline": "Oops! Quelque chose s'est mal passé", "photoBoothCameraErrorSubheadline1": "Veuillez rafraîchir votre navigateur et essayer à nouveau.", "photoBoothCameraErrorSubheadline2": "Si ce problème persiste, Veuillez contacter [email protected]", "photoBoothCameraNotSupportedHeadline": "Oops! Quelque chose s'est mal passé", "photoBoothCameraNotSupportedSubheadline": "Veuillez vous assurer que votre appareil et votre navigateur sont à jour.", "stickersDrawerTitle": "Ajouter des Accessoires", "openStickersTooltip": "Ajouter des Accessoires", "retakeButtonTooltip": "Reprendre", "clearStickersButtonTooltip": "Supprimer des Accessoires", "charactersCaptionText": "Ajouter des Amis", "sharePageLearnMoreAboutTextPart1": "Apprendre plus sur ", "sharePageLearnMoreAboutTextPart2": " et ", "sharePageLearnMoreAboutTextPart3": " ou plonger directement dans le ", "sharePageLearnMoreAboutTextPart4": "code open source", "goToGoogleIOButtonText": "Aller sur Google I\u2215O", "clearStickersDialogHeading": "Supprimer tous les accessoires?", "clearStickersDialogSubheading": "Voulez-vous supprimer tous les accessoires de l'écran?", "clearStickersDialogCancelButtonText": "Non, retourner", "clearStickersDialogConfirmButtonText": "Oui, supprimer tous", "propsReminderText": "Ajouter quelques accessoires", "stickersNextConfirmationHeading": "Prêt à voir la photo finale?", "stickersNextConfirmationSubheading": "Une fois que vous quittez cet écran, vous ne pourrez plus rien modifier", "stickersNextConfirmationCancelButtonText": "Non, je crée encore", "stickersNextConfirmationConfirmButtonText": "Oui, montre-moi", "stickersRetakeConfirmationHeading": "Êtes-vous sûr?", "stickersRetakeConfirmationSubheading": "Reprendre la photo supprimera tous les accessoires que vous avez ajoutés", "stickersRetakeConfirmationCancelButtonText": "Non, rester ici", "stickersRetakeConfirmationConfirmButtonText": "Oui, reprendre la photo", "shareRetakeConfirmationHeading": "Prêt à prendre une nouvelle photo ?", "shareRetakeConfirmationSubheading": "N'oubliez pas de télécharger ou de partager celle-ci en premier", "shareRetakeConfirmationCancelButtonText": "Non, rester ici", "shareRetakeConfirmationConfirmButtonText": "Oui, reprendre la photo", "shutterButtonLabelText": "Prendre une photo", "stickersNextButtonLabelText": "Créer la photo finale", "dashButtonLabelText": "Ajouter un ami dash", "sparkyButtonLabelText": "Ajouter un ami spaky", "dinoButtonLabelText": "Ajouter un ami dino", "androidButtonLabelText": "Ajouter un ami android jetpack", "addStickersButtonLabelText": "Ajouter des accessoires", "retakePhotoButtonLabelText": "Reprendre la photo", "clearAllStickersButtonLabelText": "Supprimer tous les accessoires" }
photobooth/lib/l10n/arb/app_fr.arb/0
{ "file_path": "photobooth/lib/l10n/arb/app_fr.arb", "repo_id": "photobooth", "token_count": 2365 }
1,158
import 'package:analytics/analytics.dart'; import 'package:flutter/material.dart'; import 'package:io_photobooth/l10n/l10n.dart'; import 'package:io_photobooth/photobooth/photobooth.dart'; class LandingTakePhotoButton extends StatelessWidget { const LandingTakePhotoButton({super.key}); @override Widget build(BuildContext context) { final l10n = context.l10n; return ElevatedButton( onPressed: () { trackEvent( category: 'button', action: 'click-start-photobooth', label: 'start-photobooth', ); Navigator.of(context).push(PhotoboothPage.route()); }, child: Text(l10n.landingPageTakePhotoButtonText), ); } }
photobooth/lib/landing/widgets/landing_take_photo_button.dart/0
{ "file_path": "photobooth/lib/landing/widgets/landing_take_photo_button.dart", "repo_id": "photobooth", "token_count": 285 }
1,159
import 'package:flutter/material.dart'; class PhotoboothBackground extends StatelessWidget { const PhotoboothBackground({super.key}); @override Widget build(BuildContext context) { final size = MediaQuery.of(context).size; return Stack( fit: StackFit.expand, children: [ Image.asset( 'assets/backgrounds/photobooth_background.jpg', repeat: ImageRepeat.repeat, filterQuality: FilterQuality.high, ), Positioned( left: 50, bottom: size.height * 0.2, child: Image.asset( 'assets/backgrounds/red_box.png', height: 150, ), ), Positioned( right: -50, top: size.height * 0.1, child: Image.asset( 'assets/backgrounds/blue_circle.png', height: 150, ), ), Positioned( right: 50, bottom: size.height * 0.1, child: Image.asset( 'assets/backgrounds/yellow_plus.png', height: 150, ), ), ], ); } }
photobooth/lib/photobooth/widgets/photobooth_background.dart/0
{ "file_path": "photobooth/lib/photobooth/widgets/photobooth_background.dart", "repo_id": "photobooth", "token_count": 564 }
1,160
export 'share_bottom_sheet.dart'; export 'share_dialog.dart'; export 'share_error_bottom_sheet.dart'; export 'share_error_dialog.dart'; export 'share_page.dart';
photobooth/lib/share/view/view.dart/0
{ "file_path": "photobooth/lib/share/view/view.dart", "repo_id": "photobooth", "token_count": 60 }
1,161
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:io_photobooth/l10n/l10n.dart'; import 'package:io_photobooth/share/share.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; class TwitterButton extends StatelessWidget { const TwitterButton({super.key}); @override Widget build(BuildContext context) { final l10n = context.l10n; return ElevatedButton( onPressed: () { final state = context.read<ShareBloc>().state; if (state.uploadStatus.isSuccess) { Navigator.of(context).pop(); openLink(state.twitterShareUrl); return; } context.read<ShareBloc>().add(const ShareOnTwitterTapped()); Navigator.of(context).pop(); }, child: Text(l10n.shareDialogTwitterButtonText), ); } }
photobooth/lib/share/widgets/twitter_button.dart/0
{ "file_path": "photobooth/lib/share/widgets/twitter_button.dart", "repo_id": "photobooth", "token_count": 345 }
1,162
export 'clear_stickers/clear_stickers.dart'; export 'stickers_drawer_layer/desktop_stickers_drawer.dart'; export 'stickers_drawer_layer/mobile_stickers_drawer.dart'; export 'stickers_drawer_layer/stickers_drawer_layer.dart'; export 'stickers_tabs.dart';
photobooth/lib/stickers/widgets/widgets.dart/0
{ "file_path": "photobooth/lib/stickers/widgets/widgets.dart", "repo_id": "photobooth", "token_count": 94 }
1,163
include: package:very_good_analysis/analysis_options.yaml linter: rules: public_member_api_docs: false
photobooth/packages/camera/camera/analysis_options.yaml/0
{ "file_path": "photobooth/packages/camera/camera/analysis_options.yaml", "repo_id": "photobooth", "token_count": 38 }
1,164
import 'package:camera/camera.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:plugin_platform_interface/plugin_platform_interface.dart'; class MockCameraController extends Mock implements CameraController {} class MockCameraPlatform extends Mock with MockPlatformInterfaceMixin implements CameraPlatform {} void main() { group('Camera', () { late CameraPlatform platform; late CameraController controller; setUp(() { platform = MockCameraPlatform(); CameraPlatform.instance = platform; controller = MockCameraController(); when(() => platform.init()).thenAnswer((_) async {}); }); testWidgets('renders placeholder (default)', (tester) async { when(() => controller.value).thenReturn( const CameraState.uninitialized(), ); await tester.pumpWidget(Camera(controller: controller)); expect(find.byType(SizedBox), findsOneWidget); }); testWidgets('renders placeholder (custom)', (tester) async { when(() => controller.value).thenReturn( const CameraState.uninitialized(), ); const key = Key('__target__'); const widget = SizedBox(key: key); await tester.pumpWidget( Camera(controller: controller, placeholder: (_) => widget), ); expect(find.byKey(key), findsOneWidget); }); testWidgets('renders error (default)', (tester) async { when(() => controller.value).thenReturn( const CameraState.unavailable(CameraUnknownException()), ); await tester.pumpWidget(Camera(controller: controller)); expect(find.byType(SizedBox), findsOneWidget); }); testWidgets('renders error (custom)', (tester) async { when(() => controller.value).thenReturn( const CameraState.unavailable(CameraUnknownException()), ); const key = Key('__target__'); const widget = SizedBox(key: key); await tester.pumpWidget( Camera(controller: controller, error: (_, __) => widget), ); expect(find.byKey(key), findsOneWidget); }); testWidgets('renders preview (default)', (tester) async { const key = Key('__target__'); const widget = SizedBox(key: key); const textureId = 0; when(() => controller.textureId).thenReturn(textureId); when(() => controller.value).thenReturn(const CameraState.available()); when(() => platform.buildView(textureId)).thenReturn(widget); await tester.pumpWidget(Camera(controller: controller)); expect(find.byKey(key), findsOneWidget); }); testWidgets('renders preview (custom)', (tester) async { const key = Key('__target__'); const previewKey = Key('__preview__'); const preview = SizedBox(key: previewKey); const textureId = 0; when(() => controller.textureId).thenReturn(textureId); when(() => controller.value).thenReturn(const CameraState.available()); when(() => platform.buildView(textureId)).thenReturn(preview); await tester.pumpWidget( Camera( controller: controller, preview: (_, preview) => SizedBox(key: key, child: preview), ), ); expect(find.byKey(key), findsOneWidget); expect(find.byKey(previewKey), findsOneWidget); }); }); }
photobooth/packages/camera/camera/test/src/camera_test.dart/0
{ "file_path": "photobooth/packages/camera/camera/test/src/camera_test.dart", "repo_id": "photobooth", "token_count": 1230 }
1,165
// 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. @TestOn('chrome') library; import 'package:camera_web/camera_web.dart'; import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } void testMain() { test('Should detect Blink', () { // Chrome Version 89.0.4389.90 (Official Build) (x86_64) / MacOS final browserEngine = detectBrowserEngineByVendorAgent( 'Google Inc.', 'mozilla/5.0 (macintosh; intel mac os x 11_2_3) applewebkit/537.36 ' '(khtml, like gecko) chrome/89.0.4389.90 safari/537.36'); expect(browserEngine, BrowserEngine.blink); }); test('Should detect Firefox', () { // 85.0.2 (64-bit) / MacOS final browserEngine = detectBrowserEngineByVendorAgent( '', 'mozilla/5.0 (macintosh; intel mac os x 10.16; rv:85.0) ' 'gecko/20100101 firefox/85.0'); expect(browserEngine, BrowserEngine.firefox); }); test('Should detect Safari', () { final browserEngine = detectBrowserEngineByVendorAgent( 'Apple Computer, Inc.', 'mozilla/5.0 (macintosh; intel mac os x 10_15_6) applewebkit/605.1.15 ' '(khtml, like gecko) version/14.0.3 safari/605.1.15'); expect(browserEngine, BrowserEngine.webkit); }); test('Should detect Samsung browser', () { // Samsung 13.2.1.70 on Galaxy Tab S6. final browserEngine = detectBrowserEngineByVendorAgent( 'Google Inc.', 'mozilla/5.0 (x11; linux x86_64) applewebkit/537.36 (khtml, like gecko)' ' samsungbrowser/13.2 chrome/83.0.4103.106 safari/537.36'); expect(browserEngine, BrowserEngine.samsung); }); }
photobooth/packages/camera/camera_web/test/src/browser_detection_test.dart/0
{ "file_path": "photobooth/packages/camera/camera_web/test/src/browser_detection_test.dart", "repo_id": "photobooth", "token_count": 701 }
1,166
export 'app_page_route.dart';
photobooth/packages/photobooth_ui/lib/src/navigation/navigation.dart/0
{ "file_path": "photobooth/packages/photobooth_ui/lib/src/navigation/navigation.dart", "repo_id": "photobooth", "token_count": 12 }
1,167
import 'package:flutter/material.dart'; /// {@template clickable} /// Makes the given [child] tappable and clickable. /// {@endtemplate} class Clickable extends StatelessWidget { /// {@macro clickable} const Clickable({ required this.child, required this.onPressed, super.key, }); /// Child to be rendered final Widget child; /// Callback that notifies when the widget has been clicked or tapped final VoidCallback onPressed; @override Widget build(BuildContext context) { return MouseRegion( cursor: SystemMouseCursors.click, child: GestureDetector( onTap: onPressed, child: child, ), ); } }
photobooth/packages/photobooth_ui/lib/src/widgets/clickable.dart/0
{ "file_path": "photobooth/packages/photobooth_ui/lib/src/widgets/clickable.dart", "repo_id": "photobooth", "token_count": 236 }
1,168
// ignore_for_file: prefer_const_constructors import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; void main() { group('PhotoboothTheme themeData', () { test('is defined for both small, medium, and standard', () { expect(PhotoboothTheme.small, isA<ThemeData>()); expect(PhotoboothTheme.medium, isA<ThemeData>()); expect(PhotoboothTheme.standard, isA<ThemeData>()); }); }); }
photobooth/packages/photobooth_ui/test/src/theme_test.dart/0
{ "file_path": "photobooth/packages/photobooth_ui/test/src/theme_test.dart", "repo_id": "photobooth", "token_count": 179 }
1,169
# photos_repository Repository that persists photos in a Firebase Storage
photobooth/packages/photos_repository/README.md/0
{ "file_path": "photobooth/packages/photos_repository/README.md", "repo_id": "photobooth", "token_count": 19 }
1,170
@TestOn('chrome') library; import 'dart:html' as html; import 'package:mocktail/mocktail.dart'; import 'package:platform_helper/src/web.dart'; import 'package:test/test.dart'; class MockWindow extends Mock implements html.Window {} class MockNavigator extends Mock implements html.Navigator {} void main() { group('WebPlatformHelper', () { late html.Window window; late html.Navigator navigator; setUp(() { window = MockWindow(); navigator = MockNavigator(); when(() => window.navigator).thenReturn(navigator); when(() => navigator.userAgent).thenReturn('iphone'); }); test('returns true when user agent is in browser from mobile', () { final helper = PlatformHelper()..window = window; expect(helper.isMobile, true); }); test('returns false by default', () { final helper = PlatformHelper(); expect(helper.isMobile, false); }); }); }
photobooth/packages/platform_helper/test/src/web_platform_helper_test.dart/0
{ "file_path": "photobooth/packages/platform_helper/test/src/web_platform_helper_test.dart", "repo_id": "photobooth", "token_count": 322 }
1,171
// ignore_for_file: prefer_const_constructors import 'package:io_photobooth/photobooth/photobooth.dart'; import 'package:mocktail/mocktail.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; import 'package:test/test.dart'; class MockAsset extends Mock implements Asset {} void main() { group('PhotoboothState', () { test('supports value equality', () { expect(PhotoboothState(), equals(PhotoboothState())); }); }); group('PhotoAsset', () { group('copyWith', () { test('updates asset', () { final assetA = MockAsset(); final assetB = MockAsset(); expect( PhotoAsset(id: '0', asset: assetA).copyWith(asset: assetB).asset, equals(assetB), ); }); }); }); }
photobooth/test/photobooth/bloc/photobooth_state_test.dart/0
{ "file_path": "photobooth/test/photobooth/bloc/photobooth_state_test.dart", "repo_id": "photobooth", "token_count": 304 }
1,172
import 'package:cross_file/cross_file.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:io_photobooth/share/share.dart'; import 'package:mocktail/mocktail.dart'; import '../../helpers/helpers.dart'; class MockXFile extends Mock implements XFile {} void main() { group('DownloadButton', () { late XFile file; setUp(() { file = MockXFile(); }); testWidgets('renders OutlinedButton', (tester) async { await tester.pumpApp(DownloadButton(file: file)); expect(find.byType(OutlinedButton), findsOneWidget); }); testWidgets('downloads file on tap', (tester) async { when(() => file.saveTo(any())).thenAnswer((_) async {}); await tester.pumpApp(DownloadButton(file: file)); await tester.tap(find.byType(OutlinedButton)); verify(() => file.saveTo('')).called(1); }); }); }
photobooth/test/share/widgets/download_button_test.dart/0
{ "file_path": "photobooth/test/share/widgets/download_button_test.dart", "repo_id": "photobooth", "token_count": 346 }
1,173
part of 'assets_manager_cubit.dart'; /// {@template assets_manager_state} /// State used to load the game assets. /// {@endtemplate} class AssetsManagerState extends Equatable { /// {@macro assets_manager_state} const AssetsManagerState({ required this.assetsCount, required this.loaded, }); /// {@macro assets_manager_state} const AssetsManagerState.initial() : this(assetsCount: 0, loaded: 0); /// Number of assets to load. final int assetsCount; /// Number of already loaded assets. final int loaded; /// Returns a value between 0 and 1 to indicate the loading progress. double get progress => loaded == 0 ? 0 : loaded / assetsCount; /// Only returns false if all the assets have been loaded. bool get isLoading => progress != 1; /// Returns a copy of this instance with the given parameters /// updated. AssetsManagerState copyWith({ int? assetsCount, int? loaded, }) { return AssetsManagerState( assetsCount: assetsCount ?? this.assetsCount, loaded: loaded ?? this.loaded, ); } @override List<Object> get props => [loaded, assetsCount]; }
pinball/lib/assets_manager/cubit/assets_manager_state.dart/0
{ "file_path": "pinball/lib/assets_manager/cubit/assets_manager_state.dart", "repo_id": "pinball", "token_count": 335 }
1,174
import 'dart:math' as math; import 'package:bloc/bloc.dart'; import 'package:equatable/equatable.dart'; import 'package:meta/meta.dart'; part 'game_event.dart'; part 'game_state.dart'; class GameBloc extends Bloc<GameEvent, GameState> { GameBloc() : super(const GameState.initial()) { on<RoundLost>(_onRoundLost); on<Scored>(_onScored); on<MultiplierIncreased>(_onIncreasedMultiplier); on<BonusActivated>(_onBonusActivated); on<GameOver>(_onGameOver); on<GameStarted>(_onGameStarted); } static const _maxScore = 9999999999; void _onGameStarted(GameStarted _, Emitter emit) { emit(const GameState.initial().copyWith(status: GameStatus.playing)); } void _onGameOver(GameOver _, Emitter emit) { emit(state.copyWith(status: GameStatus.gameOver)); } void _onRoundLost(RoundLost event, Emitter emit) { final score = math.min( state.totalScore + state.roundScore * state.multiplier, _maxScore, ); final roundsLeft = math.max(state.rounds - 1, 0); emit( state.copyWith( totalScore: score, roundScore: 0, multiplier: 1, rounds: roundsLeft, status: roundsLeft == 0 ? GameStatus.gameOver : state.status, ), ); } void _onScored(Scored event, Emitter emit) { if (state.status.isPlaying) { final combinedScore = math.min( state.totalScore + state.roundScore + event.points, _maxScore, ); emit(state.copyWith(roundScore: combinedScore - state.totalScore)); } } void _onIncreasedMultiplier(MultiplierIncreased event, Emitter emit) { if (state.status.isPlaying) { emit( state.copyWith( multiplier: math.min(state.multiplier + 1, 6), ), ); } } void _onBonusActivated(BonusActivated event, Emitter emit) { emit( state.copyWith( bonusHistory: [...state.bonusHistory, event.bonus], ), ); } }
pinball/lib/game/bloc/game_bloc.dart/0
{ "file_path": "pinball/lib/game/bloc/game_bloc.dart", "repo_id": "pinball", "token_count": 789 }
1,175
import 'dart:async'; import 'package:flame/components.dart'; import 'package:flame/input.dart'; import 'package:flutter/material.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball/l10n/l10n.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; import 'package:pinball_ui/pinball_ui.dart'; import 'package:share_repository/share_repository.dart'; /// Signature for the callback called when the user tries to share their score /// from the [GameOverInfoDisplay]. typedef OnShareTap = void Function(); final _titleTextPaint = TextPaint( style: const TextStyle( fontSize: 1.6, color: PinballColors.white, fontFamily: PinballFonts.pixeloidSans, ), ); final _titleBoldTextPaint = TextPaint( style: const TextStyle( fontSize: 1.4, color: PinballColors.white, fontFamily: PinballFonts.pixeloidSans, fontWeight: FontWeight.bold, ), ); final _linkTextPaint = TextPaint( style: const TextStyle( fontSize: 1.7, color: PinballColors.orange, fontFamily: PinballFonts.pixeloidSans, fontWeight: FontWeight.bold, ), ); final _descriptionTextPaint = TextPaint( style: const TextStyle( fontSize: 1.6, color: PinballColors.white, fontFamily: PinballFonts.pixeloidSans, ), ); /// {@template game_over_info_display} /// Display with links to share your score or go to the IO webpage. /// {@endtemplate} class GameOverInfoDisplay extends Component with HasGameRef { /// {@macro game_over_info_display} GameOverInfoDisplay({ OnShareTap? onShare, }) : super( children: [ _InstructionsComponent( onShare: onShare, ), ], ); @override Future<void> onLoad() async { await super.onLoad(); gameRef.overlays.add(PinballGame.replayButtonOverlay); } } class _InstructionsComponent extends PositionComponent with HasGameRef { _InstructionsComponent({ OnShareTap? onShare, }) : super( anchor: Anchor.center, position: Vector2(0, -25), children: [ _TitleComponent(), _LinksComponent( onShare: onShare, ), _DescriptionComponent(), ], ); } class _TitleComponent extends PositionComponent with HasGameRef { _TitleComponent() : super( anchor: Anchor.center, position: Vector2(0, 3), children: [ _TitleBackgroundSpriteComponent(), _ShareScoreTextComponent(), _ChallengeFriendsTextComponent(), ], ); } class _ShareScoreTextComponent extends TextComponent with HasGameRef { _ShareScoreTextComponent() : super( anchor: Anchor.center, position: Vector2(0, -1.5), textRenderer: _titleTextPaint, ); @override Future<void> onLoad() async { await super.onLoad(); text = readProvider<AppLocalizations>().shareYourScore; } } class _ChallengeFriendsTextComponent extends TextComponent with HasGameRef { _ChallengeFriendsTextComponent() : super( anchor: Anchor.center, position: Vector2(0, 1.5), textRenderer: _titleBoldTextPaint, ); @override Future<void> onLoad() async { await super.onLoad(); text = readProvider<AppLocalizations>().andChallengeYourFriends; } } class _TitleBackgroundSpriteComponent extends SpriteComponent with HasGameRef { _TitleBackgroundSpriteComponent() : super( anchor: Anchor.center, position: Vector2.zero(), ); @override Future<void> onLoad() async { await super.onLoad(); final sprite = Sprite( gameRef.images .fromCache(Assets.images.backbox.displayTitleDecoration.keyName), ); this.sprite = sprite; size = sprite.originalSize / 22; } } class _LinksComponent extends PositionComponent with HasGameRef { _LinksComponent({ OnShareTap? onShare, }) : super( anchor: Anchor.center, position: Vector2(0, 9.2), children: [ ShareLinkComponent(onTap: onShare), GoogleIOLinkComponent(), ], ); } /// {@template share_link_component} /// Link button to navigate to sharing score display. /// {@endtemplate} class ShareLinkComponent extends TextComponent with HasGameRef, Tappable { /// {@macro share_link_component} ShareLinkComponent({ OnShareTap? onTap, }) : _onTap = onTap, super( anchor: Anchor.center, position: Vector2(-7, 0), textRenderer: _linkTextPaint, ); final OnShareTap? _onTap; @override bool onTapDown(TapDownInfo info) { _onTap?.call(); return true; } @override Future<void> onLoad() async { await super.onLoad(); await add( RectangleComponent( size: Vector2(6.4, 0.2), paint: Paint()..color = PinballColors.orange, anchor: Anchor.center, position: Vector2(3.2, 2.3), ), ); text = readProvider<AppLocalizations>().share; } } /// {@template google_io_link_component} /// Link button to navigate to Google I/O site. /// {@endtemplate} class GoogleIOLinkComponent extends TextComponent with HasGameRef, Tappable { /// {@macro google_io_link_component} GoogleIOLinkComponent() : super( anchor: Anchor.center, position: Vector2(6, 0), textRenderer: _linkTextPaint, ); @override bool onTapUp(TapUpInfo info) { openLink(ShareRepository.googleIOEvent); return true; } @override Future<void> onLoad() async { await super.onLoad(); await add( RectangleComponent( size: Vector2(10.2, 0.2), paint: Paint()..color = PinballColors.orange, anchor: Anchor.center, position: Vector2(5.1, 2.3), ), ); text = readProvider<AppLocalizations>().gotoIO; } } class _DescriptionComponent extends PositionComponent with HasGameRef { _DescriptionComponent() : super( anchor: Anchor.center, position: Vector2(0, 13), children: [ _LearnMoreTextComponent(), _FirebaseTextComponent(), OpenSourceTextComponent(), ], ); } class _LearnMoreTextComponent extends TextComponent with HasGameRef { _LearnMoreTextComponent() : super( anchor: Anchor.center, position: Vector2.zero(), textRenderer: _descriptionTextPaint, ); @override Future<void> onLoad() async { await super.onLoad(); text = readProvider<AppLocalizations>().learnMore; } } class _FirebaseTextComponent extends TextComponent with HasGameRef { _FirebaseTextComponent() : super( anchor: Anchor.center, position: Vector2(-8.5, 2.5), textRenderer: _descriptionTextPaint, ); @override Future<void> onLoad() async { await super.onLoad(); text = readProvider<AppLocalizations>().firebaseOr; } } /// {@template open_source_link_component} /// Link text to navigate to Open Source site. /// {@endtemplate} @visibleForTesting class OpenSourceTextComponent extends TextComponent with HasGameRef, Tappable { /// {@macro open_source_link_component} OpenSourceTextComponent() : super( anchor: Anchor.center, position: Vector2(13.5, 2.5), textRenderer: _descriptionTextPaint, ); @override bool onTapUp(TapUpInfo info) { openLink(ShareRepository.openSourceCode); return true; } @override Future<void> onLoad() async { await super.onLoad(); await add( RectangleComponent( size: Vector2(16, 0.2), paint: Paint()..color = PinballColors.white, anchor: Anchor.center, position: Vector2(8, 2.3), ), ); text = readProvider<AppLocalizations>().openSourceCode; } }
pinball/lib/game/components/backbox/displays/game_over_info_display.dart/0
{ "file_path": "pinball/lib/game/components/backbox/displays/game_over_info_display.dart", "repo_id": "pinball", "token_count": 3219 }
1,176
export 'flutter_forest_bonus_behavior.dart';
pinball/lib/game/components/flutter_forest/behaviors/behaviors.dart/0
{ "file_path": "pinball/lib/game/components/flutter_forest/behaviors/behaviors.dart", "repo_id": "pinball", "token_count": 16 }
1,177
// ignore_for_file: avoid_renaming_method_parameters import 'package:flame/components.dart'; import 'package:flutter/material.dart'; import 'package:pinball/game/behaviors/behaviors.dart'; import 'package:pinball/game/components/sparky_scorch/behaviors/behaviors.dart'; import 'package:pinball_components/pinball_components.dart'; /// {@template sparky_scorch} /// Area positioned at the top left of the board containing the /// [SparkyComputer], [SparkyAnimatronic], and [SparkyBumper]s. /// {@endtemplate} class SparkyScorch extends Component { /// {@macro sparky_scorch} SparkyScorch() : super( children: [ SparkyBumper.a( children: [ ScoringContactBehavior(points: Points.twentyThousand), BumperNoiseBehavior(), ], )..initialPosition = Vector2(-22.9, -41.65), SparkyBumper.b( children: [ ScoringContactBehavior(points: Points.twentyThousand), BumperNoiseBehavior(), ], )..initialPosition = Vector2(-21.25, -57.9), SparkyBumper.c( children: [ ScoringContactBehavior(points: Points.twentyThousand), BumperNoiseBehavior(), ], )..initialPosition = Vector2(-3.3, -52.55), SparkyAnimatronic( children: [ AnimatronicLoopingBehavior(animationCoolDown: 8), ], )..position = Vector2(-14, -58.2), SparkyComputer( children: [ ScoringContactBehavior(points: Points.twoHundredThousand) ..applyTo(['turbo_charge_sensor']), ], ), SparkyComputerBonusBehavior(), ], ); /// Creates [SparkyScorch] without any children. /// /// This can be used for testing [SparkyScorch]'s behaviors in isolation. @visibleForTesting SparkyScorch.test(); }
pinball/lib/game/components/sparky_scorch/sparky_scorch.dart/0
{ "file_path": "pinball/lib/game/components/sparky_scorch/sparky_scorch.dart", "repo_id": "pinball", "token_count": 963 }
1,178
export 'assets.gen.dart';
pinball/lib/gen/gen.dart/0
{ "file_path": "pinball/lib/gen/gen.dart", "repo_id": "pinball", "token_count": 10 }
1,179
import 'package:bloc/bloc.dart'; import 'package:equatable/equatable.dart'; part 'start_game_event.dart'; part 'start_game_state.dart'; /// {@template start_game_bloc} /// Bloc that manages the app flow before the game starts. /// {@endtemplate} class StartGameBloc extends Bloc<StartGameEvent, StartGameState> { /// {@macro start_game_bloc} StartGameBloc() : super(const StartGameState.initial()) { on<PlayTapped>(_onPlayTapped); on<ReplayTapped>(_onReplayTapped); on<CharacterSelected>(_onCharacterSelected); on<HowToPlayFinished>(_onHowToPlayFinished); } void _onPlayTapped( PlayTapped event, Emitter<StartGameState> emit, ) { emit( state.copyWith( status: StartGameStatus.selectCharacter, ), ); } void _onReplayTapped( ReplayTapped event, Emitter<StartGameState> emit, ) { emit( state.copyWith( status: StartGameStatus.selectCharacter, ), ); } void _onCharacterSelected( CharacterSelected event, Emitter<StartGameState> emit, ) { emit( state.copyWith( status: StartGameStatus.howToPlay, ), ); } void _onHowToPlayFinished( HowToPlayFinished event, Emitter<StartGameState> emit, ) { emit( state.copyWith( status: StartGameStatus.play, ), ); } }
pinball/lib/start_game/bloc/start_game_bloc.dart/0
{ "file_path": "pinball/lib/start_game/bloc/start_game_bloc.dart", "repo_id": "pinball", "token_count": 554 }
1,180
import 'dart:math' as math; import 'package:vector_math/vector_math_64.dart'; /// Calculates all [Vector2]s of a circumference. /// /// A circumference can be achieved by specifying a [center] and a [radius]. /// In addition, a semi-circle can be achieved by specifying its [angle] and an /// [offsetAngle] (both in radians). /// /// The higher the [precision], the more [Vector2]s will be calculated; /// achieving a more rounded arc. /// /// For more information read: https://en.wikipedia.org/wiki/Trigonometric_functions. List<Vector2> calculateArc({ required Vector2 center, required double radius, required double angle, double offsetAngle = 0, int precision = 100, }) { final stepAngle = angle / (precision - 1); final points = <Vector2>[]; for (var i = 0; i < precision; i++) { final x = center.x + radius * math.cos((stepAngle * i) + offsetAngle); final y = center.y - radius * math.sin((stepAngle * i) + offsetAngle); final point = Vector2(x, y); points.add(point); } return points; } /// Calculates all [Vector2]s of an ellipse. /// /// An ellipse can be achieved by specifying a [center], a [majorRadius] and a /// [minorRadius]. /// /// The higher the [precision], the more [Vector2]s will be calculated; /// achieving a more rounded ellipse. /// /// For more information read: https://en.wikipedia.org/wiki/Ellipse. List<Vector2> calculateEllipse({ required Vector2 center, required double majorRadius, required double minorRadius, int precision = 100, }) { assert( 0 < minorRadius && minorRadius <= majorRadius, 'smallRadius ($minorRadius) and bigRadius ($majorRadius) must be in ' 'range 0 < smallRadius <= bigRadius', ); final stepAngle = 2 * math.pi / (precision - 1); final points = <Vector2>[]; for (var i = 0; i < precision; i++) { final x = center.x + minorRadius * math.cos(stepAngle * i); final y = center.y - majorRadius * math.sin(stepAngle * i); final point = Vector2(x, y); points.add(point); } return points; } /// Calculates all [Vector2]s of a bezier curve. /// /// A bezier curve of [controlPoints] that say how to create this curve. /// /// First and last points specify the beginning and the end respectively /// of the curve. The inner points specify the shape of the curve and /// its turning points. /// /// The [step] must be between zero and one (inclusive), indicating the /// precision to calculate the curve. /// /// For more information read: https://en.wikipedia.org/wiki/B%C3%A9zier_curve List<Vector2> calculateBezierCurve({ required List<Vector2> controlPoints, double step = 0.01, }) { assert( 0 <= step && step <= 1, 'Step ($step) must be in range 0 <= step <= 1', ); assert( controlPoints.length >= 2, 'At least 2 control points needed to create a bezier curve', ); var t = 0.0; final n = controlPoints.length - 1; final points = <Vector2>[]; do { var x = 0.0; var y = 0.0; for (var i = 0; i <= n; i++) { final point = controlPoints[i]; x += binomial(n, i) * math.pow(1 - t, n - i) * math.pow(t, i) * point.x; y += binomial(n, i) * math.pow(1 - t, n - i) * math.pow(t, i) * point.y; } points.add(Vector2(x, y)); t = t + step; } while (t <= 1); return points; } /// Calculates the binomial coefficient of 'n' and 'k'. /// /// For more information read: https://en.wikipedia.org/wiki/Binomial_coefficient num binomial(num n, num k) { assert(0 <= k && k <= n, 'k ($k) and n ($n) must be in range 0 <= k <= n'); if (k == 0 || n == k) { return 1; } else { return factorial(n) / (factorial(k) * factorial(n - k)); } } /// Calculate the factorial of 'n'. /// /// For more information read: https://en.wikipedia.org/wiki/Factorial num factorial(num n) { assert(n >= 0, 'Factorial is not defined for negative number n ($n)'); if (n == 0 || n == 1) { return 1; } else { return n * factorial(n - 1); } } /// Arithmetic mean position of all the [Vector2]s in a polygon. /// /// For more information read: https://en.wikipedia.org/wiki/Centroid Vector2 centroid(List<Vector2> vertices) { assert(vertices.isNotEmpty, 'Vertices must not be empty'); final sum = vertices.reduce((a, b) => a + b); return sum / vertices.length.toDouble(); }
pinball/packages/geometry/lib/src/geometry.dart/0
{ "file_path": "pinball/packages/geometry/lib/src/geometry.dart", "repo_id": "pinball", "token_count": 1509 }
1,181
# pinball_audio [![style: very good analysis][very_good_analysis_badge]][very_good_analysis_link] [![License: MIT][license_badge]][license_link] Package with the sound manager for the pinball game [license_badge]: https://img.shields.io/badge/license-MIT-blue.svg [license_link]: https://opensource.org/licenses/MIT [very_good_analysis_badge]: https://img.shields.io/badge/style-very_good_analysis-B22C89.svg [very_good_analysis_link]: https://pub.dev/packages/very_good_analysis
pinball/packages/pinball_audio/README.md/0
{ "file_path": "pinball/packages/pinball_audio/README.md", "repo_id": "pinball", "token_count": 170 }
1,182
/// GENERATED CODE - DO NOT MODIFY BY HAND /// ***************************************************** /// FlutterGen /// ***************************************************** // ignore_for_file: directives_ordering,unnecessary_import class FontFamily { FontFamily._(); /// Font family: PixeloidMono static const String pixeloidMono = 'PixeloidMono'; /// Font family: PixeloidSans static const String pixeloidSans = 'PixeloidSans'; }
pinball/packages/pinball_components/lib/gen/fonts.gen.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/gen/fonts.gen.dart", "repo_id": "pinball", "token_count": 114 }
1,183
import 'package:flame/components.dart'; import 'package:flame_bloc/flame_bloc.dart'; import 'package:flutter/material.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; import 'package:pinball_theme/pinball_theme.dart' as theme; export 'cubit/arcade_background_cubit.dart'; /// {@template arcade_background} /// Background of the arcade that the pinball machine lives in. /// {@endtemplate} class ArcadeBackground extends Component with ZIndex { /// {@macro arcade_background} ArcadeBackground({String? assetPath}) : this._( bloc: ArcadeBackgroundCubit(), assetPath: assetPath, ); ArcadeBackground._({required this.bloc, String? assetPath}) : super( children: [ FlameBlocProvider<ArcadeBackgroundCubit, ArcadeBackgroundState>.value( value: bloc, children: [ArcadeBackgroundSpriteComponent(assetPath: assetPath)], ) ], ) { zIndex = ZIndexes.arcadeBackground; } /// Creates an [ArcadeBackground] without any behaviors. /// /// This can be used for testing [ArcadeBackground]'s behaviors in isolation. @visibleForTesting ArcadeBackground.test({ ArcadeBackgroundCubit? bloc, String? assetPath, }) : bloc = bloc ?? ArcadeBackgroundCubit(), super( children: [ FlameBlocProvider<ArcadeBackgroundCubit, ArcadeBackgroundState>.value( value: bloc ?? ArcadeBackgroundCubit(), children: [ArcadeBackgroundSpriteComponent(assetPath: assetPath)], ) ], ); /// Bloc to update the arcade background sprite when a new character is /// selected. final ArcadeBackgroundCubit bloc; } /// {@template arcade_background_sprite_component} /// [SpriteComponent] for the [ArcadeBackground]. /// {@endtemplate} @visibleForTesting class ArcadeBackgroundSpriteComponent extends SpriteComponent with FlameBlocListenable<ArcadeBackgroundCubit, ArcadeBackgroundState>, HasGameRef { /// {@macro arcade_background_sprite_component} ArcadeBackgroundSpriteComponent({required String? assetPath}) : _assetPath = assetPath, super( anchor: Anchor.bottomCenter, position: Vector2(0, 72.3), ); final String? _assetPath; @override void onNewState(ArcadeBackgroundState state) { sprite = Sprite( gameRef.images.fromCache(state.characterTheme.background.keyName), ); } @override Future<void> onLoad() async { await super.onLoad(); final sprite = Sprite( gameRef.images .fromCache(_assetPath ?? theme.Assets.images.dash.background.keyName), ); this.sprite = sprite; size = sprite.originalSize / 10; } }
pinball/packages/pinball_components/lib/src/components/arcade_background/arcade_background.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/arcade_background/arcade_background.dart", "repo_id": "pinball", "token_count": 1061 }
1,184
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'; /// {@template boundaries} /// Pinball machine walls. /// {@endtemplate} class Boundaries extends Component { /// {@macro boundaries} Boundaries() : super( children: [ _BottomBoundary(), _OuterBoundary(), _OuterBottomBoundarySpriteComponent(), ], ); } /// {@template bottom_boundary} /// Curved boundary at the bottom of the board where the [Ball] exits the field /// of play. /// {@endtemplate bottom_boundary} class _BottomBoundary extends BodyComponent with InitialPosition, ZIndex { /// {@macro bottom_boundary} _BottomBoundary() : super( renderBody: false, children: [_BottomBoundarySpriteComponent()], ) { zIndex = ZIndexes.bottomBoundary; } List<FixtureDef> _createFixtureDefs() { final bottomLeftCurve = BezierCurveShape( controlPoints: [ Vector2(-43.9, 41.8), Vector2(-35.7, 43), Vector2(-19.9, 51), ], ); final bottomLeftCurveFixtureDef = FixtureDef(bottomLeftCurve); final bottomRightCurve = BezierCurveShape( controlPoints: [ Vector2(31.8, 44.8), Vector2(21.95, 47.7), Vector2(12.3, 52.1), ], ); final bottomRightCurveFixtureDef = FixtureDef(bottomRightCurve); return [bottomLeftCurveFixtureDef, bottomRightCurveFixtureDef]; } @override Body createBody() { final bodyDef = BodyDef()..position = initialPosition; final body = world.createBody(bodyDef); _createFixtureDefs().forEach(body.createFixture); return body; } } class _BottomBoundarySpriteComponent extends SpriteComponent with HasGameRef { _BottomBoundarySpriteComponent() : super( anchor: Anchor.center, position: Vector2(-5.2, 55.6), ); @override Future<void> onLoad() async { await super.onLoad(); final sprite = Sprite( gameRef.images.fromCache( Assets.images.boundary.bottom.keyName, ), ); this.sprite = sprite; size = sprite.originalSize / 10; } } /// {@template outer_boundary} /// Boundary enclosing the top and left side of the board. /// /// The right side of the board is closed by the barrier the [LaunchRamp] /// creates. /// {@endtemplate outer_boundary} class _OuterBoundary extends BodyComponent with InitialPosition, ZIndex { /// {@macro outer_boundary} _OuterBoundary() : super( renderBody: false, children: [_OuterBoundarySpriteComponent()], ) { zIndex = ZIndexes.outerBoundary; } List<FixtureDef> _createFixtureDefs() { final topWall = EdgeShape() ..set( Vector2(3.6, -70.2), Vector2(-14.1, -70.2), ); final topLeftCurve = BezierCurveShape( controlPoints: [ topWall.vertex2, Vector2(-31.5, -69.9), Vector2(-32.3, -57.2), ], ); final topLeftWall = EdgeShape() ..set( topLeftCurve.vertices.last, Vector2(-33.5, -44), ); final upperLeftWallCurve = BezierCurveShape( controlPoints: [ topLeftWall.vertex2, Vector2(-33.9, -40.7), Vector2(-32.5, -39), ], ); final middleLeftWallCurve = BezierCurveShape( controlPoints: [ upperLeftWallCurve.vertices.last, Vector2(-23.2, -31.4), Vector2(-33.9, -21.8), ], ); final lowerLeftWallCurve = BezierCurveShape( controlPoints: [ middleLeftWallCurve.vertices.last, Vector2(-32.4, -17.6), Vector2(-37.3, -11), ], ); final bottomLeftWall = EdgeShape() ..set( lowerLeftWallCurve.vertices.last, Vector2(-43.9, 41.8), ); return [ FixtureDef(topWall), FixtureDef(topLeftCurve), FixtureDef(topLeftWall), FixtureDef(upperLeftWallCurve), FixtureDef(middleLeftWallCurve), FixtureDef(lowerLeftWallCurve), FixtureDef(bottomLeftWall), ]; } @override Body createBody() { final bodyDef = BodyDef()..position = initialPosition; final body = world.createBody(bodyDef); _createFixtureDefs().forEach(body.createFixture); return body; } } class _OuterBoundarySpriteComponent extends SpriteComponent with HasGameRef { _OuterBoundarySpriteComponent() : super( anchor: Anchor.center, position: Vector2(0, -7.8), ); @override Future<void> onLoad() async { await super.onLoad(); final sprite = Sprite( gameRef.images.fromCache( Assets.images.boundary.outer.keyName, ), ); this.sprite = sprite; size = sprite.originalSize / 10; } } class _OuterBottomBoundarySpriteComponent extends SpriteComponent with HasGameRef, ZIndex { _OuterBottomBoundarySpriteComponent() : super( anchor: Anchor.center, position: Vector2(0, 71), ) { zIndex = ZIndexes.outerBottomBoundary; } @override Future<void> onLoad() async { await super.onLoad(); final sprite = Sprite( gameRef.images.fromCache( Assets.images.boundary.outerBottom.keyName, ), ); this.sprite = sprite; size = sprite.originalSize / 10; } }
pinball/packages/pinball_components/lib/src/components/boundaries.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/boundaries.dart", "repo_id": "pinball", "token_count": 2300 }
1,185
part of 'dash_bumpers_cubit.dart'; class DashBumpersState extends Equatable { const DashBumpersState({required this.bumperSpriteStates}); DashBumpersState.initial() : this( bumperSpriteStates: { for (var id in DashBumperId.values) id: DashBumperSpriteState.inactive }, ); final Map<DashBumperId, DashBumperSpriteState> bumperSpriteStates; bool get isFullyActivated => bumperSpriteStates.values .every((spriteState) => spriteState == DashBumperSpriteState.active); @override List<Object> get props => [...bumperSpriteStates.values]; }
pinball/packages/pinball_components/lib/src/components/dash_bumper/cubit/dash_bumpers_state.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/dash_bumper/cubit/dash_bumpers_state.dart", "repo_id": "pinball", "token_count": 241 }
1,186
export 'google_rollover_ball_contact_behavior.dart';
pinball/packages/pinball_components/lib/src/components/google_rollover/behaviors/behaviors.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/google_rollover/behaviors/behaviors.dart", "repo_id": "pinball", "token_count": 17 }
1,187
// ignore_for_file: avoid_renaming_method_parameters 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'; /// {@template launch_ramp} /// Ramp where the ball is launched from. /// {@endtemplate} class LaunchRamp extends Component { /// {@macro launch_ramp} LaunchRamp() : super( children: [ _LaunchRampBase(), _LaunchRampForegroundRailing(), ], ); } class _LaunchRampBase extends BodyComponent with Layered, ZIndex { _LaunchRampBase() : super( renderBody: false, children: [ _LaunchRampBackgroundRailingSpriteComponent(), _LaunchRampBaseSpriteComponent(), ], ) { zIndex = ZIndexes.launchRamp; layer = Layer.launcher; } List<FixtureDef> _createFixtureDefs() { final fixturesDef = <FixtureDef>[]; final rightStraightShape = EdgeShape() ..set( Vector2(31, -61.4), Vector2(46.1, 68.4), ); final rightStraightFixtureDef = FixtureDef(rightStraightShape); fixturesDef.add(rightStraightFixtureDef); final leftStraightShape = EdgeShape() ..set( Vector2(27.4, -61.4), Vector2(41.1, 68.4), ); final leftStraightFixtureDef = FixtureDef(leftStraightShape); fixturesDef.add(leftStraightFixtureDef); final topCurveShape = ArcShape( center: Vector2(20.1, -61.1), arcRadius: 11, angle: 1.6, rotation: 0.1, ); final topCurveFixtureDef = FixtureDef(topCurveShape); fixturesDef.add(topCurveFixtureDef); final bottomCurveShape = ArcShape( center: Vector2(18.9, -60.3), arcRadius: 8.5, angle: 1.48, rotation: 0.1, ); final bottomCurveFixtureDef = FixtureDef(bottomCurveShape); fixturesDef.add(bottomCurveFixtureDef); final topStraightShape = EdgeShape() ..set( Vector2(3.3, -70.1), Vector2(18.7, -72.1), ); final topStraightFixtureDef = FixtureDef(topStraightShape); fixturesDef.add(topStraightFixtureDef); final bottomStraightShape = EdgeShape() ..set( Vector2(3.3, -66.9), Vector2(18.7, -68.8), ); final bottomStraightFixtureDef = FixtureDef(bottomStraightShape); fixturesDef.add(bottomStraightFixtureDef); return fixturesDef; } @override Body createBody() { final body = world.createBody(BodyDef()); _createFixtureDefs().forEach(body.createFixture); return body; } } class _LaunchRampBaseSpriteComponent extends SpriteComponent with HasGameRef { @override Future<void> onLoad() async { await super.onLoad(); final sprite = Sprite( gameRef.images.fromCache( Assets.images.launchRamp.ramp.keyName, ), ); this.sprite = sprite; size = sprite.originalSize / 10; anchor = Anchor.center; position = Vector2(25.25, 0.7); } } class _LaunchRampBackgroundRailingSpriteComponent extends SpriteComponent with HasGameRef { @override Future<void> onLoad() async { await super.onLoad(); final sprite = Sprite( gameRef.images.fromCache( Assets.images.launchRamp.backgroundRailing.keyName, ), ); this.sprite = sprite; size = sprite.originalSize / 10; anchor = Anchor.center; position = Vector2(25.2, -1.3); } } class _LaunchRampForegroundRailing extends BodyComponent with ZIndex { _LaunchRampForegroundRailing() : super( children: [_LaunchRampForegroundRailingSpriteComponent()], renderBody: false, ) { zIndex = ZIndexes.launchRampForegroundRailing; } List<FixtureDef> _createFixtureDefs() { final fixturesDef = <FixtureDef>[]; final rightStraightShape = EdgeShape() ..set( Vector2(27.2, -57.9), Vector2(37.7, 42.6), ); final rightStraightFixtureDef = FixtureDef(rightStraightShape); fixturesDef.add(rightStraightFixtureDef); final curveShape = ArcShape( center: Vector2(19.7, -59.3), arcRadius: 7.5, angle: 1.8, rotation: -0.13, ); final curveFixtureDef = FixtureDef(curveShape); fixturesDef.add(curveFixtureDef); final topStraightShape = EdgeShape() ..set( Vector2(3.3, -66.8), Vector2(19.3, -66.8), ); final topStraightFixtureDef = FixtureDef(topStraightShape); fixturesDef.add(topStraightFixtureDef); return fixturesDef; } @override Body createBody() { final body = world.createBody(BodyDef()); _createFixtureDefs().forEach(body.createFixture); return body; } } class _LaunchRampForegroundRailingSpriteComponent extends SpriteComponent with HasGameRef { @override Future<void> onLoad() async { await super.onLoad(); final sprite = Sprite( gameRef.images.fromCache( Assets.images.launchRamp.foregroundRailing.keyName, ), ); this.sprite = sprite; size = sprite.originalSize / 10; anchor = Anchor.center; position = Vector2(22.4, 0.5); } }
pinball/packages/pinball_components/lib/src/components/launch_ramp.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/launch_ramp.dart", "repo_id": "pinball", "token_count": 2151 }
1,188
import 'package:flame/components.dart'; import 'package:flame_bloc/flame_bloc.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:pinball_components/pinball_components.dart'; class PlungerPullingBehavior extends Component with FlameBlocReader<PlungerCubit, PlungerState> { PlungerPullingBehavior({ required double strength, }) : assert(strength >= 0, "Strength can't be negative."), _strength = strength; final double _strength; late final Plunger _plunger; @override Future<void> onLoad() async { await super.onLoad(); _plunger = parent!.parent! as Plunger; } @override void update(double dt) { if (bloc.state.isPulling) { _plunger.body.linearVelocity = Vector2(0, _strength); } } } class PlungerAutoPullingBehavior extends Component with FlameBlocReader<PlungerCubit, PlungerState> { late final Plunger _plunger; @override Future<void> onLoad() async { await super.onLoad(); _plunger = parent!.parent! as Plunger; } @override void update(double dt) { if (!bloc.state.isAutoPulling) return; final joint = _plunger.body.joints.whereType<PrismaticJoint>().single; final reachedBottom = joint.getJointTranslation() <= joint.getLowerLimit(); if (reachedBottom) { bloc.released(); } } }
pinball/packages/pinball_components/lib/src/components/plunger/behaviors/plunger_pulling_behavior.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/plunger/behaviors/plunger_pulling_behavior.dart", "repo_id": "pinball", "token_count": 497 }
1,189
part of 'skill_shot_cubit.dart'; enum SkillShotSpriteState { lit, dimmed, } class SkillShotState extends Equatable { const SkillShotState({ required this.spriteState, required this.isBlinking, }); const SkillShotState.initial() : this( spriteState: SkillShotSpriteState.dimmed, isBlinking: false, ); final SkillShotSpriteState spriteState; final bool isBlinking; SkillShotState copyWith({ SkillShotSpriteState? spriteState, bool? isBlinking, }) => SkillShotState( spriteState: spriteState ?? this.spriteState, isBlinking: isBlinking ?? this.isBlinking, ); @override List<Object?> get props => [spriteState, isBlinking]; }
pinball/packages/pinball_components/lib/src/components/skill_shot/cubit/skill_shot_state.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/skill_shot/cubit/skill_shot_state.dart", "repo_id": "pinball", "token_count": 281 }
1,190
export 'sparky_computer_sensor_ball_contact_behavior.dart';
pinball/packages/pinball_components/lib/src/components/sparky_computer/behaviors/behaviors.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/sparky_computer/behaviors/behaviors.dart", "repo_id": "pinball", "token_count": 21 }
1,191
import 'package:dashbook/dashbook.dart'; import 'package:flame/game.dart'; import 'package:sandbox/common/common.dart'; const _path = 'https://github.com/flutter/pinball/tree/main/packages/pinball_components/sandbox/lib/stories/'; extension StoryAddGame on Story { void addGame({ required String title, required String description, required Game Function(DashbookContext) gameBuilder, }) { final _chapter = Chapter( title, (DashbookContext context) { final game = gameBuilder(context); if (game is Traceable) { game.trace = context.boolProperty('Trace', true); } return GameWidget(game: game); }, this, codeLink: '$_path${name.toPath()}/${title.toPath()}', info: description, ); chapters.add(_chapter); } } extension on String { String toPath() { return replaceAll(' ', '_')..toLowerCase(); } }
pinball/packages/pinball_components/sandbox/lib/common/add_game.dart/0
{ "file_path": "pinball/packages/pinball_components/sandbox/lib/common/add_game.dart", "repo_id": "pinball", "token_count": 357 }
1,192
import 'package:dashbook/dashbook.dart'; import 'package:sandbox/common/common.dart'; import 'package:sandbox/stories/ball/ball_booster_game.dart'; import 'package:sandbox/stories/ball/basic_ball_game.dart'; void addBallStories(Dashbook dashbook) { dashbook.storiesOf('Ball') ..addGame( title: 'Themed', description: BallGame.description, gameBuilder: (context) => BallGame( character: context.listProperty( 'Character', BallGame.characterBallPaths.keys.first, BallGame.characterBallPaths.keys.toList(), ), ), ) ..addGame( title: 'Booster', description: BallBoosterGame.description, gameBuilder: (context) => BallBoosterGame(), ); }
pinball/packages/pinball_components/sandbox/lib/stories/ball/stories.dart/0
{ "file_path": "pinball/packages/pinball_components/sandbox/lib/stories/ball/stories.dart", "repo_id": "pinball", "token_count": 299 }
1,193
import 'dart:async'; import 'package:flame_bloc/flame_bloc.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:sandbox/stories/ball/basic_ball_game.dart'; class DashBumperAGame extends BallGame { DashBumperAGame() : super( imagesFileNames: [ Assets.images.dash.bumper.a.active.keyName, Assets.images.dash.bumper.a.inactive.keyName, ], ); static const description = ''' Shows how the "a" DashBumper is rendered. - Activate the "trace" parameter to overlay the body. '''; @override Future<void> onLoad() async { await super.onLoad(); camera.followVector2(Vector2.zero()); await add( FlameBlocProvider<DashBumpersCubit, DashBumpersState>( create: DashBumpersCubit.new, children: [ DashBumper.a()..priority = 1, ], ), ); await traceAllBodies(); } }
pinball/packages/pinball_components/sandbox/lib/stories/flutter_forest/dash_bumper_a_game.dart/0
{ "file_path": "pinball/packages/pinball_components/sandbox/lib/stories/flutter_forest/dash_bumper_a_game.dart", "repo_id": "pinball", "token_count": 412 }
1,194
import 'package:dashbook/dashbook.dart'; import 'package:sandbox/common/common.dart'; import 'package:sandbox/stories/plunger/plunger_game.dart'; void addPlungerStories(Dashbook dashbook) { dashbook.storiesOf('Plunger').addGame( title: 'Traced', description: PlungerGame.description, gameBuilder: (_) => PlungerGame(), ); }
pinball/packages/pinball_components/sandbox/lib/stories/plunger/stories.dart/0
{ "file_path": "pinball/packages/pinball_components/sandbox/lib/stories/plunger/stories.dart", "repo_id": "pinball", "token_count": 142 }
1,195
export 'test_game.dart';
pinball/packages/pinball_components/test/helpers/helpers.dart/0
{ "file_path": "pinball/packages/pinball_components/test/helpers/helpers.dart", "repo_id": "pinball", "token_count": 10 }
1,196
// ignore_for_file: cascade_invocations import 'package:flame/components.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_theme/pinball_theme.dart' as theme; import '../../../../helpers/helpers.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); group( 'BallImpulsingBehavior', () { final asset = theme.Assets.images.dash.ball.keyName; final flameTester = FlameTester(() => TestGame([asset])); test('can be instantiated', () { expect( BallImpulsingBehavior(impulse: Vector2.zero()), isA<BallImpulsingBehavior>(), ); }); flameTester.test( 'impulses the ball with the given velocity when loaded ' 'and then removes itself', (game) async { final ball = Ball.test(); await game.ensureAdd(ball); final impulse = Vector2.all(1); final behavior = BallImpulsingBehavior(impulse: impulse); await ball.ensureAdd(behavior); expect( ball.body.linearVelocity.x, equals(impulse.x), ); expect( ball.body.linearVelocity.y, equals(impulse.y), ); expect( game.descendants().whereType<BallImpulsingBehavior>().isEmpty, isTrue, ); }, ); }, ); }
pinball/packages/pinball_components/test/src/components/ball/behaviors/ball_implusing_behavior_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/ball/behaviors/ball_implusing_behavior_test.dart", "repo_id": "pinball", "token_count": 679 }
1,197
// ignore_for_file: cascade_invocations import 'package:bloc_test/bloc_test.dart'; 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 'package:pinball_components/src/components/chrome_dino/behaviors/behaviors.dart'; import '../../../helpers/helpers.dart'; class _MockChromeDinoCubit extends Mock implements ChromeDinoCubit {} void main() { TestWidgetsFlutterBinding.ensureInitialized(); final assets = [ Assets.images.dino.animatronic.mouth.keyName, Assets.images.dino.animatronic.head.keyName, ]; final flameTester = FlameTester(() => TestGame(assets)); group('ChromeDino', () { flameTester.test( 'loads correctly', (game) async { final chromeDino = ChromeDino(); await game.ensureAdd(chromeDino); expect(game.contains(chromeDino), isTrue); }, ); flameTester.testGameWidget( 'renders correctly', setUp: (game, tester) async { await game.images.loadAll(assets); await game.ensureAdd(ChromeDino()); game.camera.followVector2(Vector2.zero()); await tester.pump(); }, verify: (game, tester) async { final swivelAnimationDuration = game .descendants() .whereType<SpriteAnimationComponent>() .first .animation! .totalDuration() / 2; game.update(swivelAnimationDuration); await tester.pump(); await expectLater( find.byGame<TestGame>(), matchesGoldenFile('golden/chrome_dino/down.png'), ); game.update(swivelAnimationDuration * 0.25); await tester.pump(); await expectLater( find.byGame<TestGame>(), matchesGoldenFile('golden/chrome_dino/middle.png'), ); game.update(swivelAnimationDuration * 0.25); await tester.pump(); await expectLater( find.byGame<TestGame>(), matchesGoldenFile('golden/chrome_dino/up.png'), ); }, ); flameTester.test('closes bloc when removed', (game) async { final bloc = _MockChromeDinoCubit(); whenListen( bloc, const Stream<ChromeDinoState>.empty(), initialState: const ChromeDinoState.initial(), ); when(bloc.close).thenAnswer((_) async {}); final chromeDino = ChromeDino.test(bloc: bloc); await game.ensureAdd(chromeDino); game.remove(chromeDino); await game.ready(); verify(bloc.close).called(1); }); group('adds', () { flameTester.test('a ChromeDinoMouthOpeningBehavior', (game) async { final chromeDino = ChromeDino(); await game.ensureAdd(chromeDino); expect( chromeDino.children .whereType<ChromeDinoMouthOpeningBehavior>() .single, isNotNull, ); }); flameTester.test('a ChromeDinoSwivelingBehavior', (game) async { final chromeDino = ChromeDino(); await game.ensureAdd(chromeDino); expect( chromeDino.children.whereType<ChromeDinoSwivelingBehavior>().single, isNotNull, ); }); flameTester.test('a ChromeDinoChompingBehavior', (game) async { final chromeDino = ChromeDino(); await game.ensureAdd(chromeDino); expect( chromeDino.children.whereType<ChromeDinoChompingBehavior>().single, isNotNull, ); }); flameTester.test('a ChromeDinoSpittingBehavior', (game) async { final chromeDino = ChromeDino(); await game.ensureAdd(chromeDino); expect( chromeDino.children.whereType<ChromeDinoSpittingBehavior>().single, isNotNull, ); }); flameTester.test('new children', (game) async { final component = Component(); final chromeDino = ChromeDino( children: [component], ); await game.ensureAdd(chromeDino); expect(chromeDino.children, contains(component)); }); }); }); }
pinball/packages/pinball_components/test/src/components/chrome_dino/chrome_dino_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/chrome_dino/chrome_dino_test.dart", "repo_id": "pinball", "token_count": 1891 }
1,198
// ignore_for_file: cascade_invocations import 'package:bloc_test/bloc_test.dart'; import 'package:flame_bloc/flame_bloc.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter/foundation.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_components/pinball_components.dart'; class _TestGame extends Forge2DGame { Future<void> pump( FlipperKeyControllingBehavior behavior, { required BoardSide side, FlipperCubit? flipperBloc, }) async { final flipper = Flipper.test(side: side); await ensureAdd(flipper); await flipper.ensureAdd( FlameBlocProvider<FlipperCubit, FlipperState>.value( value: flipperBloc ?? FlipperCubit(), children: [behavior], ), ); } } class _MockFlipperCubit extends Mock implements FlipperCubit {} 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(); } } void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('FlipperKeyControllingBehavior', () { final flameTester = FlameTester(_TestGame.new); group( 'onKeyEvent', () { late FlipperCubit flipperBloc; setUp(() { flipperBloc = _MockFlipperCubit(); whenListen<FlipperState>( flipperBloc, const Stream.empty(), initialState: FlipperState.movingDown, ); }); group('on right Flipper', () { flameTester.test( 'moves upwards when right arrow is pressed', (game) async { final behavior = FlipperKeyControllingBehavior(); await game.pump( behavior, flipperBloc: flipperBloc, side: BoardSide.right, ); final event = _MockRawKeyDownEvent(); when(() => event.logicalKey).thenReturn( LogicalKeyboardKey.arrowRight, ); behavior.onKeyEvent(event, {}); await Future<void>.delayed(Duration.zero); verify(flipperBloc.moveUp).called(1); }, ); flameTester.test( 'moves downwards when right arrow is released', (game) async { final behavior = FlipperKeyControllingBehavior(); await game.pump( behavior, side: BoardSide.right, flipperBloc: flipperBloc, ); final event = _MockRawKeyUpEvent(); when(() => event.logicalKey).thenReturn( LogicalKeyboardKey.arrowRight, ); behavior.onKeyEvent(event, {}); await Future<void>.delayed(Duration.zero); verify(flipperBloc.moveDown).called(1); }, ); flameTester.test( 'moves upwards when D is pressed', (game) async { final behavior = FlipperKeyControllingBehavior(); await game.pump( behavior, side: BoardSide.right, flipperBloc: flipperBloc, ); final event = _MockRawKeyDownEvent(); when(() => event.logicalKey).thenReturn( LogicalKeyboardKey.keyD, ); behavior.onKeyEvent(event, {}); await Future<void>.delayed(Duration.zero); verify(flipperBloc.moveUp).called(1); }, ); flameTester.test( 'moves downwards when D is released', (game) async { final behavior = FlipperKeyControllingBehavior(); await game.pump( behavior, side: BoardSide.right, flipperBloc: flipperBloc, ); final event = _MockRawKeyUpEvent(); when(() => event.logicalKey).thenReturn( LogicalKeyboardKey.keyD, ); behavior.onKeyEvent(event, {}); await Future<void>.delayed(Duration.zero); verify(flipperBloc.moveDown).called(1); }, ); group("doesn't move when", () { flameTester.test( 'left arrow is pressed', (game) async { final behavior = FlipperKeyControllingBehavior(); await game.pump( behavior, side: BoardSide.right, flipperBloc: flipperBloc, ); final event = _MockRawKeyDownEvent(); when(() => event.logicalKey).thenReturn( LogicalKeyboardKey.arrowLeft, ); behavior.onKeyEvent(event, {}); verifyNever(flipperBloc.moveDown); verifyNever(flipperBloc.moveUp); }, ); flameTester.test( 'left arrow is released', (game) async { final behavior = FlipperKeyControllingBehavior(); await game.pump( behavior, side: BoardSide.right, flipperBloc: flipperBloc, ); final event = _MockRawKeyUpEvent(); when(() => event.logicalKey).thenReturn( LogicalKeyboardKey.arrowLeft, ); behavior.onKeyEvent(event, {}); verifyNever(flipperBloc.moveDown); verifyNever(flipperBloc.moveUp); }, ); flameTester.test( 'A is pressed', (game) async { final behavior = FlipperKeyControllingBehavior(); await game.pump( behavior, side: BoardSide.right, flipperBloc: flipperBloc, ); final event = _MockRawKeyDownEvent(); when(() => event.logicalKey).thenReturn( LogicalKeyboardKey.keyA, ); behavior.onKeyEvent(event, {}); verifyNever(flipperBloc.moveDown); verifyNever(flipperBloc.moveUp); }, ); flameTester.test( 'A is released', (game) async { final behavior = FlipperKeyControllingBehavior(); await game.pump( behavior, side: BoardSide.right, flipperBloc: flipperBloc, ); final event = _MockRawKeyUpEvent(); when(() => event.logicalKey).thenReturn( LogicalKeyboardKey.keyA, ); behavior.onKeyEvent(event, {}); verifyNever(flipperBloc.moveDown); verifyNever(flipperBloc.moveUp); }, ); }); }); group('on left Flipper', () { flameTester.test( 'moves upwards when left arrow is pressed', (game) async { final behavior = FlipperKeyControllingBehavior(); await game.pump( behavior, side: BoardSide.left, flipperBloc: flipperBloc, ); final event = _MockRawKeyDownEvent(); when(() => event.logicalKey).thenReturn( LogicalKeyboardKey.arrowLeft, ); behavior.onKeyEvent(event, {}); await Future<void>.delayed(Duration.zero); verify(flipperBloc.moveUp).called(1); }, ); flameTester.test( 'moves downwards when left arrow is released', (game) async { final behavior = FlipperKeyControllingBehavior(); await game.pump( behavior, side: BoardSide.left, flipperBloc: flipperBloc, ); final event = _MockRawKeyUpEvent(); when(() => event.logicalKey).thenReturn( LogicalKeyboardKey.arrowLeft, ); behavior.onKeyEvent(event, {}); await Future<void>.delayed(Duration.zero); verify(flipperBloc.moveDown).called(1); }, ); flameTester.test( 'moves upwards when A is pressed', (game) async { final behavior = FlipperKeyControllingBehavior(); await game.pump( behavior, side: BoardSide.left, flipperBloc: flipperBloc, ); final event = _MockRawKeyDownEvent(); when(() => event.logicalKey).thenReturn( LogicalKeyboardKey.keyA, ); behavior.onKeyEvent(event, {}); await Future<void>.delayed(Duration.zero); verify(flipperBloc.moveUp).called(1); }, ); flameTester.test( 'moves downwards when A is released', (game) async { final behavior = FlipperKeyControllingBehavior(); await game.pump( behavior, side: BoardSide.left, flipperBloc: flipperBloc, ); final event = _MockRawKeyUpEvent(); when(() => event.logicalKey).thenReturn( LogicalKeyboardKey.keyA, ); behavior.onKeyEvent(event, {}); await Future<void>.delayed(Duration.zero); verify(flipperBloc.moveDown).called(1); }, ); group("doesn't move when", () { flameTester.test( 'right arrow is pressed', (game) async { final behavior = FlipperKeyControllingBehavior(); await game.pump( behavior, side: BoardSide.left, flipperBloc: flipperBloc, ); final event = _MockRawKeyDownEvent(); when(() => event.logicalKey).thenReturn( LogicalKeyboardKey.arrowRight, ); behavior.onKeyEvent(event, {}); verifyNever(flipperBloc.moveDown); verifyNever(flipperBloc.moveUp); }, ); flameTester.test( 'right arrow is released', (game) async { final behavior = FlipperKeyControllingBehavior(); await game.pump( behavior, side: BoardSide.left, flipperBloc: flipperBloc, ); final event = _MockRawKeyUpEvent(); when(() => event.logicalKey).thenReturn( LogicalKeyboardKey.arrowRight, ); behavior.onKeyEvent(event, {}); verifyNever(flipperBloc.moveDown); verifyNever(flipperBloc.moveUp); }, ); flameTester.test( 'D is pressed', (game) async { final behavior = FlipperKeyControllingBehavior(); await game.pump( behavior, side: BoardSide.left, flipperBloc: flipperBloc, ); final event = _MockRawKeyDownEvent(); when(() => event.logicalKey).thenReturn( LogicalKeyboardKey.keyD, ); behavior.onKeyEvent(event, {}); verifyNever(flipperBloc.moveDown); verifyNever(flipperBloc.moveUp); }, ); flameTester.test( 'D is released', (game) async { final behavior = FlipperKeyControllingBehavior(); await game.pump( behavior, side: BoardSide.left, flipperBloc: flipperBloc, ); final event = _MockRawKeyUpEvent(); when(() => event.logicalKey).thenReturn( LogicalKeyboardKey.keyD, ); behavior.onKeyEvent(event, {}); verifyNever(flipperBloc.moveDown); verifyNever(flipperBloc.moveUp); }, ); }); }); }, ); }); }
pinball/packages/pinball_components/test/src/components/flipper/behaviors/flipper_key_controlling_behavior_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/flipper/behaviors/flipper_key_controlling_behavior_test.dart", "repo_id": "pinball", "token_count": 7077 }
1,199
import 'package:bloc_test/bloc_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pinball_components/pinball_components.dart'; void main() { group( 'KickerCubit', () { blocTest<KickerCubit, KickerState>( 'onBallContacted emits dimmed', build: KickerCubit.new, act: (bloc) => bloc.onBallContacted(), expect: () => [KickerState.dimmed], ); blocTest<KickerCubit, KickerState>( 'onBlinked emits lit', build: KickerCubit.new, act: (bloc) => bloc.onBlinked(), expect: () => [KickerState.lit], ); }, ); }
pinball/packages/pinball_components/test/src/components/kicker/cubit/kicker_cubit_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/kicker/cubit/kicker_cubit_test.dart", "repo_id": "pinball", "token_count": 292 }
1,200
// ignore_for_file: cascade_invocations import 'dart:async'; import 'package:bloc_test/bloc_test.dart'; import 'package:flame_bloc/flame_bloc.dart'; import 'package:flame_forge2d/forge2d_game.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:pinball_components/pinball_components.dart'; class _TestGame extends Forge2DGame { Future<void> pump( PlungerReleasingBehavior behavior, { PlungerCubit? plungerBloc, }) async { final plunger = Plunger.test(); await ensureAdd(plunger); return plunger.ensureAdd( FlameBlocProvider<PlungerCubit, PlungerState>.value( value: plungerBloc ?? PlungerCubit(), children: [behavior], ), ); } } class _MockPlungerCubit extends Mock implements PlungerCubit {} void main() { group('PlungerReleasingBehavior', () { TestWidgetsFlutterBinding.ensureInitialized(); final flameTester = FlameTester(_TestGame.new); test('can be instantiated', () { expect( PlungerReleasingBehavior(strength: 0), isA<PlungerReleasingBehavior>(), ); }); test('throws assertion error when strength is negative ', () { expect( () => PlungerReleasingBehavior(strength: -1), throwsAssertionError, ); }); flameTester.test('can be loaded', (game) async { final behavior = PlungerReleasingBehavior(strength: 0); await game.pump(behavior); expect(game.descendants(), contains(behavior)); }); flameTester.test('applies vertical linear velocity', (game) async { final plungerBloc = _MockPlungerCubit(); final streamController = StreamController<PlungerState>(); whenListen<PlungerState>( plungerBloc, streamController.stream, initialState: PlungerState.pulling, ); final behavior = PlungerReleasingBehavior(strength: 2); await game.pump( behavior, plungerBloc: plungerBloc, ); streamController.add(PlungerState.releasing); await Future<void>.delayed(Duration.zero); final plunger = behavior.ancestors().whereType<Plunger>().single; expect(plunger.body.linearVelocity.x, equals(0)); expect(plunger.body.linearVelocity.y, isNot(greaterThan(0))); }); }); }
pinball/packages/pinball_components/test/src/components/plunger/behaviors/plunger_releasing_behavior_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/plunger/behaviors/plunger_releasing_behavior_test.dart", "repo_id": "pinball", "token_count": 937 }
1,201
// ignore_for_file: prefer_const_constructors import 'package:bloc_test/bloc_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pinball_components/pinball_components.dart'; void main() { group('SpaceshipRampCubit', () { group('onAscendingBallEntered', () { blocTest<SpaceshipRampCubit, SpaceshipRampState>( 'emits hits incremented and arrow goes to the next value', build: SpaceshipRampCubit.new, act: (bloc) => bloc ..onAscendingBallEntered() ..onAscendingBallEntered() ..onAscendingBallEntered(), expect: () => [ isA<SpaceshipRampState>().having((state) => state.hits, 'hits', 1), isA<SpaceshipRampState>().having((state) => state.hits, 'hits', 2), isA<SpaceshipRampState>().having((state) => state.hits, 'hits', 3), ], ); }); group('onProgressed', () { blocTest<SpaceshipRampCubit, SpaceshipRampState>( 'emits next arrow lightState', build: SpaceshipRampCubit.new, act: (bloc) => bloc ..onProgressed() ..onProgressed() ..onProgressed() ..onProgressed() ..onProgressed() ..onProgressed(), expect: () => [ isA<SpaceshipRampState>().having( (state) => state.lightState, 'lightState', ArrowLightState.active1, ), isA<SpaceshipRampState>().having( (state) => state.lightState, 'lightState', ArrowLightState.active2, ), isA<SpaceshipRampState>().having( (state) => state.lightState, 'lightState', ArrowLightState.active3, ), isA<SpaceshipRampState>().having( (state) => state.lightState, 'lightState', ArrowLightState.active4, ), isA<SpaceshipRampState>().having( (state) => state.lightState, 'lightState', ArrowLightState.active5, ), isA<SpaceshipRampState>().having( (state) => state.lightState, 'lightState', ArrowLightState.inactive, ), ], ); }); group('onReset', () { blocTest<SpaceshipRampCubit, SpaceshipRampState>( 'emits initial state', build: SpaceshipRampCubit.new, seed: () => SpaceshipRampState( hits: 100, lightState: ArrowLightState.active3, ), act: (bloc) => bloc.onReset(), expect: () => [ SpaceshipRampState.initial(), ], ); }); }); }
pinball/packages/pinball_components/test/src/components/spaceship_ramp/cubit/spaceship_ramp_cubit_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/spaceship_ramp/cubit/spaceship_ramp_cubit_test.dart", "repo_id": "pinball", "token_count": 1353 }
1,202
export 'contact_behavior.dart'; export 'layer_contact_behavior.dart'; export 'z_index_contact_behavior.dart';
pinball/packages/pinball_flame/lib/src/behaviors/behaviors.dart/0
{ "file_path": "pinball/packages/pinball_flame/lib/src/behaviors/behaviors.dart", "repo_id": "pinball", "token_count": 36 }
1,203
export 'arc_shape.dart'; export 'bezier_curve_shape.dart'; export 'ellipse_shape.dart';
pinball/packages/pinball_flame/lib/src/shapes/shapes.dart/0
{ "file_path": "pinball/packages/pinball_flame/lib/src/shapes/shapes.dart", "repo_id": "pinball", "token_count": 37 }
1,204
export 'assets.gen.dart';
pinball/packages/pinball_theme/lib/src/generated/generated.dart/0
{ "file_path": "pinball/packages/pinball_theme/lib/src/generated/generated.dart", "repo_id": "pinball", "token_count": 10 }
1,205
import 'package:flutter/material.dart'; /// Colors used in the application abstract class PinballColors { /// Color: 0xFFFFFFFF static const Color white = Color(0xFFFFFFFF); /// Color: 0xFF000000 static const Color black = Color(0xFF000000); /// Color: 0xFF0C32A4 static const Color darkBlue = Color(0xFF0C32A4); /// Color: 0xFFFFEE02 static const Color yellow = Color(0xFFFFEE02); /// Color: 0xFFE5AB05 static const Color orange = Color(0xFFE5AB05); /// Color: 0xFFF03939 static const Color red = Color(0xFFF03939); /// Color: 0xFF4B94F6 static const Color blue = Color(0xFF4B94F6); /// Color: 0x00000000 static const Color transparent = Color(0x00000000); /// Color: 0xFFE33B2D static const Color loadingDarkRed = Color(0xFFE33B2D); /// Color: 0xFFEC5E2B static const Color loadingLightRed = Color(0xFFEC5E2B); /// Color: 0xFF4087F8 static const Color loadingDarkBlue = Color(0xFF4087F8); /// Color: 0xFF6CCAE4 static const Color loadingLightBlue = Color(0xFF6CCAE4); /// Color: 0xFF274E54 static const Color crtBackground = Color(0xFF274E54); }
pinball/packages/pinball_ui/lib/src/theme/pinball_colors.dart/0
{ "file_path": "pinball/packages/pinball_ui/lib/src/theme/pinball_colors.dart", "repo_id": "pinball", "token_count": 401 }
1,206
import 'package:flutter_test/flutter_test.dart'; import 'package:pinball_ui/pinball_ui.dart'; void main() { group('PinballTheme', () { group('standard', () { test('headline1 matches PinballTextStyle#headline1', () { expect( PinballTheme.standard.textTheme.headline1!.fontSize, PinballTextStyle.headline1.fontSize, ); expect( PinballTheme.standard.textTheme.headline1!.color, PinballTextStyle.headline1.color, ); expect( PinballTheme.standard.textTheme.headline1!.fontFamily, PinballTextStyle.headline1.fontFamily, ); }); test('headline2 matches PinballTextStyle#headline2', () { expect( PinballTheme.standard.textTheme.headline2!.fontSize, PinballTextStyle.headline2.fontSize, ); expect( PinballTheme.standard.textTheme.headline2!.fontFamily, PinballTextStyle.headline2.fontFamily, ); expect( PinballTheme.standard.textTheme.headline2!.fontWeight, PinballTextStyle.headline2.fontWeight, ); }); test('headline3 matches PinballTextStyle#headline3', () { expect( PinballTheme.standard.textTheme.headline3!.fontSize, PinballTextStyle.headline3.fontSize, ); expect( PinballTheme.standard.textTheme.headline3!.color, PinballTextStyle.headline3.color, ); expect( PinballTheme.standard.textTheme.headline3!.fontFamily, PinballTextStyle.headline3.fontFamily, ); }); test('headline4 matches PinballTextStyle#headline4', () { expect( PinballTheme.standard.textTheme.headline4!.fontSize, PinballTextStyle.headline4.fontSize, ); expect( PinballTheme.standard.textTheme.headline4!.color, PinballTextStyle.headline4.color, ); expect( PinballTheme.standard.textTheme.headline4!.fontFamily, PinballTextStyle.headline4.fontFamily, ); }); test('subtitle1 matches PinballTextStyle#subtitle1', () { expect( PinballTheme.standard.textTheme.subtitle1!.fontSize, PinballTextStyle.subtitle1.fontSize, ); expect( PinballTheme.standard.textTheme.subtitle1!.color, PinballTextStyle.subtitle1.color, ); expect( PinballTheme.standard.textTheme.subtitle1!.fontFamily, PinballTextStyle.subtitle1.fontFamily, ); }); }); }); }
pinball/packages/pinball_ui/test/src/theme/pinball_theme_test.dart/0
{ "file_path": "pinball/packages/pinball_ui/test/src/theme/pinball_theme_test.dart", "repo_id": "pinball", "token_count": 1184 }
1,207
library share_repository; export 'src/models/models.dart'; export 'src/share_repository.dart';
pinball/packages/share_repository/lib/share_repository.dart/0
{ "file_path": "pinball/packages/share_repository/lib/share_repository.dart", "repo_id": "pinball", "token_count": 35 }
1,208
// 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/game/behaviors/behaviors.dart'; import 'package:pinball_audio/pinball_audio.dart'; import 'package:pinball_flame/pinball_flame.dart'; class _TestGame extends Forge2DGame { Future<void> pump( _TestBodyComponent child, { required PinballAudioPlayer audioPlayer, }) { return ensureAdd( FlameProvider<PinballAudioPlayer>.value( audioPlayer, children: [child], ), ); } } class _TestBodyComponent extends BodyComponent { @override Body createBody() => world.createBody(BodyDef()); } class _MockPinballAudioPlayer extends Mock implements PinballAudioPlayer {} class _MockContact extends Mock implements Contact {} void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('BumperNoiseBehavior', () { late PinballAudioPlayer audioPlayer; final flameTester = FlameTester(_TestGame.new); setUp(() { audioPlayer = _MockPinballAudioPlayer(); }); flameTester.testGameWidget( 'plays bumper sound', setUp: (game, _) async { final behavior = BumperNoiseBehavior(); final parent = _TestBodyComponent(); await game.pump(parent, audioPlayer: audioPlayer); await parent.ensureAdd(behavior); behavior.beginContact(Object(), _MockContact()); }, verify: (_, __) async { verify(() => audioPlayer.play(PinballAudio.bumper)).called(1); }, ); }); }
pinball/test/game/behaviors/bumper_noise_behavior_test.dart/0
{ "file_path": "pinball/test/game/behaviors/bumper_noise_behavior_test.dart", "repo_id": "pinball", "token_count": 605 }
1,209
// ignore_for_file: cascade_invocations, prefer_const_constructors import 'dart:async'; import 'package:bloc_test/bloc_test.dart'; import 'package:flame/components.dart'; import 'package:flame_bloc/flame_bloc.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:pinball/game/behaviors/behaviors.dart'; import 'package:pinball/game/components/android_acres/behaviors/behaviors.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; class _TestGame extends Forge2DGame { @override Future<void> onLoad() async { images.prefix = ''; await images.loadAll([ Assets.images.android.ramp.boardOpening.keyName, Assets.images.android.ramp.railingForeground.keyName, Assets.images.android.ramp.railingBackground.keyName, Assets.images.android.ramp.main.keyName, Assets.images.android.ramp.arrow.inactive.keyName, Assets.images.android.ramp.arrow.active1.keyName, Assets.images.android.ramp.arrow.active2.keyName, Assets.images.android.ramp.arrow.active3.keyName, Assets.images.android.ramp.arrow.active4.keyName, Assets.images.android.ramp.arrow.active5.keyName, Assets.images.android.rail.main.keyName, Assets.images.android.rail.exit.keyName, Assets.images.score.fiveThousand.keyName, ]); } Future<void> pump( List<Component> children, { required SpaceshipRampCubit bloc, required GameBloc gameBloc, }) async { await ensureAdd( FlameMultiBlocProvider( providers: [ FlameBlocProvider<GameBloc, GameState>.value( value: gameBloc, ), FlameBlocProvider<SpaceshipRampCubit, SpaceshipRampState>.value( value: bloc, ), ], children: [ ZCanvasComponent(children: children), ], ), ); } } class _MockGameBloc extends Mock implements GameBloc {} class _MockSpaceshipRampCubit extends Mock implements SpaceshipRampCubit {} void main() { TestWidgetsFlutterBinding.ensureInitialized(); late GameBloc gameBloc; setUp(() { gameBloc = _MockGameBloc(); }); group('RampShotBehavior', () { const shotPoints = Points.fiveThousand; final flameTester = FlameTester(_TestGame.new); flameTester.test( 'adds a ScoringBehavior when hit', (game) async { final bloc = _MockSpaceshipRampCubit(); final state = SpaceshipRampState.initial(); final streamController = StreamController<SpaceshipRampState>(); whenListen( bloc, streamController.stream, initialState: state, ); final behavior = RampShotBehavior(points: shotPoints); final parent = SpaceshipRamp.test(children: [behavior]); await game.pump( [parent], bloc: bloc, gameBloc: gameBloc, ); streamController.add(state.copyWith(hits: state.hits + 1)); final scores = game.descendants().whereType<ScoringBehavior>(); await game.ready(); expect(scores.length, 1); }, ); }); }
pinball/test/game/components/android_acres/behaviors/ramp_shot_behavior_test.dart/0
{ "file_path": "pinball/test/game/components/android_acres/behaviors/ramp_shot_behavior_test.dart", "repo_id": "pinball", "token_count": 1361 }
1,210
// ignore_for_file: cascade_invocations import 'package:flame_bloc/flame_bloc.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:pinball/game/components/drain/behaviors/behaviors.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_theme/pinball_theme.dart' as theme; class _TestGame extends Forge2DGame { @override Future<void> onLoad() async { images.prefix = ''; await images.load(theme.Assets.images.dash.ball.keyName); } Future<void> pump( Drain child, { required GameBloc gameBloc, }) async { await ensureAdd( FlameBlocProvider<GameBloc, GameState>.value( value: gameBloc, children: [child], ), ); } } class _MockGameBloc extends Mock implements GameBloc {} class _MockContact extends Mock implements Contact {} void main() { TestWidgetsFlutterBinding.ensureInitialized(); group( 'DrainingBehavior', () { final flameTester = FlameTester(Forge2DGame.new); test('can be instantiated', () { expect(DrainingBehavior(), isA<DrainingBehavior>()); }); flameTester.test( 'loads', (game) async { final parent = Drain.test(); final behavior = DrainingBehavior(); await parent.add(behavior); await game.ensureAdd(parent); expect(parent.contains(behavior), isTrue); }, ); group('beginContact', () { late GameBloc gameBloc; setUp(() { gameBloc = _MockGameBloc(); }); final flameBlocTester = FlameTester(_TestGame.new); flameBlocTester.test( 'adds RoundLost when no balls left', (game) async { final drain = Drain.test(); final behavior = DrainingBehavior(); final ball = Ball.test(); await drain.add(behavior); await game.pump( drain, gameBloc: gameBloc, ); await game.ensureAdd(ball); behavior.beginContact(ball, _MockContact()); await game.ready(); expect(game.descendants().whereType<Ball>(), isEmpty); verify(() => gameBloc.add(const RoundLost())).called(1); }, ); flameBlocTester.test( "doesn't add RoundLost when there are balls left", (game) async { final drain = Drain.test(); final behavior = DrainingBehavior(); final ball1 = Ball.test(); final ball2 = Ball.test(); await drain.add(behavior); await game.pump( drain, gameBloc: gameBloc, ); await game.ensureAddAll([ball1, ball2]); behavior.beginContact(ball1, _MockContact()); await game.ready(); expect(game.descendants().whereType<Ball>(), isNotEmpty); verifyNever(() => gameBloc.add(const RoundLost())); }, ); flameBlocTester.test( 'removes the Ball', (game) async { final drain = Drain.test(); final behavior = DrainingBehavior(); final ball = Ball.test(); await drain.add(behavior); await game.pump( drain, gameBloc: gameBloc, ); await game.ensureAdd(ball); behavior.beginContact(ball, _MockContact()); await game.ready(); expect(game.descendants().whereType<Ball>(), isEmpty); }, ); }); }, ); }
pinball/test/game/components/drain/behaviors/draining_behavior_test.dart/0
{ "file_path": "pinball/test/game/components/drain/behaviors/draining_behavior_test.dart", "repo_id": "pinball", "token_count": 1754 }
1,211