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/google_maps_flutter/google_maps_flutter_android/example/.pluginToolsConfig.yaml/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/example/.pluginToolsConfig.yaml", "repo_id": "packages", "token_count": 45 }
951
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter_test/flutter_test.dart'; import 'package:google_maps_flutter_platform_interface/src/types/maps_object.dart'; import 'package:google_maps_flutter_platform_interface/src/types/maps_object_updates.dart'; import 'package:google_maps_flutter_platform_interface/src/types/utils/maps_object.dart'; import 'test_maps_object.dart'; class TestMapsObjectUpdate extends MapsObjectUpdates<TestMapsObject> { TestMapsObjectUpdate.from(super.previous, super.current) : super.from(objectName: 'testObject'); } void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('tile overlay updates tests', () { test('Correctly set toRemove, toAdd and toChange', () async { const TestMapsObject to1 = TestMapsObject(MapsObjectId<TestMapsObject>('id1')); const TestMapsObject to2 = TestMapsObject(MapsObjectId<TestMapsObject>('id2')); const TestMapsObject to3 = TestMapsObject(MapsObjectId<TestMapsObject>('id3')); const TestMapsObject to3Changed = TestMapsObject(MapsObjectId<TestMapsObject>('id3'), data: 2); const TestMapsObject to4 = TestMapsObject(MapsObjectId<TestMapsObject>('id4')); final Set<TestMapsObject> previous = <TestMapsObject>{to1, to2, to3}; final Set<TestMapsObject> current = <TestMapsObject>{ to2, to3Changed, to4 }; final TestMapsObjectUpdate updates = TestMapsObjectUpdate.from(previous, current); final Set<MapsObjectId<TestMapsObject>> toRemove = <MapsObjectId<TestMapsObject>>{ const MapsObjectId<TestMapsObject>('id1') }; expect(updates.objectIdsToRemove, toRemove); final Set<TestMapsObject> toAdd = <TestMapsObject>{to4}; expect(updates.objectsToAdd, toAdd); final Set<TestMapsObject> toChange = <TestMapsObject>{to3Changed}; expect(updates.objectsToChange, toChange); }); test('toJson', () async { const TestMapsObject to1 = TestMapsObject(MapsObjectId<TestMapsObject>('id1')); const TestMapsObject to2 = TestMapsObject(MapsObjectId<TestMapsObject>('id2')); const TestMapsObject to3 = TestMapsObject(MapsObjectId<TestMapsObject>('id3')); const TestMapsObject to3Changed = TestMapsObject(MapsObjectId<TestMapsObject>('id3'), data: 2); const TestMapsObject to4 = TestMapsObject(MapsObjectId<TestMapsObject>('id4')); final Set<TestMapsObject> previous = <TestMapsObject>{to1, to2, to3}; final Set<TestMapsObject> current = <TestMapsObject>{ to2, to3Changed, to4 }; final TestMapsObjectUpdate updates = TestMapsObjectUpdate.from(previous, current); final Object json = updates.toJson(); expect(json, <String, Object>{ 'testObjectsToAdd': serializeMapsObjectSet(updates.objectsToAdd), 'testObjectsToChange': serializeMapsObjectSet(updates.objectsToChange), 'testObjectIdsToRemove': updates.objectIdsToRemove .map<String>((MapsObjectId<TestMapsObject> m) => m.value) .toList() }); }); test('equality', () async { const TestMapsObject to1 = TestMapsObject(MapsObjectId<TestMapsObject>('id1')); const TestMapsObject to2 = TestMapsObject(MapsObjectId<TestMapsObject>('id2')); const TestMapsObject to3 = TestMapsObject(MapsObjectId<TestMapsObject>('id3')); const TestMapsObject to3Changed = TestMapsObject(MapsObjectId<TestMapsObject>('id3'), data: 2); const TestMapsObject to4 = TestMapsObject(MapsObjectId<TestMapsObject>('id4')); final Set<TestMapsObject> previous = <TestMapsObject>{to1, to2, to3}; final Set<TestMapsObject> current1 = <TestMapsObject>{ to2, to3Changed, to4 }; final Set<TestMapsObject> current2 = <TestMapsObject>{ to2, to3Changed, to4 }; final Set<TestMapsObject> current3 = <TestMapsObject>{to2, to4}; final TestMapsObjectUpdate updates1 = TestMapsObjectUpdate.from(previous, current1); final TestMapsObjectUpdate updates2 = TestMapsObjectUpdate.from(previous, current2); final TestMapsObjectUpdate updates3 = TestMapsObjectUpdate.from(previous, current3); expect(updates1, updates2); expect(updates1, isNot(updates3)); }); test('hashCode', () async { const TestMapsObject to1 = TestMapsObject(MapsObjectId<TestMapsObject>('id1')); const TestMapsObject to2 = TestMapsObject(MapsObjectId<TestMapsObject>('id2')); const TestMapsObject to3 = TestMapsObject(MapsObjectId<TestMapsObject>('id3')); const TestMapsObject to3Changed = TestMapsObject(MapsObjectId<TestMapsObject>('id3'), data: 2); const TestMapsObject to4 = TestMapsObject(MapsObjectId<TestMapsObject>('id4')); final Set<TestMapsObject> previous = <TestMapsObject>{to1, to2, to3}; final Set<TestMapsObject> current = <TestMapsObject>{ to2, to3Changed, to4 }; final TestMapsObjectUpdate updates = TestMapsObjectUpdate.from(previous, current); expect( updates.hashCode, Object.hash( Object.hashAll(updates.objectsToAdd), Object.hashAll(updates.objectIdsToRemove), Object.hashAll(updates.objectsToChange))); }); test('toString', () async { const TestMapsObject to1 = TestMapsObject(MapsObjectId<TestMapsObject>('id1')); const TestMapsObject to2 = TestMapsObject(MapsObjectId<TestMapsObject>('id2')); const TestMapsObject to3 = TestMapsObject(MapsObjectId<TestMapsObject>('id3')); const TestMapsObject to3Changed = TestMapsObject(MapsObjectId<TestMapsObject>('id3'), data: 2); const TestMapsObject to4 = TestMapsObject(MapsObjectId<TestMapsObject>('id4')); final Set<TestMapsObject> previous = <TestMapsObject>{to1, to2, to3}; final Set<TestMapsObject> current = <TestMapsObject>{ to2, to3Changed, to4 }; final TestMapsObjectUpdate updates = TestMapsObjectUpdate.from(previous, current); expect( updates.toString(), 'TestMapsObjectUpdate(add: ${updates.objectsToAdd}, ' 'remove: ${updates.objectIdsToRemove}, ' 'change: ${updates.objectsToChange})'); }); }); }
packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/maps_object_updates_test.dart/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/maps_object_updates_test.dart", "repo_id": "packages", "token_count": 2753 }
952
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. library google_maps_flutter_web; import 'dart:async'; import 'dart:convert'; import 'dart:js_interop'; import 'dart:ui_web' as ui_web; import 'package:collection/collection.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_web_plugins/flutter_web_plugins.dart'; import 'package:google_maps/google_maps.dart' as gmaps; import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart'; import 'package:sanitize_html/sanitize_html.dart'; import 'package:stream_transform/stream_transform.dart'; import 'package:web/web.dart'; import 'src/dom_window_extension.dart'; import 'src/google_maps_inspector_web.dart'; import 'src/map_styler.dart'; import 'src/third_party/to_screen_location/to_screen_location.dart'; import 'src/types.dart'; import 'src/utils.dart'; part 'src/circle.dart'; part 'src/circles.dart'; part 'src/convert.dart'; part 'src/google_maps_controller.dart'; part 'src/google_maps_flutter_web.dart'; part 'src/marker.dart'; part 'src/markers.dart'; part 'src/overlay.dart'; part 'src/overlays.dart'; part 'src/polygon.dart'; part 'src/polygons.dart'; part 'src/polyline.dart'; part 'src/polylines.dart';
packages/packages/google_maps_flutter/google_maps_flutter_web/lib/google_maps_flutter_web.dart/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_web/lib/google_maps_flutter_web.dart", "repo_id": "packages", "token_count": 531 }
953
// 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 library exposes web-only methods of [GoogleSignInPlatform.instance]. /// /// The exported methods will assert that the [GoogleSignInPlatform.instance] /// is an instance of class [GoogleSignInPlugin] (the web implementation of /// `google_sign_in` provided by this package). library web_only; import 'package:flutter/widgets.dart' show Widget; import 'package:google_sign_in_platform_interface/google_sign_in_platform_interface.dart' show GoogleSignInPlatform; import 'google_sign_in_web.dart' show GoogleSignInPlugin; import 'src/button_configuration.dart' show GSIButtonConfiguration; // Export the configuration types for the renderButton method. export 'src/button_configuration.dart' show GSIButtonConfiguration, GSIButtonLogoAlignment, GSIButtonShape, GSIButtonSize, GSIButtonText, GSIButtonTheme, GSIButtonType; // Asserts that the instance of the platform is for the web. GoogleSignInPlugin get _plugin { assert(GoogleSignInPlatform.instance is GoogleSignInPlugin, 'The current GoogleSignInPlatform instance is not for web.'); return GoogleSignInPlatform.instance as GoogleSignInPlugin; } /// Render the GIS Sign-In Button widget with [configuration]. Widget renderButton({GSIButtonConfiguration? configuration}) { return _plugin.renderButton(configuration: configuration); } /// Requests server auth code from the GIS Client. /// /// See: https://developers.google.com/identity/oauth2/web/guides/use-code-model Future<String?> requestServerAuthCode() async { return _plugin.requestServerAuthCode(); }
packages/packages/google_sign_in/google_sign_in_web/lib/web_only.dart/0
{ "file_path": "packages/packages/google_sign_in/google_sign_in_web/lib/web_only.dart", "repo_id": "packages", "token_count": 536 }
954
// Mocks generated by Mockito 5.4.4 from annotations // in image_picker/test/image_picker_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i4; import 'package:cross_file/cross_file.dart' as _i5; import 'package:image_picker_platform_interface/src/platform_interface/image_picker_platform.dart' as _i3; import 'package:image_picker_platform_interface/src/types/types.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; // 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 _FakeLostData_0 extends _i1.SmartFake implements _i2.LostData { _FakeLostData_0( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeLostDataResponse_1 extends _i1.SmartFake implements _i2.LostDataResponse { _FakeLostDataResponse_1( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } /// A class which mocks [ImagePickerPlatform]. /// /// See the documentation for Mockito's code generation for more information. class MockImagePickerPlatform extends _i1.Mock implements _i3.ImagePickerPlatform { MockImagePickerPlatform() { _i1.throwOnMissingStub(this); } @override _i4.Future<_i2.PickedFile?> pickImage({ required _i2.ImageSource? source, double? maxWidth, double? maxHeight, int? imageQuality, _i2.CameraDevice? preferredCameraDevice = _i2.CameraDevice.rear, }) => (super.noSuchMethod( Invocation.method( #pickImage, [], { #source: source, #maxWidth: maxWidth, #maxHeight: maxHeight, #imageQuality: imageQuality, #preferredCameraDevice: preferredCameraDevice, }, ), returnValue: _i4.Future<_i2.PickedFile?>.value(), ) as _i4.Future<_i2.PickedFile?>); @override _i4.Future<List<_i2.PickedFile>?> pickMultiImage({ double? maxWidth, double? maxHeight, int? imageQuality, }) => (super.noSuchMethod( Invocation.method( #pickMultiImage, [], { #maxWidth: maxWidth, #maxHeight: maxHeight, #imageQuality: imageQuality, }, ), returnValue: _i4.Future<List<_i2.PickedFile>?>.value(), ) as _i4.Future<List<_i2.PickedFile>?>); @override _i4.Future<_i2.PickedFile?> pickVideo({ required _i2.ImageSource? source, _i2.CameraDevice? preferredCameraDevice = _i2.CameraDevice.rear, Duration? maxDuration, }) => (super.noSuchMethod( Invocation.method( #pickVideo, [], { #source: source, #preferredCameraDevice: preferredCameraDevice, #maxDuration: maxDuration, }, ), returnValue: _i4.Future<_i2.PickedFile?>.value(), ) as _i4.Future<_i2.PickedFile?>); @override _i4.Future<_i2.LostData> retrieveLostData() => (super.noSuchMethod( Invocation.method( #retrieveLostData, [], ), returnValue: _i4.Future<_i2.LostData>.value(_FakeLostData_0( this, Invocation.method( #retrieveLostData, [], ), )), ) as _i4.Future<_i2.LostData>); @override _i4.Future<_i5.XFile?> getImage({ required _i2.ImageSource? source, double? maxWidth, double? maxHeight, int? imageQuality, _i2.CameraDevice? preferredCameraDevice = _i2.CameraDevice.rear, }) => (super.noSuchMethod( Invocation.method( #getImage, [], { #source: source, #maxWidth: maxWidth, #maxHeight: maxHeight, #imageQuality: imageQuality, #preferredCameraDevice: preferredCameraDevice, }, ), returnValue: _i4.Future<_i5.XFile?>.value(), ) as _i4.Future<_i5.XFile?>); @override _i4.Future<List<_i5.XFile>?> getMultiImage({ double? maxWidth, double? maxHeight, int? imageQuality, }) => (super.noSuchMethod( Invocation.method( #getMultiImage, [], { #maxWidth: maxWidth, #maxHeight: maxHeight, #imageQuality: imageQuality, }, ), returnValue: _i4.Future<List<_i5.XFile>?>.value(), ) as _i4.Future<List<_i5.XFile>?>); @override _i4.Future<List<_i5.XFile>> getMedia({required _i2.MediaOptions? options}) => (super.noSuchMethod( Invocation.method( #getMedia, [], {#options: options}, ), returnValue: _i4.Future<List<_i5.XFile>>.value(<_i5.XFile>[]), ) as _i4.Future<List<_i5.XFile>>); @override _i4.Future<_i5.XFile?> getVideo({ required _i2.ImageSource? source, _i2.CameraDevice? preferredCameraDevice = _i2.CameraDevice.rear, Duration? maxDuration, }) => (super.noSuchMethod( Invocation.method( #getVideo, [], { #source: source, #preferredCameraDevice: preferredCameraDevice, #maxDuration: maxDuration, }, ), returnValue: _i4.Future<_i5.XFile?>.value(), ) as _i4.Future<_i5.XFile?>); @override _i4.Future<_i2.LostDataResponse> getLostData() => (super.noSuchMethod( Invocation.method( #getLostData, [], ), returnValue: _i4.Future<_i2.LostDataResponse>.value(_FakeLostDataResponse_1( this, Invocation.method( #getLostData, [], ), )), ) as _i4.Future<_i2.LostDataResponse>); @override _i4.Future<_i5.XFile?> getImageFromSource({ required _i2.ImageSource? source, _i2.ImagePickerOptions? options = const _i2.ImagePickerOptions(), }) => (super.noSuchMethod( Invocation.method( #getImageFromSource, [], { #source: source, #options: options, }, ), returnValue: _i4.Future<_i5.XFile?>.value(), ) as _i4.Future<_i5.XFile?>); @override _i4.Future<List<_i5.XFile>> getMultiImageWithOptions( {_i2.MultiImagePickerOptions? options = const _i2.MultiImagePickerOptions()}) => (super.noSuchMethod( Invocation.method( #getMultiImageWithOptions, [], {#options: options}, ), returnValue: _i4.Future<List<_i5.XFile>>.value(<_i5.XFile>[]), ) as _i4.Future<List<_i5.XFile>>); @override bool supportsImageSource(_i2.ImageSource? source) => (super.noSuchMethod( Invocation.method( #supportsImageSource, [source], ), returnValue: false, ) as bool); }
packages/packages/image_picker/image_picker/test/image_picker_test.mocks.dart/0
{ "file_path": "packages/packages/image_picker/image_picker/test/image_picker_test.mocks.dart", "repo_id": "packages", "token_count": 3537 }
955
// 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.imagepicker; import android.Manifest; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Build; import java.util.Arrays; final class ImagePickerUtils { /** returns true, if permission present in manifest, otherwise false */ private static boolean isPermissionPresentInManifest(Context context, String permissionName) { try { PackageManager packageManager = context.getPackageManager(); PackageInfo packageInfo; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { packageInfo = packageManager.getPackageInfo( context.getPackageName(), PackageManager.PackageInfoFlags.of(PackageManager.GET_PERMISSIONS)); } else { packageInfo = getPermissionsPackageInfoPreApi33(packageManager, context.getPackageName()); } String[] requestedPermissions = packageInfo.requestedPermissions; return Arrays.asList(requestedPermissions).contains(permissionName); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); return false; } } @SuppressWarnings("deprecation") private static PackageInfo getPermissionsPackageInfoPreApi33( PackageManager packageManager, String packageName) throws PackageManager.NameNotFoundException { return packageManager.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS); } /** * Camera permission need request if it present in manifest, because for M or great for take Photo * ar Video by intent need it permission, even if the camera permission is not used. * * <p>Camera permission may be used in another package, as example flutter_barcode_reader. * https://github.com/flutter/flutter/issues/29837 * * @return returns true, if need request camera permission, otherwise false */ static boolean needRequestCameraPermission(Context context) { boolean greatOrEqualM = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M; return greatOrEqualM && isPermissionPresentInManifest(context, Manifest.permission.CAMERA); } }
packages/packages/image_picker/image_picker_android/android/src/main/java/io/flutter/plugins/imagepicker/ImagePickerUtils.java/0
{ "file_path": "packages/packages/image_picker/image_picker_android/android/src/main/java/io/flutter/plugins/imagepicker/ImagePickerUtils.java", "repo_id": "packages", "token_count": 735 }
956
// 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:image_picker_android/image_picker_android.dart'; import 'package:image_picker_android/src/messages.g.dart'; import 'package:image_picker_platform_interface/image_picker_platform_interface.dart'; void main() { late ImagePickerAndroid picker; late _FakeImagePickerApi api; setUp(() { api = _FakeImagePickerApi(); picker = ImagePickerAndroid(api: api); }); test('registers instance', () async { ImagePickerAndroid.registerWith(); expect(ImagePickerPlatform.instance, isA<ImagePickerAndroid>()); }); group('#pickImage', () { test('calls the method correctly', () async { const String fakePath = '/foo.jpg'; api.returnValue = <String>[fakePath]; final PickedFile? result = await picker.pickImage(source: ImageSource.camera); expect(result?.path, fakePath); expect(api.lastCall, _LastPickType.image); expect(api.passedAllowMultiple, false); }); test('passes the gallery image source argument correctly', () async { await picker.pickImage(source: ImageSource.camera); expect(api.passedSource?.type, SourceType.camera); }); test('passes the camera image source argument correctly', () async { await picker.pickImage(source: ImageSource.gallery); expect(api.passedSource?.type, SourceType.gallery); }); test('passes default image options', () async { await picker.pickImage(source: ImageSource.gallery); expect(api.passedImageOptions?.maxWidth, null); expect(api.passedImageOptions?.maxHeight, null); expect(api.passedImageOptions?.quality, 100); }); test('passes image option arguments correctly', () async { await picker.pickImage( source: ImageSource.camera, maxWidth: 10.0, maxHeight: 20.0, imageQuality: 70, ); expect(api.passedImageOptions?.maxWidth, 10.0); expect(api.passedImageOptions?.maxHeight, 20.0); expect(api.passedImageOptions?.quality, 70); }); test('does not accept an invalid imageQuality argument', () { expect( () => picker.pickImage(imageQuality: -1, source: ImageSource.gallery), throwsArgumentError, ); expect( () => picker.pickImage(imageQuality: 101, source: ImageSource.gallery), throwsArgumentError, ); expect( () => picker.pickImage(imageQuality: -1, source: ImageSource.camera), throwsArgumentError, ); expect( () => picker.pickImage(imageQuality: 101, source: ImageSource.camera), throwsArgumentError, ); }); test('does not accept a negative width or height argument', () { expect( () => picker.pickImage(source: ImageSource.camera, maxWidth: -1.0), throwsArgumentError, ); expect( () => picker.pickImage(source: ImageSource.camera, maxHeight: -1.0), throwsArgumentError, ); }); test('handles a null image path response gracefully', () async { api.returnValue = null; expect(await picker.pickImage(source: ImageSource.gallery), isNull); expect(await picker.pickImage(source: ImageSource.camera), isNull); }); test('camera position defaults to back', () async { await picker.pickImage(source: ImageSource.camera); expect(api.passedSource?.camera, SourceCamera.rear); }); test('camera position can be set to front', () async { await picker.pickImage( source: ImageSource.camera, preferredCameraDevice: CameraDevice.front); expect(api.passedSource?.camera, SourceCamera.front); }); test('defaults to not using Android Photo Picker', () async { await picker.pickImage(source: ImageSource.gallery); expect(api.passedPhotoPickerFlag, false); }); test('allows using Android Photo Picker', () async { picker.useAndroidPhotoPicker = true; await picker.pickImage(source: ImageSource.gallery); expect(api.passedPhotoPickerFlag, true); }); }); group('#pickMultiImage', () { test('calls the method correctly', () async { const List<String> fakePaths = <String>['/foo.jgp', 'bar.jpg']; api.returnValue = fakePaths; final List<PickedFile>? files = await picker.pickMultiImage(); expect(api.lastCall, _LastPickType.image); expect(api.passedAllowMultiple, true); expect(files?.length, 2); expect(files?[0].path, fakePaths[0]); expect(files?[1].path, fakePaths[1]); }); test('passes default image options', () async { await picker.pickMultiImage(); expect(api.passedImageOptions?.maxWidth, null); expect(api.passedImageOptions?.maxHeight, null); expect(api.passedImageOptions?.quality, 100); }); test('passes image option arguments correctly', () async { await picker.pickMultiImage( maxWidth: 10.0, maxHeight: 20.0, imageQuality: 70, ); expect(api.passedImageOptions?.maxWidth, 10.0); expect(api.passedImageOptions?.maxHeight, 20.0); expect(api.passedImageOptions?.quality, 70); }); test('does not accept a negative width or height argument', () { expect( () => picker.pickMultiImage(maxWidth: -1.0), throwsArgumentError, ); expect( () => picker.pickMultiImage(maxHeight: -1.0), throwsArgumentError, ); }); test('does not accept an invalid imageQuality argument', () { expect( () => picker.pickMultiImage(imageQuality: -1), throwsArgumentError, ); expect( () => picker.pickMultiImage(imageQuality: 101), throwsArgumentError, ); }); test('handles an empty path response gracefully', () async { api.returnValue = <String>[]; expect(await picker.pickMultiImage(), isNull); }); test('defaults to not using Android Photo Picker', () async { await picker.pickMultiImage(); expect(api.passedPhotoPickerFlag, false); }); test('allows using Android Photo Picker', () async { picker.useAndroidPhotoPicker = true; await picker.pickMultiImage(); expect(api.passedPhotoPickerFlag, true); }); }); group('#pickVideo', () { test('calls the method correctly', () async { const String fakePath = '/foo.jpg'; api.returnValue = <String>[fakePath]; final PickedFile? result = await picker.pickVideo(source: ImageSource.camera); expect(result?.path, fakePath); expect(api.lastCall, _LastPickType.video); expect(api.passedAllowMultiple, false); }); test('passes the gallery image source argument correctly', () async { await picker.pickVideo(source: ImageSource.camera); expect(api.passedSource?.type, SourceType.camera); }); test('passes the camera image source argument correctly', () async { await picker.pickVideo(source: ImageSource.gallery); expect(api.passedSource?.type, SourceType.gallery); }); test('passes null as the default duration', () async { await picker.pickVideo(source: ImageSource.gallery); expect(api.passedVideoOptions, isNotNull); expect(api.passedVideoOptions?.maxDurationSeconds, null); }); test('passes the duration argument correctly', () async { await picker.pickVideo( source: ImageSource.camera, maxDuration: const Duration(minutes: 1), ); expect(api.passedVideoOptions?.maxDurationSeconds, 60); }); test('handles a null video path response gracefully', () async { api.returnValue = null; expect(await picker.pickVideo(source: ImageSource.gallery), isNull); expect(await picker.pickVideo(source: ImageSource.camera), isNull); }); test('camera position defaults to back', () async { await picker.pickVideo(source: ImageSource.camera); expect(api.passedSource?.camera, SourceCamera.rear); }); test('camera position can set to front', () async { await picker.pickVideo( source: ImageSource.camera, preferredCameraDevice: CameraDevice.front, ); expect(api.passedSource?.camera, SourceCamera.front); }); test('defaults to not using Android Photo Picker', () async { await picker.pickVideo(source: ImageSource.gallery); expect(api.passedPhotoPickerFlag, false); }); test('allows using Android Photo Picker', () async { picker.useAndroidPhotoPicker = true; await picker.pickVideo(source: ImageSource.gallery); expect(api.passedPhotoPickerFlag, true); }); }); group('#retrieveLostData', () { test('retrieveLostData get success response', () async { api.returnValue = CacheRetrievalResult( type: CacheRetrievalType.image, paths: <String>['/example/path']); final LostData response = await picker.retrieveLostData(); expect(response.type, RetrieveType.image); expect(response.file, isNotNull); expect(response.file!.path, '/example/path'); }); test('retrieveLostData get error response', () async { api.returnValue = CacheRetrievalResult( type: CacheRetrievalType.video, paths: <String>[], error: CacheRetrievalError( code: 'test_error_code', message: 'test_error_message')); final LostData response = await picker.retrieveLostData(); expect(response.type, RetrieveType.video); expect(response.exception, isNotNull); expect(response.exception!.code, 'test_error_code'); expect(response.exception!.message, 'test_error_message'); }); test('retrieveLostData get null response', () async { api.returnValue = null; expect((await picker.retrieveLostData()).isEmpty, true); }); test('retrieveLostData get both path and error should throw', () async { api.returnValue = CacheRetrievalResult( type: CacheRetrievalType.video, paths: <String>['/example/path'], error: CacheRetrievalError( code: 'test_error_code', message: 'test_error_message')); expect(picker.retrieveLostData(), throwsAssertionError); }); }); group('#getImage', () { test('calls the method correctly', () async { const String fakePath = '/foo.jpg'; api.returnValue = <String>[fakePath]; final XFile? result = await picker.getImage(source: ImageSource.camera); expect(result?.path, fakePath); expect(api.lastCall, _LastPickType.image); expect(api.passedAllowMultiple, false); }); test('passes the gallery image source argument correctly', () async { await picker.getImage(source: ImageSource.camera); expect(api.passedSource?.type, SourceType.camera); }); test('passes the camera image source argument correctly', () async { await picker.getImage(source: ImageSource.gallery); expect(api.passedSource?.type, SourceType.gallery); }); test('passes default image options', () async { await picker.getImage(source: ImageSource.gallery); expect(api.passedImageOptions?.maxWidth, null); expect(api.passedImageOptions?.maxHeight, null); expect(api.passedImageOptions?.quality, 100); }); test('passes image option arguments correctly', () async { await picker.getImage( source: ImageSource.camera, maxWidth: 10.0, maxHeight: 20.0, imageQuality: 70, ); expect(api.passedImageOptions?.maxWidth, 10.0); expect(api.passedImageOptions?.maxHeight, 20.0); expect(api.passedImageOptions?.quality, 70); }); test('does not accept an invalid imageQuality argument', () { expect( () => picker.getImage(imageQuality: -1, source: ImageSource.gallery), throwsArgumentError, ); expect( () => picker.getImage(imageQuality: 101, source: ImageSource.gallery), throwsArgumentError, ); expect( () => picker.getImage(imageQuality: -1, source: ImageSource.camera), throwsArgumentError, ); expect( () => picker.getImage(imageQuality: 101, source: ImageSource.camera), throwsArgumentError, ); }); test('does not accept a negative width or height argument', () { expect( () => picker.getImage(source: ImageSource.camera, maxWidth: -1.0), throwsArgumentError, ); expect( () => picker.getImage(source: ImageSource.camera, maxHeight: -1.0), throwsArgumentError, ); }); test('handles a null image path response gracefully', () async { api.returnValue = null; expect(await picker.getImage(source: ImageSource.gallery), isNull); expect(await picker.getImage(source: ImageSource.camera), isNull); }); test('camera position defaults to back', () async { await picker.getImage(source: ImageSource.camera); expect(api.passedSource?.camera, SourceCamera.rear); }); test('camera position can set to front', () async { await picker.getImage( source: ImageSource.camera, preferredCameraDevice: CameraDevice.front); expect(api.passedSource?.camera, SourceCamera.front); }); test('defaults to not using Android Photo Picker', () async { await picker.getImage(source: ImageSource.gallery); expect(api.passedPhotoPickerFlag, false); }); test('allows using Android Photo Picker', () async { picker.useAndroidPhotoPicker = true; await picker.getImage(source: ImageSource.gallery); expect(api.passedPhotoPickerFlag, true); }); }); group('#getMultiImage', () { test('calls the method correctly', () async { const List<String> fakePaths = <String>['/foo.jgp', 'bar.jpg']; api.returnValue = fakePaths; final List<XFile>? files = await picker.getMultiImage(); expect(api.lastCall, _LastPickType.image); expect(api.passedAllowMultiple, true); expect(files?.length, 2); expect(files?[0].path, fakePaths[0]); expect(files?[1].path, fakePaths[1]); }); test('passes default image options', () async { await picker.getMultiImage(); expect(api.passedImageOptions?.maxWidth, null); expect(api.passedImageOptions?.maxHeight, null); expect(api.passedImageOptions?.quality, 100); }); test('passes image option arguments correctly', () async { await picker.getMultiImage( maxWidth: 10.0, maxHeight: 20.0, imageQuality: 70, ); expect(api.passedImageOptions?.maxWidth, 10.0); expect(api.passedImageOptions?.maxHeight, 20.0); expect(api.passedImageOptions?.quality, 70); }); test('does not accept a negative width or height argument', () { expect( () => picker.getMultiImage(maxWidth: -1.0), throwsArgumentError, ); expect( () => picker.getMultiImage(maxHeight: -1.0), throwsArgumentError, ); }); test('does not accept an invalid imageQuality argument', () { expect( () => picker.getMultiImage(imageQuality: -1), throwsArgumentError, ); expect( () => picker.getMultiImage(imageQuality: 101), throwsArgumentError, ); }); test('handles an empty image path response gracefully', () async { api.returnValue = <String>[]; expect(await picker.getMultiImage(), isNull); expect(await picker.getMultiImage(), isNull); }); test('defaults to not using Android Photo Picker', () async { await picker.getMultiImage(); expect(api.passedPhotoPickerFlag, false); }); test('allows using Android Photo Picker', () async { picker.useAndroidPhotoPicker = true; await picker.getMultiImage(); expect(api.passedPhotoPickerFlag, true); }); }); group('#getVideo', () { test('calls the method correctly', () async { const String fakePath = '/foo.jpg'; api.returnValue = <String>[fakePath]; final XFile? result = await picker.getVideo(source: ImageSource.camera); expect(result?.path, fakePath); expect(api.lastCall, _LastPickType.video); expect(api.passedAllowMultiple, false); }); test('passes the gallery image source argument correctly', () async { await picker.getVideo(source: ImageSource.camera); expect(api.passedSource?.type, SourceType.camera); }); test('passes the camera image source argument correctly', () async { await picker.getVideo(source: ImageSource.gallery); expect(api.passedSource?.type, SourceType.gallery); }); test('passes null as the default duration', () async { await picker.getVideo(source: ImageSource.gallery); expect(api.passedVideoOptions, isNotNull); expect(api.passedVideoOptions?.maxDurationSeconds, null); }); test('passes the duration argument correctly', () async { await picker.getVideo( source: ImageSource.camera, maxDuration: const Duration(minutes: 1), ); expect(api.passedVideoOptions?.maxDurationSeconds, 60); }); test('handles a null video path response gracefully', () async { api.returnValue = null; expect(await picker.getVideo(source: ImageSource.gallery), isNull); expect(await picker.getVideo(source: ImageSource.camera), isNull); }); test('camera position defaults to back', () async { await picker.getVideo(source: ImageSource.camera); expect(api.passedSource?.camera, SourceCamera.rear); }); test('camera position can set to front', () async { await picker.getVideo( source: ImageSource.camera, preferredCameraDevice: CameraDevice.front, ); expect(api.passedSource?.camera, SourceCamera.front); }); test('defaults to not using Android Photo Picker', () async { await picker.getVideo(source: ImageSource.gallery); expect(api.passedPhotoPickerFlag, false); }); test('allows using Android Photo Picker', () async { picker.useAndroidPhotoPicker = true; await picker.getVideo(source: ImageSource.gallery); expect(api.passedPhotoPickerFlag, true); }); }); group('#getLostData', () { test('getLostData get success response', () async { api.returnValue = CacheRetrievalResult( type: CacheRetrievalType.image, paths: <String>['/example/path']); final LostDataResponse response = await picker.getLostData(); expect(response.type, RetrieveType.image); expect(response.file, isNotNull); expect(response.file!.path, '/example/path'); }); test('getLostData should successfully retrieve multiple files', () async { api.returnValue = CacheRetrievalResult( type: CacheRetrievalType.image, paths: <String>['/example/path0', '/example/path1']); final LostDataResponse response = await picker.getLostData(); expect(response.type, RetrieveType.image); expect(response.file, isNotNull); expect(response.file!.path, '/example/path1'); expect(response.files!.first.path, '/example/path0'); expect(response.files!.length, 2); }); test('getLostData get error response', () async { api.returnValue = CacheRetrievalResult( type: CacheRetrievalType.video, paths: <String>[], error: CacheRetrievalError( code: 'test_error_code', message: 'test_error_message')); final LostDataResponse response = await picker.getLostData(); expect(response.type, RetrieveType.video); expect(response.exception, isNotNull); expect(response.exception!.code, 'test_error_code'); expect(response.exception!.message, 'test_error_message'); }); test('getLostData get null response', () async { api.returnValue = null; expect((await picker.getLostData()).isEmpty, true); }); test('getLostData get both path and error should throw', () async { api.returnValue = CacheRetrievalResult( type: CacheRetrievalType.video, paths: <String>['/example/path'], error: CacheRetrievalError( code: 'test_error_code', message: 'test_error_message')); expect(picker.getLostData(), throwsAssertionError); }); }); group('#getMedia', () { test('calls the method correctly', () async { const List<String> fakePaths = <String>['/foo.jgp', 'bar.jpg']; api.returnValue = fakePaths; final List<XFile> files = await picker.getMedia( options: const MediaOptions( allowMultiple: true, ), ); expect(api.lastCall, _LastPickType.image); expect(files.length, 2); expect(files[0].path, fakePaths[0]); expect(files[1].path, fakePaths[1]); }); test('passes default image options', () async { await picker.getMedia( options: const MediaOptions( allowMultiple: true, ), ); expect(api.passedImageOptions?.maxWidth, null); expect(api.passedImageOptions?.maxHeight, null); expect(api.passedImageOptions?.quality, 100); }); test('passes image option arguments correctly', () async { await picker.getMedia( options: const MediaOptions( allowMultiple: true, imageOptions: ImageOptions( maxWidth: 10.0, maxHeight: 20.0, imageQuality: 70, ), )); expect(api.passedImageOptions?.maxWidth, 10.0); expect(api.passedImageOptions?.maxHeight, 20.0); expect(api.passedImageOptions?.quality, 70); }); test('does not accept a negative width or height argument', () { expect( () => picker.getMedia( options: const MediaOptions( allowMultiple: true, imageOptions: ImageOptions(maxWidth: -1.0), ), ), throwsArgumentError, ); expect( () => picker.getMedia( options: const MediaOptions( allowMultiple: true, imageOptions: ImageOptions(maxHeight: -1.0), ), ), throwsArgumentError, ); }); test('does not accept an invalid imageQuality argument', () { expect( () => picker.getMedia( options: const MediaOptions( allowMultiple: true, imageOptions: ImageOptions(imageQuality: -1), ), ), throwsArgumentError, ); expect( () => picker.getMedia( options: const MediaOptions( allowMultiple: true, imageOptions: ImageOptions(imageQuality: 101), ), ), throwsArgumentError, ); }); test('handles an empty path response gracefully', () async { api.returnValue = <String>[]; expect( await picker.getMedia( options: const MediaOptions( allowMultiple: true, ), ), <String>[]); }); test('defaults to not using Android Photo Picker', () async { await picker.getMedia( options: const MediaOptions( allowMultiple: true, ), ); expect(api.passedPhotoPickerFlag, false); }); test('allows using Android Photo Picker', () async { picker.useAndroidPhotoPicker = true; await picker.getMedia( options: const MediaOptions( allowMultiple: true, ), ); expect(api.passedPhotoPickerFlag, true); }); }); group('#getImageFromSource', () { test('calls the method correctly', () async { const String fakePath = '/foo.jpg'; api.returnValue = <String>[fakePath]; final XFile? result = await picker.getImage(source: ImageSource.camera); expect(result?.path, fakePath); expect(api.lastCall, _LastPickType.image); expect(api.passedAllowMultiple, false); }); test('passes the gallery image source argument correctly', () async { await picker.getImageFromSource(source: ImageSource.camera); expect(api.passedSource?.type, SourceType.camera); }); test('passes the camera image source argument correctly', () async { await picker.getImageFromSource(source: ImageSource.gallery); expect(api.passedSource?.type, SourceType.gallery); }); test('passes default image options', () async { await picker.getImageFromSource(source: ImageSource.gallery); expect(api.passedImageOptions?.maxWidth, null); expect(api.passedImageOptions?.maxHeight, null); expect(api.passedImageOptions?.quality, 100); }); test('passes image option arguments correctly', () async { await picker.getImageFromSource( source: ImageSource.camera, options: const ImagePickerOptions( maxWidth: 10.0, maxHeight: 20.0, imageQuality: 70, ), ); expect(api.passedImageOptions?.maxWidth, 10.0); expect(api.passedImageOptions?.maxHeight, 20.0); expect(api.passedImageOptions?.quality, 70); }); test('does not accept an invalid imageQuality argument', () { expect( () => picker.getImageFromSource( source: ImageSource.gallery, options: const ImagePickerOptions(imageQuality: -1), ), throwsArgumentError, ); expect( () => picker.getImageFromSource( source: ImageSource.gallery, options: const ImagePickerOptions(imageQuality: 101), ), throwsArgumentError, ); expect( () => picker.getImageFromSource( source: ImageSource.camera, options: const ImagePickerOptions(imageQuality: -1), ), throwsArgumentError, ); expect( () => picker.getImageFromSource( source: ImageSource.camera, options: const ImagePickerOptions(imageQuality: 101), ), throwsArgumentError, ); }); test('does not accept a negative width or height argument', () { expect( () => picker.getImageFromSource( source: ImageSource.camera, options: const ImagePickerOptions(maxWidth: -1.0), ), throwsArgumentError, ); expect( () => picker.getImageFromSource( source: ImageSource.camera, options: const ImagePickerOptions(maxHeight: -1.0), ), throwsArgumentError, ); }); test('handles a null image path response gracefully', () async { api.returnValue = null; expect( await picker.getImageFromSource(source: ImageSource.gallery), isNull); expect( await picker.getImageFromSource(source: ImageSource.camera), isNull); }); test('camera position defaults to back', () async { await picker.getImageFromSource(source: ImageSource.camera); expect(api.passedSource?.camera, SourceCamera.rear); }); test('camera position can be set to front', () async { await picker.getImageFromSource( source: ImageSource.camera, options: const ImagePickerOptions( preferredCameraDevice: CameraDevice.front)); expect(api.passedSource?.camera, SourceCamera.front); }); test('defaults to not using Android Photo Picker', () async { await picker.getImageFromSource(source: ImageSource.gallery); expect(api.passedPhotoPickerFlag, false); }); test('allows using Android Photo Picker', () async { picker.useAndroidPhotoPicker = true; await picker.getImageFromSource(source: ImageSource.gallery); expect(api.passedPhotoPickerFlag, true); }); }); } enum _LastPickType { image, video } class _FakeImagePickerApi implements ImagePickerApi { // The value to return. Object? returnValue; // Passed arguments. SourceSpecification? passedSource; ImageSelectionOptions? passedImageOptions; VideoSelectionOptions? passedVideoOptions; bool? passedAllowMultiple; bool? passedPhotoPickerFlag; _LastPickType? lastCall; @override Future<List<String?>> pickImages( SourceSpecification source, ImageSelectionOptions options, GeneralOptions generalOptions, ) async { lastCall = _LastPickType.image; passedSource = source; passedImageOptions = options; passedAllowMultiple = generalOptions.allowMultiple; passedPhotoPickerFlag = generalOptions.usePhotoPicker; return returnValue as List<String?>? ?? <String>[]; } @override Future<List<String?>> pickMedia( MediaSelectionOptions options, GeneralOptions generalOptions, ) async { lastCall = _LastPickType.image; passedImageOptions = options.imageSelectionOptions; passedPhotoPickerFlag = generalOptions.usePhotoPicker; passedAllowMultiple = generalOptions.allowMultiple; return returnValue as List<String?>? ?? <String>[]; } @override Future<List<String?>> pickVideos( SourceSpecification source, VideoSelectionOptions options, GeneralOptions generalOptions, ) async { lastCall = _LastPickType.video; passedSource = source; passedVideoOptions = options; passedAllowMultiple = generalOptions.allowMultiple; passedPhotoPickerFlag = generalOptions.usePhotoPicker; return returnValue as List<String?>? ?? <String>[]; } @override Future<CacheRetrievalResult?> retrieveLostResults() async { return returnValue as CacheRetrievalResult?; } }
packages/packages/image_picker/image_picker_android/test/image_picker_android_test.dart/0
{ "file_path": "packages/packages/image_picker/image_picker_android/test/image_picker_android_test.dart", "repo_id": "packages", "token_count": 11419 }
957
// 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:web/web.dart' as web; /// Adds a `toList` method to [web.FileList] objects. extension WebFileListToDartList on web.FileList { /// Converts a [web.FileList] into a [List] of [web.File]. /// /// This method makes a copy. List<web.File> get toList => <web.File>[for (int i = 0; i < length; i++) item(i)!]; }
packages/packages/image_picker/image_picker_for_web/lib/src/pkg_web_tweaks.dart/0
{ "file_path": "packages/packages/image_picker/image_picker_for_web/lib/src/pkg_web_tweaks.dart", "repo_id": "packages", "token_count": 170 }
958
// 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 header is available in the Test module. Import via "@import image_picker_ios_ios.Test;" #import <image_picker_ios/FLTImagePickerPlugin.h> #import "messages.g.h" NS_ASSUME_NONNULL_BEGIN /// The return handler used for all method calls, which internally adapts the provided result list /// to return either a list or a single element depending on the original call. typedef void (^FlutterResultAdapter)(NSArray<NSString *> *_Nullable, FlutterError *_Nullable); /// A container class for context to use when handling a method call from the Dart side. @interface FLTImagePickerMethodCallContext : NSObject /// Initializes a new context that calls |result| on completion of the operation. - (instancetype)initWithResult:(nonnull FlutterResultAdapter)result; /// The callback to provide results to the Dart caller. @property(nonatomic, copy, nonnull) FlutterResultAdapter result; /// The maximum size to enforce on the results. /// /// If nil, no resizing is done. @property(nonatomic, strong, nullable) FLTMaxSize *maxSize; /// The image quality to resample the results to. /// /// If nil, no resampling is done. @property(nonatomic, strong, nullable) NSNumber *imageQuality; /// Maximum number of images to select. 0 indicates no maximum. @property(nonatomic, assign) int maxImageCount; /// Whether the image should be picked with full metadata (requires gallery permissions) @property(nonatomic, assign) BOOL requestFullMetadata; /// Whether the picker should include videos in the list*/ @property(nonatomic, assign) BOOL includeVideo; @end #pragma mark - /// Methods exposed for unit testing. @interface FLTImagePickerPlugin () <FLTImagePickerApi, UINavigationControllerDelegate, UIImagePickerControllerDelegate, PHPickerViewControllerDelegate, UIAdaptivePresentationControllerDelegate> /// The context of the Flutter method call that is currently being handled, if any. @property(strong, nonatomic, nullable) FLTImagePickerMethodCallContext *callContext; - (UIViewController *)viewControllerWithWindow:(nullable UIWindow *)window; /// Validates the provided paths list, then sends it via `callContext.result` as the result of the /// original platform channel method call, clearing the in-progress call state. /// /// @param pathList The paths to return. nil indicates a cancelled operation. - (void)sendCallResultWithSavedPathList:(nullable NSArray *)pathList; /// Tells the delegate that the user cancelled the pick operation. /// /// Your delegate’s implementation of this method should dismiss the picker view /// by calling the dismissModalViewControllerAnimated: method of the parent /// view controller. /// /// Implementation of this method is optional, but expected. /// /// @param picker The controller object managing the image picker interface. - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker; /// Sets UIImagePickerController instances that will be used when a new /// controller would normally be created. Each call to /// createImagePickerController will remove the current first element from /// the array. /// /// Should be used for testing purposes only. - (void)setImagePickerControllerOverrides: (NSArray<UIImagePickerController *> *)imagePickerControllers; @end NS_ASSUME_NONNULL_END
packages/packages/image_picker/image_picker_ios/ios/Classes/FLTImagePickerPlugin_Test.h/0
{ "file_path": "packages/packages/image_picker/image_picker_ios/ios/Classes/FLTImagePickerPlugin_Test.h", "repo_id": "packages", "token_count": 1052 }
959
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:file_selector_platform_interface/file_selector_platform_interface.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:image_picker_linux/image_picker_linux.dart'; import 'package:image_picker_platform_interface/image_picker_platform_interface.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'image_picker_linux_test.mocks.dart'; @GenerateMocks(<Type>[FileSelectorPlatform]) void main() { TestWidgetsFlutterBinding.ensureInitialized(); // Returns the captured type groups from a mock call result, assuming that // exactly one call was made and only the type groups were captured. List<XTypeGroup> capturedTypeGroups(VerificationResult result) { return result.captured.single as List<XTypeGroup>; } late ImagePickerLinux plugin; late MockFileSelectorPlatform mockFileSelectorPlatform; setUp(() { plugin = ImagePickerLinux(); mockFileSelectorPlatform = MockFileSelectorPlatform(); when(mockFileSelectorPlatform.openFile( acceptedTypeGroups: anyNamed('acceptedTypeGroups'))) .thenAnswer((_) async => null); when(mockFileSelectorPlatform.openFiles( acceptedTypeGroups: anyNamed('acceptedTypeGroups'))) .thenAnswer((_) async => List<XFile>.empty()); ImagePickerLinux.fileSelector = mockFileSelectorPlatform; }); test('registered instance', () { ImagePickerLinux.registerWith(); expect(ImagePickerPlatform.instance, isA<ImagePickerLinux>()); }); group('images', () { test('pickImage passes the accepted type groups correctly', () async { await plugin.pickImage(source: ImageSource.gallery); final VerificationResult result = verify(mockFileSelectorPlatform .openFile(acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups'))); expect(capturedTypeGroups(result)[0].mimeTypes, <String>['image/*']); }); test('getImage passes the accepted type groups correctly', () async { await plugin.getImage(source: ImageSource.gallery); final VerificationResult result = verify(mockFileSelectorPlatform .openFile(acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups'))); expect(capturedTypeGroups(result)[0].mimeTypes, <String>['image/*']); }); test('getImageFromSource passes the accepted type groups correctly', () async { await plugin.getImageFromSource(source: ImageSource.gallery); final VerificationResult result = verify(mockFileSelectorPlatform .openFile(acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups'))); expect(capturedTypeGroups(result)[0].mimeTypes, <String>['image/*']); }); test('getImageFromSource calls delegate when source is camera', () async { const String fakePath = '/tmp/foo'; plugin.cameraDelegate = FakeCameraDelegate(result: XFile(fakePath)); expect( (await plugin.getImageFromSource(source: ImageSource.camera))!.path, fakePath); }); test( 'getImageFromSource throws StateError when source is camera with no delegate', () async { await expectLater(plugin.getImageFromSource(source: ImageSource.camera), throwsStateError); }); test('getMultiImage passes the accepted type groups correctly', () async { await plugin.getMultiImage(); final VerificationResult result = verify( mockFileSelectorPlatform.openFiles( acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups'))); expect(capturedTypeGroups(result)[0].mimeTypes, <String>['image/*']); }); }); group('videos', () { test('pickVideo passes the accepted type groups correctly', () async { await plugin.pickVideo(source: ImageSource.gallery); final VerificationResult result = verify(mockFileSelectorPlatform .openFile(acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups'))); expect(capturedTypeGroups(result)[0].mimeTypes, <String>['video/*']); }); test('getVideo passes the accepted type groups correctly', () async { await plugin.getVideo(source: ImageSource.gallery); final VerificationResult result = verify(mockFileSelectorPlatform .openFile(acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups'))); expect(capturedTypeGroups(result)[0].mimeTypes, <String>['video/*']); }); test('getVideo calls delegate when source is camera', () async { const String fakePath = '/tmp/foo'; plugin.cameraDelegate = FakeCameraDelegate(result: XFile(fakePath)); expect( (await plugin.getVideo(source: ImageSource.camera))!.path, fakePath); }); test('getVideo throws StateError when source is camera with no delegate', () async { await expectLater( plugin.getVideo(source: ImageSource.camera), throwsStateError); }); }); group('media', () { test('getMedia passes the accepted type groups correctly', () async { await plugin.getMedia(options: const MediaOptions(allowMultiple: true)); final VerificationResult result = verify( mockFileSelectorPlatform.openFiles( acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups'))); expect(capturedTypeGroups(result)[0].extensions, <String>['image/*', 'video/*']); }); test('multiple media handles an empty path response gracefully', () async { expect( await plugin.getMedia( options: const MediaOptions( allowMultiple: true, ), ), <String>[]); }); test('single media handles an empty path response gracefully', () async { expect( await plugin.getMedia( options: const MediaOptions( allowMultiple: false, ), ), <String>[]); }); }); } class FakeCameraDelegate extends ImagePickerCameraDelegate { FakeCameraDelegate({this.result}); XFile? result; @override Future<XFile?> takePhoto( {ImagePickerCameraDelegateOptions options = const ImagePickerCameraDelegateOptions()}) async { return result; } @override Future<XFile?> takeVideo( {ImagePickerCameraDelegateOptions options = const ImagePickerCameraDelegateOptions()}) async { return result; } }
packages/packages/image_picker/image_picker_linux/test/image_picker_linux_test.dart/0
{ "file_path": "packages/packages/image_picker/image_picker_linux/test/image_picker_linux_test.dart", "repo_id": "packages", "token_count": 2291 }
960
// 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.inapppurchase; import android.content.Context; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.android.billingclient.api.BillingClient; import com.android.billingclient.api.UserChoiceBillingListener; import io.flutter.Log; import io.flutter.plugin.common.MethodChannel; import io.flutter.plugins.inapppurchase.MethodCallHandlerImpl.BillingChoiceMode; /** The implementation for {@link BillingClientFactory} for the plugin. */ final class BillingClientFactoryImpl implements BillingClientFactory { @Override public BillingClient createBillingClient( @NonNull Context context, @NonNull MethodChannel channel, int billingChoiceMode, @Nullable UserChoiceBillingListener userChoiceBillingListener) { BillingClient.Builder builder = BillingClient.newBuilder(context).enablePendingPurchases(); switch (billingChoiceMode) { case BillingChoiceMode.ALTERNATIVE_BILLING_ONLY: // https://developer.android.com/google/play/billing/alternative/alternative-billing-without-user-choice-in-app builder.enableAlternativeBillingOnly(); break; case BillingChoiceMode.USER_CHOICE_BILLING: if (userChoiceBillingListener != null) { // https://developer.android.com/google/play/billing/alternative/alternative-billing-with-user-choice-in-app builder.enableUserChoiceBilling(userChoiceBillingListener); } else { Log.e( "BillingClientFactoryImpl", "userChoiceBillingListener null when USER_CHOICE_BILLING set. Defaulting to PLAY_BILLING_ONLY"); } break; case BillingChoiceMode.PLAY_BILLING_ONLY: // Do nothing. break; default: Log.e( "BillingClientFactoryImpl", "Unknown BillingChoiceMode " + billingChoiceMode + ", Defaulting to PLAY_BILLING_ONLY"); break; } return builder.setListener(new PluginPurchaseListener(channel)).build(); } }
packages/packages/in_app_purchase/in_app_purchase_android/android/src/main/java/io/flutter/plugins/inapppurchase/BillingClientFactoryImpl.java/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_android/android/src/main/java/io/flutter/plugins/inapppurchase/BillingClientFactoryImpl.java", "repo_id": "packages", "token_count": 775 }
961
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'billing_response_wrapper.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** BillingResultWrapper _$BillingResultWrapperFromJson(Map json) => BillingResultWrapper( responseCode: const BillingResponseConverter() .fromJson(json['responseCode'] as int?), debugMessage: json['debugMessage'] as String?, );
packages/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/billing_response_wrapper.g.dart/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/billing_response_wrapper.g.dart", "repo_id": "packages", "token_count": 145 }
962
// 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/services.dart'; import 'package:flutter/widgets.dart' as widgets; import 'package:flutter_test/flutter_test.dart'; import 'package:in_app_purchase_android/billing_client_wrappers.dart'; import 'package:in_app_purchase_android/in_app_purchase_android.dart'; import 'package:in_app_purchase_android/src/channel.dart'; import 'package:in_app_purchase_platform_interface/in_app_purchase_platform_interface.dart'; import 'billing_client_wrappers/product_details_wrapper_test.dart'; import 'billing_client_wrappers/purchase_wrapper_test.dart'; import 'stub_in_app_purchase_platform.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); final StubInAppPurchasePlatform stubPlatform = StubInAppPurchasePlatform(); late InAppPurchaseAndroidPlatform iapAndroidPlatform; const String startConnectionCall = 'BillingClient#startConnection(BillingClientStateListener)'; const String endConnectionCall = 'BillingClient#endConnection()'; const String acknowledgePurchaseCall = 'BillingClient#acknowledgePurchase(AcknowledgePurchaseParams, AcknowledgePurchaseResponseListener)'; const String onBillingServiceDisconnectedCallback = 'BillingClientStateListener#onBillingServiceDisconnected()'; setUpAll(() { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockMethodCallHandler(channel, stubPlatform.fakeMethodCallHandler); }); setUp(() { widgets.WidgetsFlutterBinding.ensureInitialized(); const String debugMessage = 'dummy message'; const BillingResponse responseCode = BillingResponse.ok; const BillingResultWrapper expectedBillingResult = BillingResultWrapper( responseCode: responseCode, debugMessage: debugMessage); stubPlatform.addResponse( name: startConnectionCall, value: buildBillingResultMap(expectedBillingResult)); stubPlatform.addResponse(name: endConnectionCall); InAppPurchaseAndroidPlatform.registerPlatform(); iapAndroidPlatform = InAppPurchasePlatform.instance as InAppPurchaseAndroidPlatform; }); tearDown(() { stubPlatform.reset(); }); group('connection management', () { test('connects on initialization', () { //await iapAndroidPlatform.isAvailable(); expect(stubPlatform.countPreviousCalls(startConnectionCall), equals(1)); }); test('re-connects when client sends onBillingServiceDisconnected', () { iapAndroidPlatform.billingClientManager.client.callHandler( const MethodCall(onBillingServiceDisconnectedCallback, <String, dynamic>{'handle': 0}), ); expect(stubPlatform.countPreviousCalls(startConnectionCall), equals(2)); }); test( 're-connects when operation returns BillingResponse.clientDisconnected', () async { final Map<String, dynamic> okValue = buildBillingResultMap( const BillingResultWrapper(responseCode: BillingResponse.ok)); stubPlatform.addResponse( name: acknowledgePurchaseCall, value: buildBillingResultMap( const BillingResultWrapper( responseCode: BillingResponse.serviceDisconnected, ), ), ); stubPlatform.addResponse( name: startConnectionCall, value: okValue, additionalStepBeforeReturn: (dynamic _) => stubPlatform.addResponse( name: acknowledgePurchaseCall, value: okValue), ); final PurchaseDetails purchase = GooglePlayPurchaseDetails.fromPurchase(dummyUnacknowledgedPurchase) .first; final BillingResultWrapper result = await iapAndroidPlatform.completePurchase(purchase); expect( stubPlatform.countPreviousCalls(acknowledgePurchaseCall), equals(2), ); expect(stubPlatform.countPreviousCalls(startConnectionCall), equals(2)); expect(result.responseCode, equals(BillingResponse.ok)); }); }); group('isAvailable', () { test('true', () async { stubPlatform.addResponse(name: 'BillingClient#isReady()', value: true); expect(await iapAndroidPlatform.isAvailable(), isTrue); }); test('false', () async { stubPlatform.addResponse(name: 'BillingClient#isReady()', value: false); expect(await iapAndroidPlatform.isAvailable(), isFalse); }); }); group('queryProductDetails', () { const String queryMethodName = 'BillingClient#queryProductDetailsAsync(QueryProductDetailsParams, ProductDetailsResponseListener)'; test('handles empty productDetails', () async { const String debugMessage = 'dummy message'; const BillingResponse responseCode = BillingResponse.ok; const BillingResultWrapper expectedBillingResult = BillingResultWrapper( responseCode: responseCode, debugMessage: debugMessage); stubPlatform.addResponse(name: queryMethodName, value: <String, dynamic>{ 'billingResult': buildBillingResultMap(expectedBillingResult), 'productDetailsList': <Map<String, dynamic>>[], }); final ProductDetailsResponse response = await iapAndroidPlatform.queryProductDetails(<String>{''}); expect(response.productDetails, isEmpty); }); test('should get correct product details', () async { const String debugMessage = 'dummy message'; const BillingResponse responseCode = BillingResponse.ok; const BillingResultWrapper expectedBillingResult = BillingResultWrapper( responseCode: responseCode, debugMessage: debugMessage); stubPlatform.addResponse(name: queryMethodName, value: <String, dynamic>{ 'billingResult': buildBillingResultMap(expectedBillingResult), 'productDetailsList': <Map<String, dynamic>>[ buildProductMap(dummyOneTimeProductDetails) ] }); // Since queryProductDetails makes 2 platform method calls (one for each ProductType), the result will contain 2 dummyWrapper instead // of 1. final ProductDetailsResponse response = await iapAndroidPlatform.queryProductDetails(<String>{'valid'}); expect(response.productDetails.first.title, dummyOneTimeProductDetails.title); expect(response.productDetails.first.description, dummyOneTimeProductDetails.description); expect( response.productDetails.first.price, dummyOneTimeProductDetails .oneTimePurchaseOfferDetails?.formattedPrice); expect(response.productDetails.first.currencySymbol, r'$'); }); test('should get the correct notFoundIDs', () async { const String debugMessage = 'dummy message'; const BillingResponse responseCode = BillingResponse.ok; const BillingResultWrapper expectedBillingResult = BillingResultWrapper( responseCode: responseCode, debugMessage: debugMessage); stubPlatform.addResponse(name: queryMethodName, value: <String, dynamic>{ 'billingResult': buildBillingResultMap(expectedBillingResult), 'productDetailsList': <Map<String, dynamic>>[ buildProductMap(dummyOneTimeProductDetails) ] }); // Since queryProductDetails makes 2 platform method calls (one for each ProductType), the result will contain 2 dummyWrapper instead // of 1. final ProductDetailsResponse response = await iapAndroidPlatform.queryProductDetails(<String>{'invalid'}); expect(response.notFoundIDs.first, 'invalid'); }); test( 'should have error stored in the response when platform exception is thrown', () async { const BillingResponse responseCode = BillingResponse.ok; stubPlatform.addResponse( name: queryMethodName, value: <String, dynamic>{ 'responseCode': const BillingResponseConverter().toJson(responseCode), 'productDetailsList': <Map<String, dynamic>>[ buildProductMap(dummyOneTimeProductDetails) ] }, additionalStepBeforeReturn: (dynamic _) { throw PlatformException( code: 'error_code', message: 'error_message', details: <dynamic, dynamic>{'info': 'error_info'}, ); }); // Since queryProductDetails makes 2 platform method calls (one for each ProductType), the result will contain 2 dummyWrapper instead // of 1. final ProductDetailsResponse response = await iapAndroidPlatform.queryProductDetails(<String>{'invalid'}); expect(response.notFoundIDs, <String>['invalid']); expect(response.productDetails, isEmpty); expect(response.error, isNotNull); expect(response.error!.source, kIAPSource); expect(response.error!.code, 'error_code'); expect(response.error!.message, 'error_message'); expect(response.error!.details, <String, dynamic>{'info': 'error_info'}); }); }); group('restorePurchases', () { const String queryMethodName = 'BillingClient#queryPurchasesAsync(QueryPurchaseParams, PurchaseResponseListener)'; test('handles error', () async { const String debugMessage = 'dummy message'; const BillingResponse responseCode = BillingResponse.developerError; const BillingResultWrapper expectedBillingResult = BillingResultWrapper( responseCode: responseCode, debugMessage: debugMessage); stubPlatform.addResponse(name: queryMethodName, value: <dynamic, dynamic>{ 'billingResult': buildBillingResultMap(expectedBillingResult), 'responseCode': const BillingResponseConverter().toJson(responseCode), 'purchasesList': <Map<String, dynamic>>[] }); expect( iapAndroidPlatform.restorePurchases(), throwsA( isA<InAppPurchaseException>() .having( (InAppPurchaseException e) => e.source, 'source', kIAPSource) .having((InAppPurchaseException e) => e.code, 'code', kRestoredPurchaseErrorCode) .having((InAppPurchaseException e) => e.message, 'message', responseCode.toString()), ), ); }); test('should store platform exception in the response', () async { const String debugMessage = 'dummy message'; const BillingResponse responseCode = BillingResponse.developerError; const BillingResultWrapper expectedBillingResult = BillingResultWrapper( responseCode: responseCode, debugMessage: debugMessage); stubPlatform.addResponse( name: queryMethodName, value: <dynamic, dynamic>{ 'responseCode': const BillingResponseConverter().toJson(responseCode), 'billingResult': buildBillingResultMap(expectedBillingResult), 'purchasesList': <Map<String, dynamic>>[] }, additionalStepBeforeReturn: (dynamic _) { throw PlatformException( code: 'error_code', message: 'error_message', details: <dynamic, dynamic>{'info': 'error_info'}, ); }); expect( iapAndroidPlatform.restorePurchases(), throwsA( isA<PlatformException>() .having((PlatformException e) => e.code, 'code', 'error_code') .having((PlatformException e) => e.message, 'message', 'error_message') .having((PlatformException e) => e.details, 'details', <String, dynamic>{'info': 'error_info'}), ), ); }); test('returns ProductDetailsResponseWrapper', () async { final Completer<List<PurchaseDetails>> completer = Completer<List<PurchaseDetails>>(); final Stream<List<PurchaseDetails>> stream = iapAndroidPlatform.purchaseStream; late StreamSubscription<List<PurchaseDetails>> subscription; subscription = stream.listen((List<PurchaseDetails> purchaseDetailsList) { if (purchaseDetailsList.first.status == PurchaseStatus.restored) { completer.complete(purchaseDetailsList); subscription.cancel(); } }); const String debugMessage = 'dummy message'; const BillingResponse responseCode = BillingResponse.ok; const BillingResultWrapper expectedBillingResult = BillingResultWrapper( responseCode: responseCode, debugMessage: debugMessage); stubPlatform.addResponse(name: queryMethodName, value: <String, dynamic>{ 'billingResult': buildBillingResultMap(expectedBillingResult), 'responseCode': const BillingResponseConverter().toJson(responseCode), 'purchasesList': <Map<String, dynamic>>[ buildPurchaseMap(dummyPurchase), ] }); // Since queryPastPurchases makes 2 platform method calls (one for each // ProductType), the result will contain 2 dummyPurchase instances instead // of 1. await iapAndroidPlatform.restorePurchases(); final List<PurchaseDetails> restoredPurchases = await completer.future; expect(restoredPurchases.length, 2); for (final PurchaseDetails element in restoredPurchases) { final GooglePlayPurchaseDetails purchase = element as GooglePlayPurchaseDetails; expect(purchase.productID, dummyPurchase.products.first); expect(purchase.purchaseID, dummyPurchase.orderId); expect(purchase.verificationData.localVerificationData, dummyPurchase.originalJson); expect(purchase.verificationData.serverVerificationData, dummyPurchase.purchaseToken); expect(purchase.verificationData.source, kIAPSource); expect(purchase.transactionDate, dummyPurchase.purchaseTime.toString()); expect(purchase.billingClientPurchase, dummyPurchase); expect(purchase.status, PurchaseStatus.restored); } }); }); group('make payment', () { const String launchMethodName = 'BillingClient#launchBillingFlow(Activity, BillingFlowParams)'; const String consumeMethodName = 'BillingClient#consumeAsync(ConsumeParams, ConsumeResponseListener)'; test('buy non consumable, serializes and deserializes data', () async { const ProductDetailsWrapper productDetails = dummyOneTimeProductDetails; const String accountId = 'hashedAccountId'; const String debugMessage = 'dummy message'; const BillingResponse sentCode = BillingResponse.ok; const BillingResultWrapper expectedBillingResult = BillingResultWrapper( responseCode: sentCode, debugMessage: debugMessage); stubPlatform.addResponse( name: launchMethodName, value: buildBillingResultMap(expectedBillingResult), additionalStepBeforeReturn: (dynamic _) { // Mock java update purchase callback. final MethodCall call = MethodCall(kOnPurchasesUpdated, <dynamic, dynamic>{ 'billingResult': buildBillingResultMap(expectedBillingResult), 'responseCode': const BillingResponseConverter().toJson(sentCode), 'purchasesList': <dynamic>[ <dynamic, dynamic>{ 'orderId': 'orderID1', 'products': <String>[productDetails.productId], 'isAutoRenewing': false, 'packageName': 'package', 'purchaseTime': 1231231231, 'purchaseToken': 'token', 'signature': 'sign', 'originalJson': 'json', 'developerPayload': 'dummy payload', 'isAcknowledged': true, 'purchaseState': 1, } ] }); iapAndroidPlatform.billingClientManager.client.callHandler(call); }); final Completer<PurchaseDetails> completer = Completer<PurchaseDetails>(); PurchaseDetails purchaseDetails; final Stream<List<PurchaseDetails>> purchaseStream = iapAndroidPlatform.purchaseStream; late StreamSubscription<List<PurchaseDetails>> subscription; subscription = purchaseStream.listen((List<PurchaseDetails> details) { purchaseDetails = details.first; completer.complete(purchaseDetails); subscription.cancel(); }, onDone: () {}); final GooglePlayPurchaseParam purchaseParam = GooglePlayPurchaseParam( productDetails: GooglePlayProductDetails.fromProductDetails(productDetails).first, applicationUserName: accountId); final bool launchResult = await iapAndroidPlatform.buyNonConsumable( purchaseParam: purchaseParam); final PurchaseDetails result = await completer.future; expect(launchResult, isTrue); expect(result.purchaseID, 'orderID1'); expect(result.status, PurchaseStatus.purchased); expect(result.productID, productDetails.productId); }); test('handles an error with an empty purchases list', () async { const ProductDetailsWrapper productDetails = dummyOneTimeProductDetails; const String accountId = 'hashedAccountId'; const String debugMessage = 'dummy message'; const BillingResponse sentCode = BillingResponse.error; const BillingResultWrapper expectedBillingResult = BillingResultWrapper( responseCode: sentCode, debugMessage: debugMessage); stubPlatform.addResponse( name: launchMethodName, value: buildBillingResultMap(expectedBillingResult), additionalStepBeforeReturn: (dynamic _) { // Mock java update purchase callback. final MethodCall call = MethodCall(kOnPurchasesUpdated, <dynamic, dynamic>{ 'billingResult': buildBillingResultMap(expectedBillingResult), 'responseCode': const BillingResponseConverter().toJson(sentCode), 'purchasesList': const <dynamic>[] }); iapAndroidPlatform.billingClientManager.client.callHandler(call); }); final Completer<PurchaseDetails> completer = Completer<PurchaseDetails>(); PurchaseDetails purchaseDetails; final Stream<List<PurchaseDetails>> purchaseStream = iapAndroidPlatform.purchaseStream; late StreamSubscription<List<PurchaseDetails>> subscription; subscription = purchaseStream.listen((List<PurchaseDetails> details) { purchaseDetails = details.first; completer.complete(purchaseDetails); subscription.cancel(); }, onDone: () {}); final GooglePlayPurchaseParam purchaseParam = GooglePlayPurchaseParam( productDetails: GooglePlayProductDetails.fromProductDetails(productDetails).first, applicationUserName: accountId); await iapAndroidPlatform.buyNonConsumable(purchaseParam: purchaseParam); final PurchaseDetails result = await completer.future; expect(result.error, isNotNull); expect(result.error!.source, kIAPSource); expect(result.status, PurchaseStatus.error); expect(result.purchaseID, isEmpty); }); test('buy consumable with auto consume, serializes and deserializes data', () async { const ProductDetailsWrapper productDetails = dummyOneTimeProductDetails; const String accountId = 'hashedAccountId'; const String debugMessage = 'dummy message'; const BillingResponse sentCode = BillingResponse.ok; const BillingResultWrapper expectedBillingResult = BillingResultWrapper( responseCode: sentCode, debugMessage: debugMessage); stubPlatform.addResponse( name: launchMethodName, value: buildBillingResultMap(expectedBillingResult), additionalStepBeforeReturn: (dynamic _) { // Mock java update purchase callback. final MethodCall call = MethodCall(kOnPurchasesUpdated, <dynamic, dynamic>{ 'billingResult': buildBillingResultMap(expectedBillingResult), 'responseCode': const BillingResponseConverter().toJson(sentCode), 'purchasesList': <dynamic>[ <dynamic, dynamic>{ 'orderId': 'orderID1', 'products': <String>[productDetails.productId], 'isAutoRenewing': false, 'packageName': 'package', 'purchaseTime': 1231231231, 'purchaseToken': 'token', 'signature': 'sign', 'originalJson': 'json', 'developerPayload': 'dummy payload', 'isAcknowledged': true, 'purchaseState': 1, } ] }); iapAndroidPlatform.billingClientManager.client.callHandler(call); }); final Completer<String> consumeCompleter = Completer<String>(); // adding call back for consume purchase const BillingResponse expectedCode = BillingResponse.ok; const BillingResultWrapper expectedBillingResultForConsume = BillingResultWrapper( responseCode: expectedCode, debugMessage: debugMessage); stubPlatform.addResponse( name: consumeMethodName, value: buildBillingResultMap(expectedBillingResultForConsume), additionalStepBeforeReturn: (dynamic args) { final String purchaseToken = (args as Map<Object?, Object?>)['purchaseToken']! as String; consumeCompleter.complete(purchaseToken); }); final Completer<PurchaseDetails> completer = Completer<PurchaseDetails>(); PurchaseDetails purchaseDetails; final Stream<List<PurchaseDetails>> purchaseStream = iapAndroidPlatform.purchaseStream; late StreamSubscription<List<PurchaseDetails>> subscription; subscription = purchaseStream.listen((List<PurchaseDetails> details) { purchaseDetails = details.first; completer.complete(purchaseDetails); subscription.cancel(); }, onDone: () {}); final GooglePlayPurchaseParam purchaseParam = GooglePlayPurchaseParam( productDetails: GooglePlayProductDetails.fromProductDetails(productDetails).first, applicationUserName: accountId); final bool launchResult = await iapAndroidPlatform.buyConsumable(purchaseParam: purchaseParam); // Verify that the result has succeeded final GooglePlayPurchaseDetails result = await completer.future as GooglePlayPurchaseDetails; expect(launchResult, isTrue); expect(result.billingClientPurchase, isNotNull); expect(result.billingClientPurchase.purchaseToken, await consumeCompleter.future); expect(result.status, PurchaseStatus.purchased); expect(result.error, isNull); }); test('buyNonConsumable propagates failures to launch the billing flow', () async { const String debugMessage = 'dummy message'; const BillingResponse sentCode = BillingResponse.error; const BillingResultWrapper expectedBillingResult = BillingResultWrapper( responseCode: sentCode, debugMessage: debugMessage); stubPlatform.addResponse( name: launchMethodName, value: buildBillingResultMap(expectedBillingResult)); final bool result = await iapAndroidPlatform.buyNonConsumable( purchaseParam: GooglePlayPurchaseParam( productDetails: GooglePlayProductDetails.fromProductDetails( dummyOneTimeProductDetails) .first)); // Verify that the failure has been converted and returned expect(result, isFalse); }); test('buyConsumable propagates failures to launch the billing flow', () async { const String debugMessage = 'dummy message'; const BillingResponse sentCode = BillingResponse.developerError; const BillingResultWrapper expectedBillingResult = BillingResultWrapper( responseCode: sentCode, debugMessage: debugMessage); stubPlatform.addResponse( name: launchMethodName, value: buildBillingResultMap(expectedBillingResult), ); final bool result = await iapAndroidPlatform.buyConsumable( purchaseParam: GooglePlayPurchaseParam( productDetails: GooglePlayProductDetails.fromProductDetails( dummyOneTimeProductDetails) .first)); // Verify that the failure has been converted and returned expect(result, isFalse); }); test('adds consumption failures to PurchaseDetails objects', () async { const ProductDetailsWrapper productDetails = dummyOneTimeProductDetails; const String accountId = 'hashedAccountId'; const String debugMessage = 'dummy message'; const BillingResponse sentCode = BillingResponse.ok; const BillingResultWrapper expectedBillingResult = BillingResultWrapper( responseCode: sentCode, debugMessage: debugMessage); stubPlatform.addResponse( name: launchMethodName, value: buildBillingResultMap(expectedBillingResult), additionalStepBeforeReturn: (dynamic _) { // Mock java update purchase callback. final MethodCall call = MethodCall(kOnPurchasesUpdated, <dynamic, dynamic>{ 'billingResult': buildBillingResultMap(expectedBillingResult), 'responseCode': const BillingResponseConverter().toJson(sentCode), 'purchasesList': <dynamic>[ <dynamic, dynamic>{ 'orderId': 'orderID1', 'products': <String>[productDetails.productId], 'isAutoRenewing': false, 'packageName': 'package', 'purchaseTime': 1231231231, 'purchaseToken': 'token', 'signature': 'sign', 'originalJson': 'json', 'developerPayload': 'dummy payload', 'isAcknowledged': true, 'purchaseState': 1, } ] }); iapAndroidPlatform.billingClientManager.client.callHandler(call); }); final Completer<String> consumeCompleter = Completer<String>(); // adding call back for consume purchase const BillingResponse expectedCode = BillingResponse.error; const BillingResultWrapper expectedBillingResultForConsume = BillingResultWrapper( responseCode: expectedCode, debugMessage: debugMessage); stubPlatform.addResponse( name: consumeMethodName, value: buildBillingResultMap(expectedBillingResultForConsume), additionalStepBeforeReturn: (dynamic args) { final String purchaseToken = (args as Map<Object?, Object?>)['purchaseToken']! as String; consumeCompleter.complete(purchaseToken); }); final Completer<PurchaseDetails> completer = Completer<PurchaseDetails>(); PurchaseDetails purchaseDetails; final Stream<List<PurchaseDetails>> purchaseStream = iapAndroidPlatform.purchaseStream; late StreamSubscription<List<PurchaseDetails>> subscription; subscription = purchaseStream.listen((List<PurchaseDetails> details) { purchaseDetails = details.first; completer.complete(purchaseDetails); subscription.cancel(); }, onDone: () {}); final GooglePlayPurchaseParam purchaseParam = GooglePlayPurchaseParam( productDetails: GooglePlayProductDetails.fromProductDetails(productDetails).first, applicationUserName: accountId); await iapAndroidPlatform.buyConsumable(purchaseParam: purchaseParam); // Verify that the result has an error for the failed consumption final GooglePlayPurchaseDetails result = await completer.future as GooglePlayPurchaseDetails; expect(result.billingClientPurchase, isNotNull); expect(result.billingClientPurchase.purchaseToken, await consumeCompleter.future); expect(result.status, PurchaseStatus.error); expect(result.error, isNotNull); expect(result.error!.code, kConsumptionFailedErrorCode); }); test( 'buy consumable without auto consume, consume api should not receive calls', () async { const ProductDetailsWrapper productDetails = dummyOneTimeProductDetails; const String accountId = 'hashedAccountId'; const String debugMessage = 'dummy message'; const BillingResponse sentCode = BillingResponse.developerError; const BillingResultWrapper expectedBillingResult = BillingResultWrapper( responseCode: sentCode, debugMessage: debugMessage); stubPlatform.addResponse( name: launchMethodName, value: buildBillingResultMap(expectedBillingResult), additionalStepBeforeReturn: (dynamic _) { // Mock java update purchase callback. final MethodCall call = MethodCall(kOnPurchasesUpdated, <dynamic, dynamic>{ 'billingResult': buildBillingResultMap(expectedBillingResult), 'responseCode': const BillingResponseConverter().toJson(sentCode), 'purchasesList': <dynamic>[ <dynamic, dynamic>{ 'orderId': 'orderID1', 'products': <String>[productDetails.productId], 'isAutoRenewing': false, 'packageName': 'package', 'purchaseTime': 1231231231, 'purchaseToken': 'token', 'signature': 'sign', 'originalJson': 'json', 'developerPayload': 'dummy payload', 'isAcknowledged': true, 'purchaseState': 1, } ] }); iapAndroidPlatform.billingClientManager.client.callHandler(call); }); final Completer<String?> consumeCompleter = Completer<String?>(); // adding call back for consume purchase const BillingResponse expectedCode = BillingResponse.ok; const BillingResultWrapper expectedBillingResultForConsume = BillingResultWrapper( responseCode: expectedCode, debugMessage: debugMessage); stubPlatform.addResponse( name: consumeMethodName, value: buildBillingResultMap(expectedBillingResultForConsume), additionalStepBeforeReturn: (dynamic args) { final String purchaseToken = (args as Map<Object?, Object?>)['purchaseToken']! as String; consumeCompleter.complete(purchaseToken); }); final Stream<List<PurchaseDetails>> purchaseStream = iapAndroidPlatform.purchaseStream; late StreamSubscription<List<PurchaseDetails>> subscription; subscription = purchaseStream.listen((_) { consumeCompleter.complete(null); subscription.cancel(); }, onDone: () {}); final GooglePlayPurchaseParam purchaseParam = GooglePlayPurchaseParam( productDetails: GooglePlayProductDetails.fromProductDetails(productDetails).first, applicationUserName: accountId); await iapAndroidPlatform.buyConsumable( purchaseParam: purchaseParam, autoConsume: false); expect(null, await consumeCompleter.future); }); test( 'should get canceled purchase status when response code is BillingResponse.userCanceled', () async { const ProductDetailsWrapper productDetails = dummyOneTimeProductDetails; const String accountId = 'hashedAccountId'; const String debugMessage = 'dummy message'; const BillingResponse sentCode = BillingResponse.userCanceled; const BillingResultWrapper expectedBillingResult = BillingResultWrapper( responseCode: sentCode, debugMessage: debugMessage); stubPlatform.addResponse( name: launchMethodName, value: buildBillingResultMap(expectedBillingResult), additionalStepBeforeReturn: (dynamic _) { // Mock java update purchase callback. final MethodCall call = MethodCall(kOnPurchasesUpdated, <dynamic, dynamic>{ 'billingResult': buildBillingResultMap(expectedBillingResult), 'responseCode': const BillingResponseConverter().toJson(sentCode), 'purchasesList': <dynamic>[ <dynamic, dynamic>{ 'orderId': 'orderID1', 'products': <String>[productDetails.productId], 'isAutoRenewing': false, 'packageName': 'package', 'purchaseTime': 1231231231, 'purchaseToken': 'token', 'signature': 'sign', 'originalJson': 'json', 'developerPayload': 'dummy payload', 'isAcknowledged': true, 'purchaseState': 1, } ] }); iapAndroidPlatform.billingClientManager.client.callHandler(call); }); final Completer<String> consumeCompleter = Completer<String>(); // adding call back for consume purchase const BillingResponse expectedCode = BillingResponse.userCanceled; const BillingResultWrapper expectedBillingResultForConsume = BillingResultWrapper( responseCode: expectedCode, debugMessage: debugMessage); stubPlatform.addResponse( name: consumeMethodName, value: buildBillingResultMap(expectedBillingResultForConsume), additionalStepBeforeReturn: (dynamic args) { final String purchaseToken = (args as Map<Object?, Object?>)['purchaseToken']! as String; consumeCompleter.complete(purchaseToken); }); final Completer<PurchaseDetails> completer = Completer<PurchaseDetails>(); PurchaseDetails purchaseDetails; final Stream<List<PurchaseDetails>> purchaseStream = iapAndroidPlatform.purchaseStream; late StreamSubscription<List<PurchaseDetails>> subscription; subscription = purchaseStream.listen((List<PurchaseDetails> details) { purchaseDetails = details.first; completer.complete(purchaseDetails); subscription.cancel(); }, onDone: () {}); final GooglePlayPurchaseParam purchaseParam = GooglePlayPurchaseParam( productDetails: GooglePlayProductDetails.fromProductDetails(productDetails).first, applicationUserName: accountId); await iapAndroidPlatform.buyConsumable(purchaseParam: purchaseParam); // Verify that the result has an error for the failed consumption final GooglePlayPurchaseDetails result = await completer.future as GooglePlayPurchaseDetails; expect(result.status, PurchaseStatus.canceled); }); test( 'should get purchased purchase status when upgrading subscription by deferred proration mode', () async { const ProductDetailsWrapper productDetails = dummyOneTimeProductDetails; const String accountId = 'hashedAccountId'; const String debugMessage = 'dummy message'; const BillingResponse sentCode = BillingResponse.ok; const BillingResultWrapper expectedBillingResult = BillingResultWrapper( responseCode: sentCode, debugMessage: debugMessage); stubPlatform.addResponse( name: launchMethodName, value: buildBillingResultMap(expectedBillingResult), additionalStepBeforeReturn: (dynamic _) { // Mock java update purchase callback. final MethodCall call = MethodCall(kOnPurchasesUpdated, <dynamic, dynamic>{ 'billingResult': buildBillingResultMap(expectedBillingResult), 'responseCode': const BillingResponseConverter().toJson(sentCode), 'purchasesList': const <dynamic>[] }); iapAndroidPlatform.billingClientManager.client.callHandler(call); }); final Completer<PurchaseDetails> completer = Completer<PurchaseDetails>(); PurchaseDetails purchaseDetails; final Stream<List<PurchaseDetails>> purchaseStream = iapAndroidPlatform.purchaseStream; late StreamSubscription<List<PurchaseDetails>> subscription; subscription = purchaseStream.listen((List<PurchaseDetails> details) { purchaseDetails = details.first; completer.complete(purchaseDetails); subscription.cancel(); }, onDone: () {}); final GooglePlayPurchaseParam purchaseParam = GooglePlayPurchaseParam( productDetails: GooglePlayProductDetails.fromProductDetails(productDetails).first, applicationUserName: accountId, changeSubscriptionParam: ChangeSubscriptionParam( oldPurchaseDetails: GooglePlayPurchaseDetails.fromPurchase( dummyUnacknowledgedPurchase) .first, prorationMode: ProrationMode.deferred, )); await iapAndroidPlatform.buyNonConsumable(purchaseParam: purchaseParam); final PurchaseDetails result = await completer.future; expect(result.status, PurchaseStatus.purchased); }); }); group('complete purchase', () { const String completeMethodName = 'BillingClient#acknowledgePurchase(AcknowledgePurchaseParams, AcknowledgePurchaseResponseListener)'; test('complete purchase success', () async { const BillingResponse expectedCode = BillingResponse.ok; const String debugMessage = 'dummy message'; const BillingResultWrapper expectedBillingResult = BillingResultWrapper( responseCode: expectedCode, debugMessage: debugMessage); stubPlatform.addResponse( name: completeMethodName, value: buildBillingResultMap(expectedBillingResult), ); final PurchaseDetails purchaseDetails = GooglePlayPurchaseDetails.fromPurchase(dummyUnacknowledgedPurchase) .first; final Completer<BillingResultWrapper> completer = Completer<BillingResultWrapper>(); purchaseDetails.status = PurchaseStatus.purchased; if (purchaseDetails.pendingCompletePurchase) { final BillingResultWrapper billingResultWrapper = await iapAndroidPlatform.completePurchase(purchaseDetails); expect(billingResultWrapper, equals(expectedBillingResult)); completer.complete(billingResultWrapper); } expect(await completer.future, equals(expectedBillingResult)); }); }); }
packages/packages/in_app_purchase/in_app_purchase_android/test/in_app_purchase_android_platform_test.dart/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_android/test/in_app_purchase_android_platform_test.dart", "repo_id": "packages", "token_count": 14810 }
963
// 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 "FIAObjectTranslator.h" #pragma mark - SKProduct Coders @implementation FIAObjectTranslator + (NSDictionary *)getMapFromSKProduct:(SKProduct *)product { if (!product) { return nil; } NSMutableDictionary *map = [[NSMutableDictionary alloc] initWithDictionary:@{ @"localizedDescription" : product.localizedDescription ?: [NSNull null], @"localizedTitle" : product.localizedTitle ?: [NSNull null], @"productIdentifier" : product.productIdentifier ?: [NSNull null], @"price" : product.price.description ?: [NSNull null] }]; // TODO(cyanglaz): NSLocale is a complex object, want to see the actual need of getting this // expanded to a map. Matching android to only get the currencySymbol for now. // https://github.com/flutter/flutter/issues/26610 [map setObject:[FIAObjectTranslator getMapFromNSLocale:product.priceLocale] ?: [NSNull null] forKey:@"priceLocale"]; [map setObject:[FIAObjectTranslator getMapFromSKProductSubscriptionPeriod:product.subscriptionPeriod] ?: [NSNull null] forKey:@"subscriptionPeriod"]; [map setObject:[FIAObjectTranslator getMapFromSKProductDiscount:product.introductoryPrice] ?: [NSNull null] forKey:@"introductoryPrice"]; if (@available(iOS 12.2, *)) { [map setObject:[FIAObjectTranslator getMapArrayFromSKProductDiscounts:product.discounts] forKey:@"discounts"]; } [map setObject:product.subscriptionGroupIdentifier ?: [NSNull null] forKey:@"subscriptionGroupIdentifier"]; return map; } + (NSDictionary *)getMapFromSKProductSubscriptionPeriod:(SKProductSubscriptionPeriod *)period { if (!period) { return nil; } return @{@"numberOfUnits" : @(period.numberOfUnits), @"unit" : @(period.unit)}; } + (nonnull NSArray *)getMapArrayFromSKProductDiscounts: (nonnull NSArray<SKProductDiscount *> *)productDiscounts { NSMutableArray *discountsMapArray = [[NSMutableArray alloc] init]; for (SKProductDiscount *productDiscount in productDiscounts) { [discountsMapArray addObject:[FIAObjectTranslator getMapFromSKProductDiscount:productDiscount]]; } return discountsMapArray; } + (NSDictionary *)getMapFromSKProductDiscount:(SKProductDiscount *)discount { if (!discount) { return nil; } NSMutableDictionary *map = [[NSMutableDictionary alloc] initWithDictionary:@{ @"price" : discount.price.description ?: [NSNull null], @"numberOfPeriods" : @(discount.numberOfPeriods), @"subscriptionPeriod" : [FIAObjectTranslator getMapFromSKProductSubscriptionPeriod:discount.subscriptionPeriod] ?: [NSNull null], @"paymentMode" : @(discount.paymentMode), }]; if (@available(iOS 12.2, *)) { [map setObject:discount.identifier ?: [NSNull null] forKey:@"identifier"]; [map setObject:@(discount.type) forKey:@"type"]; } // TODO(cyanglaz): NSLocale is a complex object, want to see the actual need of getting this // expanded to a map. Matching android to only get the currencySymbol for now. // https://github.com/flutter/flutter/issues/26610 [map setObject:[FIAObjectTranslator getMapFromNSLocale:discount.priceLocale] ?: [NSNull null] forKey:@"priceLocale"]; return map; } + (NSDictionary *)getMapFromSKProductsResponse:(SKProductsResponse *)productResponse { if (!productResponse) { return nil; } NSMutableArray *productsMapArray = [NSMutableArray new]; for (SKProduct *product in productResponse.products) { [productsMapArray addObject:[FIAObjectTranslator getMapFromSKProduct:product]]; } return @{ @"products" : productsMapArray, @"invalidProductIdentifiers" : productResponse.invalidProductIdentifiers ?: @[] }; } + (NSDictionary *)getMapFromSKPayment:(SKPayment *)payment { if (!payment) { return nil; } NSMutableDictionary *map = [[NSMutableDictionary alloc] initWithDictionary:@{ @"productIdentifier" : payment.productIdentifier ?: [NSNull null], @"requestData" : payment.requestData ? [[NSString alloc] initWithData:payment.requestData encoding:NSUTF8StringEncoding] : [NSNull null], @"quantity" : @(payment.quantity), @"applicationUsername" : payment.applicationUsername ?: [NSNull null] }]; [map setObject:@(payment.simulatesAskToBuyInSandbox) forKey:@"simulatesAskToBuyInSandbox"]; return map; } + (NSDictionary *)getMapFromNSLocale:(NSLocale *)locale { if (!locale) { return nil; } NSMutableDictionary *map = [[NSMutableDictionary alloc] init]; [map setObject:[locale objectForKey:NSLocaleCurrencySymbol] ?: [NSNull null] forKey:@"currencySymbol"]; [map setObject:[locale objectForKey:NSLocaleCurrencyCode] ?: [NSNull null] forKey:@"currencyCode"]; [map setObject:[locale objectForKey:NSLocaleCountryCode] ?: [NSNull null] forKey:@"countryCode"]; return map; } + (SKMutablePayment *)getSKMutablePaymentFromMap:(NSDictionary *)map { if (!map) { return nil; } SKMutablePayment *payment = [[SKMutablePayment alloc] init]; payment.productIdentifier = map[@"productIdentifier"]; NSString *utf8String = map[@"requestData"]; payment.requestData = [utf8String dataUsingEncoding:NSUTF8StringEncoding]; payment.quantity = [map[@"quantity"] integerValue]; payment.applicationUsername = map[@"applicationUsername"]; payment.simulatesAskToBuyInSandbox = [map[@"simulatesAskToBuyInSandbox"] boolValue]; return payment; } + (NSDictionary *)getMapFromSKPaymentTransaction:(SKPaymentTransaction *)transaction { if (!transaction) { return nil; } NSMutableDictionary *map = [[NSMutableDictionary alloc] initWithDictionary:@{ @"error" : [FIAObjectTranslator getMapFromNSError:transaction.error] ?: [NSNull null], @"payment" : transaction.payment ? [FIAObjectTranslator getMapFromSKPayment:transaction.payment] : [NSNull null], @"originalTransaction" : transaction.originalTransaction ? [FIAObjectTranslator getMapFromSKPaymentTransaction:transaction.originalTransaction] : [NSNull null], @"transactionTimeStamp" : transaction.transactionDate ? @(transaction.transactionDate.timeIntervalSince1970) : [NSNull null], @"transactionIdentifier" : transaction.transactionIdentifier ?: [NSNull null], @"transactionState" : @(transaction.transactionState) }]; return map; } + (NSDictionary *)getMapFromNSError:(NSError *)error { if (!error) { return nil; } return @{ @"code" : @(error.code), @"domain" : error.domain ?: @"", @"userInfo" : [FIAObjectTranslator encodeNSErrorUserInfo:error.userInfo] }; } + (id)encodeNSErrorUserInfo:(id)value { if ([value isKindOfClass:[NSError class]]) { return [FIAObjectTranslator getMapFromNSError:value]; } else if ([value isKindOfClass:[NSURL class]]) { return [value absoluteString]; } else if ([value isKindOfClass:[NSNumber class]]) { return value; } else if ([value isKindOfClass:[NSString class]]) { return value; } else if ([value isKindOfClass:[NSArray class]]) { NSMutableArray *errors = [[NSMutableArray alloc] init]; for (id error in value) { [errors addObject:[FIAObjectTranslator encodeNSErrorUserInfo:error]]; } return errors; } else if ([value isKindOfClass:[NSDictionary class]]) { NSMutableDictionary *errors = [[NSMutableDictionary alloc] init]; for (id key in value) { errors[key] = [FIAObjectTranslator encodeNSErrorUserInfo:value[key]]; } return errors; } else { return [NSString stringWithFormat: @"Unable to encode native userInfo object of type %@ to map. Please submit an issue at " @"https://github.com/flutter/flutter/issues/new with the title " @"\"[in_app_purchase_storekit] " @"Unable to encode userInfo of type %@\" and add reproduction steps and the error " @"details in " @"the description field.", [value class], [value class]]; } } + (NSDictionary *)getMapFromSKStorefront:(SKStorefront *)storefront { if (!storefront) { return nil; } NSMutableDictionary *map = [[NSMutableDictionary alloc] initWithDictionary:@{ @"countryCode" : storefront.countryCode, @"identifier" : storefront.identifier }]; return map; } + (NSDictionary *)getMapFromSKStorefront:(SKStorefront *)storefront andSKPaymentTransaction:(SKPaymentTransaction *)transaction { if (!storefront || !transaction) { return nil; } NSMutableDictionary *map = [[NSMutableDictionary alloc] initWithDictionary:@{ @"storefront" : [FIAObjectTranslator getMapFromSKStorefront:storefront], @"transaction" : [FIAObjectTranslator getMapFromSKPaymentTransaction:transaction] }]; return map; } + (SKPaymentDiscount *)getSKPaymentDiscountFromMap:(NSDictionary *)map withError:(NSString **)error { if (!map || map.count <= 0) { return nil; } NSString *identifier = map[@"identifier"]; NSString *keyIdentifier = map[@"keyIdentifier"]; NSString *nonce = map[@"nonce"]; NSString *signature = map[@"signature"]; NSNumber *timestamp = map[@"timestamp"]; if (!identifier || ![identifier isKindOfClass:NSString.class] || [identifier isEqualToString:@""]) { if (error) { *error = @"When specifying a payment discount the 'identifier' field is mandatory."; } return nil; } if (!keyIdentifier || ![keyIdentifier isKindOfClass:NSString.class] || [keyIdentifier isEqualToString:@""]) { if (error) { *error = @"When specifying a payment discount the 'keyIdentifier' field is mandatory."; } return nil; } if (!nonce || ![nonce isKindOfClass:NSString.class] || [nonce isEqualToString:@""]) { if (error) { *error = @"When specifying a payment discount the 'nonce' field is mandatory."; } return nil; } if (!signature || ![signature isKindOfClass:NSString.class] || [signature isEqualToString:@""]) { if (error) { *error = @"When specifying a payment discount the 'signature' field is mandatory."; } return nil; } if (!timestamp || ![timestamp isKindOfClass:NSNumber.class] || [timestamp longLongValue] <= 0) { if (error) { *error = @"When specifying a payment discount the 'timestamp' field is mandatory."; } return nil; } SKPaymentDiscount *discount = [[SKPaymentDiscount alloc] initWithIdentifier:identifier keyIdentifier:keyIdentifier nonce:[[NSUUID alloc] initWithUUIDString:nonce] signature:signature timestamp:timestamp]; return discount; } + (nullable SKPaymentTransactionMessage *)convertTransactionToPigeon: (nullable SKPaymentTransaction *)transaction API_AVAILABLE(ios(12.2)) { if (!transaction) { return nil; } SKPaymentTransactionMessage *msg = [SKPaymentTransactionMessage makeWithPayment:[self convertPaymentToPigeon:transaction.payment] transactionState:[self convertTransactionStateToPigeon:transaction.transactionState] originalTransaction:transaction.originalTransaction ? [self convertTransactionToPigeon:transaction.originalTransaction] : nil transactionTimeStamp:[NSNumber numberWithDouble:[transaction.transactionDate timeIntervalSince1970]] transactionIdentifier:transaction.transactionIdentifier error:[self convertSKErrorToPigeon:transaction.error]]; return msg; } + (nullable SKErrorMessage *)convertSKErrorToPigeon:(nullable NSError *)error { if (!error) { return nil; } NSMutableDictionary *userInfo = [NSMutableDictionary new]; for (NSErrorUserInfoKey key in error.userInfo) { id value = error.userInfo[key]; userInfo[key] = [FIAObjectTranslator encodeNSErrorUserInfo:value]; } SKErrorMessage *msg = [SKErrorMessage makeWithCode:error.code domain:error.domain userInfo:userInfo]; return msg; } + (SKPaymentTransactionStateMessage)convertTransactionStateToPigeon: (SKPaymentTransactionState)state { switch (state) { case SKPaymentTransactionStatePurchasing: return SKPaymentTransactionStateMessagePurchasing; case SKPaymentTransactionStatePurchased: return SKPaymentTransactionStateMessagePurchased; case SKPaymentTransactionStateFailed: return SKPaymentTransactionStateMessageFailed; case SKPaymentTransactionStateRestored: return SKPaymentTransactionStateMessageRestored; case SKPaymentTransactionStateDeferred: return SKPaymentTransactionStateMessageDeferred; } } + (nullable SKPaymentMessage *)convertPaymentToPigeon:(nullable SKPayment *)payment API_AVAILABLE(ios(12.2)) { if (!payment) { return nil; } SKPaymentMessage *msg = [SKPaymentMessage makeWithProductIdentifier:payment.productIdentifier applicationUsername:payment.applicationUsername requestData:[[NSString alloc] initWithData:payment.requestData encoding:NSUTF8StringEncoding] quantity:payment.quantity simulatesAskToBuyInSandbox:payment.simulatesAskToBuyInSandbox paymentDiscount:[self convertPaymentDiscountToPigeon:payment.paymentDiscount]]; return msg; } + (nullable SKPaymentDiscountMessage *)convertPaymentDiscountToPigeon: (nullable SKPaymentDiscount *)discount API_AVAILABLE(ios(12.2)) { if (!discount) { return nil; } SKPaymentDiscountMessage *msg = [SKPaymentDiscountMessage makeWithIdentifier:discount.identifier keyIdentifier:discount.keyIdentifier nonce:[discount.nonce UUIDString] signature:discount.signature timestamp:[discount.timestamp intValue]]; return msg; } + (nullable SKStorefrontMessage *)convertStorefrontToPigeon:(nullable SKStorefront *)storefront API_AVAILABLE(ios(13.0)) { if (!storefront) { return nil; } SKStorefrontMessage *msg = [SKStorefrontMessage makeWithCountryCode:storefront.countryCode identifier:storefront.identifier]; return msg; } + (nullable SKProductSubscriptionPeriodMessage *)convertSKProductSubscriptionPeriodToPigeon: (nullable SKProductSubscriptionPeriod *)period API_AVAILABLE(ios(12.2)) { if (!period) { return nil; } SKSubscriptionPeriodUnitMessage unit; switch (period.unit) { case SKProductPeriodUnitDay: unit = SKSubscriptionPeriodUnitMessageDay; break; case SKProductPeriodUnitWeek: unit = SKSubscriptionPeriodUnitMessageWeek; break; case SKProductPeriodUnitMonth: unit = SKSubscriptionPeriodUnitMessageMonth; break; case SKProductPeriodUnitYear: unit = SKSubscriptionPeriodUnitMessageYear; break; } SKProductSubscriptionPeriodMessage *msg = [SKProductSubscriptionPeriodMessage makeWithNumberOfUnits:period.numberOfUnits unit:unit]; return msg; } + (nullable SKProductDiscountMessage *)convertProductDiscountToPigeon: (nullable SKProductDiscount *)productDiscount API_AVAILABLE(ios(12.2)) { if (!productDiscount) { return nil; } SKProductDiscountPaymentModeMessage paymentMode; switch (productDiscount.paymentMode) { case SKProductDiscountPaymentModeFreeTrial: paymentMode = SKProductDiscountPaymentModeMessageFreeTrial; break; case SKProductDiscountPaymentModePayAsYouGo: paymentMode = SKProductDiscountPaymentModeMessagePayAsYouGo; break; case SKProductDiscountPaymentModePayUpFront: paymentMode = SKProductDiscountPaymentModeMessagePayUpFront; break; } SKProductDiscountTypeMessage type; switch (productDiscount.type) { case SKProductDiscountTypeIntroductory: type = SKProductDiscountTypeMessageIntroductory; break; case SKProductDiscountTypeSubscription: type = SKProductDiscountTypeMessageSubscription; break; } SKProductDiscountMessage *msg = [SKProductDiscountMessage makeWithPrice:productDiscount.price.description priceLocale:[self convertNSLocaleToPigeon:productDiscount.priceLocale] numberOfPeriods:productDiscount.numberOfPeriods paymentMode:paymentMode subscriptionPeriod:[self convertSKProductSubscriptionPeriodToPigeon:productDiscount .subscriptionPeriod] identifier:productDiscount.identifier type:type]; return msg; } + (nullable SKPriceLocaleMessage *)convertNSLocaleToPigeon:(nullable NSLocale *)locale API_AVAILABLE(ios(12.2)) { if (!locale) { return nil; } SKPriceLocaleMessage *msg = [SKPriceLocaleMessage makeWithCurrencySymbol:locale.currencySymbol currencyCode:locale.currencyCode countryCode:locale.countryCode]; return msg; } + (nullable SKProductMessage *)convertProductToPigeon:(nullable SKProduct *)product API_AVAILABLE(ios(12.2)) { if (!product) { return nil; } NSArray<SKProductDiscount *> *skProductDiscounts = product.discounts; NSMutableArray<SKProductDiscountMessage *> *pigeonProductDiscounts = [NSMutableArray arrayWithCapacity:skProductDiscounts.count]; for (SKProductDiscount *productDiscount in skProductDiscounts) { [pigeonProductDiscounts addObject:[self convertProductDiscountToPigeon:productDiscount]]; }; SKProductMessage *msg = [SKProductMessage makeWithProductIdentifier:product.productIdentifier localizedTitle:product.localizedTitle localizedDescription:product.localizedDescription priceLocale:[self convertNSLocaleToPigeon:product.priceLocale] subscriptionGroupIdentifier:product.subscriptionGroupIdentifier price:product.price.description subscriptionPeriod: [self convertSKProductSubscriptionPeriodToPigeon:product.subscriptionPeriod] introductoryPrice:[self convertProductDiscountToPigeon:product.introductoryPrice] discounts:pigeonProductDiscounts]; return msg; } + (nullable SKProductsResponseMessage *)convertProductsResponseToPigeon: (nullable SKProductsResponse *)productsResponse API_AVAILABLE(ios(12.2)) { if (!productsResponse) { return nil; } NSArray<SKProduct *> *skProducts = productsResponse.products; NSMutableArray<SKProductMessage *> *pigeonProducts = [NSMutableArray arrayWithCapacity:skProducts.count]; for (SKProduct *product in skProducts) { [pigeonProducts addObject:[self convertProductToPigeon:product]]; }; SKProductsResponseMessage *msg = [SKProductsResponseMessage makeWithProducts:pigeonProducts invalidProductIdentifiers:productsResponse.invalidProductIdentifiers]; return msg; } @end
packages/packages/in_app_purchase/in_app_purchase_storekit/darwin/Classes/FIAObjectTranslator.m/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_storekit/darwin/Classes/FIAObjectTranslator.m", "repo_id": "packages", "token_count": 7752 }
964
#include "../../Flutter/Flutter-Debug.xcconfig"
packages/packages/in_app_purchase/in_app_purchase_storekit/example/macos/Runner/Configs/Debug.xcconfig/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_storekit/example/macos/Runner/Configs/Debug.xcconfig", "repo_id": "packages", "token_count": 19 }
965
<resources> <dimen name="medium_text_size">16sp</dimen> <dimen name="huge_text_size">20sp</dimen> </resources>
packages/packages/local_auth/local_auth_android/android/src/main/res/values/dimens.xml/0
{ "file_path": "packages/packages/local_auth/local_auth_android/android/src/main/res/values/dimens.xml", "repo_id": "packages", "token_count": 46 }
966
// Mocks generated by Mockito 5.4.4 from annotations // in local_auth_android/test/local_auth_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i3; import 'package:local_auth_android/src/messages.g.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; // 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 /// A class which mocks [LocalAuthApi]. /// /// See the documentation for Mockito's code generation for more information. class MockLocalAuthApi extends _i1.Mock implements _i2.LocalAuthApi { MockLocalAuthApi() { _i1.throwOnMissingStub(this); } @override _i3.Future<bool> isDeviceSupported() => (super.noSuchMethod( Invocation.method( #isDeviceSupported, [], ), returnValue: _i3.Future<bool>.value(false), ) as _i3.Future<bool>); @override _i3.Future<bool> deviceCanSupportBiometrics() => (super.noSuchMethod( Invocation.method( #deviceCanSupportBiometrics, [], ), returnValue: _i3.Future<bool>.value(false), ) as _i3.Future<bool>); @override _i3.Future<bool> stopAuthentication() => (super.noSuchMethod( Invocation.method( #stopAuthentication, [], ), returnValue: _i3.Future<bool>.value(false), ) as _i3.Future<bool>); @override _i3.Future<List<_i2.AuthClassificationWrapper?>> getEnrolledBiometrics() => (super.noSuchMethod( Invocation.method( #getEnrolledBiometrics, [], ), returnValue: _i3.Future<List<_i2.AuthClassificationWrapper?>>.value( <_i2.AuthClassificationWrapper?>[]), ) as _i3.Future<List<_i2.AuthClassificationWrapper?>>); @override _i3.Future<_i2.AuthResult> authenticate( _i2.AuthOptions? arg_options, _i2.AuthStrings? arg_strings, ) => (super.noSuchMethod( Invocation.method( #authenticate, [ arg_options, arg_strings, ], ), returnValue: _i3.Future<_i2.AuthResult>.value(_i2.AuthResult.success), ) as _i3.Future<_i2.AuthResult>); }
packages/packages/local_auth/local_auth_android/test/local_auth_test.mocks.dart/0
{ "file_path": "packages/packages/local_auth/local_auth_android/test/local_auth_test.mocks.dart", "repo_id": "packages", "token_count": 1151 }
967
{ "context": { "date": "2021-11-09T15:08:32-08:00", "host_name": "test", "executable": "benchmarks", "num_cpus": 16, "mhz_per_cpu": 2300, "cpu_scaling_enabled": false, "caches": [ { "type": "Data", "level": 1, "size": 32768, "num_sharing": 2 }, { "type": "Instruction", "level": 1, "size": 32768, "num_sharing": 2 }, { "type": "Unified", "level": 2, "size": 262144, "num_sharing": 2 }, { "type": "Unified", "level": 3, "size": 16777216, "num_sharing": 16 } ], "load_avg": [2.59033,17.2754,24.2168], "library_build_type": "release" }, "benchmarks": [ { "name": "BM_PaintRecordInit", "family_index": 0, "per_family_instance_index": 0, "run_name": "BM_PaintRecordInit", "run_type": "iteration", "repetitions": 1, "repetition_index": 0, "threads": 1, "iterations": 3072884, "real_time": 101, "cpu_time": 101, "time_unit": "ns" }, { "name": "SkParagraphFixture/ShortLayout", "family_index": 22, "per_family_instance_index": 0, "run_name": "SkParagraphFixture/ShortLayout", "run_type": "iteration", "repetitions": 1, "repetition_index": 0, "threads": 1, "iterations": 200874, "real_time": 4460, "cpu_time": 4460, "time_unit": "ns" }, { "name": "SkParagraphFixture/TextBigO_BigO", "family_index": 26, "per_family_instance_index": 0, "run_name": "SkParagraphFixture/TextBigO", "run_type": "aggregate", "repetitions": 1, "threads": 1, "aggregate_name": "BigO", "aggregate_unit": "time", "cpu_coefficient": 6548, "real_coefficient": 6548, "big_o": "N", "time_unit": "ns" }, { "name": "ParagraphFixture/TextBigO_BigO", "family_index": 5, "per_family_instance_index": 0, "run_name": "ParagraphFixture/TextBigO", "run_type": "aggregate", "repetitions": 1, "threads": 1, "aggregate_name": "BigO", "aggregate_unit": "time", "cpu_coefficient": 3.8, "real_coefficient": 3.89, "big_o": "N", "time_unit": "ns" }, { "name": "ParagraphFixture/TextBigO_RMS", "family_index": 5, "per_family_instance_index": 0, "run_name": "ParagraphFixture/TextBigO", "run_type": "aggregate", "repetitions": 1, "threads": 1, "aggregate_name": "RMS", "aggregate_unit": "percentage", "rms": 4.89 } ] }
packages/packages/metrics_center/test/example_google_benchmark.json/0
{ "file_path": "packages/packages/metrics_center/test/example_google_benchmark.json", "repo_id": "packages", "token_count": 1917 }
968
// 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 'src/constants.dart'; import 'src/lookup_resolver.dart'; import 'src/native_protocol_client.dart'; import 'src/packet.dart'; import 'src/resource_record.dart'; export 'package:multicast_dns/src/resource_record.dart'; /// A callback type for [MDnsQuerier.start] to iterate available network /// interfaces. /// /// Implementations must ensure they return interfaces appropriate for the /// [type] parameter. /// /// See also: /// * [MDnsQuerier.allInterfacesFactory] typedef NetworkInterfacesFactory = Future<Iterable<NetworkInterface>> Function( InternetAddressType type); /// A factory for construction of datagram sockets. /// /// This can be injected into the [MDnsClient] to provide alternative /// implementations of [RawDatagramSocket.bind]. typedef RawDatagramSocketFactory = Future<RawDatagramSocket> Function( dynamic host, int port, {bool reuseAddress, bool reusePort, int ttl}); /// Client for DNS lookup and publishing using the mDNS protocol. /// /// Users should call [MDnsQuerier.start] when ready to start querying and /// listening. [MDnsQuerier.stop] must be called when done to clean up /// resources. /// /// This client only supports "One-Shot Multicast DNS Queries" as described in /// section 5.1 of [RFC 6762](https://tools.ietf.org/html/rfc6762). class MDnsClient { /// Create a new [MDnsClient]. MDnsClient({ RawDatagramSocketFactory rawDatagramSocketFactory = RawDatagramSocket.bind, }) : _rawDatagramSocketFactory = rawDatagramSocketFactory; bool _starting = false; bool _started = false; final List<RawDatagramSocket> _sockets = <RawDatagramSocket>[]; final List<RawDatagramSocket> _toBeClosed = <RawDatagramSocket>[]; final LookupResolver _resolver = LookupResolver(); final ResourceRecordCache _cache = ResourceRecordCache(); final RawDatagramSocketFactory _rawDatagramSocketFactory; InternetAddress? _mDnsAddress; int? _mDnsPort; /// Find all network interfaces with an the [InternetAddressType] specified. Future<Iterable<NetworkInterface>> allInterfacesFactory( InternetAddressType type) { return NetworkInterface.list( includeLinkLocal: true, type: type, includeLoopback: true, ); } /// Start the mDNS client. /// /// With no arguments, this method will listen on the IPv4 multicast address /// on all IPv4 network interfaces. /// /// The [listenAddress] parameter must be either [InternetAddress.anyIPv4] or /// [InternetAddress.anyIPv6], and will default to anyIPv4. /// /// The [interfaceFactory] defaults to [allInterfacesFactory]. /// /// The [mDnsPort] allows configuring what port is used for the mDNS /// query. If not provided, defaults to `5353`. /// /// The [mDnsAddress] allows configuring what internet address is used /// for the mDNS query. If not provided, defaults to either `224.0.0.251` or /// or `FF02::FB`. /// /// Subsequent calls to this method are ignored while the mDNS client is in /// started state. Future<void> start({ InternetAddress? listenAddress, NetworkInterfacesFactory? interfacesFactory, int mDnsPort = mDnsPort, InternetAddress? mDnsAddress, }) async { listenAddress ??= InternetAddress.anyIPv4; interfacesFactory ??= allInterfacesFactory; assert(listenAddress.address == InternetAddress.anyIPv4.address || listenAddress.address == InternetAddress.anyIPv6.address); if (_started || _starting) { return; } _starting = true; final int selectedMDnsPort = _mDnsPort = mDnsPort; _mDnsAddress = mDnsAddress; // Listen on all addresses. final RawDatagramSocket incoming = await _rawDatagramSocketFactory( listenAddress.address, selectedMDnsPort, reuseAddress: true, reusePort: true, ttl: 255, ); // Can't send to IPv6 any address. if (incoming.address != InternetAddress.anyIPv6) { _sockets.add(incoming); } else { _toBeClosed.add(incoming); } _mDnsAddress ??= incoming.address.type == InternetAddressType.IPv4 ? mDnsAddressIPv4 : mDnsAddressIPv6; final List<NetworkInterface> interfaces = (await interfacesFactory(listenAddress.type)).toList(); for (final NetworkInterface interface in interfaces) { // Create a socket for sending on each adapter. final InternetAddress targetAddress = interface.addresses[0]; final RawDatagramSocket socket = await _rawDatagramSocketFactory( targetAddress, selectedMDnsPort, reuseAddress: true, reusePort: true, ttl: 255, ); _sockets.add(socket); // Ensure that we're using this address/interface for multicast. if (targetAddress.type == InternetAddressType.IPv4) { socket.setRawOption(RawSocketOption( RawSocketOption.levelIPv4, RawSocketOption.IPv4MulticastInterface, targetAddress.rawAddress, )); } else { socket.setRawOption(RawSocketOption.fromInt( RawSocketOption.levelIPv6, RawSocketOption.IPv6MulticastInterface, interface.index, )); } // Join multicast on this interface. incoming.joinMulticast(_mDnsAddress!, interface); } incoming.listen((RawSocketEvent event) => _handleIncoming(event, incoming)); _started = true; _starting = false; } /// Stop the client and close any associated sockets. void stop() { if (!_started) { return; } if (_starting) { throw StateError('Cannot stop mDNS client while it is starting.'); } for (final RawDatagramSocket socket in _sockets) { socket.close(); } _sockets.clear(); for (final RawDatagramSocket socket in _toBeClosed) { socket.close(); } _toBeClosed.clear(); _resolver.clearPendingRequests(); _started = false; } /// Lookup a [ResourceRecord], potentially from the cache. /// /// The [type] parameter must be a valid [ResourceRecordType]. The [fullyQualifiedName] /// parameter is the name of the service to lookup, and must not be null. The /// [timeout] parameter specifies how long the internal cache should hold on /// to the record. The [multicast] parameter specifies whether the query /// should be sent as unicast (QU) or multicast (QM). /// /// Some publishers have been observed to not respond to unicast requests /// properly, so the default is true. Stream<T> lookup<T extends ResourceRecord>( ResourceRecordQuery query, { Duration timeout = const Duration(seconds: 5), }) { final int? selectedMDnsPort = _mDnsPort; if (!_started || selectedMDnsPort == null) { throw StateError('mDNS client must be started before calling lookup.'); } // Look for entries in the cache. final List<T> cached = <T>[]; _cache.lookup<T>( query.fullyQualifiedName, query.resourceRecordType, cached); if (cached.isNotEmpty) { final StreamController<T> controller = StreamController<T>(); cached.forEach(controller.add); controller.close(); return controller.stream; } // Add the pending request before sending the query. final Stream<T> results = _resolver.addPendingRequest<T>( query.resourceRecordType, query.fullyQualifiedName, timeout); // Send the request on all interfaces. final List<int> packet = query.encode(); for (final RawDatagramSocket socket in _sockets) { socket.send(packet, _mDnsAddress!, selectedMDnsPort); } return results; } // Process incoming datagrams. void _handleIncoming(RawSocketEvent event, RawDatagramSocket incoming) { if (event == RawSocketEvent.read) { final Datagram? datagram = incoming.receive(); if (datagram == null) { return; } // Check for published responses. final List<ResourceRecord>? response = decodeMDnsResponse(datagram.data); if (response != null) { _cache.updateRecords(response); _resolver.handleResponse(response); return; } // TODO(dnfield): Support queries coming in for published entries. } } }
packages/packages/multicast_dns/lib/multicast_dns.dart/0
{ "file_path": "packages/packages/multicast_dns/lib/multicast_dns.dart", "repo_id": "packages", "token_count": 2841 }
969
// 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:ui' as ui show Codec, FrameInfo, Image, instantiateImageCodec; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:palette_generator/palette_generator.dart'; import 'encoded_images.dart'; /// An image provider implementation for testing that takes a pre-loaded image. /// This avoids handling asynchronous I/O in the test zone, which is /// problematic. class FakeImageProvider extends ImageProvider<FakeImageProvider> { const FakeImageProvider(this._image, {this.scale = 1.0}); final ui.Image _image; /// The scale to place in the [ImageInfo] object of the image. final double scale; @override Future<FakeImageProvider> obtainKey(ImageConfiguration configuration) { return SynchronousFuture<FakeImageProvider>(this); } @override ImageStreamCompleter loadImage( FakeImageProvider key, ImageDecoderCallback decode, ) { assert(key == this); return OneFrameImageStreamCompleter( SynchronousFuture<ImageInfo>( ImageInfo(image: _image, scale: scale), ), ); } } Future<FakeImageProvider> loadImage(Uint8List data) async { final ui.Codec codec = await ui.instantiateImageCodec(data); final ui.FrameInfo frameInfo = await codec.getNextFrame(); return FakeImageProvider(frameInfo.image); } Future<void> main() async { // Load the images outside of the test zone so that IO doesn't get // complicated. final Map<String, FakeImageProvider> testImages = <String, FakeImageProvider>{ 'tall_blue': await loadImage(kImageDataTallBlue), 'wide_red': await loadImage(kImageDataWideRed), 'dominant': await loadImage(kImageDataDominant), 'landscape': await loadImage(kImageDataLandscape), }; testWidgets('Initialize the image cache', (WidgetTester tester) async { // We need to have a testWidgets test in order to initialize the image // cache for the other tests, but they timeout if they too are testWidgets // tests. await tester.pumpWidget(const Placeholder()); }); test( "PaletteGenerator.fromByteData throws when the size doesn't match the byte data size", () { expect( () async { final ByteData? data = await testImages['tall_blue']!._image.toByteData(); await PaletteGenerator.fromByteData( EncodedImage( data!, width: 1, height: 1, ), ); }, throwsAssertionError, ); }); test('PaletteGenerator.fromImage works', () async { final PaletteGenerator palette = await PaletteGenerator.fromImage(testImages['tall_blue']!._image); expect(palette.paletteColors.length, equals(1)); expect(palette.paletteColors[0].color, within<Color>(distance: 8, from: const Color(0xff0000ff))); }); test('PaletteGenerator works on 1-pixel tall blue image', () async { final PaletteGenerator palette = await PaletteGenerator.fromImageProvider(testImages['tall_blue']!); expect(palette.paletteColors.length, equals(1)); expect(palette.paletteColors[0].color, within<Color>(distance: 8, from: const Color(0xff0000ff))); }); test('PaletteGenerator works on 1-pixel wide red image', () async { final PaletteGenerator palette = await PaletteGenerator.fromImageProvider(testImages['wide_red']!); expect(palette.paletteColors.length, equals(1)); expect(palette.paletteColors[0].color, within<Color>(distance: 8, from: const Color(0xffff0000))); }); test('PaletteGenerator finds dominant color and text colors', () async { final PaletteGenerator palette = await PaletteGenerator.fromImageProvider(testImages['dominant']!); expect(palette.paletteColors.length, equals(3)); expect(palette.dominantColor, isNotNull); expect(palette.dominantColor!.color, within<Color>(distance: 8, from: const Color(0xff0000ff))); expect(palette.dominantColor!.titleTextColor, within<Color>(distance: 8, from: const Color(0x8affffff))); expect(palette.dominantColor!.bodyTextColor, within<Color>(distance: 8, from: const Color(0xb2ffffff))); }); test('PaletteGenerator works with regions', () async { final ImageProvider imageProvider = testImages['dominant']!; Rect region = const Rect.fromLTRB(0.0, 0.0, 100.0, 100.0); const Size size = Size(100.0, 100.0); PaletteGenerator palette = await PaletteGenerator.fromImageProvider( imageProvider, region: region, size: size); expect(palette.paletteColors.length, equals(3)); expect(palette.dominantColor, isNotNull); expect(palette.dominantColor!.color, within<Color>(distance: 8, from: const Color(0xff0000ff))); region = const Rect.fromLTRB(0.0, 0.0, 10.0, 10.0); palette = await PaletteGenerator.fromImageProvider(imageProvider, region: region, size: size); expect(palette.paletteColors.length, equals(1)); expect(palette.dominantColor, isNotNull); expect(palette.dominantColor!.color, within<Color>(distance: 8, from: const Color(0xffff0000))); region = const Rect.fromLTRB(0.0, 0.0, 30.0, 20.0); palette = await PaletteGenerator.fromImageProvider(imageProvider, region: region, size: size); expect(palette.paletteColors.length, equals(3)); expect(palette.dominantColor, isNotNull); expect(palette.dominantColor!.color, within<Color>(distance: 8, from: const Color(0xff00ff00))); }); test('PaletteGenerator works as expected on a real image', () async { final PaletteGenerator palette = await PaletteGenerator.fromImageProvider(testImages['landscape']!); final List<PaletteColor> expectedSwatches = <PaletteColor>[ PaletteColor(const Color(0xff3f630c), 10137), PaletteColor(const Color(0xff3c4b2a), 4773), PaletteColor(const Color(0xff81b2e9), 4762), PaletteColor(const Color(0xffc0d6ec), 4714), PaletteColor(const Color(0xff4c4f50), 2465), PaletteColor(const Color(0xff5c635b), 2463), PaletteColor(const Color(0xff6e80a2), 2421), PaletteColor(const Color(0xff9995a3), 1214), PaletteColor(const Color(0xff676c4d), 1213), PaletteColor(const Color(0xffc4b2b2), 1173), PaletteColor(const Color(0xff445166), 1040), PaletteColor(const Color(0xff475d83), 1019), PaletteColor(const Color(0xff7e7360), 589), PaletteColor(const Color(0xfff6b835), 286), PaletteColor(const Color(0xffb9983d), 152), PaletteColor(const Color(0xffe3ab35), 149), ]; final Iterable<Color> expectedColors = expectedSwatches.map<Color>((PaletteColor swatch) => swatch.color); expect(palette.paletteColors, containsAll(expectedSwatches)); expect(palette.vibrantColor, isNotNull); expect(palette.lightVibrantColor, isNotNull); expect(palette.darkVibrantColor, isNotNull); expect(palette.mutedColor, isNotNull); expect(palette.lightMutedColor, isNotNull); expect(palette.darkMutedColor, isNotNull); expect(palette.vibrantColor!.color, within<Color>(distance: 8, from: const Color(0xfff6b835))); expect(palette.lightVibrantColor!.color, within<Color>(distance: 8, from: const Color(0xff82b2e9))); expect(palette.darkVibrantColor!.color, within<Color>(distance: 8, from: const Color(0xff3f630c))); expect(palette.mutedColor!.color, within<Color>(distance: 8, from: const Color(0xff6c7fa2))); expect(palette.lightMutedColor!.color, within<Color>(distance: 8, from: const Color(0xffc4b2b2))); expect(palette.darkMutedColor!.color, within<Color>(distance: 8, from: const Color(0xff3c4b2a))); expect(palette.colors, containsAllInOrder(expectedColors)); expect(palette.colors.length, equals(palette.paletteColors.length)); }); test('PaletteGenerator limits max colors', () async { final ImageProvider imageProvider = testImages['landscape']!; PaletteGenerator palette = await PaletteGenerator.fromImageProvider( imageProvider, maximumColorCount: 32); expect(palette.paletteColors.length, equals(31)); palette = await PaletteGenerator.fromImageProvider(imageProvider, maximumColorCount: 1); expect(palette.paletteColors.length, equals(1)); palette = await PaletteGenerator.fromImageProvider(imageProvider, maximumColorCount: 15); expect(palette.paletteColors.length, equals(15)); }); test('PaletteGenerator filters work', () async { final ImageProvider imageProvider = testImages['landscape']!; // First, test that supplying the default filter is the same as not supplying one. List<PaletteFilter> filters = <PaletteFilter>[ avoidRedBlackWhitePaletteFilter ]; PaletteGenerator palette = await PaletteGenerator.fromImageProvider( imageProvider, filters: filters); final List<PaletteColor> expectedSwatches = <PaletteColor>[ PaletteColor(const Color(0xff3f630c), 10137), PaletteColor(const Color(0xff3c4b2a), 4773), PaletteColor(const Color(0xff81b2e9), 4762), PaletteColor(const Color(0xffc0d6ec), 4714), PaletteColor(const Color(0xff4c4f50), 2465), PaletteColor(const Color(0xff5c635b), 2463), PaletteColor(const Color(0xff6e80a2), 2421), PaletteColor(const Color(0xff9995a3), 1214), PaletteColor(const Color(0xff676c4d), 1213), PaletteColor(const Color(0xffc4b2b2), 1173), PaletteColor(const Color(0xff445166), 1040), PaletteColor(const Color(0xff475d83), 1019), PaletteColor(const Color(0xff7e7360), 589), PaletteColor(const Color(0xfff6b835), 286), PaletteColor(const Color(0xffb9983d), 152), PaletteColor(const Color(0xffe3ab35), 149), ]; final Iterable<Color> expectedColors = expectedSwatches.map<Color>((PaletteColor swatch) => swatch.color); expect(palette.paletteColors, containsAll(expectedSwatches)); expect(palette.dominantColor, isNotNull); expect(palette.dominantColor!.color, within<Color>(distance: 8, from: const Color(0xff3f630c))); expect(palette.colors, containsAllInOrder(expectedColors)); // A non-default filter works (and the default filter isn't applied too). filters = <PaletteFilter>[onlyBluePaletteFilter]; palette = await PaletteGenerator.fromImageProvider(imageProvider, filters: filters); final List<PaletteColor> blueSwatches = <PaletteColor>[ PaletteColor(const Color(0xff4c5c75), 1515), PaletteColor(const Color(0xff7483a1), 1505), PaletteColor(const Color(0xff515661), 1476), PaletteColor(const Color(0xff769dd4), 1470), PaletteColor(const Color(0xff3e4858), 777), PaletteColor(const Color(0xff98a3bc), 760), PaletteColor(const Color(0xffb4c7e0), 760), PaletteColor(const Color(0xff99bbe5), 742), PaletteColor(const Color(0xffcbdef0), 701), PaletteColor(const Color(0xff1c212b), 429), PaletteColor(const Color(0xff393c46), 417), PaletteColor(const Color(0xff526483), 394), PaletteColor(const Color(0xff61708b), 372), PaletteColor(const Color(0xff5e8ccc), 345), PaletteColor(const Color(0xff587ab4), 194), PaletteColor(const Color(0xff5584c8), 182), ]; final Iterable<Color> expectedBlues = blueSwatches.map<Color>((PaletteColor swatch) => swatch.color); expect(palette.paletteColors, containsAll(blueSwatches)); expect(palette.dominantColor, isNotNull); expect(palette.dominantColor!.color, within<Color>(distance: 8, from: const Color(0xff4c5c75))); expect(palette.colors, containsAllInOrder(expectedBlues)); // More than one filter is the intersection of the two filters. filters = <PaletteFilter>[onlyBluePaletteFilter, onlyCyanPaletteFilter]; palette = await PaletteGenerator.fromImageProvider(imageProvider, filters: filters); final List<PaletteColor> blueGreenSwatches = <PaletteColor>[ PaletteColor(const Color(0xffc8e8f8), 87), PaletteColor(const Color(0xff5c6c74), 73), PaletteColor(const Color(0xff6f8088), 49), PaletteColor(const Color(0xff687880), 49), PaletteColor(const Color(0xff506068), 45), PaletteColor(const Color(0xff485860), 39), PaletteColor(const Color(0xff405058), 21), PaletteColor(const Color(0xffd6ebf3), 11), PaletteColor(const Color(0xff2f3f47), 7), PaletteColor(const Color(0xff0f1f27), 6), PaletteColor(const Color(0xffc0e0f0), 6), PaletteColor(const Color(0xff203038), 3), PaletteColor(const Color(0xff788890), 2), PaletteColor(const Color(0xff384850), 2), PaletteColor(const Color(0xff98a8b0), 1), PaletteColor(const Color(0xffa8b8c0), 1), ]; final Iterable<Color> expectedBlueGreens = blueGreenSwatches.map<Color>((PaletteColor swatch) => swatch.color); expect(palette.paletteColors, containsAll(blueGreenSwatches)); expect(palette.dominantColor, isNotNull); expect(palette.dominantColor!.color, within<Color>(distance: 8, from: const Color(0xffc8e8f8))); expect(palette.colors, containsAllInOrder(expectedBlueGreens)); // Mutually exclusive filters return an empty palette. filters = <PaletteFilter>[onlyBluePaletteFilter, onlyGreenPaletteFilter]; palette = await PaletteGenerator.fromImageProvider(imageProvider, filters: filters); expect(palette.paletteColors, isEmpty); expect(palette.dominantColor, isNull); expect(palette.colors, isEmpty); }); test('PaletteGenerator targets work', () async { final ImageProvider imageProvider = testImages['landscape']!; // Passing an empty set of targets works the same as passing a null targets // list. PaletteGenerator palette = await PaletteGenerator.fromImageProvider( imageProvider, targets: <PaletteTarget>[]); expect(palette.selectedSwatches, isNotEmpty); expect(palette.vibrantColor, isNotNull); expect(palette.lightVibrantColor, isNotNull); expect(palette.darkVibrantColor, isNotNull); expect(palette.mutedColor, isNotNull); expect(palette.lightMutedColor, isNotNull); expect(palette.darkMutedColor, isNotNull); // Passing targets augments the baseTargets, and those targets are found. final List<PaletteTarget> saturationExtremeTargets = <PaletteTarget>[ PaletteTarget(minimumSaturation: 0.85), PaletteTarget(maximumSaturation: .25), ]; palette = await PaletteGenerator.fromImageProvider(imageProvider, targets: saturationExtremeTargets); expect(palette.vibrantColor, isNotNull); expect(palette.lightVibrantColor, isNotNull); expect(palette.darkVibrantColor, isNotNull); expect(palette.mutedColor, isNotNull); expect(palette.lightMutedColor, isNotNull); expect(palette.darkMutedColor, isNotNull); expect(palette.selectedSwatches.length, equals(PaletteTarget.baseTargets.length + 2)); final PaletteColor? selectedSwatchesFirst = palette.selectedSwatches[saturationExtremeTargets[0]]; final PaletteColor? selectedSwatchesSecond = palette.selectedSwatches[saturationExtremeTargets[1]]; expect(selectedSwatchesFirst, isNotNull); expect(selectedSwatchesSecond, isNotNull); expect(selectedSwatchesFirst!.color, equals(const Color(0xfff6b835))); expect(selectedSwatchesSecond!.color, equals(const Color(0xff6e80a2))); }); test('PaletteGenerator produces consistent results', () async { final ImageProvider imageProvider = testImages['landscape']!; PaletteGenerator lastPalette = await PaletteGenerator.fromImageProvider(imageProvider); for (int i = 0; i < 5; ++i) { final PaletteGenerator palette = await PaletteGenerator.fromImageProvider(imageProvider); expect(palette.paletteColors.length, lastPalette.paletteColors.length); expect(palette.vibrantColor, equals(lastPalette.vibrantColor)); expect(palette.lightVibrantColor, equals(lastPalette.lightVibrantColor)); expect(palette.darkVibrantColor, equals(lastPalette.darkVibrantColor)); expect(palette.mutedColor, equals(lastPalette.mutedColor)); expect(palette.lightMutedColor, equals(lastPalette.lightMutedColor)); expect(palette.darkMutedColor, equals(lastPalette.darkMutedColor)); expect(palette.dominantColor, isNotNull); expect(lastPalette.dominantColor, isNotNull); expect(palette.dominantColor!.color, within<Color>(distance: 8, from: lastPalette.dominantColor!.color)); lastPalette = palette; } }); // TODO(gspencergoog): rewrite to use fromImageProvider when https://github.com/flutter/flutter/issues/10647 is resolved, // since fromImageProvider calls fromImage which calls fromByteData test('PaletteGenerator.fromByteData works in non-root isolate', () async { final ui.Image image = testImages['tall_blue']!._image; final ByteData? data = await image.toByteData(); final PaletteGenerator palette = await compute<EncodedImage, PaletteGenerator>( _computeFromByteData, EncodedImage(data!, width: image.width, height: image.height), ); expect(palette.paletteColors.length, equals(1)); expect(palette.paletteColors[0].color, within<Color>(distance: 8, from: const Color(0xff0000ff))); }); test('PaletteColor == does not crash on invalid comparisons', () { final PaletteColor paletteColorA = PaletteColor(const Color(0xFFFFFFFF), 1); final PaletteColor paletteColorB = PaletteColor(const Color(0xFFFFFFFF), 1); final Object object = Object(); expect(paletteColorA == paletteColorB, true); expect(paletteColorA == object, false); }); test('PaletteTarget == does not crash on invalid comparisons', () { final PaletteTarget paletteTargetA = PaletteTarget(); final PaletteTarget paletteTargetB = PaletteTarget(); final Object object = Object(); expect(paletteTargetA == paletteTargetB, true); expect(paletteTargetA == object, false); }); } Future<PaletteGenerator> _computeFromByteData(EncodedImage encodedImage) async { return PaletteGenerator.fromByteData(encodedImage); } bool onlyBluePaletteFilter(HSLColor hslColor) { const double blueLineMinHue = 185.0; const double blueLineMaxHue = 260.0; const double blueLineMaxSaturation = 0.82; return hslColor.hue >= blueLineMinHue && hslColor.hue <= blueLineMaxHue && hslColor.saturation <= blueLineMaxSaturation; } bool onlyCyanPaletteFilter(HSLColor hslColor) { const double cyanLineMinHue = 165.0; const double cyanLineMaxHue = 200.0; const double cyanLineMaxSaturation = 0.82; return hslColor.hue >= cyanLineMinHue && hslColor.hue <= cyanLineMaxHue && hslColor.saturation <= cyanLineMaxSaturation; } bool onlyGreenPaletteFilter(HSLColor hslColor) { const double greenLineMinHue = 80.0; const double greenLineMaxHue = 165.0; const double greenLineMaxSaturation = 0.82; return hslColor.hue >= greenLineMinHue && hslColor.hue <= greenLineMaxHue && hslColor.saturation <= greenLineMaxSaturation; }
packages/packages/palette_generator/test/palette_generator_test.dart/0
{ "file_path": "packages/packages/palette_generator/test/palette_generator_test.dart", "repo_id": "packages", "token_count": 7113 }
970
// 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, do not edit directly. // See also: https://pub.dev/packages/pigeon import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.CLASS; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.flutter.plugin.common.BasicMessageChannel; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugin.common.MessageCodec; import io.flutter.plugin.common.StandardMessageCodec; import java.io.ByteArrayOutputStream; import java.lang.annotation.Retention; import java.lang.annotation.Target; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; /** Generated class from Pigeon. */ @SuppressWarnings({"unused", "unchecked", "CodeBlock2Expr", "RedundantSuppression", "serial"}) public class Messages { /** Error class for passing custom error details to Flutter via a thrown PlatformException. */ public static class FlutterError extends RuntimeException { /** The error code. */ public final String code; /** The error details. Must be a datatype supported by the api codec. */ public final Object details; public FlutterError(@NonNull String code, @Nullable String message, @Nullable Object details) { super(message); this.code = code; this.details = details; } } @NonNull protected static ArrayList<Object> wrapError(@NonNull Throwable exception) { ArrayList<Object> errorList = new ArrayList<Object>(3); if (exception instanceof FlutterError) { FlutterError error = (FlutterError) exception; errorList.add(error.code); errorList.add(error.getMessage()); errorList.add(error.details); } else { errorList.add(exception.toString()); errorList.add(exception.getClass().getSimpleName()); errorList.add( "Cause: " + exception.getCause() + ", Stacktrace: " + Log.getStackTraceString(exception)); } return errorList; } @NonNull protected static FlutterError createConnectionError(@NonNull String channelName) { return new FlutterError( "channel-error", "Unable to establish connection on channel: " + channelName + ".", ""); } @Target(METHOD) @Retention(CLASS) @interface CanIgnoreReturnValue {} public enum Code { ONE(0), TWO(1); final int index; private Code(final int index) { this.index = index; } } /** Generated class from Pigeon that represents data sent in messages. */ public static final class MessageData { private @Nullable String name; public @Nullable String getName() { return name; } public void setName(@Nullable String setterArg) { this.name = setterArg; } private @Nullable String description; public @Nullable String getDescription() { return description; } public void setDescription(@Nullable String setterArg) { this.description = setterArg; } private @NonNull Code code; public @NonNull Code getCode() { return code; } public void setCode(@NonNull Code setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"code\" is null."); } this.code = setterArg; } private @NonNull Map<String, String> data; public @NonNull Map<String, String> getData() { return data; } public void setData(@NonNull Map<String, String> setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"data\" is null."); } this.data = setterArg; } /** Constructor is non-public to enforce null safety; use Builder. */ MessageData() {} public static final class Builder { private @Nullable String name; @CanIgnoreReturnValue public @NonNull Builder setName(@Nullable String setterArg) { this.name = setterArg; return this; } private @Nullable String description; @CanIgnoreReturnValue public @NonNull Builder setDescription(@Nullable String setterArg) { this.description = setterArg; return this; } private @Nullable Code code; @CanIgnoreReturnValue public @NonNull Builder setCode(@NonNull Code setterArg) { this.code = setterArg; return this; } private @Nullable Map<String, String> data; @CanIgnoreReturnValue public @NonNull Builder setData(@NonNull Map<String, String> setterArg) { this.data = setterArg; return this; } public @NonNull MessageData build() { MessageData pigeonReturn = new MessageData(); pigeonReturn.setName(name); pigeonReturn.setDescription(description); pigeonReturn.setCode(code); pigeonReturn.setData(data); return pigeonReturn; } } @NonNull ArrayList<Object> toList() { ArrayList<Object> toListResult = new ArrayList<Object>(4); toListResult.add(name); toListResult.add(description); toListResult.add(code == null ? null : code.index); toListResult.add(data); return toListResult; } static @NonNull MessageData fromList(@NonNull ArrayList<Object> list) { MessageData pigeonResult = new MessageData(); Object name = list.get(0); pigeonResult.setName((String) name); Object description = list.get(1); pigeonResult.setDescription((String) description); Object code = list.get(2); pigeonResult.setCode(Code.values()[(int) code]); Object data = list.get(3); pigeonResult.setData((Map<String, String>) data); return pigeonResult; } } /** Asynchronous error handling return type for non-nullable API method returns. */ public interface Result<T> { /** Success case callback method for handling returns. */ void success(@NonNull T result); /** Failure case callback method for handling errors. */ void error(@NonNull Throwable error); } /** Asynchronous error handling return type for nullable API method returns. */ public interface NullableResult<T> { /** Success case callback method for handling returns. */ void success(@Nullable T result); /** Failure case callback method for handling errors. */ void error(@NonNull Throwable error); } /** Asynchronous error handling return type for void API method returns. */ public interface VoidResult { /** Success case callback method for handling returns. */ void success(); /** Failure case callback method for handling errors. */ void error(@NonNull Throwable error); } private static class ExampleHostApiCodec extends StandardMessageCodec { public static final ExampleHostApiCodec INSTANCE = new ExampleHostApiCodec(); private ExampleHostApiCodec() {} @Override protected Object readValueOfType(byte type, @NonNull ByteBuffer buffer) { switch (type) { case (byte) 128: return MessageData.fromList((ArrayList<Object>) readValue(buffer)); default: return super.readValueOfType(type, buffer); } } @Override protected void writeValue(@NonNull ByteArrayOutputStream stream, Object value) { if (value instanceof MessageData) { stream.write(128); writeValue(stream, ((MessageData) value).toList()); } else { super.writeValue(stream, value); } } } /** Generated interface from Pigeon that represents a handler of messages from Flutter. */ public interface ExampleHostApi { @NonNull String getHostLanguage(); @NonNull Long add(@NonNull Long a, @NonNull Long b); void sendMessage(@NonNull MessageData message, @NonNull Result<Boolean> result); /** The codec used by ExampleHostApi. */ static @NonNull MessageCodec<Object> getCodec() { return ExampleHostApiCodec.INSTANCE; } /** Sets up an instance of `ExampleHostApi` to handle messages through the `binaryMessenger`. */ static void setUp(@NonNull BinaryMessenger binaryMessenger, @Nullable ExampleHostApi api) { { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.pigeon_example_package.ExampleHostApi.getHostLanguage", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); try { String output = api.getHostLanguage(); wrapped.add(0, output); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.pigeon_example_package.ExampleHostApi.add", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number aArg = (Number) args.get(0); Number bArg = (Number) args.get(1); try { Long output = api.add( (aArg == null) ? null : aArg.longValue(), (bArg == null) ? null : bArg.longValue()); wrapped.add(0, output); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.pigeon_example_package.ExampleHostApi.sendMessage", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; MessageData messageArg = (MessageData) args.get(0); Result<Boolean> resultCallback = new Result<Boolean>() { public void success(Boolean result) { wrapped.add(0, result); reply.reply(wrapped); } public void error(Throwable error) { ArrayList<Object> wrappedError = wrapError(error); reply.reply(wrappedError); } }; api.sendMessage(messageArg, resultCallback); }); } else { channel.setMessageHandler(null); } } } } /** Generated class from Pigeon that represents Flutter messages that can be called from Java. */ public static class MessageFlutterApi { private final @NonNull BinaryMessenger binaryMessenger; public MessageFlutterApi(@NonNull BinaryMessenger argBinaryMessenger) { this.binaryMessenger = argBinaryMessenger; } /** Public interface for sending reply. */ /** The codec used by MessageFlutterApi. */ static @NonNull MessageCodec<Object> getCodec() { return new StandardMessageCodec(); } public void flutterMethod(@Nullable String aStringArg, @NonNull Result<String> result) { final String channelName = "dev.flutter.pigeon.pigeon_example_package.MessageFlutterApi.flutterMethod"; BasicMessageChannel<Object> channel = new BasicMessageChannel<>(binaryMessenger, channelName, getCodec()); channel.send( new ArrayList<Object>(Collections.singletonList(aStringArg)), channelReply -> { if (channelReply instanceof List) { List<Object> listReply = (List<Object>) channelReply; if (listReply.size() > 1) { result.error( new FlutterError( (String) listReply.get(0), (String) listReply.get(1), (String) listReply.get(2))); } else if (listReply.get(0) == null) { result.error( new FlutterError( "null-error", "Flutter api returned null value for non-null return value.", "")); } else { @SuppressWarnings("ConstantConditions") String output = (String) listReply.get(0); result.success(output); } } else { result.error(createConnectionError(channelName)); } }); } } }
packages/packages/pigeon/example/app/android/app/src/main/java/io/flutter/plugins/Messages.java/0
{ "file_path": "packages/packages/pigeon/example/app/android/app/src/main/java/io/flutter/plugins/Messages.java", "repo_id": "packages", "token_count": 5549 }
971
#include "../../Flutter/Flutter-Debug.xcconfig" #include "Warnings.xcconfig"
packages/packages/pigeon/example/app/macos/Runner/Configs/Debug.xcconfig/0
{ "file_path": "packages/packages/pigeon/example/app/macos/Runner/Configs/Debug.xcconfig", "repo_id": "packages", "token_count": 32 }
972
name: pigeon_example description: example app to show basic usage of pigeon. publish_to: none environment: sdk: ^3.1.0 dependencies: dev_dependencies: build_runner: ^2.1.10
packages/packages/pigeon/example/pubspec.yaml/0
{ "file_path": "packages/packages/pigeon/example/pubspec.yaml", "repo_id": "packages", "token_count": 64 }
973
This directory contains Pigeon API definitions used to generate code for tests. Please do not add new files to this directory unless absolutely necessary; most additions should go into core_tests.dart. See https://github.com/flutter/flutter/issues/115168 for context.
packages/packages/pigeon/pigeons/README.md/0
{ "file_path": "packages/packages/pigeon/pigeons/README.md", "repo_id": "packages", "token_count": 65 }
974
# alternate_language_test_plugin Tests for languages not covered by `test_plugin`. See [the `platform_tests` README](../README.md) for details. To run these tests, use [`test.dart`](../tool/test.dart)
packages/packages/pigeon/platform_tests/alternate_language_test_plugin/README.md/0
{ "file_path": "packages/packages/pigeon/platform_tests/alternate_language_test_plugin/README.md", "repo_id": "packages", "token_count": 68 }
975
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package com.example.alternate_language_test_plugin; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import com.example.alternate_language_test_plugin.CoreTests.HostSmallApi; import io.flutter.plugin.common.BinaryMessenger; import org.junit.Test; import org.mockito.ArgumentCaptor; public class PigeonTest { @Test public void clearsHandler() { HostSmallApi mockApi = mock(HostSmallApi.class); BinaryMessenger binaryMessenger = mock(BinaryMessenger.class); HostSmallApi.setUp(binaryMessenger, mockApi); ArgumentCaptor<String> channelName = ArgumentCaptor.forClass(String.class); verify(binaryMessenger, atLeast(1)).setMessageHandler(channelName.capture(), isNotNull()); HostSmallApi.setUp(binaryMessenger, null); verify(binaryMessenger, atLeast(1)).setMessageHandler(eq(channelName.getValue()), isNull()); } }
packages/packages/pigeon/platform_tests/alternate_language_test_plugin/android/src/test/java/com/example/alternate_language_test_plugin/PigeonTest.java/0
{ "file_path": "packages/packages/pigeon/platform_tests/alternate_language_test_plugin/android/src/test/java/com/example/alternate_language_test_plugin/PigeonTest.java", "repo_id": "packages", "token_count": 338 }
976
// 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 alternate_language_test_plugin; #import "MockBinaryMessenger.h" /////////////////////////////////////////////////////////////////////////////////////////// @interface MockHostSmallApi : NSObject <FLTHostSmallApi> @property(nonatomic, copy) NSString *output; @property(nonatomic, retain) FlutterError *voidVoidError; @end /////////////////////////////////////////////////////////////////////////////////////////// @implementation MockHostSmallApi - (void)echoString:(NSString *)value completion:(nonnull void (^)(NSString *_Nullable, FlutterError *_Nullable))completion { if (self.output) { completion(self.output, nil); } else { completion(nil, [FlutterError errorWithCode:@"hey" message:@"ho" details:nil]); } } - (void)voidVoidWithCompletion:(nonnull void (^)(FlutterError *_Nullable))completion { completion(self.voidVoidError); } @end /////////////////////////////////////////////////////////////////////////////////////////// @interface AsyncHandlersTest : XCTestCase @end /////////////////////////////////////////////////////////////////////////////////////////// @implementation AsyncHandlersTest - (void)testAsyncHost2Flutter { MockBinaryMessenger *binaryMessenger = [[MockBinaryMessenger alloc] initWithCodec:FLTFlutterIntegrationCoreApiGetCodec()]; NSString *value = @"Test"; binaryMessenger.result = value; FLTFlutterIntegrationCoreApi *flutterApi = [[FLTFlutterIntegrationCoreApi alloc] initWithBinaryMessenger:binaryMessenger]; XCTestExpectation *expectation = [self expectationWithDescription:@"echo callback"]; [flutterApi echoAsyncString:value completion:^(NSString *_Nonnull output, FlutterError *_Nullable error) { XCTAssertEqualObjects(output, value); [expectation fulfill]; }]; [self waitForExpectationsWithTimeout:1.0 handler:nil]; } - (void)testAsyncFlutter2HostVoidVoid { MockBinaryMessenger *binaryMessenger = [[MockBinaryMessenger alloc] initWithCodec:FLTHostSmallApiGetCodec()]; MockHostSmallApi *mockHostSmallApi = [[MockHostSmallApi alloc] init]; SetUpFLTHostSmallApi(binaryMessenger, mockHostSmallApi); NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.HostSmallApi.voidVoid"; XCTAssertNotNil(binaryMessenger.handlers[channelName]); XCTestExpectation *expectation = [self expectationWithDescription:@"voidvoid callback"]; binaryMessenger.handlers[channelName](nil, ^(NSData *data) { NSArray *outputList = [binaryMessenger.codec decode:data]; XCTAssertEqualObjects(outputList[0], [NSNull null]); [expectation fulfill]; }); [self waitForExpectationsWithTimeout:1.0 handler:nil]; } - (void)testAsyncFlutter2HostVoidVoidError { MockBinaryMessenger *binaryMessenger = [[MockBinaryMessenger alloc] initWithCodec:FLTHostSmallApiGetCodec()]; MockHostSmallApi *mockHostSmallApi = [[MockHostSmallApi alloc] init]; mockHostSmallApi.voidVoidError = [FlutterError errorWithCode:@"code" message:@"message" details:nil]; SetUpFLTHostSmallApi(binaryMessenger, mockHostSmallApi); NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.HostSmallApi.voidVoid"; XCTAssertNotNil(binaryMessenger.handlers[channelName]); XCTestExpectation *expectation = [self expectationWithDescription:@"voidvoid callback"]; binaryMessenger.handlers[channelName](nil, ^(NSData *data) { NSArray *outputList = [binaryMessenger.codec decode:data]; XCTAssertNotNil(outputList); XCTAssertEqualObjects(outputList[0], mockHostSmallApi.voidVoidError.code); [expectation fulfill]; }); [self waitForExpectationsWithTimeout:1.0 handler:nil]; } - (void)testAsyncFlutter2Host { MockBinaryMessenger *binaryMessenger = [[MockBinaryMessenger alloc] initWithCodec:FLTHostSmallApiGetCodec()]; MockHostSmallApi *mockHostSmallApi = [[MockHostSmallApi alloc] init]; NSString *value = @"Test"; mockHostSmallApi.output = value; SetUpFLTHostSmallApi(binaryMessenger, mockHostSmallApi); NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.HostSmallApi.echo"; XCTAssertNotNil(binaryMessenger.handlers[channelName]); NSData *inputEncoded = [binaryMessenger.codec encode:@[ value ]]; XCTestExpectation *expectation = [self expectationWithDescription:@"echo callback"]; binaryMessenger.handlers[channelName](inputEncoded, ^(NSData *data) { NSArray *outputList = [binaryMessenger.codec decode:data]; NSString *output = outputList[0]; XCTAssertEqualObjects(output, value); [expectation fulfill]; }); [self waitForExpectationsWithTimeout:1.0 handler:nil]; } - (void)testAsyncFlutter2HostError { MockBinaryMessenger *binaryMessenger = [[MockBinaryMessenger alloc] initWithCodec:FLTHostSmallApiGetCodec()]; MockHostSmallApi *mockHostSmallApi = [[MockHostSmallApi alloc] init]; SetUpFLTHostSmallApi(binaryMessenger, mockHostSmallApi); NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.HostSmallApi.echo"; XCTAssertNotNil(binaryMessenger.handlers[channelName]); NSData *inputEncoded = [binaryMessenger.codec encode:@[ @"Test" ]]; XCTestExpectation *expectation = [self expectationWithDescription:@"echo callback"]; binaryMessenger.handlers[channelName](inputEncoded, ^(NSData *data) { NSArray *outputList = [binaryMessenger.codec decode:data]; XCTAssertNotNil(outputList); XCTAssertEqualObjects(outputList[0], @"hey"); XCTAssertEqualObjects(outputList[1], @"ho"); [expectation fulfill]; }); [self waitForExpectationsWithTimeout:1.0 handler:nil]; } @end
packages/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/RunnerTests/AsyncHandlersTest.m/0
{ "file_path": "packages/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/RunnerTests/AsyncHandlersTest.m", "repo_id": "packages", "token_count": 2099 }
977
This package contains the shared code (generated Pigeon output, example app, integration tests) for `test_plugin` and `alternate_language_shared_plugin`. Since those two plugin projects are intended to be identical, and only exist as separate projects because of the Java/Kotlin and Obj-C/Swift overlap that prevents combining them, almost all Dart code should be in this package rather than in the plugins themselves.
packages/packages/pigeon/platform_tests/shared_test_plugin_code/README.md/0
{ "file_path": "packages/packages/pigeon/platform_tests/shared_test_plugin_code/README.md", "repo_id": "packages", "token_count": 99 }
978
// 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 Foundation typealias HandlerBinaryMessengerHandler = ([Any?]) -> Any class HandlerBinaryMessenger: NSObject, FlutterBinaryMessenger { let codec: FlutterMessageCodec let handler: HandlerBinaryMessengerHandler private var count = 0 init(codec: FlutterMessageCodec, handler: @escaping HandlerBinaryMessengerHandler) { self.codec = codec self.handler = handler super.init() } func send(onChannel channel: String, message: Data?) { // Method not implemented because this messenger is just for handling } func send( onChannel channel: String, message: Data?, binaryReply callback: FlutterBinaryReply? = nil ) { guard let callback = callback else { return } guard let args = self.codec.decode(message) as? [Any?] else { callback(nil) return } let result = self.handler(args) callback(self.codec.encode([result])) } func setMessageHandlerOnChannel( _ channel: String, binaryMessageHandler handler: FlutterBinaryMessageHandler? = nil ) -> FlutterBinaryMessengerConnection { self.count += 1 return FlutterBinaryMessengerConnection(self.count) } func cleanUpConnection(_ connection: FlutterBinaryMessengerConnection) { // Method not implemented because this messenger is just for handling } }
packages/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/HandlerBinaryMessenger.swift/0
{ "file_path": "packages/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/HandlerBinaryMessenger.swift", "repo_id": "packages", "token_count": 454 }
979
#include "../../Flutter/Flutter-Debug.xcconfig" #include "Warnings.xcconfig"
packages/packages/pigeon/platform_tests/test_plugin/example/macos/Runner/Configs/Debug.xcconfig/0
{ "file_path": "packages/packages/pigeon/platform_tests/test_plugin/example/macos/Runner/Configs/Debug.xcconfig", "repo_id": "packages", "token_count": 32 }
980
// 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 <gtest/gtest.h> #include "pigeon/primitive.gen.h" #include "test/utils/fake_host_messenger.h" namespace primitive_pigeontest { namespace { using flutter::EncodableList; using flutter::EncodableMap; using flutter::EncodableValue; using testing::FakeHostMessenger; class TestHostApi : public PrimitiveHostApi { public: TestHostApi() {} virtual ~TestHostApi() {} protected: ErrorOr<int64_t> AnInt(int64_t value) override { return value; } ErrorOr<bool> ABool(bool value) override { return value; } ErrorOr<std::string> AString(const std::string& value) override { return std::string(value); } ErrorOr<double> ADouble(double value) override { return value; } ErrorOr<flutter::EncodableMap> AMap( const flutter::EncodableMap& value) override { return value; } ErrorOr<flutter::EncodableList> AList( const flutter::EncodableList& value) override { return value; } ErrorOr<std::vector<int32_t>> AnInt32List( const std::vector<int32_t>& value) override { return value; } ErrorOr<flutter::EncodableList> ABoolList( const flutter::EncodableList& value) override { return value; } ErrorOr<flutter::EncodableMap> AStringIntMap( const flutter::EncodableMap& value) override { return value; } }; const EncodableValue& GetResult(const EncodableValue& pigeon_response) { return std::get<EncodableList>(pigeon_response)[0]; } } // namespace TEST(Primitive, HostInt) { FakeHostMessenger messenger(&PrimitiveHostApi::GetCodec()); TestHostApi api; PrimitiveHostApi::SetUp(&messenger, &api); int64_t result = 0; messenger.SendHostMessage( "dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.anInt", EncodableValue(EncodableList({EncodableValue(7)})), [&result](const EncodableValue& reply) { result = GetResult(reply).LongValue(); }); EXPECT_EQ(result, 7); } TEST(Primitive, HostBool) { FakeHostMessenger messenger(&PrimitiveHostApi::GetCodec()); TestHostApi api; PrimitiveHostApi::SetUp(&messenger, &api); bool result = false; messenger.SendHostMessage( "dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aBool", EncodableValue(EncodableList({EncodableValue(true)})), [&result](const EncodableValue& reply) { result = std::get<bool>(GetResult(reply)); }); EXPECT_EQ(result, true); } TEST(Primitive, HostDouble) { FakeHostMessenger messenger(&PrimitiveHostApi::GetCodec()); TestHostApi api; PrimitiveHostApi::SetUp(&messenger, &api); double result = 0.0; messenger.SendHostMessage( "dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aDouble", EncodableValue(EncodableList({EncodableValue(3.0)})), [&result](const EncodableValue& reply) { result = std::get<double>(GetResult(reply)); }); EXPECT_EQ(result, 3.0); } TEST(Primitive, HostString) { FakeHostMessenger messenger(&PrimitiveHostApi::GetCodec()); TestHostApi api; PrimitiveHostApi::SetUp(&messenger, &api); std::string result; messenger.SendHostMessage( "dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aString", EncodableValue(EncodableList({EncodableValue("hello")})), [&result](const EncodableValue& reply) { result = std::get<std::string>(GetResult(reply)); }); EXPECT_EQ(result, "hello"); } TEST(Primitive, HostList) { FakeHostMessenger messenger(&PrimitiveHostApi::GetCodec()); TestHostApi api; PrimitiveHostApi::SetUp(&messenger, &api); EncodableList result; messenger.SendHostMessage( "dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aList", EncodableValue(EncodableList({EncodableValue(EncodableList({1, 2, 3}))})), [&result](const EncodableValue& reply) { result = std::get<EncodableList>(GetResult(reply)); }); EXPECT_EQ(result.size(), 3); EXPECT_EQ(result[2].LongValue(), 3); } TEST(Primitive, HostMap) { FakeHostMessenger messenger(&PrimitiveHostApi::GetCodec()); TestHostApi api; PrimitiveHostApi::SetUp(&messenger, &api); EncodableMap result; messenger.SendHostMessage( "dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aMap", EncodableValue(EncodableList({EncodableValue(EncodableMap({ {EncodableValue("foo"), EncodableValue("bar")}, }))})), [&result](const EncodableValue& reply) { result = std::get<EncodableMap>(GetResult(reply)); }); EXPECT_EQ(result.size(), 1); EXPECT_EQ(result[EncodableValue("foo")], EncodableValue("bar")); } // TODO(stuartmorgan): Add FlutterApi versions of the tests. } // namespace primitive_pigeontest
packages/packages/pigeon/platform_tests/test_plugin/windows/test/primitive_test.cpp/0
{ "file_path": "packages/packages/pigeon/platform_tests/test_plugin/windows/test/primitive_test.cpp", "repo_id": "packages", "token_count": 1843 }
981
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:pigeon/ast.dart'; import 'package:pigeon/kotlin_generator.dart'; import 'package:test/test.dart'; const String DEFAULT_PACKAGE_NAME = 'test_package'; final Class emptyClass = Class(name: 'className', fields: <NamedType>[ NamedType( name: 'namedTypeName', type: const TypeDeclaration(baseName: 'baseName', isNullable: false), ) ]); final Enum emptyEnum = Enum( name: 'enumName', members: <EnumMember>[EnumMember(name: 'enumMemberName')], ); void main() { test('gen one class', () { final Class classDefinition = Class( name: 'Foobar', fields: <NamedType>[ NamedType( type: const TypeDeclaration( baseName: 'int', isNullable: true, ), name: 'field1', ), ], ); final Root root = Root( apis: <Api>[], classes: <Class>[classDefinition], enums: <Enum>[], ); final StringBuffer sink = StringBuffer(); const KotlinOptions kotlinOptions = KotlinOptions(); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('data class Foobar (')); expect(code, contains('val field1: Long? = null')); expect(code, contains('fun fromList(list: List<Any?>): Foobar')); expect(code, contains('fun toList(): List<Any?>')); }); test('gen one enum', () { final Enum anEnum = Enum( name: 'Foobar', members: <EnumMember>[ EnumMember(name: 'one'), EnumMember(name: 'two'), ], ); final Root root = Root( apis: <Api>[], classes: <Class>[], enums: <Enum>[anEnum], ); final StringBuffer sink = StringBuffer(); const KotlinOptions kotlinOptions = KotlinOptions(); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('enum class Foobar(val raw: Int) {')); expect(code, contains('ONE(0)')); expect(code, contains('TWO(1)')); }); test('gen class with enum', () { final Root root = Root( apis: <Api>[], classes: <Class>[ Class( name: 'Bar', fields: <NamedType>[ NamedType( name: 'field1', type: TypeDeclaration( baseName: 'Foo', isNullable: false, associatedEnum: emptyEnum, ), ), NamedType( name: 'field2', type: const TypeDeclaration( baseName: 'String', isNullable: false, ), ), ], ), ], enums: <Enum>[ Enum( name: 'Foo', members: <EnumMember>[ EnumMember(name: 'one'), EnumMember(name: 'two'), ], ), ], ); final StringBuffer sink = StringBuffer(); const KotlinOptions kotlinOptions = KotlinOptions(); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('enum class Foo(val raw: Int) {')); expect(code, contains('data class Bar (')); expect(code, contains('val field1: Foo,')); expect(code, contains('val field2: String')); expect(code, contains('fun fromList(list: List<Any?>): Bar')); expect(code, contains('val field1 = Foo.ofRaw(list[0] as Int)!!\n')); expect(code, contains('val field2 = list[1] as String\n')); expect(code, contains('fun toList(): List<Any?>')); }); test('primitive enum host', () { final Root root = Root(apis: <Api>[ AstHostApi(name: 'Bar', methods: <Method>[ Method( name: 'bar', location: ApiLocation.host, returnType: const TypeDeclaration.voidDeclaration(), parameters: <Parameter>[ Parameter( name: 'foo', type: TypeDeclaration( baseName: 'Foo', isNullable: false, associatedEnum: emptyEnum, )) ]) ]) ], classes: <Class>[], enums: <Enum>[ Enum(name: 'Foo', members: <EnumMember>[ EnumMember(name: 'one'), EnumMember(name: 'two'), ]) ]); final StringBuffer sink = StringBuffer(); const KotlinOptions kotlinOptions = KotlinOptions(); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('enum class Foo(val raw: Int) {')); expect(code, contains('val fooArg = Foo.ofRaw(args[0] as Int)')); }); test('gen one host api', () { final Root root = Root(apis: <Api>[ AstHostApi(name: 'Api', methods: <Method>[ Method( name: 'doSomething', location: ApiLocation.host, parameters: <Parameter>[ Parameter( type: TypeDeclaration( baseName: 'Input', associatedClass: emptyClass, isNullable: false, ), name: 'input', ) ], returnType: TypeDeclaration( baseName: 'Output', associatedClass: emptyClass, isNullable: false, ), ) ]) ], classes: <Class>[ Class(name: 'Input', fields: <NamedType>[ NamedType( type: const TypeDeclaration( baseName: 'String', isNullable: true, ), name: 'input', ) ]), Class(name: 'Output', fields: <NamedType>[ NamedType( type: const TypeDeclaration( baseName: 'String', isNullable: true, ), name: 'output', ) ]) ], enums: <Enum>[]); final StringBuffer sink = StringBuffer(); const KotlinOptions kotlinOptions = KotlinOptions(); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('interface Api')); expect(code, contains('fun doSomething(input: Input): Output')); expect(code, contains('channel.setMessageHandler')); expect(code, contains(''' if (api != null) { channel.setMessageHandler { message, reply -> val args = message as List<Any?> val inputArg = args[0] as Input var wrapped: List<Any?> try { wrapped = listOf<Any?>(api.doSomething(inputArg)) } catch (exception: Throwable) { wrapped = wrapError(exception) } reply.reply(wrapped) } } else { channel.setMessageHandler(null) } ''')); }); test('all the simple datatypes header', () { final Root root = Root(apis: <Api>[], classes: <Class>[ Class(name: 'Foobar', fields: <NamedType>[ NamedType( type: const TypeDeclaration( baseName: 'bool', isNullable: false, ), name: 'aBool', ), NamedType( type: const TypeDeclaration( baseName: 'int', isNullable: false, ), name: 'aInt', ), NamedType( type: const TypeDeclaration( baseName: 'double', isNullable: false, ), name: 'aDouble', ), NamedType( type: const TypeDeclaration( baseName: 'String', isNullable: false, ), name: 'aString', ), NamedType( type: const TypeDeclaration( baseName: 'Uint8List', isNullable: true, ), name: 'aUint8List', ), NamedType( type: const TypeDeclaration( baseName: 'Int32List', isNullable: false, ), name: 'aInt32List', ), NamedType( type: const TypeDeclaration( baseName: 'Int64List', isNullable: false, ), name: 'aInt64List', ), NamedType( type: const TypeDeclaration( baseName: 'Float64List', isNullable: false, ), name: 'aFloat64List', ), NamedType( type: const TypeDeclaration( baseName: 'bool', isNullable: true, ), name: 'aNullableBool', ), NamedType( type: const TypeDeclaration( baseName: 'int', isNullable: true, ), name: 'aNullableInt', ), NamedType( type: const TypeDeclaration( baseName: 'double', isNullable: true, ), name: 'aNullableDouble', ), NamedType( type: const TypeDeclaration( baseName: 'String', isNullable: true, ), name: 'aNullableString', ), NamedType( type: const TypeDeclaration( baseName: 'Uint8List', isNullable: true, ), name: 'aNullableUint8List', ), NamedType( type: const TypeDeclaration( baseName: 'Int32List', isNullable: true, ), name: 'aNullableInt32List', ), NamedType( type: const TypeDeclaration( baseName: 'Int64List', isNullable: true, ), name: 'aNullableInt64List', ), NamedType( type: const TypeDeclaration( baseName: 'Float64List', isNullable: true, ), name: 'aNullableFloat64List', ), ]), ], enums: <Enum>[]); final StringBuffer sink = StringBuffer(); const KotlinOptions kotlinOptions = KotlinOptions(); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('val aBool: Boolean')); expect(code, contains('val aInt: Long')); expect(code, contains('val aDouble: Double')); expect(code, contains('val aString: String')); expect(code, contains('val aUint8List: ByteArray')); expect(code, contains('val aInt32List: IntArray')); expect(code, contains('val aInt64List: LongArray')); expect(code, contains('val aFloat64List: DoubleArray')); expect( code, contains( 'val aInt = list[1].let { if (it is Int) it.toLong() else it as Long }')); expect(code, contains('val aNullableBool: Boolean? = null')); expect(code, contains('val aNullableInt: Long? = null')); expect(code, contains('val aNullableDouble: Double? = null')); expect(code, contains('val aNullableString: String? = null')); expect(code, contains('val aNullableUint8List: ByteArray? = null')); expect(code, contains('val aNullableInt32List: IntArray? = null')); expect(code, contains('val aNullableInt64List: LongArray? = null')); expect(code, contains('val aNullableFloat64List: DoubleArray? = null')); expect( code, contains( 'val aNullableInt = list[9].let { if (it is Int) it.toLong() else it as Long? }')); }); test('gen one flutter api', () { final Root root = Root(apis: <Api>[ AstFlutterApi(name: 'Api', methods: <Method>[ Method( name: 'doSomething', location: ApiLocation.flutter, parameters: <Parameter>[ Parameter( type: TypeDeclaration( baseName: 'Input', associatedClass: emptyClass, isNullable: false, ), name: '', ) ], returnType: TypeDeclaration( baseName: 'Output', associatedClass: emptyClass, isNullable: false, ), ) ]) ], classes: <Class>[ Class(name: 'Input', fields: <NamedType>[ NamedType( type: const TypeDeclaration( baseName: 'String', isNullable: true, ), name: 'input', ) ]), Class(name: 'Output', fields: <NamedType>[ NamedType( type: const TypeDeclaration( baseName: 'String', isNullable: true, ), name: 'output', ) ]) ], enums: <Enum>[]); final StringBuffer sink = StringBuffer(); const KotlinOptions kotlinOptions = KotlinOptions(); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('class Api(private val binaryMessenger: BinaryMessenger)')); expect(code, matches('fun doSomething.*Input.*Output')); }); test('gen host void api', () { final Root root = Root(apis: <Api>[ AstHostApi(name: 'Api', methods: <Method>[ Method( name: 'doSomething', location: ApiLocation.host, parameters: <Parameter>[ Parameter( type: TypeDeclaration( baseName: 'Input', associatedClass: emptyClass, isNullable: false, ), name: '', ) ], returnType: const TypeDeclaration.voidDeclaration(), ) ]) ], classes: <Class>[ Class(name: 'Input', fields: <NamedType>[ NamedType( type: const TypeDeclaration( baseName: 'String', isNullable: true, ), name: 'input', ) ]), ], enums: <Enum>[]); final StringBuffer sink = StringBuffer(); const KotlinOptions kotlinOptions = KotlinOptions(); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, isNot(matches('.*doSomething(.*) ->'))); expect(code, matches('doSomething(.*)')); }); test('gen flutter void return api', () { final Root root = Root(apis: <Api>[ AstFlutterApi(name: 'Api', methods: <Method>[ Method( name: 'doSomething', location: ApiLocation.flutter, parameters: <Parameter>[ Parameter( type: TypeDeclaration( baseName: 'Input', associatedClass: emptyClass, isNullable: false, ), name: '', ) ], returnType: const TypeDeclaration.voidDeclaration(), ) ]) ], classes: <Class>[ Class(name: 'Input', fields: <NamedType>[ NamedType( type: const TypeDeclaration( baseName: 'String', isNullable: true, ), name: 'input', ) ]), ], enums: <Enum>[]); final StringBuffer sink = StringBuffer(); const KotlinOptions kotlinOptions = KotlinOptions(); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('callback: (Result<Unit>) -> Unit')); expect(code, contains('callback(Result.success(Unit))')); // Lines should not end in semicolons. expect(code, isNot(contains(RegExp(r';\n')))); }); test('gen host void argument api', () { final Root root = Root(apis: <Api>[ AstHostApi(name: 'Api', methods: <Method>[ Method( name: 'doSomething', location: ApiLocation.host, parameters: <Parameter>[], returnType: TypeDeclaration( baseName: 'Output', associatedClass: emptyClass, isNullable: false, ), ) ]) ], classes: <Class>[ Class(name: 'Output', fields: <NamedType>[ NamedType( type: const TypeDeclaration( baseName: 'String', isNullable: true, ), name: 'output', ) ]), ], enums: <Enum>[]); final StringBuffer sink = StringBuffer(); const KotlinOptions kotlinOptions = KotlinOptions(); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('fun doSomething(): Output')); expect(code, contains('wrapped = listOf<Any?>(api.doSomething())')); expect(code, contains('wrapped = wrapError(exception)')); expect(code, contains('reply(wrapped)')); }); test('gen flutter void argument api', () { final Root root = Root(apis: <Api>[ AstFlutterApi(name: 'Api', methods: <Method>[ Method( name: 'doSomething', location: ApiLocation.flutter, parameters: <Parameter>[], returnType: TypeDeclaration( baseName: 'Output', associatedClass: emptyClass, isNullable: false, ), ) ]) ], classes: <Class>[ Class(name: 'Output', fields: <NamedType>[ NamedType( type: const TypeDeclaration( baseName: 'String', isNullable: true, ), name: 'output', ) ]), ], enums: <Enum>[]); final StringBuffer sink = StringBuffer(); const KotlinOptions kotlinOptions = KotlinOptions(); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect( code, contains('fun doSomething(callback: (Result<Output>) -> Unit)')); expect(code, contains('channel.send(null)')); }); test('gen list', () { final Root root = Root(apis: <Api>[], classes: <Class>[ Class(name: 'Foobar', fields: <NamedType>[ NamedType( type: const TypeDeclaration( baseName: 'List', isNullable: true, ), name: 'field1', ) ]), ], enums: <Enum>[]); final StringBuffer sink = StringBuffer(); const KotlinOptions kotlinOptions = KotlinOptions(); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('data class Foobar')); expect(code, contains('val field1: List<Any?>? = null')); }); test('gen map', () { final Root root = Root(apis: <Api>[], classes: <Class>[ Class(name: 'Foobar', fields: <NamedType>[ NamedType( type: const TypeDeclaration( baseName: 'Map', isNullable: true, ), name: 'field1', ) ]), ], enums: <Enum>[]); final StringBuffer sink = StringBuffer(); const KotlinOptions kotlinOptions = KotlinOptions(); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('data class Foobar')); expect(code, contains('val field1: Map<Any, Any?>? = null')); }); test('gen nested', () { final Class classDefinition = Class( name: 'Outer', fields: <NamedType>[ NamedType( type: TypeDeclaration( baseName: 'Nested', associatedClass: emptyClass, isNullable: true, ), name: 'nested', ) ], ); final Class nestedClass = Class( name: 'Nested', fields: <NamedType>[ NamedType( type: const TypeDeclaration( baseName: 'int', isNullable: true, ), name: 'data', ) ], ); final Root root = Root( apis: <Api>[], classes: <Class>[classDefinition, nestedClass], enums: <Enum>[], ); final StringBuffer sink = StringBuffer(); const KotlinOptions kotlinOptions = KotlinOptions(); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('data class Outer')); expect(code, contains('data class Nested')); expect(code, contains('val nested: Nested? = null')); expect(code, contains('fun fromList(list: List<Any?>): Outer')); expect( code, contains('val nested: Nested? = (list[0] as List<Any?>?)?.let')); expect(code, contains('Nested.fromList(it)')); expect(code, contains('fun toList(): List<Any?>')); }); test('gen one async Host Api', () { final Root root = Root(apis: <Api>[ AstHostApi(name: 'Api', methods: <Method>[ Method( name: 'doSomething', location: ApiLocation.host, parameters: <Parameter>[ Parameter( type: TypeDeclaration( baseName: 'Input', associatedClass: emptyClass, isNullable: false, ), name: 'arg', ) ], returnType: TypeDeclaration( baseName: 'Output', associatedClass: emptyClass, isNullable: false, ), isAsynchronous: true, ) ]) ], classes: <Class>[ Class(name: 'Input', fields: <NamedType>[ NamedType( type: const TypeDeclaration( baseName: 'String', isNullable: true, ), name: 'input', ) ]), Class(name: 'Output', fields: <NamedType>[ NamedType( type: const TypeDeclaration( baseName: 'String', isNullable: true, ), name: 'output', ) ]) ], enums: <Enum>[]); final StringBuffer sink = StringBuffer(); const KotlinOptions kotlinOptions = KotlinOptions(); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('interface Api')); expect(code, contains('api.doSomething(argArg) {')); expect(code, contains('reply.reply(wrapResult(data))')); }); test('gen one async Flutter Api', () { final Root root = Root(apis: <Api>[ AstFlutterApi(name: 'Api', methods: <Method>[ Method( name: 'doSomething', location: ApiLocation.flutter, parameters: <Parameter>[ Parameter( type: TypeDeclaration( baseName: 'Input', associatedClass: emptyClass, isNullable: false, ), name: '', ) ], returnType: TypeDeclaration( baseName: 'Output', associatedClass: emptyClass, isNullable: false, ), isAsynchronous: true, ) ]) ], classes: <Class>[ Class(name: 'Input', fields: <NamedType>[ NamedType( type: const TypeDeclaration( baseName: 'String', isNullable: true, ), name: 'input', ) ]), Class(name: 'Output', fields: <NamedType>[ NamedType( type: const TypeDeclaration( baseName: 'String', isNullable: true, ), name: 'output', ) ]) ], enums: <Enum>[]); final StringBuffer sink = StringBuffer(); const KotlinOptions kotlinOptions = KotlinOptions(); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('class Api')); expect(code, matches('fun doSomething.*Input.*callback.*Output.*Unit')); }); test('gen one enum class', () { final Enum anEnum = Enum( name: 'SampleEnum', members: <EnumMember>[ EnumMember(name: 'sampleVersion'), EnumMember(name: 'sampleTest'), ], ); final Class classDefinition = Class( name: 'EnumClass', fields: <NamedType>[ NamedType( type: TypeDeclaration( baseName: 'SampleEnum', associatedEnum: emptyEnum, isNullable: true, ), name: 'sampleEnum', ), ], ); final Root root = Root( apis: <Api>[], classes: <Class>[classDefinition], enums: <Enum>[anEnum], ); final StringBuffer sink = StringBuffer(); const KotlinOptions kotlinOptions = KotlinOptions(); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('enum class SampleEnum(val raw: Int)')); expect(code, contains('SAMPLE_VERSION(0)')); expect(code, contains('SAMPLE_TEST(1)')); }); Iterable<String> makeIterable(String string) sync* { yield string; } test('header', () { final Root root = Root(apis: <Api>[], classes: <Class>[], enums: <Enum>[]); final StringBuffer sink = StringBuffer(); final KotlinOptions kotlinOptions = KotlinOptions( copyrightHeader: makeIterable('hello world'), ); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, startsWith('// hello world')); }); test('generics - list', () { final Class classDefinition = Class( name: 'Foobar', fields: <NamedType>[ NamedType( type: const TypeDeclaration( baseName: 'List', isNullable: true, typeArguments: <TypeDeclaration>[ TypeDeclaration(baseName: 'int', isNullable: true) ]), name: 'field1', ), ], ); final Root root = Root( apis: <Api>[], classes: <Class>[classDefinition], enums: <Enum>[], ); final StringBuffer sink = StringBuffer(); const KotlinOptions kotlinOptions = KotlinOptions(); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('data class Foobar')); expect(code, contains('val field1: List<Long?>')); }); test('generics - maps', () { final Class classDefinition = Class( name: 'Foobar', fields: <NamedType>[ NamedType( type: const TypeDeclaration( baseName: 'Map', isNullable: true, typeArguments: <TypeDeclaration>[ TypeDeclaration(baseName: 'String', isNullable: true), TypeDeclaration(baseName: 'String', isNullable: true), ]), name: 'field1', ), ], ); final Root root = Root( apis: <Api>[], classes: <Class>[classDefinition], enums: <Enum>[], ); final StringBuffer sink = StringBuffer(); const KotlinOptions kotlinOptions = KotlinOptions(); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('data class Foobar')); expect(code, contains('val field1: Map<String?, String?>')); }); test('host generics argument', () { final Root root = Root( apis: <Api>[ AstHostApi(name: 'Api', methods: <Method>[ Method( name: 'doit', location: ApiLocation.host, returnType: const TypeDeclaration.voidDeclaration(), parameters: <Parameter>[ Parameter( type: const TypeDeclaration( baseName: 'List', isNullable: false, typeArguments: <TypeDeclaration>[ TypeDeclaration(baseName: 'int', isNullable: true) ]), name: 'arg', ) ]) ]) ], classes: <Class>[], enums: <Enum>[], ); final StringBuffer sink = StringBuffer(); const KotlinOptions kotlinOptions = KotlinOptions(); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('fun doit(arg: List<Long?>')); }); test('flutter generics argument', () { final Root root = Root( apis: <Api>[ AstFlutterApi(name: 'Api', methods: <Method>[ Method( name: 'doit', location: ApiLocation.flutter, returnType: const TypeDeclaration.voidDeclaration(), parameters: <Parameter>[ Parameter( type: const TypeDeclaration( baseName: 'List', isNullable: false, typeArguments: <TypeDeclaration>[ TypeDeclaration(baseName: 'int', isNullable: true) ]), name: 'arg', ) ]) ]) ], classes: <Class>[], enums: <Enum>[], ); final StringBuffer sink = StringBuffer(); const KotlinOptions kotlinOptions = KotlinOptions(); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('fun doit(argArg: List<Long?>')); }); test('host generics return', () { final Root root = Root( apis: <Api>[ AstHostApi(name: 'Api', methods: <Method>[ Method( name: 'doit', location: ApiLocation.host, returnType: const TypeDeclaration( baseName: 'List', isNullable: false, typeArguments: <TypeDeclaration>[ TypeDeclaration(baseName: 'int', isNullable: true) ]), parameters: <Parameter>[]) ]) ], classes: <Class>[], enums: <Enum>[], ); final StringBuffer sink = StringBuffer(); const KotlinOptions kotlinOptions = KotlinOptions(); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('fun doit(): List<Long?>')); expect(code, contains('wrapped = listOf<Any?>(api.doit())')); expect(code, contains('reply.reply(wrapped)')); }); test('flutter generics return', () { final Root root = Root( apis: <Api>[ AstFlutterApi(name: 'Api', methods: <Method>[ Method( name: 'doit', location: ApiLocation.flutter, returnType: const TypeDeclaration( baseName: 'List', isNullable: false, typeArguments: <TypeDeclaration>[ TypeDeclaration(baseName: 'int', isNullable: true) ]), parameters: <Parameter>[]) ]) ], classes: <Class>[], enums: <Enum>[], ); final StringBuffer sink = StringBuffer(); const KotlinOptions kotlinOptions = KotlinOptions(); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('fun doit(callback: (Result<List<Long?>>) -> Unit)')); expect(code, contains('val output = it[0] as List<Long?>')); expect(code, contains('callback(Result.success(output))')); }); test('host multiple args', () { final Root root = Root(apis: <Api>[ AstHostApi(name: 'Api', methods: <Method>[ Method( name: 'add', location: ApiLocation.host, parameters: <Parameter>[ Parameter( name: 'x', type: const TypeDeclaration(isNullable: false, baseName: 'int')), Parameter( name: 'y', type: const TypeDeclaration(isNullable: false, baseName: 'int')), ], returnType: const TypeDeclaration(baseName: 'int', isNullable: false), ) ]) ], classes: <Class>[], enums: <Enum>[]); final StringBuffer sink = StringBuffer(); const KotlinOptions kotlinOptions = KotlinOptions(); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('fun add(x: Long, y: Long): Long')); expect(code, contains('val args = message as List<Any?>')); expect( code, contains( 'val xArg = args[0].let { if (it is Int) it.toLong() else it as Long }')); expect( code, contains( 'val yArg = args[1].let { if (it is Int) it.toLong() else it as Long }')); expect(code, contains('wrapped = listOf<Any?>(api.add(xArg, yArg))')); expect(code, contains('reply.reply(wrapped)')); }); test('flutter multiple args', () { final Root root = Root(apis: <Api>[ AstFlutterApi(name: 'Api', methods: <Method>[ Method( name: 'add', location: ApiLocation.flutter, parameters: <Parameter>[ Parameter( name: 'x', type: const TypeDeclaration(baseName: 'int', isNullable: false)), Parameter( name: 'y', type: const TypeDeclaration(baseName: 'int', isNullable: false)), ], returnType: const TypeDeclaration(baseName: 'int', isNullable: false), ) ]) ], classes: <Class>[], enums: <Enum>[]); final StringBuffer sink = StringBuffer(); const KotlinOptions kotlinOptions = KotlinOptions(); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('val channel = BasicMessageChannel')); expect( code, contains( 'val output = it[0].let { if (it is Int) it.toLong() else it as Long }'), ); expect(code, contains('callback(Result.success(output))')); expect( code, contains( 'fun add(xArg: Long, yArg: Long, callback: (Result<Long>) -> Unit)')); expect(code, contains('channel.send(listOf(xArg, yArg)) {')); }); test('return nullable host', () { final Root root = Root( apis: <Api>[ AstHostApi(name: 'Api', methods: <Method>[ Method( name: 'doit', location: ApiLocation.host, returnType: const TypeDeclaration( baseName: 'int', isNullable: true, ), parameters: <Parameter>[]) ]) ], classes: <Class>[], enums: <Enum>[], ); final StringBuffer sink = StringBuffer(); const KotlinOptions kotlinOptions = KotlinOptions(); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('fun doit(): Long?')); }); test('return nullable host async', () { final Root root = Root( apis: <Api>[ AstHostApi(name: 'Api', methods: <Method>[ Method( name: 'doit', location: ApiLocation.host, returnType: const TypeDeclaration( baseName: 'int', isNullable: true, ), isAsynchronous: true, parameters: <Parameter>[]) ]) ], classes: <Class>[], enums: <Enum>[], ); final StringBuffer sink = StringBuffer(); const KotlinOptions kotlinOptions = KotlinOptions(); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('fun doit(callback: (Result<Long?>) -> Unit')); }); test('nullable argument host', () { final Root root = Root( apis: <Api>[ AstHostApi(name: 'Api', methods: <Method>[ Method( name: 'doit', location: ApiLocation.host, returnType: const TypeDeclaration.voidDeclaration(), parameters: <Parameter>[ Parameter( name: 'foo', type: const TypeDeclaration( baseName: 'int', isNullable: true, )), ]) ]) ], classes: <Class>[], enums: <Enum>[], ); final StringBuffer sink = StringBuffer(); const KotlinOptions kotlinOptions = KotlinOptions(); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect( code, contains( 'val fooArg = args[0].let { if (it is Int) it.toLong() else it as Long? }')); }); test('nullable argument flutter', () { final Root root = Root( apis: <Api>[ AstFlutterApi(name: 'Api', methods: <Method>[ Method( name: 'doit', location: ApiLocation.flutter, returnType: const TypeDeclaration.voidDeclaration(), parameters: <Parameter>[ Parameter( name: 'foo', type: const TypeDeclaration( baseName: 'int', isNullable: true, )), ]) ]) ], classes: <Class>[], enums: <Enum>[], ); final StringBuffer sink = StringBuffer(); const KotlinOptions kotlinOptions = KotlinOptions(); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect( code, contains('fun doit(fooArg: Long?, callback: (Result<Unit>) -> Unit)'), ); }); test('nonnull fields', () { final Root root = Root(apis: <Api>[ AstHostApi(name: 'Api', methods: <Method>[ Method( name: 'doSomething', location: ApiLocation.host, parameters: <Parameter>[ Parameter( type: TypeDeclaration( baseName: 'Input', associatedClass: emptyClass, isNullable: false, ), name: '', ) ], returnType: const TypeDeclaration.voidDeclaration(), ) ]) ], classes: <Class>[ Class(name: 'Input', fields: <NamedType>[ NamedType( type: const TypeDeclaration( baseName: 'String', isNullable: false, ), name: 'input', ) ]), ], enums: <Enum>[]); final StringBuffer sink = StringBuffer(); const KotlinOptions kotlinOptions = KotlinOptions(); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('val input: String\n')); }); test('transfers documentation comments', () { final List<String> comments = <String>[ ' api comment', ' api method comment', ' class comment', ' class field comment', ' enum comment', ' enum member comment', ]; int count = 0; final List<String> unspacedComments = <String>['////////']; int unspacedCount = 0; final Root root = Root( apis: <Api>[ AstFlutterApi( name: 'api', documentationComments: <String>[comments[count++]], methods: <Method>[ Method( name: 'method', location: ApiLocation.flutter, returnType: const TypeDeclaration.voidDeclaration(), documentationComments: <String>[comments[count++]], parameters: <Parameter>[ Parameter( name: 'field', type: const TypeDeclaration( baseName: 'int', isNullable: true, ), ), ], ) ], ) ], classes: <Class>[ Class( name: 'class', documentationComments: <String>[comments[count++]], fields: <NamedType>[ NamedType( documentationComments: <String>[comments[count++]], type: const TypeDeclaration( baseName: 'Map', isNullable: true, typeArguments: <TypeDeclaration>[ TypeDeclaration(baseName: 'String', isNullable: true), TypeDeclaration(baseName: 'int', isNullable: true), ]), name: 'field1', ), ], ), ], enums: <Enum>[ Enum( name: 'enum', documentationComments: <String>[ comments[count++], unspacedComments[unspacedCount++] ], members: <EnumMember>[ EnumMember( name: 'one', documentationComments: <String>[comments[count++]], ), EnumMember(name: 'two'), ], ), ], ); final StringBuffer sink = StringBuffer(); const KotlinOptions kotlinOptions = KotlinOptions(); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); for (final String comment in comments) { // This regex finds the comment only between the open and close comment block expect( RegExp(r'(?<=\/\*\*.*?)' + comment + r'(?=.*?\*\/)', dotAll: true) .hasMatch(code), true); } expect(code, isNot(contains('*//'))); }); test("doesn't create codecs if no custom datatypes", () { final Root root = Root( apis: <Api>[ AstFlutterApi( name: 'Api', methods: <Method>[ Method( name: 'method', location: ApiLocation.flutter, returnType: const TypeDeclaration.voidDeclaration(), parameters: <Parameter>[ Parameter( name: 'field', type: const TypeDeclaration( baseName: 'int', isNullable: true, ), ), ], ) ], ) ], classes: <Class>[], enums: <Enum>[], ); final StringBuffer sink = StringBuffer(); const KotlinOptions kotlinOptions = KotlinOptions(); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, isNot(contains(' : StandardMessageCodec() '))); expect(code, contains('StandardMessageCodec')); }); test('creates custom codecs if custom datatypes present', () { final Root root = Root(apis: <Api>[ AstFlutterApi(name: 'Api', methods: <Method>[ Method( name: 'doSomething', location: ApiLocation.flutter, parameters: <Parameter>[ Parameter( type: TypeDeclaration( baseName: 'Input', associatedClass: emptyClass, isNullable: false, ), name: '') ], returnType: TypeDeclaration( baseName: 'Output', associatedClass: emptyClass, isNullable: false, ), isAsynchronous: true, ) ]) ], classes: <Class>[ Class(name: 'Input', fields: <NamedType>[ NamedType( type: const TypeDeclaration( baseName: 'String', isNullable: true, ), name: 'input') ]), Class(name: 'Output', fields: <NamedType>[ NamedType( type: const TypeDeclaration( baseName: 'String', isNullable: true, ), name: 'output') ]) ], enums: <Enum>[]); final StringBuffer sink = StringBuffer(); const KotlinOptions kotlinOptions = KotlinOptions(); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains(' : StandardMessageCodec() ')); }); test('creates api error class for custom errors', () { final Method method = Method( name: 'doSomething', location: ApiLocation.host, returnType: const TypeDeclaration.voidDeclaration(), parameters: <Parameter>[]); final AstHostApi api = AstHostApi(name: 'SomeApi', methods: <Method>[method]); final Root root = Root( apis: <Api>[api], classes: <Class>[], enums: <Enum>[], ); final StringBuffer sink = StringBuffer(); const KotlinOptions kotlinOptions = KotlinOptions(errorClassName: 'SomeError'); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('class SomeError')); expect(code, contains('if (exception is SomeError)')); expect(code, contains('exception.code,')); expect(code, contains('exception.message,')); expect(code, contains('exception.details')); }); test('connection error contains channel name', () { final Root root = Root( apis: <Api>[ AstFlutterApi( name: 'Api', methods: <Method>[ Method( name: 'method', location: ApiLocation.flutter, returnType: const TypeDeclaration.voidDeclaration(), parameters: <Parameter>[ Parameter( name: 'field', type: const TypeDeclaration( baseName: 'int', isNullable: true, ), ), ], ) ], ) ], classes: <Class>[], enums: <Enum>[], ); final StringBuffer sink = StringBuffer(); const KotlinOptions kotlinOptions = KotlinOptions(); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect( code, contains( 'return FlutterError("channel-error", "Unable to establish connection on channel: \'\$channelName\'.", "")')); expect( code, contains( 'callback(Result.failure(createConnectionError(channelName)))')); }); test('gen host uses default error class', () { final Root root = Root( apis: <Api>[ AstHostApi( name: 'Api', methods: <Method>[ Method( name: 'method', location: ApiLocation.host, returnType: const TypeDeclaration.voidDeclaration(), parameters: <Parameter>[ Parameter( name: 'field', type: const TypeDeclaration( baseName: 'int', isNullable: true, ), ), ], ) ], ) ], classes: <Class>[], enums: <Enum>[], ); final StringBuffer sink = StringBuffer(); const KotlinOptions kotlinOptions = KotlinOptions(); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('FlutterError')); }); test('gen flutter uses default error class', () { final Root root = Root( apis: <Api>[ AstFlutterApi( name: 'Api', methods: <Method>[ Method( name: 'method', location: ApiLocation.flutter, returnType: const TypeDeclaration.voidDeclaration(), parameters: <Parameter>[ Parameter( name: 'field', type: const TypeDeclaration( baseName: 'int', isNullable: true, ), ), ], ) ], ) ], classes: <Class>[], enums: <Enum>[], ); final StringBuffer sink = StringBuffer(); const KotlinOptions kotlinOptions = KotlinOptions(); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('FlutterError')); }); test('gen host uses error class', () { final Root root = Root( apis: <Api>[ AstHostApi( name: 'Api', methods: <Method>[ Method( name: 'method', location: ApiLocation.host, returnType: const TypeDeclaration.voidDeclaration(), parameters: <Parameter>[ Parameter( name: 'field', type: const TypeDeclaration( baseName: 'int', isNullable: true, ), ), ], ) ], ) ], classes: <Class>[], enums: <Enum>[], ); final StringBuffer sink = StringBuffer(); const String errorClassName = 'FooError'; const KotlinOptions kotlinOptions = KotlinOptions(errorClassName: errorClassName); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains(errorClassName)); expect(code, isNot(contains('FlutterError'))); }); test('gen flutter uses error class', () { final Root root = Root( apis: <Api>[ AstFlutterApi( name: 'Api', methods: <Method>[ Method( name: 'method', location: ApiLocation.flutter, returnType: const TypeDeclaration.voidDeclaration(), parameters: <Parameter>[ Parameter( name: 'field', type: const TypeDeclaration( baseName: 'int', isNullable: true, ), ), ], ) ], ) ], classes: <Class>[], enums: <Enum>[], ); final StringBuffer sink = StringBuffer(); const String errorClassName = 'FooError'; const KotlinOptions kotlinOptions = KotlinOptions(errorClassName: errorClassName); const KotlinGenerator generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains(errorClassName)); expect(code, isNot(contains('FlutterError'))); }); }
packages/packages/pigeon/test/kotlin_generator_test.dart/0
{ "file_path": "packages/packages/pigeon/test/kotlin_generator_test.dart", "repo_id": "packages", "token_count": 26064 }
982
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:platform/platform.dart'; /// This sample app shows the platform details of the device it is running on. void main() => runApp(const MyApp()); /// The main app. class MyApp extends StatelessWidget { /// Constructs a [MyApp] const MyApp({super.key}); @override Widget build(BuildContext context) { const LocalPlatform platform = LocalPlatform(); return MaterialApp( title: 'Platform Example', home: Scaffold( appBar: AppBar( title: const Text('Platform Example'), ), body: Center( child: SingleChildScrollView( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ FormatDetails( title: 'Operating System:', value: platform.operatingSystem, ), FormatDetails( title: 'Number of Processors:', value: platform.numberOfProcessors.toString(), ), FormatDetails( title: 'Path Separator:', value: platform.pathSeparator, ), FormatDetails( title: 'Local Hostname:', value: platform.localHostname, ), FormatDetails( title: 'Environment:', value: platform.environment.toString(), ), FormatDetails( title: 'Executable:', value: platform.executable, ), FormatDetails( title: 'Resolved Executable:', value: platform.resolvedExecutable, ), FormatDetails( title: 'Script:', value: platform.script.toString(), ), FormatDetails( title: 'Executable Arguments:', value: platform.executableArguments.toString(), ), FormatDetails( title: 'Package Config:', value: platform.packageConfig.toString(), ), FormatDetails( title: 'Version:', value: platform.version, ), FormatDetails( title: 'Stdin Supports ANSI:', value: platform.stdinSupportsAnsi.toString(), ), FormatDetails( title: 'Stdout Supports ANSI:', value: platform.stdoutSupportsAnsi.toString(), ), FormatDetails( title: 'Locale Name:', value: platform.localeName, ), FormatDetails( title: 'isAndroid:', value: platform.isAndroid.toString(), ), FormatDetails( title: 'isFuchsia:', value: platform.isFuchsia.toString(), ), FormatDetails( title: 'isIOS:', value: platform.isIOS.toString(), ), FormatDetails( title: 'isLinux:', value: platform.isLinux.toString(), ), FormatDetails( title: 'isMacOS:', value: platform.isMacOS.toString(), ), FormatDetails( title: 'isWindows:', value: platform.isWindows.toString(), ), ], ), ), ), ), ); } } /// A widget to format the details. class FormatDetails extends StatelessWidget { /// Constructs a [FormatDetails]. const FormatDetails({ super.key, required this.title, required this.value, }); /// The title of the field. final String title; /// The value of the field. final String value; @override Widget build(BuildContext context) { return Column( children: <Widget>[ Text( title, style: Theme.of(context).textTheme.titleLarge, ), Text(value), const SizedBox(height: 20), ], ); } }
packages/packages/platform/example/lib/main.dart/0
{ "file_path": "packages/packages/platform/example/lib/main.dart", "repo_id": "packages", "token_count": 2418 }
983
# plugin_platform_interface This package provides a base class for platform interfaces of [federated flutter plugins](https://flutter.dev/go/federated-plugins). Platform implementations should `extends` their platform interface class rather than `implement`s it, as newly added methods to platform interfaces are not considered breaking changes. Extending a platform interface ensures that subclasses will get the default implementations from the base class, while platform implementations that `implements` their platform interface will be broken by newly added methods. This class package provides common functionality for platform interface to enforce that they are extended and not implemented. ## Sample usage: <?code-excerpt "test/plugin_platform_interface_test.dart (Example)"?> ```dart abstract class SamplePluginPlatform extends PlatformInterface { SamplePluginPlatform() : super(token: _token); static final Object _token = Object(); // A plugin can have a default implementation, as shown here, or `instance` // can be nullable, and the default instance can be null. static SamplePluginPlatform _instance = SamplePluginDefault(); static SamplePluginPlatform get instance => _instance; /// Platform-specific implementations should set this to their own /// platform-specific class that extends [SamplePluginPlatform] when they /// register themselves. static set instance(SamplePluginPlatform instance) { PlatformInterface.verify(instance, _token); _instance = instance; } // Methods for the plugin's platform interface would go here, often with // implementations that throw UnimplementedError. } class SamplePluginDefault extends SamplePluginPlatform { // A default real implementation of the platform interface would go here. } ``` This guarantees that UrlLauncherPlatform.instance cannot be set to an object that `implements` UrlLauncherPlatform (it can only be set to an object that `extends` UrlLauncherPlatform). ## Mocking or faking platform interfaces Test implementations of platform interfaces, such as those using `mockito`'s `Mock` or `test`'s `Fake`, will fail the verification done by `verify`. This package provides a `MockPlatformInterfaceMixin` which can be used in test code only to disable the `extends` enforcement. For example, a Mockito mock of a platform interface can be created with: <?code-excerpt "test/plugin_platform_interface_test.dart (Mock)"?> ```dart class SamplePluginPlatformMock extends Mock with MockPlatformInterfaceMixin implements SamplePluginPlatform {} ``` ## A note about `base` In Dart 3, [the `base` keyword](https://dart.dev/language/class-modifiers#base) was introduced to the language, which enforces that subclasses use `extends` rather than `implements` at compile time. The Flutter team is [considering deprecating this package in favor of using `base`](https://github.com/flutter/flutter/issues/127396) for platfom interfaces, but no decision has been made yet since it removes the ability to do mocking/faking as shown above. Plugin authors may want to consider using `base` instead of this package when creating new plugins. https://github.com/flutter/flutter/issues/127396
packages/packages/plugin_platform_interface/README.md/0
{ "file_path": "packages/packages/plugin_platform_interface/README.md", "repo_id": "packages", "token_count": 800 }
984
// 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 UIKit public class PointerInterceptorView: NSObject, FlutterPlatformView { let interceptorView: UIView init(frame: CGRect, debug: Bool) { interceptorView = UIView(frame: frame) interceptorView.backgroundColor = debug ? UIColor(red: 1, green: 0, blue: 0, alpha: 0.5) : UIColor.clear } public func view() -> UIView { return interceptorView } }
packages/packages/pointer_interceptor/pointer_interceptor_ios/ios/Classes/PointerInterceptorView.swift/0
{ "file_path": "packages/packages/pointer_interceptor/pointer_interceptor_ios/ios/Classes/PointerInterceptorView.swift", "repo_id": "packages", "token_count": 183 }
985
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/widgets.dart'; import 'package:flutter_web_plugins/flutter_web_plugins.dart'; import 'package:pointer_interceptor_platform_interface/pointer_interceptor_platform_interface.dart'; import 'package:web/web.dart' as web; /// The web implementation of the `PointerInterceptor` widget. /// /// A `Widget` that prevents clicks from being swallowed by [HtmlElementView]s. class PointerInterceptorWeb extends PointerInterceptorPlatform { /// Register the plugin static void registerWith(Registrar? registrar) { PointerInterceptorPlatform.instance = PointerInterceptorWeb(); } // Slightly modify the created `element` (for `debug` mode). void _onElementCreated(Object element) { (element as web.HTMLElement) ..style.width = '100%' ..style.height = '100%' ..style.backgroundColor = 'rgba(255, 0, 0, .5)'; } @override Widget buildWidget({ required Widget child, bool debug = false, bool intercepting = true, Key? key, }) { if (!intercepting) { return child; } return Stack( alignment: Alignment.center, children: <Widget>[ Positioned.fill( child: HtmlElementView.fromTagName( tagName: 'div', isVisible: false, onElementCreated: debug ? _onElementCreated : null, ), ), child, ], ); } }
packages/packages/pointer_interceptor/pointer_interceptor_web/lib/pointer_interceptor_web.dart/0
{ "file_path": "packages/packages/pointer_interceptor/pointer_interceptor_web/lib/pointer_interceptor_web.dart", "repo_id": "packages", "token_count": 566 }
986
// 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:process/process.dart'; import 'package:test/test.dart'; void main() { group('ProcessWrapper', () { late TestProcess delegate; late ProcessWrapper process; setUp(() { delegate = TestProcess(); process = ProcessWrapper(delegate); }); group('done', () { late bool done; setUp(() { done = false; // ignore: unawaited_futures process.done.then((int result) { done = true; }); }); test('completes only when all done', () async { expect(done, isFalse); delegate.exitCodeCompleter.complete(0); await Future<void>.value(); expect(done, isFalse); await delegate.stdoutController.close(); await Future<void>.value(); expect(done, isFalse); await delegate.stderrController.close(); await Future<void>.value(); expect(done, isTrue); expect(await process.exitCode, 0); }); test('works in conjunction with subscribers to stdio streams', () async { process.stdout .transform<String>(utf8.decoder) .transform<String>(const LineSplitter()) // ignore: avoid_print .listen(print); delegate.exitCodeCompleter.complete(0); await delegate.stdoutController.close(); await delegate.stderrController.close(); await Future<void>.value(); expect(done, isTrue); }); }); group('stdio', () { test('streams properly close', () async { Future<void> testStream( Stream<List<int>> stream, StreamController<List<int>> controller, String name, ) async { bool closed = false; stream.listen( (_) {}, onDone: () { closed = true; }, ); await controller.close(); await Future<void>.value(); expect(closed, isTrue, reason: 'for $name'); } await testStream(process.stdout, delegate.stdoutController, 'stdout'); await testStream(process.stderr, delegate.stderrController, 'stderr'); }); }); }); } class TestProcess implements io.Process { TestProcess([this.pid = 123]) : exitCodeCompleter = Completer<int>(), stdoutController = StreamController<List<int>>(), stderrController = StreamController<List<int>>(); @override final int pid; final Completer<int> exitCodeCompleter; final StreamController<List<int>> stdoutController; final StreamController<List<int>> stderrController; @override Future<int> get exitCode => exitCodeCompleter.future; @override bool kill([io.ProcessSignal signal = io.ProcessSignal.sigterm]) { exitCodeCompleter.complete(-1); return true; } @override Stream<List<int>> get stderr => stderrController.stream; @override io.IOSink get stdin => throw UnsupportedError('Not supported'); @override Stream<List<int>> get stdout => stdoutController.stream; }
packages/packages/process/test/src/interface/process_wrapper_test.dart/0
{ "file_path": "packages/packages/process/test/src/interface/process_wrapper_test.dart", "repo_id": "packages", "token_count": 1328 }
987
org.gradle.jvmargs=-Xmx4G android.useAndroidX=true android.enableJetifier=true
packages/packages/quick_actions/quick_actions_android/example/android/gradle.properties/0
{ "file_path": "packages/packages/quick_actions/quick_actions_android/example/android/gradle.properties", "repo_id": "packages", "token_count": 30 }
988
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; import 'package:quick_actions_platform_interface/quick_actions_platform_interface.dart'; import 'messages.g.dart'; export 'package:quick_actions_platform_interface/types/types.dart'; late QuickActionHandler _handler; /// An implementation of [QuickActionsPlatform] for iOS. class QuickActionsIos extends QuickActionsPlatform { /// Creates a new plugin implementation instance. QuickActionsIos({ @visibleForTesting IOSQuickActionsApi? api, }) : _hostApi = api ?? IOSQuickActionsApi(); final IOSQuickActionsApi _hostApi; /// Registers this class as the default instance of [QuickActionsPlatform]. static void registerWith() { QuickActionsPlatform.instance = QuickActionsIos(); } @override Future<void> initialize(QuickActionHandler handler) async { final _QuickActionHandlerApi quickActionsHandlerApi = _QuickActionHandlerApi(); IOSQuickActionsFlutterApi.setup(quickActionsHandlerApi); _handler = handler; } @override Future<void> setShortcutItems(List<ShortcutItem> items) async { await _hostApi.setShortcutItems( items.map(_shortcutItemToShortcutItemMessage).toList(), ); } @override Future<void> clearShortcutItems() => _hostApi.clearShortcutItems(); ShortcutItemMessage _shortcutItemToShortcutItemMessage(ShortcutItem item) { return ShortcutItemMessage( type: item.type, localizedTitle: item.localizedTitle, icon: item.icon, ); } } class _QuickActionHandlerApi extends IOSQuickActionsFlutterApi { @override void launchAction(String action) { _handler(action); } }
packages/packages/quick_actions/quick_actions_ios/lib/quick_actions_ios.dart/0
{ "file_path": "packages/packages/quick_actions/quick_actions_ios/lib/quick_actions_ios.dart", "repo_id": "packages", "token_count": 582 }
989
#include "ephemeral/Flutter-Generated.xcconfig"
packages/packages/rfw/example/hello/macos/Flutter/Flutter-Debug.xcconfig/0
{ "file_path": "packages/packages/rfw/example/hello/macos/Flutter/Flutter-Debug.xcconfig", "repo_id": "packages", "token_count": 19 }
990
{ "name": "hello", "short_name": "hello", "start_url": ".", "display": "standalone", "background_color": "#0175C2", "theme_color": "#0175C2", "description": "Hello World example for RFW", "orientation": "portrait-primary", "prefer_related_applications": false, "icons": [ { "src": "icons/Icon-192.png", "sizes": "192x192", "type": "image/png" }, { "src": "icons/Icon-512.png", "sizes": "512x512", "type": "image/png" }, { "src": "icons/Icon-maskable-192.png", "sizes": "192x192", "type": "image/png", "purpose": "maskable" }, { "src": "icons/Icon-maskable-512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" } ] }
packages/packages/rfw/example/hello/web/manifest.json/0
{ "file_path": "packages/packages/rfw/example/hello/web/manifest.json", "repo_id": "packages", "token_count": 512 }
991
// 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 is hand-formatted. import 'dart:collection'; import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import '../../formats.dart'; import 'content.dart'; /// Signature of builders for local widgets. /// /// The [LocalWidgetLibrary] class wraps a map of widget names to /// [LocalWidgetBuilder] callbacks. typedef LocalWidgetBuilder = Widget Function(BuildContext context, DataSource source); /// Signature of builders for remote widgets. typedef _RemoteWidgetBuilder = _CurriedWidget Function(DynamicMap builderArg); /// Signature of the callback passed to a [RemoteWidget]. /// /// This is used by [RemoteWidget] and [Runtime.build] as the callback for /// events triggered by remote widgets. typedef RemoteEventHandler = void Function(String eventName, DynamicMap eventArguments); /// Signature of the callback passed to [DataSource.handler]. /// /// The callback should return a function of type `T`. That function should call /// `trigger`. /// /// See [DataSource.handler] for details. typedef HandlerGenerator<T extends Function> = T Function(HandlerTrigger trigger); /// Signature of the callback passed to a [HandlerGenerator]. /// /// See [DataSource.handler] for details. typedef HandlerTrigger = void Function([DynamicMap? extraArguments]); /// Used to indicate that there is an error with one of the libraries loaded /// into the Remote Flutter Widgets [Runtime]. /// /// For example, a reference to a state variable did not match any actual state /// values, or a library import loop. class RemoteFlutterWidgetsException implements Exception { /// Creates a [RemoteFlutterWidgetsException]. /// /// The message should be a complete sentence, starting with a capital letter /// and ending with a period. const RemoteFlutterWidgetsException(this.message); /// A description of the problem that was detected. /// /// This will end with a period. final String message; @override String toString() => message; } /// Interface for [LocalWidgetBuilder] to obtain data from arguments. /// /// The interface exposes the [v] method, the argument to which is a list of /// keys forming a path to a node in the arguments expected by the widget. If /// the method's type argument does not match the value obtained, null is /// returned instead. /// /// In addition, to fetch widgets specifically, the [child] and [childList] /// methods must be used, and to fetch event handlers, the [handler] method must /// be used. /// /// The [isList] and [isMap] methods can be used to avoid inspecting keys that /// may not be present (e.g. before reading 15 keys in a map that isn't even /// present, consider checking if the map is present using [isMap] and /// short-circuiting the key lookups if it is not). /// /// To iterate over a list, the [length] method can be used to find the number /// of items in the list. abstract class DataSource { /// Return the int, double, bool, or String value at the given path of the /// arguments to the widget. /// /// `T` must be one of [int], [double], [bool], or [String]. /// /// If `T` does not match the type of the value obtained, then the method /// returns null. T? v<T extends Object>(List<Object> argsKey); /// Return true if the given key identifies a list, otherwise false. bool isList(List<Object> argsKey); /// Return the length of the list at the given path of the arguments to the /// widget. /// /// If the given path does not identify a list, returns zero. int length(List<Object> argsKey); /// Return true if the given key identifies a map, otherwise false. bool isMap(List<Object> argsKey); /// Build the child at the given key. /// /// If the node specified is not a widget, returns an [ErrorWidget]. /// /// See also: /// /// * [optionalChild], which returns null if the widget is missing. Widget child(List<Object> argsKey); /// Build the child at the given key. /// /// If the node specified is not a widget, returns null. /// /// See also: /// /// * [child], which returns an [ErrorWidget] instead of null if the widget /// is missing. Widget? optionalChild(List<Object> argsKey); /// Builds the children at the given key. /// /// If the node is missing, returns an empty list. /// /// If the node specified is not a list of widgets, returns a list with the /// non-widget nodes replaced by [ErrorWidget]. List<Widget> childList(List<Object> argsKey); /// Builds the widget builder at the given key. /// /// If the node is not a widget builder, returns an [ErrorWidget]. /// /// See also: /// /// * [optionalBuilder], which returns null if the widget builder is missing. Widget builder(List<Object> argsKey, DynamicMap builderArg); /// Builds the widget builder at the given key. /// /// If the node is not a widget builder, returns null. /// /// See also: /// /// * [builder], which returns an [ErrorWidget] instead of null if the widget /// builder is missing. Widget? optionalBuilder(List<Object> argsKey, DynamicMap builderArg); /// Gets a [VoidCallback] event handler at the given key. /// /// If the node specified is an [AnyEventHandler] or a [DynamicList] of /// [AnyEventHandler]s, returns a callback that invokes the specified event /// handler(s), merging the given `extraArguments` into the arguments /// specified in each event handler. In the event of a key conflict (where /// both the arguments specified in the remote widget declaration and the /// argument provided to this method have the same name), the arguments /// specified here take precedence. VoidCallback? voidHandler(List<Object> argsKey, [ DynamicMap? extraArguments ]); /// Gets an event handler at the given key. /// /// The event handler can be of any Function type, as specified by the type /// argument `T`. /// /// When this method is called, the second argument, `generator`, is invoked. /// The `generator` callback must return a function, which we will call /// _entrypoint_, that matches the signature of `T`. The `generator` callback /// receives an argument, which we will call `trigger`. The _entrypoint_ /// function must call `trigger`, optionally passing it any extra arguments /// that should be merged into the arguments specified in each event handler. /// /// This is admittedly a little confusing. At its core, the problem is that /// this method cannot itself automatically create a function (_entrypoint_) /// of the right type (`T`), and therefore a callback (`generator`) that knows /// how to wrap a function body (`trigger`) in the right signature (`T`) is /// needed to actually build that function (_entrypoint_). T? handler<T extends Function>(List<Object> argsKey, HandlerGenerator<T> generator); } /// Widgets defined by the client application. All remote widgets eventually /// bottom out in these widgets. class LocalWidgetLibrary extends WidgetLibrary { /// Create a [LocalWidgetLibrary]. /// /// The given map must not change once the object is created. LocalWidgetLibrary(this._widgets); final Map<String, LocalWidgetBuilder> _widgets; /// Returns the builder for the widget of the given name, if any. @protected LocalWidgetBuilder? findConstructor(String name) { return _widgets[name]; } /// The widgets defined by this [LocalWidgetLibrary]. /// /// The returned map is an immutable view of the map provided to the constructor. /// They keys are the unqualified widget names, and the values are the corresponding /// [LocalWidgetBuilder]s. /// /// The map never changes during the lifetime of the [LocalWidgetLibrary], but a new /// instance of an [UnmodifiableMapView] is returned each time this getter is used. /// /// See also: /// /// * [createCoreWidgets], a function that creates a [Map] of local widgets. UnmodifiableMapView<String, LocalWidgetBuilder> get widgets { return UnmodifiableMapView<String, LocalWidgetBuilder>(_widgets); } } class _ResolvedConstructor { const _ResolvedConstructor(this.fullName, this.constructor); final FullyQualifiedWidgetName fullName; final Object constructor; } /// The logic that builds and maintains Remote Flutter Widgets. /// /// To declare the libraries of widgets, the [update] method is used. /// /// At least one [LocalWidgetLibrary] instance must be declared /// so that [RemoteWidgetLibrary] instances can resolve to real widgets. /// /// The [build] method returns a [Widget] generated from one of the libraries of /// widgets added in this manner. Generally, it is simpler to use the /// [RemoteWidget] widget (which calls [build]). class Runtime extends ChangeNotifier { /// Create a [Runtime] object. /// /// This object should be [dispose]d when it is no longer needed. Runtime(); final Map<LibraryName, WidgetLibrary> _libraries = <LibraryName, WidgetLibrary>{}; /// Replace the definitions of the specified library (`name`). /// /// References to widgets that are not defined in the available libraries will /// default to using the [ErrorWidget] widget. /// /// [LocalWidgetLibrary] and [RemoteWidgetLibrary] instances are added using /// this method. /// /// [RemoteWidgetLibrary] instances are typically first obtained using /// [decodeLibraryBlob]. /// /// To remove a library, the libraries must be cleared using [clearLibraries] /// and then the libraries being retained must be readded. void update(LibraryName name, WidgetLibrary library) { _libraries[name] = library; _clearCache(); } /// Remove all the libraries and start afresh. /// /// Calling this notifies the listeners, which typically causes them to /// rebuild their widgets in the next frame (for example, that is how /// [RemoteWidget] is implemented). If no libraries are readded after calling /// [clearLibraries], and there are any listeners, they will fail to rebuild /// any widgets that they were configured to create. For this reason, this /// call should usually be immediately followed by calls to [update]. void clearLibraries() { _libraries.clear(); _clearCache(); } /// The widget libraries imported in this [Runtime]. /// /// The returned map is an immutable view of the map updated by calls to /// [update] and [clearLibraries]. /// /// The keys are instances [LibraryName] which encode fully qualified library /// names, and the values are the corresponding [WidgetLibrary]s. /// /// The returned map is an immutable copy of the registered libraries /// at the time of this call. /// /// See also: /// /// * [update] and [clearLibraries], functions that populate this map. UnmodifiableMapView<LibraryName, WidgetLibrary> get libraries { return UnmodifiableMapView<LibraryName, WidgetLibrary>(Map<LibraryName, WidgetLibrary>.from(_libraries)); } final Map<FullyQualifiedWidgetName, _ResolvedConstructor?> _cachedConstructors = <FullyQualifiedWidgetName, _ResolvedConstructor?>{}; final Map<FullyQualifiedWidgetName, _CurriedWidget> _widgets = <FullyQualifiedWidgetName, _CurriedWidget>{}; void _clearCache() { _cachedConstructors.clear(); _widgets.clear(); notifyListeners(); } /// Build the root widget of a Remote Widget subtree. /// /// The widget is identified by a [FullyQualifiedWidgetName], which identifies /// a library and a widget name. The widget does not strictly have to be in /// that library, so long as it is in that library's dependencies. /// /// The data for the widget is given by the `data` argument. That object can /// be updated independently, the widget will rebuild appropriately as it /// changes. /// /// The `remoteEventTarget` argument is the callback that the RFW runtime will /// invoke whenever a remote widget event handler is triggered. Widget build( BuildContext context, FullyQualifiedWidgetName widget, DynamicContent data, RemoteEventHandler remoteEventTarget, ) { _CurriedWidget? boundWidget = _widgets[widget]; if (boundWidget == null) { _checkForImportLoops(widget.library); boundWidget = _applyConstructorAndBindArguments( widget, const <String, Object?>{}, const <String, Object?>{}, -1, <FullyQualifiedWidgetName>{}, null, ); _widgets[widget] = boundWidget; } return boundWidget.build(context, data, remoteEventTarget, const <_WidgetState>[]); } /// Returns the [BlobNode] that most closely corresponds to a given [BuildContext]. /// /// If the `context` is not a remote widget and has no ancestor remote widget, /// then this function returns null. /// /// The [BlobNode] is typically either a [WidgetDeclaration] (whose /// [WidgetDeclaration.root] argument is a [ConstructorCall] or a [Switch] /// that resolves to a [ConstructorCall]), indicating the [BuildContext] maps /// to a remote widget, or a [ConstructorCall] directly, in the case where it /// maps to a local widget. Widgets that correspond to render objects (i.e. /// anything that might be found by hit testing on the screen) are always /// local widgets. static BlobNode? blobNodeFor(BuildContext context) { if (context.widget is! _Widget) { context.visitAncestorElements((Element element) { if (element.widget is _Widget) { context = element; return false; } return true; }); } if (context.widget is! _Widget) { return null; } return (context.widget as _Widget).curriedWidget; } void _checkForImportLoops(LibraryName name, [ Set<LibraryName>? visited ]) { final WidgetLibrary? library = _libraries[name]; if (library is RemoteWidgetLibrary) { visited ??= <LibraryName>{}; visited.add(name); for (final Import import in library.imports) { final LibraryName dependency = import.name; if (visited.contains(dependency)) { final List<LibraryName> path = <LibraryName>[dependency]; for (final LibraryName name in visited.toList().reversed) { if (name == dependency) { break; } path.add(name); } if (path.length == 1) { assert(path.single == dependency); throw RemoteFlutterWidgetsException('Library $dependency depends on itself.'); } else { throw RemoteFlutterWidgetsException('Library $dependency indirectly depends on itself via ${path.reversed.join(" which depends on ")}.'); } } _checkForImportLoops(dependency, visited.toSet()); } } } _ResolvedConstructor? _findConstructor(FullyQualifiedWidgetName fullName) { final _ResolvedConstructor? result = _cachedConstructors[fullName]; if (result != null) { return result; } final WidgetLibrary? library = _libraries[fullName.library]; if (library is RemoteWidgetLibrary) { for (final WidgetDeclaration constructor in library.widgets) { if (constructor.name == fullName.widget) { return _cachedConstructors[fullName] = _ResolvedConstructor(fullName, constructor); } } for (final Import import in library.imports) { final LibraryName dependency = import.name; final _ResolvedConstructor? result = _findConstructor(FullyQualifiedWidgetName(dependency, fullName.widget)); if (result != null) { // We cache the constructor under each name that we tried to look it up with, so // that next time it takes less time to find it. return _cachedConstructors[fullName] = result; } } } else if (library is LocalWidgetLibrary) { final LocalWidgetBuilder? constructor = library.findConstructor(fullName.widget); if (constructor != null) { return _cachedConstructors[fullName] = _ResolvedConstructor(fullName, constructor); } } else { assert(library is Null); // ignore: prefer_void_to_null, type_check_with_null, https://github.com/dart-lang/sdk/issues/47017#issuecomment-907562014 } _cachedConstructors[fullName] = null; return null; } Iterable<LibraryName> _findMissingLibraries(LibraryName library) sync* { final WidgetLibrary? root = _libraries[library]; if (root == null) { yield library; return; } if (root is LocalWidgetLibrary) { return; } root as RemoteWidgetLibrary; for (final Import import in root.imports) { yield* _findMissingLibraries(import.name); } } /// Resolves `fullName` to a [_ResolvedConstructor], then binds its arguments /// to `arguments` (binding any [ArgsReference]s to [BoundArgsReference]s) and /// expands any references to [ConstructorCall]s so that all remaining widgets /// are [_CurriedWidget]s. /// /// Widgets can't reference each other recursively; this is enforced using the /// `usedWidgets` argument. /// /// The `source` argument is the [BlobNode] that referenced the widget /// constructor, in the event that the widget comes from a /// [LocalWidgetBuilder] rather than a [WidgetDeclaration], and is used to /// provide source information for local widgets (which otherwise could not be /// associated with a part of the source). See also [Runtime.blobNodeFor]. _CurriedWidget _applyConstructorAndBindArguments( FullyQualifiedWidgetName fullName, DynamicMap arguments, DynamicMap widgetBuilderScope, int stateDepth, Set<FullyQualifiedWidgetName> usedWidgets, BlobNode? source, ) { final _ResolvedConstructor? widget = _findConstructor(fullName); if (widget != null) { if (widget.constructor is WidgetDeclaration) { if (usedWidgets.contains(widget.fullName)) { return _CurriedLocalWidget.error( fullName, 'Widget loop: Tried to call ${widget.fullName} constructor reentrantly.', )..propagateSource(source); } usedWidgets = usedWidgets.toSet()..add(widget.fullName); final WidgetDeclaration constructor = widget.constructor as WidgetDeclaration; final int newDepth; if (constructor.initialState != null) { newDepth = stateDepth + 1; } else { newDepth = stateDepth; } Object result = _bindArguments( widget.fullName, constructor.root, arguments, widgetBuilderScope, newDepth, usedWidgets, ); if (result is Switch) { result = _CurriedSwitch( widget.fullName, result, arguments, widgetBuilderScope, constructor.initialState, )..propagateSource(result); } else { result as _CurriedWidget; if (constructor.initialState != null) { result = _CurriedRemoteWidget( widget.fullName, result, arguments, widgetBuilderScope, constructor.initialState, )..propagateSource(result); } } return result as _CurriedWidget; } assert(widget.constructor is LocalWidgetBuilder); return _CurriedLocalWidget( widget.fullName, widget.constructor as LocalWidgetBuilder, arguments, widgetBuilderScope, )..propagateSource(source); } final Set<LibraryName> missingLibraries = _findMissingLibraries(fullName.library).toSet(); if (missingLibraries.isNotEmpty) { return _CurriedLocalWidget.error( fullName, 'Could not find remote widget named ${fullName.widget} in ${fullName.library}, ' 'possibly because some dependencies were missing: ${missingLibraries.join(", ")}', )..propagateSource(source); } return _CurriedLocalWidget.error(fullName, 'Could not find remote widget named ${fullName.widget} in ${fullName.library}.') ..propagateSource(source); } Object _bindArguments( FullyQualifiedWidgetName context, Object node, Object arguments, DynamicMap widgetBuilderScope, int stateDepth, Set<FullyQualifiedWidgetName> usedWidgets, ) { if (node is ConstructorCall) { final DynamicMap subArguments = _bindArguments( context, node.arguments, arguments, widgetBuilderScope, stateDepth, usedWidgets, ) as DynamicMap; return _applyConstructorAndBindArguments( FullyQualifiedWidgetName(context.library, node.name), subArguments, widgetBuilderScope, stateDepth, usedWidgets, node, ); } if (node is WidgetBuilderDeclaration) { return (DynamicMap widgetBuilderArg) { final DynamicMap newWidgetBuilderScope = <String, Object?> { ...widgetBuilderScope, node.argumentName: widgetBuilderArg, }; final Object result = _bindArguments( context, node.widget, arguments, newWidgetBuilderScope, stateDepth, usedWidgets, ); if (result is Switch) { return _CurriedSwitch( FullyQualifiedWidgetName(context.library, ''), result, arguments as DynamicMap, newWidgetBuilderScope, const <String, Object?>{}, )..propagateSource(result); } return result as _CurriedWidget; }; } if (node is DynamicMap) { return node.map<String, Object?>( (String name, Object? value) => MapEntry<String, Object?>( name, _bindArguments(context, value!, arguments, widgetBuilderScope, stateDepth, usedWidgets), ), ); } if (node is DynamicList) { return List<Object>.generate( node.length, (int index) => _bindArguments( context, node[index]!, arguments, widgetBuilderScope, stateDepth, usedWidgets, ), growable: false, ); } if (node is Loop) { final Object input = _bindArguments(context, node.input, arguments, widgetBuilderScope, stateDepth, usedWidgets); final Object output = _bindArguments(context, node.output, arguments, widgetBuilderScope, stateDepth, usedWidgets); return Loop(input, output) ..propagateSource(node); } if (node is Switch) { return Switch( _bindArguments(context, node.input, arguments, widgetBuilderScope, stateDepth, usedWidgets), node.outputs.map<Object?, Object>( (Object? key, Object value) { return MapEntry<Object?, Object>( key == null ? key : _bindArguments(context, key, arguments, widgetBuilderScope, stateDepth, usedWidgets), _bindArguments(context, value, arguments, widgetBuilderScope, stateDepth, usedWidgets), ); }, ), )..propagateSource(node); } if (node is ArgsReference) { return node.bind(arguments)..propagateSource(node); } if (node is StateReference) { return node.bind(stateDepth)..propagateSource(node); } if (node is EventHandler) { return EventHandler( node.eventName, _bindArguments( context, node.eventArguments, arguments, widgetBuilderScope, stateDepth, usedWidgets, ) as DynamicMap, )..propagateSource(node); } if (node is SetStateHandler) { assert(node.stateReference is StateReference); final BoundStateReference stateReference = (node.stateReference as StateReference).bind(stateDepth); return SetStateHandler( stateReference, _bindArguments(context, node.value, arguments, widgetBuilderScope, stateDepth, usedWidgets), )..propagateSource(node); } assert(node is! WidgetDeclaration); return node; } } // Internal structure to represent the result of indexing into a list. // // There are two ways this can go: either we index in and find a result, in // which case [result] is that value and the other fields are null, or we fail // to index into the list and we obtain the length as a side-effect, in which // case [result] is null, [rawList] is the raw list (might contain [Loop] objects), // and [length] is the effective length after expanding all the internal loops. class _ResolvedDynamicList { const _ResolvedDynamicList(this.rawList, this.result, this.length); final DynamicList? rawList; final Object? result; // null means out of range final int? length; // might be null if result is not null } typedef _DataResolverCallback = Object Function(List<Object> dataKey); typedef _StateResolverCallback = Object Function(List<Object> stateKey, int depth); typedef _WidgetBuilderArgResolverCallback = Object Function(List<Object> argKey); abstract class _CurriedWidget extends BlobNode { const _CurriedWidget( this.fullName, this.arguments, this.widgetBuilderScope, this.initialState, ); final FullyQualifiedWidgetName fullName; final DynamicMap arguments; final DynamicMap widgetBuilderScope; final DynamicMap? initialState; static Object _bindLoopVariable(Object node, Object argument, int depth) { if (node is DynamicMap) { return node.map<String, Object?>( (String name, Object? value) => MapEntry<String, Object?>(name, _bindLoopVariable(value!, argument, depth)), ); } if (node is DynamicList) { return List<Object>.generate( node.length, (int index) => _bindLoopVariable(node[index]!, argument, depth), growable: false, ); } if (node is Loop) { return Loop(_bindLoopVariable(node.input, argument, depth), _bindLoopVariable(node.output, argument, depth + 1)) ..propagateSource(node); } if (node is Switch) { return Switch( _bindLoopVariable(node.input, argument, depth), node.outputs.map<Object?, Object>( (Object? key, Object value) => MapEntry<Object?, Object>( key == null ? null : _bindLoopVariable(key, argument, depth), _bindLoopVariable(value, argument, depth), ), ) )..propagateSource(node); } if (node is _CurriedLocalWidget) { return _CurriedLocalWidget( node.fullName, node.child, _bindLoopVariable(node.arguments, argument, depth) as DynamicMap, _bindLoopVariable(node.widgetBuilderScope, argument, depth) as DynamicMap, )..propagateSource(node); } if (node is _CurriedRemoteWidget) { return _CurriedRemoteWidget( node.fullName, _bindLoopVariable(node.child, argument, depth) as _CurriedWidget, _bindLoopVariable(node.arguments, argument, depth) as DynamicMap, _bindLoopVariable(node.widgetBuilderScope, argument, depth) as DynamicMap, node.initialState, )..propagateSource(node); } if (node is _CurriedSwitch) { return _CurriedSwitch( node.fullName, _bindLoopVariable(node.root, argument, depth) as Switch, _bindLoopVariable(node.arguments, argument, depth) as DynamicMap, _bindLoopVariable(node.widgetBuilderScope, argument, depth) as DynamicMap, node.initialState, )..propagateSource(node); } if (node is LoopReference) { if (node.loop == depth) { return node.bind(argument)..propagateSource(node); } return node; } if (node is BoundArgsReference) { return BoundArgsReference(_bindLoopVariable(node.arguments, argument, depth), node.parts) ..propagateSource(node); } if (node is EventHandler) { return EventHandler(node.eventName, _bindLoopVariable(node.eventArguments, argument, depth) as DynamicMap) ..propagateSource(node); } if (node is SetStateHandler) { return SetStateHandler(node.stateReference, _bindLoopVariable(node.value, argument, depth)) ..propagateSource(node); } return node; } /// Look up the _index_th entry in `list`, expanding any loops in `list`. /// /// If `targetEffectiveIndex` is -1, this evaluates the entire list to ensure /// the length is available. // // TODO(ianh): This really should have some sort of caching. Right now, evaluating a whole list // ends up being around O(N^2) since we have to walk the list from the start for every entry. static _ResolvedDynamicList _listLookup( DynamicList list, int targetEffectiveIndex, _StateResolverCallback stateResolver, _DataResolverCallback dataResolver, _WidgetBuilderArgResolverCallback widgetBuilderArgResolver, ) { int currentIndex = 0; // where we are in `list` (some entries of which might represent multiple values, because they are themselves loops) int effectiveIndex = 0; // where we are in the fully expanded list (the coordinate space in which we're aiming for `targetEffectiveIndex`) while ((effectiveIndex <= targetEffectiveIndex || targetEffectiveIndex < 0) && currentIndex < list.length) { final Object node = list[currentIndex]!; if (node is Loop) { Object inputList = node.input; while (inputList is! DynamicList) { if (inputList is BoundArgsReference) { inputList = _resolveFrom( inputList.arguments, inputList.parts, stateResolver, dataResolver, widgetBuilderArgResolver, ); } else if (inputList is DataReference) { inputList = dataResolver(inputList.parts); } else if (inputList is BoundStateReference) { inputList = stateResolver(inputList.parts, inputList.depth); } else if (inputList is BoundLoopReference) { inputList = _resolveFrom( inputList.value, inputList.parts, stateResolver, dataResolver, widgetBuilderArgResolver, ); } else if (inputList is Switch) { inputList = _resolveFrom( inputList, const <Object>[], stateResolver, dataResolver, widgetBuilderArgResolver, ); } else { // e.g. it's a map or something else that isn't indexable inputList = DynamicList.empty(); } assert(inputList is! _ResolvedDynamicList); } final _ResolvedDynamicList entry = _listLookup( inputList, targetEffectiveIndex >= 0 ? targetEffectiveIndex - effectiveIndex : -1, stateResolver, dataResolver, widgetBuilderArgResolver, ); if (entry.result != null) { final Object boundResult = _bindLoopVariable(node.output, entry.result!, 0); return _ResolvedDynamicList(null, boundResult, null); } effectiveIndex += entry.length!; } else { // list[currentIndex] is not a Loop if (effectiveIndex == targetEffectiveIndex) { return _ResolvedDynamicList(null, list[currentIndex], null); } effectiveIndex += 1; } currentIndex += 1; } return _ResolvedDynamicList(list, null, effectiveIndex); } static Object _resolveFrom( Object root, List<Object> parts, _StateResolverCallback stateResolver, _DataResolverCallback dataResolver, _WidgetBuilderArgResolverCallback widgetBuilderArgResolver, ) { int index = 0; Object current = root; while (true) { if (current is DataReference) { if (index < parts.length) { current = current.constructReference(parts.sublist(index)); index = parts.length; } current = dataResolver(current.parts); continue; } else if (current is WidgetBuilderArgReference) { current = widgetBuilderArgResolver(<Object>[current.argumentName, ...current.parts]); continue; } else if (current is BoundArgsReference) { List<Object> nextParts = current.parts; if (index < parts.length) { nextParts += parts.sublist(index); } parts = nextParts; current = current.arguments; index = 0; continue; } else if (current is BoundStateReference) { if (index < parts.length) { current = current.constructReference(parts.sublist(index)); index = parts.length; } current = stateResolver(current.parts, current.depth); continue; } else if (current is BoundLoopReference) { List<Object> nextParts = current.parts; if (index < parts.length) { nextParts += parts.sublist(index); } parts = nextParts; current = current.value; index = 0; continue; } else if (current is Switch) { final Object key = _resolveFrom( current.input, const <Object>[], stateResolver, dataResolver, widgetBuilderArgResolver, ); Object? value = current.outputs[key]; if (value == null) { value = current.outputs[null]; if (value == null) { return missing; } } current = value; continue; } else if (index >= parts.length) { // We've reached the end of the line. // We handle some special leaf cases that still need processing before we return. if (current is EventHandler) { current = EventHandler( current.eventName, _fix(current.eventArguments, stateResolver, dataResolver, widgetBuilderArgResolver) as DynamicMap, ); } else if (current is SetStateHandler) { current = SetStateHandler( current.stateReference, _fix(current.value, stateResolver, dataResolver, widgetBuilderArgResolver), ); } // else `current` is nothing special, and we'll just return it below. break; // This is where the loop ends. } else if (current is DynamicMap) { if (parts[index] is! String) { return missing; } if (!current.containsKey(parts[index])) { return missing; } current = current[parts[index]]!; } else if (current is DynamicList) { if (parts[index] is! int) { return missing; } current = _listLookup( current, parts[index] as int, stateResolver, dataResolver, widgetBuilderArgResolver, ).result ?? missing; } else { assert(current is! ArgsReference); assert(current is! StateReference); assert(current is! LoopReference); return missing; } index += 1; } assert(current is! Reference, 'Unexpected unbound reference (of type ${current.runtimeType}): $current'); assert(current is! Switch); assert(current is! Loop); return current; } static Object _fix( Object root, _StateResolverCallback stateResolver, _DataResolverCallback dataResolver, _WidgetBuilderArgResolverCallback widgetBuilderArgResolver, ) { if (root is DynamicMap) { return root.map((String key, Object? value) => MapEntry<String, Object?>( key, _fix(root[key]!, stateResolver, dataResolver, widgetBuilderArgResolver), ), ); } else if (root is DynamicList) { if (root.any((Object? entry) => entry is Loop)) { final int length = _listLookup( root, -1, stateResolver, dataResolver, widgetBuilderArgResolver, ).length!; return DynamicList.generate( length, (int index) => _fix( _listLookup(root, index, stateResolver, dataResolver, widgetBuilderArgResolver).result!, stateResolver, dataResolver, widgetBuilderArgResolver, ), ); } else { return DynamicList.generate( root.length, (int index) => _fix(root[index]!, stateResolver, dataResolver, widgetBuilderArgResolver), ); } } else if (root is BlobNode) { return _resolveFrom(root, const <Object>[], stateResolver, dataResolver, widgetBuilderArgResolver); } else { return root; } } Object resolve( List<Object> parts, _StateResolverCallback stateResolver, _DataResolverCallback dataResolver, _WidgetBuilderArgResolverCallback widgetBuilderArgResolver, { required bool expandLists, }) { Object result = _resolveFrom(arguments, parts, stateResolver, dataResolver, widgetBuilderArgResolver); if (result is DynamicList && expandLists) { result = _listLookup(result, -1, stateResolver, dataResolver, widgetBuilderArgResolver); } assert(result is! Reference); assert(result is! Switch); assert(result is! Loop); return result; } Widget build( BuildContext context, DynamicContent data, RemoteEventHandler remoteEventTarget, List<_WidgetState> states, ) { return _Widget( curriedWidget: this, data: data, widgetBuilderScope: DynamicContent(widgetBuilderScope), remoteEventTarget: remoteEventTarget, states: states, ); } Widget buildChild( BuildContext context, DataSource source, DynamicContent data, RemoteEventHandler remoteEventTarget, List<_WidgetState> states, _StateResolverCallback stateResolver, _DataResolverCallback dataResolver, _WidgetBuilderArgResolverCallback widgetBuilderArgResolver, ); @override String toString() => '$fullName ${initialState ?? "{}"} $arguments'; } class _CurriedLocalWidget extends _CurriedWidget { const _CurriedLocalWidget( FullyQualifiedWidgetName fullName, this.child, DynamicMap arguments, DynamicMap widgetBuilderScope, ) : super(fullName, arguments, widgetBuilderScope, null); factory _CurriedLocalWidget.error(FullyQualifiedWidgetName fullName, String message) { return _CurriedLocalWidget( fullName, (BuildContext context, DataSource data) => _buildErrorWidget(message), const <String, Object?>{}, const <String, Object?>{}, ); } final LocalWidgetBuilder child; @override Widget buildChild( BuildContext context, DataSource source, DynamicContent data, RemoteEventHandler remoteEventTarget, List<_WidgetState> states, _StateResolverCallback stateResolver, _DataResolverCallback dataResolver, _WidgetBuilderArgResolverCallback widgetBuilderArgResolver, ) { return child(context, source); } } class _CurriedRemoteWidget extends _CurriedWidget { const _CurriedRemoteWidget( FullyQualifiedWidgetName fullName, this.child, DynamicMap arguments, DynamicMap widgetBuilderScope, DynamicMap? initialState, ) : super(fullName, arguments, widgetBuilderScope, initialState); final _CurriedWidget child; @override Widget buildChild( BuildContext context, DataSource source, DynamicContent data, RemoteEventHandler remoteEventTarget, List<_WidgetState> states, _StateResolverCallback stateResolver, _DataResolverCallback dataResolver, _WidgetBuilderArgResolverCallback widgetBuilderArgResolver, ) { return child.build(context, data, remoteEventTarget, states); } @override String toString() => '${super.toString()} = $child'; } class _CurriedSwitch extends _CurriedWidget { const _CurriedSwitch( FullyQualifiedWidgetName fullName, this.root, DynamicMap arguments, DynamicMap widgetBuilderScope, DynamicMap? initialState, ) : super(fullName, arguments, widgetBuilderScope, initialState); final Switch root; @override Widget buildChild( BuildContext context, DataSource source, DynamicContent data, RemoteEventHandler remoteEventTarget, List<_WidgetState> states, _StateResolverCallback stateResolver, _DataResolverCallback dataResolver, _WidgetBuilderArgResolverCallback widgetBuilderArgResolver, ) { final Object resolvedWidget = _CurriedWidget._resolveFrom( root, const <Object>[], stateResolver, dataResolver, widgetBuilderArgResolver, ); if (resolvedWidget is _CurriedWidget) { return resolvedWidget.build(context, data, remoteEventTarget, states); } return _buildErrorWidget('Switch in $fullName did not resolve to a widget (got $resolvedWidget).'); } @override String toString() => '${super.toString()} = $root'; } class _Widget extends StatefulWidget { const _Widget({ required this.curriedWidget, required this.data, required this.widgetBuilderScope, required this.remoteEventTarget, required this.states, }); final _CurriedWidget curriedWidget; final DynamicContent data; final DynamicContent widgetBuilderScope; final RemoteEventHandler remoteEventTarget; final List<_WidgetState> states; @override State<_Widget> createState() => _WidgetState(); } class _WidgetState extends State<_Widget> implements DataSource { DynamicContent? _state; DynamicMap? _stateStore; late List<_WidgetState> _states; @override void initState() { super.initState(); _updateState(); } @override void didUpdateWidget(_Widget oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.curriedWidget != widget.curriedWidget) { _updateState(); } if (oldWidget.data != widget.data || oldWidget.curriedWidget != widget.curriedWidget || oldWidget.states != widget.states) { _unsubscribe(); } } @override void dispose() { _unsubscribe(); super.dispose(); } void _updateState() { _stateStore = deepClone(widget.curriedWidget.initialState) as DynamicMap?; if (_stateStore != null) { _state ??= DynamicContent(); _state!.updateAll(_stateStore!); } else { _state = null; } _states = widget.states; if (_state != null) { _states = _states.toList()..add(this); } } void _handleSetState(int depth, List<Object> parts, Object value) { _states[depth].applySetState(parts, value); } void applySetState(List<Object> parts, Object value) { assert(parts.isNotEmpty); assert(_stateStore != null); int index = 0; Object current = _stateStore!; while (index < parts.length) { final Object subindex = parts[index]; if (current is DynamicMap) { if (subindex is! String) { throw RemoteFlutterWidgetsException('${parts.join(".")} does not identify existing state.'); } if (!current.containsKey(subindex)) { throw RemoteFlutterWidgetsException('${parts.join(".")} does not identify existing state.'); } if (index == parts.length - 1) { current[subindex] = value; } else { current = current[parts[index]]!; } } else if (current is DynamicList) { if (subindex is! int) { throw RemoteFlutterWidgetsException('${parts.join(".")} does not identify existing state.'); } if (subindex < 0 || subindex >= current.length) { throw RemoteFlutterWidgetsException('${parts.join(".")} does not identify existing state.'); } if (index == parts.length - 1) { current[subindex] = value; } else { current = current[subindex]!; } } else { throw RemoteFlutterWidgetsException('${parts.join(".")} does not identify existing state.'); } index += 1; } _state!.updateAll(_stateStore!); } // List of subscriptions into [widget.data]. // // Keys are into the [DynamicContent] object. final Map<_Key, _Subscription> _subscriptions = <_Key, _Subscription>{}; void _unsubscribe() { for (final _Subscription value in _subscriptions.values) { value.dispose(); } _subscriptions.clear(); _argsCache.clear(); } @override T? v<T extends Object>(List<Object> argsKey) { assert(T == int || T == double || T == bool || T == String); final Object value = _fetch(argsKey, expandLists: false); return value is T ? value : null; } @override bool isList(List<Object> argsKey) { final Object value = _fetch(argsKey, expandLists: false); return value is _ResolvedDynamicList || value is DynamicList; } @override int length(List<Object> argsKey) { final Object value = _fetch(argsKey, expandLists: true); if (value is _ResolvedDynamicList) { if (value.rawList != null) { assert(value.length != null); return value.length!; } } assert(value is! DynamicList); return 0; } @override bool isMap(List<Object> argsKey) { final Object value = _fetch(argsKey, expandLists: false); return value is DynamicMap; } @override Widget child(List<Object> argsKey) { final Object value = _fetch(argsKey, expandLists: false); if (value is _CurriedWidget) { return value.build(context, widget.data, widget.remoteEventTarget, widget.states); } return _buildErrorWidget('Not a widget at $argsKey (got $value) for ${widget.curriedWidget.fullName}.'); } @override Widget? optionalChild(List<Object> argsKey) { final Object value = _fetch(argsKey, expandLists: false); if (value is _CurriedWidget) { return value.build(context, widget.data, widget.remoteEventTarget, widget.states); } return null; } @override List<Widget> childList(List<Object> argsKey) { final Object value = _fetch(argsKey, expandLists: true); if (value is _ResolvedDynamicList) { assert(value.length != null); final DynamicList fullList = _fetchList(argsKey, value.length!); return List<Widget>.generate( fullList.length, (int index) { final Object? node = fullList[index]; if (node is _CurriedWidget) { return node.build(context, widget.data, widget.remoteEventTarget, _states); } return _buildErrorWidget('Not a widget at $argsKey (got $node) for ${widget.curriedWidget.fullName}.'); }, ); } if (value == missing) { return const <Widget>[]; } return <Widget>[ _buildErrorWidget('Not a widget list at $argsKey (got $value) for ${widget.curriedWidget.fullName}.'), ]; } @override Widget builder(List<Object> argsKey, DynamicMap builderArg) { return _fetchBuilder(argsKey, builderArg, optional: false)!; } @override Widget? optionalBuilder(List<Object> argsKey, DynamicMap builderArg) { return _fetchBuilder(argsKey, builderArg); } Widget? _fetchBuilder( List<Object> argsKey, DynamicMap builderArg, { bool optional = true, }) { final Object value = _fetch(argsKey, expandLists: false); if (value is _RemoteWidgetBuilder) { final _CurriedWidget curriedWidget = value(builderArg); return curriedWidget.build( context, widget.data, widget.remoteEventTarget, widget.states, ); } return optional ? null : _buildErrorWidget('Not a builder at $argsKey (got $value) for ${widget.curriedWidget.fullName}.'); } @override VoidCallback? voidHandler(List<Object> argsKey, [ DynamicMap? extraArguments ]) { return handler<VoidCallback>(argsKey, (HandlerTrigger callback) => () => callback(extraArguments)); } @override T? handler<T extends Function>(List<Object> argsKey, HandlerGenerator<T> generator) { Object value = _fetch(argsKey, expandLists: true); if (value is AnyEventHandler) { value = <Object>[ value ]; } else if (value is _ResolvedDynamicList) { value = _fetchList(argsKey, value.length!); } if (value is DynamicList) { final List<AnyEventHandler> handlers = value.whereType<AnyEventHandler>().toList(); if (handlers.isNotEmpty) { return generator(([DynamicMap? extraArguments]) { for (final AnyEventHandler entry in handlers) { if (entry is EventHandler) { DynamicMap arguments = entry.eventArguments; if (extraArguments != null) { arguments = DynamicMap.fromEntries(arguments.entries.followedBy(extraArguments.entries)); } widget.remoteEventTarget(entry.eventName, arguments); } else if (entry is SetStateHandler) { assert(entry.stateReference is BoundStateReference); _handleSetState((entry.stateReference as BoundStateReference).depth, entry.stateReference.parts, entry.value); } } }); } } return null; } // null values means the data is not in the cache final Map<_Key, Object?> _argsCache = <_Key, Object?>{}; bool _debugFetching = false; final List<_Subscription> _dependencies = <_Subscription>[]; Object _fetch(List<Object> argsKey, { required bool expandLists }) { final _Key key = _Key(_kArgsSection, argsKey); final Object? value = _argsCache[key]; if (value != null && (value is! DynamicList || !expandLists)) { return value; } assert(!_debugFetching); try { _debugFetching = true; final Object result = widget.curriedWidget.resolve( argsKey, _stateResolver, _dataResolver, _widgetBuilderArgResolver, expandLists: expandLists, ); for (final _Subscription subscription in _dependencies) { subscription.addClient(key); } _argsCache[key] = result; return result; } finally { _dependencies.clear(); _debugFetching = false; } } DynamicList _fetchList(List<Object> argsKey, int length) { return DynamicList.generate(length, (int index) { return _fetch(<Object>[...argsKey, index], expandLists: false); }); } Object _dataResolver(List<Object> rawDataKey) { final _Key dataKey = _Key(_kDataSection, rawDataKey); final _Subscription subscription; if (!_subscriptions.containsKey(dataKey)) { subscription = _Subscription(widget.data, this, rawDataKey); _subscriptions[dataKey] = subscription; } else { subscription = _subscriptions[dataKey]!; } _dependencies.add(subscription); return subscription.value; } Object _widgetBuilderArgResolver(List<Object> rawDataKey) { final _Key widgetBuilderArgKey = _Key(_kWidgetBuilderArgSection, rawDataKey); final _Subscription subscription = _subscriptions[widgetBuilderArgKey] ??= _Subscription( widget.widgetBuilderScope, this, rawDataKey, ); _dependencies.add(subscription); return subscription.value; } Object _stateResolver(List<Object> rawStateKey, int depth) { final _Key stateKey = _Key(depth, rawStateKey); final _Subscription subscription; if (!_subscriptions.containsKey(stateKey)) { if (depth >= _states.length) { throw const RemoteFlutterWidgetsException('Reference to state value did not correspond to any stateful remote widget.'); } final DynamicContent? state = _states[depth]._state; if (state == null) { return missing; } subscription = _Subscription(state, this, rawStateKey); _subscriptions[stateKey] = subscription; } else { subscription = _subscriptions[stateKey]!; } _dependencies.add(subscription); return subscription.value; } void updateData(Set<_Key> affectedArgs) { setState(() { for (final _Key key in affectedArgs) { _argsCache[key] = null; } }); } @override Widget build(BuildContext context) { // TODO(ianh): what if this creates some _dependencies? return widget.curriedWidget.buildChild( context, this, widget.data, widget.remoteEventTarget, _states, _stateResolver, _dataResolver, _widgetBuilderArgResolver, ); } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(StringProperty('name', '${widget.curriedWidget.fullName}')); } } const int _kDataSection = -1; const int _kArgsSection = -2; const int _kWidgetBuilderArgSection = -3; @immutable class _Key { _Key(this.section, this.parts) : assert(_isValidKey(parts), '$parts is not a valid key'); static bool _isValidKey(List<Object> parts) { return parts.every((Object segment) => segment is int || segment is String); } final int section; final List<Object> parts; @override bool operator ==(Object other) { return other is _Key // _Key has no subclasses, don't need to check runtimeType && section == other.section && listEquals(parts, other.parts); } @override int get hashCode => Object.hash(section, Object.hashAll(parts)); } class _Subscription { _Subscription(this._data, this._state, this._dataKey) { _update(_data.subscribe(_dataKey, _update)); } final DynamicContent _data; final _WidgetState _state; final List<Object> _dataKey; final Set<_Key> _clients = <_Key>{}; Object get value => _value; late Object _value; void _update(Object value) { _state.updateData(_clients); _value = value; } void addClient(_Key key) { _clients.add(key); } void dispose() { _data.unsubscribe(_dataKey, _update); } } Widget _buildErrorWidget(String message) { final FlutterErrorDetails detail = FlutterErrorDetails( exception: message, stack: StackTrace.current, library: 'Remote Flutter Widgets', ); FlutterError.reportError(detail); return ErrorWidget.builder(detail); }
packages/packages/rfw/lib/src/flutter/runtime.dart/0
{ "file_path": "packages/packages/rfw/lib/src/flutter/runtime.dart", "repo_id": "packages", "token_count": 19378 }
992
name: test_coverage description: "Internal coverage test logic for package:rfw." version: 1.0.0 publish_to: none environment: sdk: ^3.2.0 dependencies: lcov_parser: 0.1.1 meta: ^1.7.0
packages/packages/rfw/test_coverage/pubspec.yaml/0
{ "file_path": "packages/packages/rfw/test_coverage/pubspec.yaml", "repo_id": "packages", "token_count": 79 }
993
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="io.flutter.plugins.sharedpreferences"> </manifest>
packages/packages/shared_preferences/shared_preferences_android/android/src/main/AndroidManifest.xml/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences_android/android/src/main/AndroidManifest.xml", "repo_id": "packages", "token_count": 47 }
994
## NEXT * Updates minimum supported SDK version to Flutter 3.13/Dart 3.1. ## 2.3.2 * Updates `package:file` version constraints. ## 2.3.1 * Adds pub topics to package metadata. * Updates minimum supported SDK version to Flutter 3.7/Dart 2.19. ## 2.3.0 * Adds `clearWithParameters` and `getAllWithParameters` methods. * Updates minimum supported SDK version to Flutter 3.3/Dart 2.18. ## 2.2.0 * Adds `getAllWithPrefix` and `clearWithPrefix` methods. ## 2.1.5 * Clarifies explanation of endorsement in README. * Aligns Dart and Flutter SDK constraints. ## 2.1.4 * Updates links for the merge of flutter/plugins into flutter/packages. * Updates minimum Flutter version to 3.0. ## 2.1.3 * Updates code for stricter lint checks. ## 2.1.2 * Updates code for stricter lint checks. * Updates code for `no_leading_underscores_for_local_identifiers` lint. * Updates minimum Flutter version to 2.10. ## 2.1.1 * Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors lint warnings. ## 2.1.0 * Deprecated `SharedPreferencesWindows.instance` in favor of `SharedPreferencesStorePlatform.instance`. ## 2.0.4 * Removes dependency on `meta`. ## 2.0.3 * Removed obsolete `pluginClass: none` from pubpsec. * Fixes newly enabled analyzer options. ## 2.0.2 * Updated installation instructions in README. ## 2.0.1 * Add `implements` to pubspec.yaml. * Add `registerWith` to the Dart main class. ## 2.0.0 * Migrate to null-safety. ## 0.0.2+3 * Remove 'ffi' dependency. ## 0.0.2+2 * Relax 'ffi' version constraint. ## 0.0.2+1 * Update Flutter SDK constraint. ## 0.0.2 * Update integration test examples to use `testWidgets` instead of `test`. ## 0.0.1+3 * Remove unused `test` dependency. ## 0.0.1+2 * Check in windows/ directory for example/ ## 0.0.1+1 * Add iOS stub for compatibility with 1.17 and earlier. ## 0.0.1 * Initial release to support shared_preferences on Windows.
packages/packages/shared_preferences/shared_preferences_windows/CHANGELOG.md/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences_windows/CHANGELOG.md", "repo_id": "packages", "token_count": 685 }
995
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'package:file/memory.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:path/path.dart' as path; import 'package:path_provider_platform_interface/path_provider_platform_interface.dart'; import 'package:path_provider_windows/path_provider_windows.dart'; import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart'; import 'package:shared_preferences_platform_interface/types.dart'; import 'package:shared_preferences_windows/shared_preferences_windows.dart'; void main() { late MemoryFileSystem fs; late PathProviderWindows pathProvider; SharedPreferencesWindows.registerWith(); 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); setUp(() { fs = MemoryFileSystem.test(); pathProvider = FakePathProviderWindows(); }); Future<String> getFilePath() async { final String? directory = await pathProvider.getApplicationSupportPath(); return path.join(directory!, 'shared_preferences.json'); } Future<void> writeTestFile(String value) async { fs.file(await getFilePath()) ..createSync(recursive: true) ..writeAsStringSync(value); } Future<String> readTestFile() async { return fs.file(await getFilePath()).readAsStringSync(); } SharedPreferencesWindows getPreferences() { final SharedPreferencesWindows prefs = SharedPreferencesWindows(); prefs.fs = fs; prefs.pathProvider = pathProvider; return prefs; } test('registered instance', () { SharedPreferencesWindows.registerWith(); expect(SharedPreferencesStorePlatform.instance, isA<SharedPreferencesWindows>()); }); test('getAll', () async { await writeTestFile(json.encode(allTestValues)); final SharedPreferencesWindows prefs = getPreferences(); final Map<String, Object> values = await prefs.getAll(); expect(values, hasLength(5)); expect(values, flutterTestValues); }); test('getAllWithPrefix', () async { await writeTestFile(json.encode(allTestValues)); final SharedPreferencesWindows prefs = getPreferences(); final Map<String, Object> values = await prefs.getAllWithPrefix('prefix.'); expect(values, hasLength(5)); expect(values, prefixTestValues); }); test('getAllWithParameters with Prefix', () async { await writeTestFile(json.encode(allTestValues)); final SharedPreferencesWindows prefs = getPreferences(); final Map<String, Object> values = await prefs.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: 'prefix.'), ), ); expect(values, hasLength(5)); expect(values, prefixTestValues); }); test('getAllWithParameters with Prefix with allow list', () async { await writeTestFile(json.encode(allTestValues)); final SharedPreferencesWindows prefs = getPreferences(); final Map<String?, Object?> all = await prefs.getAllWithParameters( GetAllParameters( filter: PreferencesFilter( prefix: 'prefix.', allowList: <String>{'prefix.Bool'}, ), ), ); expect(all.length, 1); expect(all['prefix.Bool'], prefixTestValues['prefix.Bool']); }); test('remove', () async { await writeTestFile('{"key1":"one","key2":2}'); final SharedPreferencesWindows prefs = getPreferences(); await prefs.remove('key2'); expect(await readTestFile(), '{"key1":"one"}'); }); test('setValue', () async { await writeTestFile('{}'); final SharedPreferencesWindows prefs = getPreferences(); await prefs.setValue('', 'key1', 'one'); await prefs.setValue('', 'key2', 2); expect(await readTestFile(), '{"key1":"one","key2":2}'); }); test('clear', () async { await writeTestFile(json.encode(flutterTestValues)); final SharedPreferencesWindows prefs = getPreferences(); expect(await readTestFile(), json.encode(flutterTestValues)); await prefs.clear(); expect(await readTestFile(), '{}'); }); test('clearWithPrefix', () async { await writeTestFile(json.encode(flutterTestValues)); final SharedPreferencesWindows prefs = getPreferences(); await prefs.clearWithPrefix('prefix.'); final Map<String, Object> noValues = await prefs.getAllWithPrefix('prefix.'); expect(noValues, hasLength(0)); final Map<String, Object> values = await prefs.getAll(); expect(values, hasLength(5)); expect(values, flutterTestValues); }); test('getAllWithNoPrefix', () async { await writeTestFile(json.encode(allTestValues)); final SharedPreferencesWindows prefs = getPreferences(); final Map<String, Object> values = await prefs.getAllWithPrefix(''); expect(values, hasLength(15)); expect(values, allTestValues); }); test('clearWithNoPrefix', () async { await writeTestFile(json.encode(flutterTestValues)); final SharedPreferencesWindows prefs = getPreferences(); await prefs.clearWithPrefix(''); final Map<String, Object> noValues = await prefs.getAllWithPrefix(''); expect(noValues, hasLength(0)); }); test('clearWithParameters with Prefix', () async { await writeTestFile(json.encode(flutterTestValues)); final SharedPreferencesWindows prefs = getPreferences(); await prefs.clearWithParameters( ClearParameters( filter: PreferencesFilter(prefix: 'prefix.'), ), ); final Map<String, Object> noValues = await prefs.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: 'prefix.'), ), ); expect(noValues, hasLength(0)); final Map<String, Object> values = await prefs.getAll(); expect(values, hasLength(5)); expect(values, flutterTestValues); }); test('clearWithParameters with allow list', () async { await writeTestFile(json.encode(prefixTestValues)); final SharedPreferencesWindows prefs = getPreferences(); await prefs.clearWithParameters( ClearParameters( filter: PreferencesFilter( prefix: 'prefix.', allowList: <String>{'prefix.StringList'}, ), ), ); final Map<String, Object> noValues = await prefs.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: 'prefix.'), ), ); expect(noValues, hasLength(4)); }); test('getAllWithNoPrefix', () async { await writeTestFile(json.encode(allTestValues)); final SharedPreferencesWindows prefs = getPreferences(); final Map<String, Object> values = await prefs.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: ''), ), ); expect(values, hasLength(15)); expect(values, allTestValues); }); test('clearWithNoPrefix', () async { await writeTestFile(json.encode(flutterTestValues)); final SharedPreferencesWindows prefs = getPreferences(); await prefs.clearWithParameters( ClearParameters( filter: PreferencesFilter(prefix: ''), ), ); final Map<String, Object> noValues = await prefs.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: ''), ), ); expect(noValues, hasLength(0)); }); } /// Fake implementation of PathProviderWindows that returns hard-coded paths, /// allowing tests to run on any platform. /// /// Note that this should only be used with an in-memory filesystem, as the /// path it returns is a root path that does not actually exist on Windows. class FakePathProviderWindows extends PathProviderPlatform implements PathProviderWindows { @override late VersionInfoQuerier versionInfoQuerier; @override Future<String?> getApplicationSupportPath() async => r'C:\appsupport'; @override Future<String?> getTemporaryPath() async => null; @override Future<String?> getLibraryPath() async => null; @override Future<String?> getApplicationDocumentsPath() async => null; @override Future<String?> getDownloadsPath() async => null; @override Future<String> getPath(String folderID) async => ''; }
packages/packages/shared_preferences/shared_preferences_windows/test/shared_preferences_windows_test.dart/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences_windows/test/shared_preferences_windows_test.dart", "repo_id": "packages", "token_count": 3068 }
996
## 0.1.2 * Fixes a layout issue for unpinned merged cells that follow pinned table spans. * Updates outdated sample code. ## 0.1.1 * Fixes a layout issue when pinned cells are merged. ## 0.1.0 * [Breaking change] Adds support for merged cells in the TableView. ## 0.0.6 * Fixes an error in TableSpanDecoration when one or both axes are reversed. ## 0.0.5+2 * Fixes must_call_super lint warning from pending framework change. ## 0.0.5+1 * Fixes new lint warnings. ## 0.0.5 * Exposes addAutomaticKeepAlives in TableCellBuilderDelegate and TableCellListDelegate * Fixes bug where having one reversed axis caused incorrect painting of a pinned row. * Adds support for BorderRadius in TableSpanDecorations. ## 0.0.4 * Adds TableSpanPadding, TableSpan.padding, and TableSpanDecoration.consumeSpanPadding. ## 0.0.3 * Fixes paint issue when axes are reversed and TableView has pinned rows and columns. ## 0.0.2 * Fixes override of default TwoDimensionalChildBuilderDelegate.addRepaintBoundaries. ## 0.0.1+1 * Adds pub topics to package metadata. ## 0.0.1 * Initial release - TableView
packages/packages/two_dimensional_scrollables/CHANGELOG.md/0
{ "file_path": "packages/packages/two_dimensional_scrollables/CHANGELOG.md", "repo_id": "packages", "token_count": 347 }
997
// 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/gestures.dart'; import 'package:flutter/material.dart'; import 'package:two_dimensional_scrollables/two_dimensional_scrollables.dart'; // Print statements are only for illustrative purposes, not recommended for // production applications. // ignore_for_file: avoid_print void main() { runApp(const TableExampleApp()); } /// A sample application that utilizes the TableView API. class TableExampleApp extends StatelessWidget { /// Creates an instance of the TableView example app. const TableExampleApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Table Example', theme: ThemeData( useMaterial3: true, ), home: const TableExample(), ); } } /// The class containing the TableView for the sample application. class TableExample extends StatefulWidget { /// Creates a screen that demonstrates the TableView widget. const TableExample({super.key}); @override State<TableExample> createState() => _TableExampleState(); } class _TableExampleState extends State<TableExample> { late final ScrollController _verticalController = ScrollController(); int _rowCount = 20; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Table Example'), ), body: Padding( padding: const EdgeInsets.symmetric(horizontal: 50), child: TableView.builder( verticalDetails: ScrollableDetails.vertical(controller: _verticalController), cellBuilder: _buildCell, columnCount: 20, columnBuilder: _buildColumnSpan, rowCount: _rowCount, rowBuilder: _buildRowSpan, ), ), persistentFooterButtons: <Widget>[ TextButton( onPressed: () { _verticalController.jumpTo(0); }, child: const Text('Jump to Top'), ), TextButton( onPressed: () { _verticalController .jumpTo(_verticalController.position.maxScrollExtent); }, child: const Text('Jump to Bottom'), ), TextButton( onPressed: () { setState(() { _rowCount += 10; }); }, child: const Text('Add 10 Rows'), ), ], ); } TableViewCell _buildCell(BuildContext context, TableVicinity vicinity) { return TableViewCell( child: Center( child: Text('Tile c: ${vicinity.column}, r: ${vicinity.row}'), ), ); } TableSpan _buildColumnSpan(int index) { const TableSpanDecoration decoration = TableSpanDecoration( border: TableSpanBorder( trailing: BorderSide(), ), ); switch (index % 5) { case 0: return TableSpan( foregroundDecoration: decoration, extent: const FixedTableSpanExtent(100), onEnter: (_) => print('Entered column $index'), recognizerFactories: <Type, GestureRecognizerFactory>{ TapGestureRecognizer: GestureRecognizerFactoryWithHandlers<TapGestureRecognizer>( () => TapGestureRecognizer(), (TapGestureRecognizer t) => t.onTap = () => print('Tap column $index'), ), }, ); case 1: return TableSpan( foregroundDecoration: decoration, extent: const FractionalTableSpanExtent(0.5), onEnter: (_) => print('Entered column $index'), cursor: SystemMouseCursors.contextMenu, ); case 2: return TableSpan( foregroundDecoration: decoration, extent: const FixedTableSpanExtent(120), onEnter: (_) => print('Entered column $index'), ); case 3: return TableSpan( foregroundDecoration: decoration, extent: const FixedTableSpanExtent(145), onEnter: (_) => print('Entered column $index'), ); case 4: return TableSpan( foregroundDecoration: decoration, extent: const FixedTableSpanExtent(200), onEnter: (_) => print('Entered column $index'), ); } throw AssertionError( 'This should be unreachable, as every index is accounted for in the switch clauses.'); } TableSpan _buildRowSpan(int index) { final TableSpanDecoration decoration = TableSpanDecoration( color: index.isEven ? Colors.purple[100] : null, border: const TableSpanBorder( trailing: BorderSide( width: 3, ), ), ); switch (index % 3) { case 0: return TableSpan( backgroundDecoration: decoration, extent: const FixedTableSpanExtent(50), recognizerFactories: <Type, GestureRecognizerFactory>{ TapGestureRecognizer: GestureRecognizerFactoryWithHandlers<TapGestureRecognizer>( () => TapGestureRecognizer(), (TapGestureRecognizer t) => t.onTap = () => print('Tap row $index'), ), }, ); case 1: return TableSpan( backgroundDecoration: decoration, extent: const FixedTableSpanExtent(65), cursor: SystemMouseCursors.click, ); case 2: return TableSpan( backgroundDecoration: decoration, extent: const FractionalTableSpanExtent(0.15), ); } throw AssertionError( 'This should be unreachable, as every index is accounted for in the switch clauses.'); } }
packages/packages/two_dimensional_scrollables/example/lib/main.dart/0
{ "file_path": "packages/packages/two_dimensional_scrollables/example/lib/main.dart", "repo_id": "packages", "token_count": 2465 }
998
// 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. /// The [TableView] and associated widgets. /// /// To use, import `package:two_dimensional_scrollables/two_dimensional_scrollables.dart`. library table_view; export 'src/table_view/table.dart'; export 'src/table_view/table_cell.dart'; export 'src/table_view/table_delegate.dart'; export 'src/table_view/table_span.dart';
packages/packages/two_dimensional_scrollables/lib/two_dimensional_scrollables.dart/0
{ "file_path": "packages/packages/two_dimensional_scrollables/lib/two_dimensional_scrollables.dart", "repo_id": "packages", "token_count": 151 }
999
// 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.urllauncher; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.provider.Browser; import androidx.browser.customtabs.CustomTabsIntent; import androidx.test.core.app.ApplicationProvider; import java.util.HashMap; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.robolectric.RobolectricTestRunner; @RunWith(RobolectricTestRunner.class) public class UrlLauncherTest { @Test public void canLaunch_createsIntentWithPassedUrl() { UrlLauncher.IntentResolver resolver = mock(UrlLauncher.IntentResolver.class); UrlLauncher api = new UrlLauncher(ApplicationProvider.getApplicationContext(), resolver); Uri url = Uri.parse("https://flutter.dev"); when(resolver.getHandlerComponentName(any())).thenReturn(null); api.canLaunchUrl(url.toString()); final ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class); verify(resolver).getHandlerComponentName(intentCaptor.capture()); assertEquals(url, intentCaptor.getValue().getData()); } @Test public void canLaunch_returnsTrue() { UrlLauncher api = new UrlLauncher(ApplicationProvider.getApplicationContext(), intent -> "some.component"); Boolean result = api.canLaunchUrl("https://flutter.dev"); assertTrue(result); } @Test public void canLaunch_returnsFalse() { UrlLauncher api = new UrlLauncher(ApplicationProvider.getApplicationContext(), intent -> null); Boolean result = api.canLaunchUrl("https://flutter.dev"); assertFalse(result); } // Integration testing on emulators won't work as expected without the workaround this tests // for, since it will be returned even for intentionally bogus schemes. @Test public void canLaunch_returnsFalseForEmulatorFallbackComponent() { UrlLauncher api = new UrlLauncher( ApplicationProvider.getApplicationContext(), intent -> "{com.android.fallback/com.android.fallback.Fallback}"); Boolean result = api.canLaunchUrl("https://flutter.dev"); assertFalse(result); } @Test public void launch_throwsForNoCurrentActivity() { UrlLauncher api = new UrlLauncher(ApplicationProvider.getApplicationContext()); api.setActivity(null); Messages.FlutterError exception = assertThrows( Messages.FlutterError.class, () -> api.launchUrl("https://flutter.dev", new HashMap<>())); assertEquals("NO_ACTIVITY", exception.code); } @Test public void launch_createsIntentWithPassedUrl() { Activity activity = mock(Activity.class); String url = "https://flutter.dev"; UrlLauncher api = new UrlLauncher(ApplicationProvider.getApplicationContext()); api.setActivity(activity); doThrow(new ActivityNotFoundException()).when(activity).startActivity(any()); api.launchUrl("https://flutter.dev", new HashMap<>()); final ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class); verify(activity).startActivity(intentCaptor.capture()); assertEquals(url, intentCaptor.getValue().getData().toString()); } @Test public void launch_returnsFalse() { Activity activity = mock(Activity.class); UrlLauncher api = new UrlLauncher(ApplicationProvider.getApplicationContext()); api.setActivity(activity); doThrow(new ActivityNotFoundException()).when(activity).startActivity(any()); boolean result = api.launchUrl("https://flutter.dev", new HashMap<>()); assertFalse(result); } @Test public void launch_returnsTrue() { Activity activity = mock(Activity.class); UrlLauncher api = new UrlLauncher(ApplicationProvider.getApplicationContext()); api.setActivity(activity); boolean result = api.launchUrl("https://flutter.dev", new HashMap<>()); assertTrue(result); } @Test public void openUrlInApp_opensUrlInWebViewIfNecessary() { Activity activity = mock(Activity.class); UrlLauncher api = new UrlLauncher(ApplicationProvider.getApplicationContext()); api.setActivity(activity); String url = "https://flutter.dev"; boolean enableJavaScript = false; boolean enableDomStorage = false; HashMap<String, String> headers = new HashMap<>(); headers.put("key", "value"); boolean showTitle = false; boolean result = api.openUrlInApp( url, true, new Messages.WebViewOptions.Builder() .setEnableJavaScript(enableJavaScript) .setEnableDomStorage(enableDomStorage) .setHeaders(headers) .build(), new Messages.BrowserOptions.Builder().setShowTitle(showTitle).build()); final ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class); verify(activity).startActivity(intentCaptor.capture()); assertTrue(result); assertEquals(url, intentCaptor.getValue().getExtras().getString(WebViewActivity.URL_EXTRA)); assertEquals( enableJavaScript, intentCaptor.getValue().getExtras().getBoolean(WebViewActivity.ENABLE_JS_EXTRA)); assertEquals( enableDomStorage, intentCaptor.getValue().getExtras().getBoolean(WebViewActivity.ENABLE_DOM_EXTRA)); } @Test public void openWebView_opensUrlInWebViewIfRequested() { Activity activity = mock(Activity.class); UrlLauncher api = new UrlLauncher(ApplicationProvider.getApplicationContext()); api.setActivity(activity); String url = "https://flutter.dev"; boolean result = api.openUrlInApp( url, false, new Messages.WebViewOptions.Builder() .setEnableJavaScript(false) .setEnableDomStorage(false) .setHeaders(new HashMap<>()) .build(), new Messages.BrowserOptions.Builder().setShowTitle(true).build()); final ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class); verify(activity).startActivity(intentCaptor.capture()); assertTrue(result); assertEquals(url, intentCaptor.getValue().getExtras().getString(WebViewActivity.URL_EXTRA)); } @Test public void openWebView_opensUrlInCustomTabs() { Activity activity = mock(Activity.class); UrlLauncher api = new UrlLauncher(ApplicationProvider.getApplicationContext()); api.setActivity(activity); String url = "https://flutter.dev"; boolean result = api.openUrlInApp( url, true, new Messages.WebViewOptions.Builder() .setEnableJavaScript(false) .setEnableDomStorage(false) .setHeaders(new HashMap<>()) .build(), new Messages.BrowserOptions.Builder().setShowTitle(false).build()); final ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class); verify(activity).startActivity(intentCaptor.capture(), isNull()); assertTrue(result); assertEquals(Intent.ACTION_VIEW, intentCaptor.getValue().getAction()); assertNull(intentCaptor.getValue().getComponent()); } @Test public void openWebView_opensUrlInCustomTabsWithCORSAllowedHeader() { Activity activity = mock(Activity.class); UrlLauncher api = new UrlLauncher(ApplicationProvider.getApplicationContext()); api.setActivity(activity); String url = "https://flutter.dev"; HashMap<String, String> headers = new HashMap<>(); String headerKey = "Content-Type"; headers.put(headerKey, "text/plain"); boolean result = api.openUrlInApp( url, true, new Messages.WebViewOptions.Builder() .setEnableJavaScript(false) .setEnableDomStorage(false) .setHeaders(headers) .build(), new Messages.BrowserOptions.Builder().setShowTitle(false).build()); final ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class); verify(activity).startActivity(intentCaptor.capture(), isNull()); assertTrue(result); assertEquals(Intent.ACTION_VIEW, intentCaptor.getValue().getAction()); assertNull(intentCaptor.getValue().getComponent()); final Bundle passedHeaders = intentCaptor.getValue().getExtras().getBundle(Browser.EXTRA_HEADERS); assertEquals(headers.get(headerKey), passedHeaders.getString(headerKey)); } @Test public void openWebView_opensUrlInCustomTabsWithShowTitle() { Activity activity = mock(Activity.class); UrlLauncher api = new UrlLauncher(ApplicationProvider.getApplicationContext()); api.setActivity(activity); String url = "https://flutter.dev"; HashMap<String, String> headers = new HashMap<>(); boolean result = api.openUrlInApp( url, true, new Messages.WebViewOptions.Builder() .setEnableJavaScript(false) .setEnableDomStorage(false) .setHeaders(headers) .build(), new Messages.BrowserOptions.Builder().setShowTitle(true).build()); final ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class); verify(activity).startActivity(intentCaptor.capture(), isNull()); assertTrue(result); assertEquals(Intent.ACTION_VIEW, intentCaptor.getValue().getAction()); assertNull(intentCaptor.getValue().getComponent()); assertEquals( intentCaptor.getValue().getExtras().getInt(CustomTabsIntent.EXTRA_TITLE_VISIBILITY_STATE), CustomTabsIntent.SHOW_PAGE_TITLE); } @Test public void openWebView_opensUrlInCustomTabsWithoutShowTitle() { Activity activity = mock(Activity.class); UrlLauncher api = new UrlLauncher(ApplicationProvider.getApplicationContext()); api.setActivity(activity); String url = "https://flutter.dev"; HashMap<String, String> headers = new HashMap<>(); boolean result = api.openUrlInApp( url, true, new Messages.WebViewOptions.Builder() .setEnableJavaScript(false) .setEnableDomStorage(false) .setHeaders(headers) .build(), new Messages.BrowserOptions.Builder().setShowTitle(false).build()); final ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class); verify(activity).startActivity(intentCaptor.capture(), isNull()); assertTrue(result); assertEquals(Intent.ACTION_VIEW, intentCaptor.getValue().getAction()); assertNull(intentCaptor.getValue().getComponent()); assertEquals( intentCaptor.getValue().getExtras().getInt(CustomTabsIntent.EXTRA_TITLE_VISIBILITY_STATE), CustomTabsIntent.NO_TITLE); } @Test public void openWebView_fallsBackToWebViewIfCustomTabFails() { Activity activity = mock(Activity.class); UrlLauncher api = new UrlLauncher(ApplicationProvider.getApplicationContext()); api.setActivity(activity); String url = "https://flutter.dev"; doThrow(new ActivityNotFoundException()) .when(activity) .startActivity(any(), isNull()); // for custom tabs intent boolean result = api.openUrlInApp( url, true, new Messages.WebViewOptions.Builder() .setEnableJavaScript(false) .setEnableDomStorage(false) .setHeaders(new HashMap<>()) .build(), new Messages.BrowserOptions.Builder().setShowTitle(false).build()); final ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class); verify(activity).startActivity(intentCaptor.capture()); assertTrue(result); assertEquals(url, intentCaptor.getValue().getExtras().getString(WebViewActivity.URL_EXTRA)); assertEquals( false, intentCaptor.getValue().getExtras().getBoolean(WebViewActivity.ENABLE_JS_EXTRA)); assertEquals( false, intentCaptor.getValue().getExtras().getBoolean(WebViewActivity.ENABLE_DOM_EXTRA)); } @Test public void openWebView_handlesEnableJavaScript() { Activity activity = mock(Activity.class); UrlLauncher api = new UrlLauncher(ApplicationProvider.getApplicationContext()); api.setActivity(activity); boolean enableJavaScript = true; HashMap<String, String> headers = new HashMap<>(); headers.put("key", "value"); api.openUrlInApp( "https://flutter.dev", true, new Messages.WebViewOptions.Builder() .setEnableJavaScript(enableJavaScript) .setEnableDomStorage(false) .setHeaders(headers) .build(), new Messages.BrowserOptions.Builder().setShowTitle(false).build()); final ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class); verify(activity).startActivity(intentCaptor.capture()); assertEquals( enableJavaScript, intentCaptor.getValue().getExtras().getBoolean(WebViewActivity.ENABLE_JS_EXTRA)); } @Test public void openWebView_handlesHeaders() { Activity activity = mock(Activity.class); UrlLauncher api = new UrlLauncher(ApplicationProvider.getApplicationContext()); api.setActivity(activity); HashMap<String, String> headers = new HashMap<>(); final String key1 = "key"; final String key2 = "key2"; headers.put(key1, "value"); headers.put(key2, "value2"); api.openUrlInApp( "https://flutter.dev", true, new Messages.WebViewOptions.Builder() .setEnableJavaScript(false) .setEnableDomStorage(false) .setHeaders(headers) .build(), new Messages.BrowserOptions.Builder().setShowTitle(false).build()); final ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class); verify(activity).startActivity(intentCaptor.capture()); final Bundle passedHeaders = intentCaptor.getValue().getExtras().getBundle(Browser.EXTRA_HEADERS); assertEquals(headers.size(), passedHeaders.size()); assertEquals(headers.get(key1), passedHeaders.getString(key1)); assertEquals(headers.get(key2), passedHeaders.getString(key2)); } @Test public void openWebView_handlesEnableDomStorage() { Activity activity = mock(Activity.class); UrlLauncher api = new UrlLauncher(ApplicationProvider.getApplicationContext()); api.setActivity(activity); boolean enableDomStorage = true; HashMap<String, String> headers = new HashMap<>(); headers.put("key", "value"); api.openUrlInApp( "https://flutter.dev", true, new Messages.WebViewOptions.Builder() .setEnableJavaScript(false) .setEnableDomStorage(enableDomStorage) .setHeaders(headers) .build(), new Messages.BrowserOptions.Builder().setShowTitle(false).build()); final ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class); verify(activity).startActivity(intentCaptor.capture()); assertEquals( enableDomStorage, intentCaptor.getValue().getExtras().getBoolean(WebViewActivity.ENABLE_DOM_EXTRA)); } @Test public void openWebView_handlesEnableShowTitle() { Activity activity = mock(Activity.class); UrlLauncher api = new UrlLauncher(ApplicationProvider.getApplicationContext()); api.setActivity(activity); boolean enableDomStorage = true; HashMap<String, String> headers = new HashMap<>(); boolean showTitle = true; api.openUrlInApp( "https://flutter.dev", true, new Messages.WebViewOptions.Builder() .setEnableJavaScript(false) .setEnableDomStorage(enableDomStorage) .setHeaders(headers) .build(), new Messages.BrowserOptions.Builder().setShowTitle(showTitle).build()); final ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class); verify(activity).startActivity(intentCaptor.capture(), isNull()); assertEquals( intentCaptor.getValue().getExtras().getInt(CustomTabsIntent.EXTRA_TITLE_VISIBILITY_STATE), CustomTabsIntent.SHOW_PAGE_TITLE); } @Test public void openWebView_throwsForNoCurrentActivity() { UrlLauncher api = new UrlLauncher(ApplicationProvider.getApplicationContext()); api.setActivity(null); Messages.FlutterError exception = assertThrows( Messages.FlutterError.class, () -> api.openUrlInApp( "https://flutter.dev", true, new Messages.WebViewOptions.Builder() .setEnableJavaScript(false) .setEnableDomStorage(false) .setHeaders(new HashMap<>()) .build(), new Messages.BrowserOptions.Builder().setShowTitle(false).build())); assertEquals("NO_ACTIVITY", exception.code); } @Test public void openWebView_returnsFalse() { Activity activity = mock(Activity.class); UrlLauncher api = new UrlLauncher(ApplicationProvider.getApplicationContext()); api.setActivity(activity); doThrow(new ActivityNotFoundException()) .when(activity) .startActivity(any(), isNull()); // for custom tabs intent doThrow(new ActivityNotFoundException()) .when(activity) .startActivity(any()); // for webview intent boolean result = api.openUrlInApp( "https://flutter.dev", true, new Messages.WebViewOptions.Builder() .setEnableJavaScript(false) .setEnableDomStorage(false) .setHeaders(new HashMap<>()) .build(), new Messages.BrowserOptions.Builder().setShowTitle(false).build()); assertFalse(result); } @Test public void closeWebView_closes() { Context context = mock(Context.class); UrlLauncher api = new UrlLauncher(context); api.closeWebView(); final ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class); verify(context).sendBroadcast(intentCaptor.capture()); assertEquals(WebViewActivity.ACTION_CLOSE, intentCaptor.getValue().getAction()); } }
packages/packages/url_launcher/url_launcher_android/android/src/test/java/io/flutter/plugins/urllauncher/UrlLauncherTest.java/0
{ "file_path": "packages/packages/url_launcher/url_launcher_android/android/src/test/java/io/flutter/plugins/urllauncher/UrlLauncherTest.java", "repo_id": "packages", "token_count": 7190 }
1,000
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:url_launcher_linux/url_launcher_linux.dart'; import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('UrlLauncherLinux', () { const MethodChannel channel = MethodChannel('plugins.flutter.io/url_launcher_linux'); final List<MethodCall> log = <MethodCall>[]; TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockMethodCallHandler(channel, (MethodCall methodCall) async { log.add(methodCall); // Return null explicitly instead of relying on the implicit null // returned by the method channel if no return statement is specified. return null; }); tearDown(() { log.clear(); }); test('registers instance', () { UrlLauncherLinux.registerWith(); expect(UrlLauncherPlatform.instance, isA<UrlLauncherLinux>()); }); test('canLaunch', () async { final UrlLauncherLinux launcher = UrlLauncherLinux(); await launcher.canLaunch('http://example.com/'); expect( log, <Matcher>[isMethodCall('canLaunch', arguments: 'http://example.com/')], ); }); test('canLaunch should return false if platform returns null', () async { final UrlLauncherLinux launcher = UrlLauncherLinux(); final bool canLaunch = await launcher.canLaunch('http://example.com/'); expect(canLaunch, false); }); test('launch', () async { final UrlLauncherLinux launcher = UrlLauncherLinux(); await launcher.launch( 'http://example.com/', useSafariVC: true, useWebView: false, enableJavaScript: false, enableDomStorage: false, universalLinksOnly: false, headers: const <String, String>{}, ); expect( log, <Matcher>[isMethodCall('launch', arguments: 'http://example.com/')], ); }); test('launch should return false if platform returns null', () async { final UrlLauncherLinux launcher = UrlLauncherLinux(); final bool launched = await launcher.launch( 'http://example.com/', useSafariVC: true, useWebView: false, enableJavaScript: false, enableDomStorage: false, universalLinksOnly: false, headers: const <String, String>{}, ); expect(launched, false); }); group('launchUrl', () { test('passes URL', () async { final UrlLauncherLinux launcher = UrlLauncherLinux(); await launcher.launchUrl('http://example.com/', const LaunchOptions()); expect( log, <Matcher>[isMethodCall('launch', arguments: 'http://example.com/')], ); }); test('returns false if platform returns null', () async { final UrlLauncherLinux launcher = UrlLauncherLinux(); final bool launched = await launcher.launchUrl( 'http://example.com/', const LaunchOptions()); expect(launched, false); }); }); group('supportsMode', () { test('returns true for platformDefault', () async { final UrlLauncherLinux launcher = UrlLauncherLinux(); expect(await launcher.supportsMode(PreferredLaunchMode.platformDefault), true); }); test('returns true for external application', () async { final UrlLauncherLinux launcher = UrlLauncherLinux(); expect( await launcher .supportsMode(PreferredLaunchMode.externalApplication), true); }); test('returns false for other modes', () async { final UrlLauncherLinux launcher = UrlLauncherLinux(); expect( await launcher.supportsMode( PreferredLaunchMode.externalNonBrowserApplication), false); expect( await launcher.supportsMode(PreferredLaunchMode.inAppBrowserView), false); expect(await launcher.supportsMode(PreferredLaunchMode.inAppWebView), false); }); }); test('supportsCloseForMode returns false', () async { final UrlLauncherLinux launcher = UrlLauncherLinux(); expect( await launcher .supportsCloseForMode(PreferredLaunchMode.platformDefault), false); expect( await launcher .supportsCloseForMode(PreferredLaunchMode.externalApplication), false); }); }); }
packages/packages/url_launcher/url_launcher_linux/test/url_launcher_linux_test.dart/0
{ "file_path": "packages/packages/url_launcher/url_launcher_linux/test/url_launcher_linux_test.dart", "repo_id": "packages", "token_count": 1832 }
1,001
# url\_launcher\_web The web implementation of [`url_launcher`][1]. ## Usage This package is [endorsed][2], which means you can simply use `url_launcher` normally. This package will be automatically included in your app when you do, so you do not need to add it to your `pubspec.yaml`. However, if you `import` this package to use any of its APIs directly, you should add it to your `pubspec.yaml` as usual. [1]: https://pub.dev/packages/url_launcher [2]: https://flutter.dev/docs/development/packages-and-plugins/developing-packages#endorsed-federated-plugin ## Limitations on the Web platform ### A launch needs to be triggered by a user action Web browsers prevent launching URLs in a new tab/window, unless triggered by a user action (e.g. a button click). Even if a user triggers a launch through a button click, if there is a delay due to awaiting a Future before the launch, the browser may still block it. This is because the browser might perceive the launch as not being a direct result of user interaction, particularly if the Future takes too long to complete. In such cases, you can use the `webOnlyWindowName` parameter, setting it to `_self`, to open the URL within the current tab. Another approach is to ensure that the `uri` is synchronously ready. Read more: MDN > [Transient activation](https://developer.mozilla.org/en-US/docs/Glossary/Transient_activation).
packages/packages/url_launcher/url_launcher_web/README.md/0
{ "file_path": "packages/packages/url_launcher/url_launcher_web/README.md", "repo_id": "packages", "token_count": 384 }
1,002
## NEXT * Updates minimum supported SDK version to Flutter 3.13/Dart 3.1. ## 3.1.1 * Updates `launchUrl` to return false instead of throwing when there is no handler. * Updates minimum supported SDK version to Flutter 3.10/Dart 3.0. ## 3.1.0 * Implements `supportsMode` and `supportsCloseForMode`. ## 3.0.8 * Adds pub topics to package metadata. * Updates minimum supported SDK version to Flutter 3.7/Dart 2.19. ## 3.0.7 * Updates pigeon dependency for url_launcher_windows to "^10.1.2". * Updates minimum supported SDK version to Flutter 3.3/Dart 2.18. ## 3.0.6 * Sets a cmake_policy compatibility version to fix build warnings. ## 3.0.5 * Clarifies explanation of endorsement in README. * Aligns Dart and Flutter SDK constraints. ## 3.0.4 * Updates links for the merge of flutter/plugins into flutter/packages. ## 3.0.3 * Converts internal implentation to Pigeon. * Updates minimum Flutter version to 3.0. ## 3.0.2 * Updates code for stricter lint checks. * Updates minimum Flutter version to 2.10. ## 3.0.1 * Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors lint warnings. ## 3.0.0 * Changes the major version since, due to a typo in `default_package` in existing versions of `url_launcher`, requiring Dart registration in this package is in practice a breaking change. * Does not include any API changes; clients can allow both 2.x or 3.x. ## 2.0.3 **\[Retracted\]** * Switches to an in-package method channel implementation. * Adds unit tests. * Updates code for new analysis options. ## 2.0.2 * Replaced reference to `shared_preferences` plugin with the `url_launcher` in the README. ## 2.0.1 * Updated installation instructions in README. ## 2.0.0 * Migrate to null-safety. * Update the example app: remove the deprecated `RaisedButton` and `FlatButton` widgets. * Set `implementation` in pubspec.yaml ## 0.0.2+1 * Update Flutter SDK constraint. ## 0.0.2 * Update integration test examples to use `testWidgets` instead of `test`. ## 0.0.1+3 * Update Dart SDK constraint in example. ## 0.0.1+2 * Check in windows/ directory for example/ ## 0.0.1+1 * Update README to reflect endorsement. ## 0.0.1 * Initial Windows implementation of `url_launcher`.
packages/packages/url_launcher/url_launcher_windows/CHANGELOG.md/0
{ "file_path": "packages/packages/url_launcher/url_launcher_windows/CHANGELOG.md", "repo_id": "packages", "token_count": 743 }
1,003
name: url_launcher_windows description: Windows implementation of the url_launcher plugin. repository: https://github.com/flutter/packages/tree/main/packages/url_launcher/url_launcher_windows issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+url_launcher%22 version: 3.1.1 environment: sdk: ^3.1.0 flutter: ">=3.13.0" flutter: plugin: implements: url_launcher platforms: windows: pluginClass: UrlLauncherWindows dartPluginClass: UrlLauncherWindows dependencies: flutter: sdk: flutter url_launcher_platform_interface: ^2.2.0 dev_dependencies: flutter_test: sdk: flutter pigeon: ^13.0.0 test: ^1.16.3 topics: - links - os-integration - url-launcher - urls
packages/packages/url_launcher/url_launcher_windows/pubspec.yaml/0
{ "file_path": "packages/packages/url_launcher/url_launcher_windows/pubspec.yaml", "repo_id": "packages", "token_count": 316 }
1,004
<?code-excerpt path-base="example/lib"?> # Video Player plugin for Flutter [![pub package](https://img.shields.io/pub/v/video_player.svg)](https://pub.dev/packages/video_player) A Flutter plugin for iOS, Android and Web for playing back video on a Widget surface. | | Android | iOS | macOS | Web | |-------------|---------|-------|--------|-------| | **Support** | SDK 16+ | 12.0+ | 10.14+ | Any\* | ![The example app running in iOS](https://github.com/flutter/packages/blob/main/packages/video_player/video_player/doc/demo_ipod.gif?raw=true) ## Installation First, add `video_player` as a [dependency in your pubspec.yaml file](https://flutter.dev/using-packages/). ### iOS If you need to access videos using `http` (rather than `https`) URLs, you will need to add the appropriate `NSAppTransportSecurity` permissions to your app's _Info.plist_ file, located in `<project root>/ios/Runner/Info.plist`. See [Apple's documentation](https://developer.apple.com/documentation/bundleresources/information_property_list/nsapptransportsecurity) to determine the right combination of entries for your use case and supported iOS versions. ### Android If you are using network-based videos, ensure that the following permission is present in your Android Manifest file, located in `<project root>/android/app/src/main/AndroidManifest.xml`: ```xml <uses-permission android:name="android.permission.INTERNET"/> ``` ### macOS If you are using network-based videos, you will need to [add the `com.apple.security.network.client` entitlement](https://docs.flutter.dev/platform-integration/macos/building#entitlements-and-the-app-sandbox) ### Web > The Web platform does **not** support `dart:io`, so avoid using the `VideoPlayerController.file` constructor for the plugin. Using the constructor attempts to create a `VideoPlayerController.file` that will throw an `UnimplementedError`. \* Different web browsers may have different video-playback capabilities (supported formats, autoplay...). Check [package:video_player_web](https://pub.dev/packages/video_player_web) for more web-specific information. The `VideoPlayerOptions.mixWithOthers` option can't be implemented in web, at least at the moment. If you use this option in web it will be silently ignored. ## Supported Formats - On iOS and macOS, the backing player is [AVPlayer](https://developer.apple.com/documentation/avfoundation/avplayer). The supported formats vary depending on the version of iOS, [AVURLAsset](https://developer.apple.com/documentation/avfoundation/avurlasset) class has [audiovisualTypes](https://developer.apple.com/documentation/avfoundation/avurlasset/1386800-audiovisualtypes?language=objc) that you can query for supported av formats. - On Android, the backing player is [ExoPlayer](https://google.github.io/ExoPlayer/), please refer [here](https://google.github.io/ExoPlayer/supported-formats.html) for list of supported formats. - On Web, available formats depend on your users' browsers (vendor and version). Check [package:video_player_web](https://pub.dev/packages/video_player_web) for more specific information. ## Example <?code-excerpt "basic.dart (basic-example)"?> ```dart import 'package:flutter/material.dart'; import 'package:video_player/video_player.dart'; void main() => runApp(const VideoApp()); /// Stateful widget to fetch and then display video content. class VideoApp extends StatefulWidget { const VideoApp({super.key}); @override _VideoAppState createState() => _VideoAppState(); } class _VideoAppState extends State<VideoApp> { late VideoPlayerController _controller; @override void initState() { super.initState(); _controller = VideoPlayerController.networkUrl(Uri.parse( 'https://flutter.github.io/assets-for-api-docs/assets/videos/bee.mp4')) ..initialize().then((_) { // Ensure the first frame is shown after the video is initialized, even before the play button has been pressed. setState(() {}); }); } @override Widget build(BuildContext context) { return MaterialApp( title: 'Video Demo', home: Scaffold( body: Center( child: _controller.value.isInitialized ? AspectRatio( aspectRatio: _controller.value.aspectRatio, child: VideoPlayer(_controller), ) : Container(), ), floatingActionButton: FloatingActionButton( onPressed: () { setState(() { _controller.value.isPlaying ? _controller.pause() : _controller.play(); }); }, child: Icon( _controller.value.isPlaying ? Icons.pause : Icons.play_arrow, ), ), ), ); } @override void dispose() { super.dispose(); _controller.dispose(); } } ``` ## Usage The following section contains usage information that goes beyond what is included in the documentation in order to give a more elaborate overview of the API. This is not complete as of now. You can contribute to this section by [opening a pull request](https://github.com/flutter/packages/pulls). ### Playback speed You can set the playback speed on your `_controller` (instance of `VideoPlayerController`) by calling `_controller.setPlaybackSpeed`. `setPlaybackSpeed` takes a `double` speed value indicating the rate of playback for your video. For example, when given a value of `2.0`, your video will play at 2x the regular playback speed and so on. To learn about playback speed limitations, see the [`setPlaybackSpeed` method documentation](https://pub.dev/documentation/video_player/latest/video_player/VideoPlayerController/setPlaybackSpeed.html). Furthermore, see the example app for an example playback speed implementation.
packages/packages/video_player/video_player/README.md/0
{ "file_path": "packages/packages/video_player/video_player/README.md", "repo_id": "packages", "token_count": 1895 }
1,005
// 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:js_interop'; import 'dart:math' as math; import 'dart:ui'; import 'dart:ui_web' as ui_web; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'package:meta/meta.dart'; import 'package:web/web.dart' as html; import 'common.dart'; /// The number of samples from warm-up iterations. /// /// We warm-up the benchmark prior to measuring to allow JIT and caches to settle. const int _kWarmUpSampleCount = 200; /// The total number of samples collected by a benchmark. const int kTotalSampleCount = _kWarmUpSampleCount + kMeasuredSampleCount; /// A benchmark metric that includes frame-related computations prior to /// submitting layer and picture operations to the underlying renderer, such as /// HTML and CanvasKit. During this phase we compute transforms, clips, and /// other information needed for rendering. const String kProfilePrerollFrame = 'preroll_frame'; /// A benchmark metric that includes submitting layer and picture information /// to the renderer. const String kProfileApplyFrame = 'apply_frame'; /// Measures the amount of time [action] takes. Duration timeAction(VoidCallback action) { final Stopwatch stopwatch = Stopwatch()..start(); action(); stopwatch.stop(); return stopwatch.elapsed; } /// A function that performs asynchronous work. typedef AsyncVoidCallback = Future<void> Function(); /// An [AsyncVoidCallback] that doesn't do anything. /// /// This is used just so we don't have to deal with null all over the place. Future<void> _dummyAsyncVoidCallback() async {} /// Runs the benchmark using the given [recorder]. /// /// Notifies about "set up" and "tear down" events via the [setUpAllDidRun] /// and [tearDownAllWillRun] callbacks. @sealed class Runner { /// Creates a runner for the [recorder]. /// /// All arguments must not be null. Runner({ required this.recorder, this.setUpAllDidRun = _dummyAsyncVoidCallback, this.tearDownAllWillRun = _dummyAsyncVoidCallback, }); /// The recorder that will run and record the benchmark. final Recorder recorder; /// Called immediately after [Recorder.setUpAll] future is resolved. /// /// This is useful, for example, to kick off a profiler or a tracer such that /// the "set up" computations are not included in the metrics. final AsyncVoidCallback setUpAllDidRun; /// Called just before calling [Recorder.tearDownAll]. /// /// This is useful, for example, to stop a profiler or a tracer such that /// the "tear down" computations are not included in the metrics. final AsyncVoidCallback tearDownAllWillRun; /// Runs the benchmark and reports the results. Future<Profile> run() async { await recorder.setUpAll(); await setUpAllDidRun(); final Profile profile = await recorder.run(); await tearDownAllWillRun(); await recorder.tearDownAll(); return profile; } } /// Base class for benchmark recorders. /// /// Each benchmark recorder has a [name] and a [run] method at a minimum. abstract class Recorder { Recorder._(this.name, this.isTracingEnabled); /// Whether this recorder requires tracing using Chrome's DevTools Protocol's /// "Tracing" API. final bool isTracingEnabled; /// The name of the benchmark. /// /// The results displayed in the Flutter Dashboard will use this name as a /// prefix. final String name; /// Returns the recorded profile. /// /// This value is only available while the benchmark is running. Profile? get profile; /// Whether the benchmark should continue running. /// /// Returns `false` if the benchmark collected enough data and it's time to /// stop. bool shouldContinue() => profile!.shouldContinue(); /// Called once before all runs of this benchmark recorder. /// /// This is useful for doing one-time setup work that's needed for the /// benchmark. Future<void> setUpAll() async {} /// The implementation of the benchmark that will produce a [Profile]. Future<Profile> run(); /// Called once after all runs of this benchmark recorder. /// /// This is useful for doing one-time clean up work after the benchmark is /// complete. Future<void> tearDownAll() async {} } /// A recorder for benchmarking raw execution of Dart code. /// /// This is useful for benchmarks that don't need frames or widgets. /// /// Example: /// /// ``` /// class BenchForLoop extends RawRecorder { /// BenchForLoop() : super(name: benchmarkName); /// /// static const String benchmarkName = 'for_loop'; /// /// @override /// void body(Profile profile) { /// profile.record('loop', () { /// double x = 0; /// for (int i = 0; i < 10000000; i++) { /// x *= 1.5; /// } /// }); /// } /// } /// ``` abstract class RawRecorder extends Recorder { /// Creates a raw benchmark recorder with a name. /// /// [name] must not be null. RawRecorder({required String name}) : super._(name, false); /// The body of the benchmark. /// /// This is the part that records measurements of the benchmark. void body(Profile profile); @override Profile get profile => _profile; late Profile _profile; @override @nonVirtual Future<Profile> run() async { _profile = Profile(name: name); do { await Future<void>.delayed(Duration.zero); body(_profile); } while (shouldContinue()); return _profile; } } /// A recorder for benchmarking interactions with the engine without the /// framework by directly exercising [SceneBuilder]. /// /// To implement a benchmark, extend this class and implement [onDrawFrame]. /// /// Example: /// /// ``` /// class BenchDrawCircle extends SceneBuilderRecorder { /// BenchDrawCircle() : super(name: benchmarkName); /// /// static const String benchmarkName = 'draw_circle'; /// /// @override /// void onDrawFrame(SceneBuilder sceneBuilder) { /// final PictureRecorder pictureRecorder = PictureRecorder(); /// final Canvas canvas = Canvas(pictureRecorder); /// final Paint paint = Paint()..color = const Color.fromARGB(255, 255, 0, 0); /// final Size windowSize = window.physicalSize; /// canvas.drawCircle(windowSize.center(Offset.zero), 50.0, paint); /// final Picture picture = pictureRecorder.endRecording(); /// sceneBuilder.addPicture(picture); /// } /// } /// ``` abstract class SceneBuilderRecorder extends Recorder { /// Creates a [SceneBuilder] benchmark recorder. /// /// [name] must not be null. SceneBuilderRecorder({required String name}) : super._(name, true); @override Profile get profile => _profile; late Profile _profile; /// Called from [Window.onBeginFrame]. @mustCallSuper void onBeginFrame() {} /// Called on every frame. /// /// An implementation should exercise the [sceneBuilder] to build a frame. /// However, it must not call [SceneBuilder.build] or [Window.render]. /// Instead the benchmark harness will call them and time them appropriately. void onDrawFrame(SceneBuilder sceneBuilder); @override Future<Profile> run() { final Completer<Profile> profileCompleter = Completer<Profile>(); _profile = Profile(name: name); PlatformDispatcher.instance.onBeginFrame = (_) { try { startMeasureFrame(profile); onBeginFrame(); } catch (error, stackTrace) { profileCompleter.completeError(error, stackTrace); rethrow; } }; PlatformDispatcher.instance.onDrawFrame = () { final FlutterView? view = PlatformDispatcher.instance.implicitView; try { _profile.record('drawFrameDuration', () { final SceneBuilder sceneBuilder = SceneBuilder(); onDrawFrame(sceneBuilder); _profile.record('sceneBuildDuration', () { final Scene scene = sceneBuilder.build(); _profile.record('windowRenderDuration', () { assert(view != null, 'Cannot profile windowRenderDuration on a null View.'); view!.render(scene); }, reported: false); }, reported: false); }, reported: true); endMeasureFrame(); if (shouldContinue()) { PlatformDispatcher.instance.scheduleFrame(); } else { profileCompleter.complete(_profile); } } catch (error, stackTrace) { profileCompleter.completeError(error, stackTrace); rethrow; } }; PlatformDispatcher.instance.scheduleFrame(); return profileCompleter.future; } } /// A recorder for benchmarking interactions with the framework by creating /// widgets. /// /// To implement a benchmark, extend this class and implement [createWidget]. /// /// Example: /// /// ``` /// class BenchListView extends WidgetRecorder { /// BenchListView() : super(name: benchmarkName); /// /// static const String benchmarkName = 'bench_list_view'; /// /// @override /// Widget createWidget() { /// return Directionality( /// textDirection: TextDirection.ltr, /// child: _TestListViewWidget(), /// ); /// } /// } /// /// class _TestListViewWidget extends StatefulWidget { /// @override /// State<StatefulWidget> createState() { /// return _TestListViewWidgetState(); /// } /// } /// /// class _TestListViewWidgetState extends State<_TestListViewWidget> { /// ScrollController scrollController; /// /// @override /// void initState() { /// super.initState(); /// scrollController = ScrollController(); /// Timer.run(() async { /// bool forward = true; /// while (true) { /// await scrollController.animateTo( /// forward ? 300 : 0, /// curve: Curves.linear, /// duration: const Duration(seconds: 1), /// ); /// forward = !forward; /// } /// }); /// } /// /// @override /// Widget build(BuildContext context) { /// return ListView.builder( /// controller: scrollController, /// itemCount: 10000, /// itemBuilder: (BuildContext context, int index) { /// return Text('Item #$index'); /// }, /// ); /// } /// } /// ``` abstract class WidgetRecorder extends Recorder implements FrameRecorder { /// Creates a widget benchmark recorder. /// /// [name] must not be null. /// /// If [useCustomWarmUp] is true, delegates the benchmark warm-up to the /// benchmark implementation instead of using a built-in strategy. The /// benchmark is expected to call [Profile.stopWarmingUp] to signal that /// the warm-up phase is finished. WidgetRecorder({ required String name, this.useCustomWarmUp = false, }) : super._(name, true); /// Creates a widget to be benchmarked. /// /// The widget must create its own animation to drive the benchmark. The /// animation should continue indefinitely. The benchmark harness will stop /// pumping frames automatically. Widget createWidget(); final List<VoidCallback> _didStopCallbacks = <VoidCallback>[]; @override void registerDidStop(VoidCallback fn) { _didStopCallbacks.add(fn); } @override late Profile profile; // This will be initialized in [run]. late Completer<void> _runCompleter; /// Whether to delimit warm-up frames in a custom way. final bool useCustomWarmUp; late Stopwatch _drawFrameStopwatch; @override @mustCallSuper void frameWillDraw() { startMeasureFrame(profile); _drawFrameStopwatch = Stopwatch()..start(); } @override @mustCallSuper void frameDidDraw() { endMeasureFrame(); profile.addDataPoint('drawFrameDuration', _drawFrameStopwatch.elapsed, reported: true); if (shouldContinue()) { PlatformDispatcher.instance.scheduleFrame(); } else { for (final VoidCallback fn in _didStopCallbacks) { fn(); } _runCompleter.complete(); } } @override void _onError(dynamic error, StackTrace? stackTrace) { _runCompleter.completeError(error as Object, stackTrace); } @override Future<Profile> run() async { _runCompleter = Completer<void>(); final Profile localProfile = profile = Profile(name: name, useCustomWarmUp: useCustomWarmUp); final _RecordingWidgetsBinding binding = _RecordingWidgetsBinding.ensureInitialized(); final Widget widget = createWidget(); registerEngineBenchmarkValueListener(kProfilePrerollFrame, (num value) { localProfile.addDataPoint( kProfilePrerollFrame, Duration(microseconds: value.toInt()), reported: false, ); }); registerEngineBenchmarkValueListener(kProfileApplyFrame, (num value) { localProfile.addDataPoint( kProfileApplyFrame, Duration(microseconds: value.toInt()), reported: false, ); }); binding._beginRecording(this, widget); try { await _runCompleter.future; return localProfile; } finally { stopListeningToEngineBenchmarkValues(kProfilePrerollFrame); stopListeningToEngineBenchmarkValues(kProfileApplyFrame); } } } /// A recorder for measuring the performance of building a widget from scratch /// starting from an empty frame. /// /// The recorder will call [createWidget] and render it, then it will pump /// another frame that clears the screen. It repeats this process, measuring the /// performance of frames that render the widget and ignoring the frames that /// clear the screen. abstract class WidgetBuildRecorder extends Recorder implements FrameRecorder { /// Creates a widget build benchmark recorder. /// /// [name] must not be null. WidgetBuildRecorder({required String name}) : super._(name, true); /// Creates a widget to be benchmarked. /// /// The widget is not expected to animate as we only care about construction /// of the widget. If you are interested in benchmarking an animation, /// consider using [WidgetRecorder]. Widget createWidget(); final List<VoidCallback> _didStopCallbacks = <VoidCallback>[]; @override void registerDidStop(VoidCallback fn) { _didStopCallbacks.add(fn); } @override late Profile profile; Completer<void>? _runCompleter; late Stopwatch _drawFrameStopwatch; /// Whether in this frame we should call [createWidget] and render it. /// /// If false, then this frame will clear the screen. bool showWidget = true; /// The state that hosts the widget under test. late _WidgetBuildRecorderHostState _hostState; Widget? _getWidgetForFrame() { if (showWidget) { return createWidget(); } else { return null; } } @override @mustCallSuper void frameWillDraw() { if (showWidget) { startMeasureFrame(profile); _drawFrameStopwatch = Stopwatch()..start(); } } @override @mustCallSuper void frameDidDraw() { // Only record frames that show the widget. if (showWidget) { endMeasureFrame(); profile.addDataPoint('drawFrameDuration', _drawFrameStopwatch.elapsed, reported: true); } if (shouldContinue()) { showWidget = !showWidget; _hostState._setStateTrampoline(); } else { for (final VoidCallback fn in _didStopCallbacks) { fn(); } _runCompleter!.complete(); } } @override void _onError(dynamic error, StackTrace? stackTrace) { _runCompleter!.completeError(error as Object, stackTrace); } @override Future<Profile> run() async { _runCompleter = Completer<void>(); final Profile localProfile = profile = Profile(name: name); final _RecordingWidgetsBinding binding = _RecordingWidgetsBinding.ensureInitialized(); binding._beginRecording(this, _WidgetBuildRecorderHost(this)); try { await _runCompleter!.future; return localProfile; } finally { _runCompleter = null; } } } /// Hosts widgets created by [WidgetBuildRecorder]. class _WidgetBuildRecorderHost extends StatefulWidget { const _WidgetBuildRecorderHost(this.recorder); final WidgetBuildRecorder recorder; @override State<StatefulWidget> createState() => _WidgetBuildRecorderHostState(); } class _WidgetBuildRecorderHostState extends State<_WidgetBuildRecorderHost> { @override void initState() { super.initState(); widget.recorder._hostState = this; } // This is just to bypass the @protected on setState. void _setStateTrampoline() { setState(() {}); } @override Widget build(BuildContext context) { return SizedBox.expand( child: widget.recorder._getWidgetForFrame(), ); } } /// Series of time recordings indexed in time order. /// /// It can calculate [average], [standardDeviation] and [noise]. If the amount /// of data collected is higher than [_kMeasuredSampleCount], then these /// calculations will only apply to the latest [_kMeasuredSampleCount] data /// points. class Timeseries { /// Creates an empty timeseries. /// /// [name], [isReported], and [useCustomWarmUp] must not be null. Timeseries(this.name, this.isReported, {this.useCustomWarmUp = false}) : _warmUpFrameCount = useCustomWarmUp ? 0 : null; /// The label of this timeseries used for debugging and result inspection. final String name; /// Whether this timeseries is reported to the benchmark dashboard. /// /// If `true` a new benchmark card is created for the timeseries and is /// visible on the dashboard. /// /// If `false` the data is stored but it does not show up on the dashboard. /// Use unreported metrics for metrics that are useful for manual inspection /// but that are too fine-grained to be useful for tracking on the dashboard. final bool isReported; /// Whether to delimit warm-up frames in a custom way. final bool useCustomWarmUp; /// The number of frames ignored as warm-up frames, used only /// when [useCustomWarmUp] is true. int? _warmUpFrameCount; /// The number of frames ignored as warm-up frames. int get warmUpFrameCount => useCustomWarmUp ? _warmUpFrameCount! : count - kMeasuredSampleCount; /// List of all the values that have been recorded. /// /// This list has no limit. final List<double> _allValues = <double>[]; /// The total amount of data collected, including ones that were dropped /// because of the sample size limit. int get count => _allValues.length; /// Extracts useful statistics out of this timeseries. /// /// See [TimeseriesStats] for more details. TimeseriesStats computeStats() { final int finalWarmUpFrameCount = warmUpFrameCount; assert(finalWarmUpFrameCount >= 0 && finalWarmUpFrameCount < count); // The first few values we simply discard and never look at. They're from the warm-up phase. final List<double> warmUpValues = _allValues.sublist(0, finalWarmUpFrameCount); // Values we analyze. final List<double> candidateValues = _allValues.sublist(finalWarmUpFrameCount); // The average that includes outliers. final double dirtyAverage = _computeAverage(name, candidateValues); // The standard deviation that includes outliers. final double dirtyStandardDeviation = _computeStandardDeviationForPopulation(name, candidateValues); // Any value that's higher than this is considered an outlier. final double outlierCutOff = dirtyAverage + dirtyStandardDeviation; // Candidates with outliers removed. final Iterable<double> cleanValues = candidateValues.where((double value) => value <= outlierCutOff); // Outlier candidates. final Iterable<double> outliers = candidateValues.where((double value) => value > outlierCutOff); // Final statistics. final double cleanAverage = _computeAverage(name, cleanValues); final double standardDeviation = _computeStandardDeviationForPopulation(name, cleanValues); final double noise = cleanAverage > 0.0 ? standardDeviation / cleanAverage : 0.0; // Compute outlier average. If there are no outliers the outlier average is // the same as clean value average. In other words, in a perfect benchmark // with no noise the difference between average and outlier average is zero, // which the best possible outcome. Noise produces a positive difference // between the two. final double outlierAverage = outliers.isNotEmpty ? _computeAverage(name, outliers) : cleanAverage; final List<AnnotatedSample> annotatedValues = <AnnotatedSample>[ for (final double warmUpValue in warmUpValues) AnnotatedSample( magnitude: warmUpValue, isOutlier: warmUpValue > outlierCutOff, isWarmUpValue: true, ), for (final double candidate in candidateValues) AnnotatedSample( magnitude: candidate, isOutlier: candidate > outlierCutOff, isWarmUpValue: false, ), ]; return TimeseriesStats( name: name, average: cleanAverage, outlierCutOff: outlierCutOff, outlierAverage: outlierAverage, standardDeviation: standardDeviation, noise: noise, cleanSampleCount: cleanValues.length, outlierSampleCount: outliers.length, samples: annotatedValues, ); } /// Adds a value to this timeseries. void add(double value, {required bool isWarmUpValue}) { if (value < 0.0) { throw StateError( 'Timeseries $name: negative metric values are not supported. Got: $value', ); } _allValues.add(value); if (useCustomWarmUp && isWarmUpValue) { _warmUpFrameCount = warmUpFrameCount + 1; } } } /// Various statistics about a [Timeseries]. /// /// See the docs on the individual fields for more details. @sealed class TimeseriesStats { /// Creates statistics for a time series. const TimeseriesStats({ required this.name, required this.average, required this.outlierCutOff, required this.outlierAverage, required this.standardDeviation, required this.noise, required this.cleanSampleCount, required this.outlierSampleCount, required this.samples, }); /// The label used to refer to the corresponding timeseries. final String name; /// The average value of the measured samples without outliers. final double average; /// The standard deviation in the measured samples without outliers. final double standardDeviation; /// The noise as a multiple of the [average] value takes from clean samples. /// /// This value can be multiplied by 100.0 to get noise as a percentage of /// the average. /// /// If [average] is zero, treats the result as perfect score, returns zero. final double noise; /// The maximum value a sample can have without being considered an outlier. /// /// See [Timeseries.computeStats] for details on how this value is computed. final double outlierCutOff; /// The average of outlier samples. /// /// This value can be used to judge how badly we jank, when we jank. /// /// Another useful metrics is the difference between [outlierAverage] and /// [average]. The smaller the value the more predictable is the performance /// of the corresponding benchmark. final double outlierAverage; /// The number of measured samples after outlier are removed. final int cleanSampleCount; /// The number of outliers. final int outlierSampleCount; /// All collected samples, annotated with statistical information. /// /// See [AnnotatedSample] for more details. final List<AnnotatedSample> samples; /// Outlier average divided by clean average. /// /// This is a measure of performance consistency. The higher this number the /// worse is jank when it happens. Smaller is better, with 1.0 being the /// perfect score. If [average] is zero, this value defaults to 1.0. double get outlierRatio => average > 0.0 ? outlierAverage / average : 1.0; // this can only happen in perfect benchmark that reports only zeros @override String toString() { final StringBuffer buffer = StringBuffer(); buffer.writeln( '$name: (samples: $cleanSampleCount clean/$outlierSampleCount ' 'outliers/${cleanSampleCount + outlierSampleCount} ' 'measured/${samples.length} total)', ); buffer.writeln(' | average: $average μs'); buffer.writeln(' | outlier average: $outlierAverage μs'); buffer.writeln(' | outlier/clean ratio: ${outlierRatio}x'); buffer.writeln(' | noise: ${_ratioToPercent(noise)}'); return buffer.toString(); } } /// Annotates a single measurement with statistical information. @sealed class AnnotatedSample { /// Creates an annotated measurement sample. const AnnotatedSample({ required this.magnitude, required this.isOutlier, required this.isWarmUpValue, }); /// The non-negative raw result of the measurement. final double magnitude; /// Whether this sample was considered an outlier. final bool isOutlier; /// Whether this sample was taken during the warm-up phase. /// /// If this value is `true`, this sample does not participate in /// statistical computations. However, the sample would still be /// shown in the visualization of results so that the benchmark /// can be inspected manually to make sure there's a predictable /// warm-up regression slope. final bool isWarmUpValue; } /// Base class for a profile collected from running a benchmark. class Profile { /// Creates an empty profile. /// /// [name] and [useCustomWarmUp] must not be null. Profile({required this.name, this.useCustomWarmUp = false}) : _isWarmingUp = useCustomWarmUp; /// The name of the benchmark that produced this profile. final String name; /// Whether to delimit warm-up frames in a custom way. final bool useCustomWarmUp; /// Whether we are measuring warm-up frames currently. bool get isWarmingUp => _isWarmingUp; bool _isWarmingUp; /// Stop the warm-up phase. /// /// Call this method only when [useCustomWarmUp] and [isWarmingUp] are both /// true. /// Call this method only once for each profile. void stopWarmingUp() { if (!useCustomWarmUp) { throw Exception( '`stopWarmingUp` should be used only when `useCustomWarmUp` is true.'); } else if (!_isWarmingUp) { throw Exception('Warm-up already stopped.'); } else { _isWarmingUp = false; } } /// This data will be used to display cards in the Flutter Dashboard. final Map<String, Timeseries> scoreData = <String, Timeseries>{}; /// This data isn't displayed anywhere. It's stored for completeness purposes. final Map<String, dynamic> extraData = <String, dynamic>{}; /// Invokes [callback] and records the duration of its execution under [key]. Duration record(String key, VoidCallback callback, {required bool reported}) { final Duration duration = timeAction(callback); addDataPoint(key, duration, reported: reported); return duration; } /// Adds a timed sample to the timeseries corresponding to [key]. /// /// Set [reported] to `true` to report the timeseries to the dashboard UI. /// /// Set [reported] to `false` to store the data, but not show it on the /// dashboard UI. void addDataPoint(String key, Duration duration, {required bool reported}) { scoreData .putIfAbsent( key, () => Timeseries(key, reported, useCustomWarmUp: useCustomWarmUp), ) .add(duration.inMicroseconds.toDouble(), isWarmUpValue: isWarmingUp); } /// Decides whether the data collected so far is sufficient to stop, or /// whether the benchmark should continue collecting more data. /// /// The signals used are sample size, noise, and duration. /// /// If any of the timeseries doesn't satisfy the noise requirements, this /// method will return true (asking the benchmark to continue collecting /// data). bool shouldContinue() { // If there are no `Timeseries` in the `scoreData`, then we haven't // recorded anything yet. Don't stop. if (scoreData.isEmpty) { return true; } // We have recorded something, but do we have enough samples? If every // timeseries has collected enough samples, stop the benchmark. return !scoreData.keys .every((String key) => scoreData[key]!.count >= kTotalSampleCount); } /// Returns a JSON representation of the profile that will be sent to the /// server. Map<String, dynamic> toJson() { final List<String> scoreKeys = <String>[]; final Map<String, dynamic> json = <String, dynamic>{ 'name': name, 'scoreKeys': scoreKeys, }; for (final String key in scoreData.keys) { final Timeseries timeseries = scoreData[key]!; if (timeseries.isReported) { scoreKeys.add('$key.average'); // Report `outlierRatio` rather than `outlierAverage`, because // the absolute value of outliers is less interesting than the // ratio. scoreKeys.add('$key.outlierRatio'); } final TimeseriesStats stats = timeseries.computeStats(); json['$key.average'] = stats.average; json['$key.outlierAverage'] = stats.outlierAverage; json['$key.outlierRatio'] = stats.outlierRatio; json['$key.noise'] = stats.noise; } json.addAll(extraData); return json; } @override String toString() { final StringBuffer buffer = StringBuffer(); buffer.writeln('name: $name'); for (final String key in scoreData.keys) { final Timeseries timeseries = scoreData[key]!; final TimeseriesStats stats = timeseries.computeStats(); buffer.writeln(stats.toString()); } for (final String key in extraData.keys) { final dynamic value = extraData[key]; if (value is List) { buffer.writeln('$key:'); for (final dynamic item in value) { buffer.writeln(' - $item'); } } else { buffer.writeln('$key: $value'); } } return buffer.toString(); } } /// Computes the arithmetic mean (or average) of given [values]. double _computeAverage(String label, Iterable<double> values) { if (values.isEmpty) { throw StateError( '$label: attempted to compute an average of an empty value list.'); } final double sum = values.reduce((double a, double b) => a + b); return sum / values.length; } /// Computes population standard deviation. /// /// Unlike sample standard deviation, which divides by N - 1, this divides by N. /// /// See also: /// /// * https://en.wikipedia.org/wiki/Standard_deviation double _computeStandardDeviationForPopulation( String label, Iterable<double> population) { if (population.isEmpty) { throw StateError( '$label: attempted to compute the standard deviation of empty population.'); } final double mean = _computeAverage(label, population); final double sumOfSquaredDeltas = population.fold<double>( 0.0, (double previous, double value) => previous += math.pow(value - mean, 2), ); return math.sqrt(sumOfSquaredDeltas / population.length); } String _ratioToPercent(double value) { return '${(value * 100).toStringAsFixed(2)}%'; } /// Implemented by recorders that use [_RecordingWidgetsBinding] to receive /// frame life-cycle calls. abstract class FrameRecorder { /// Add a callback that will be called by the recorder when it stops recording. void registerDidStop(VoidCallback cb); /// Called just before calling [SchedulerBinding.handleDrawFrame]. void frameWillDraw(); /// Called immediately after calling [SchedulerBinding.handleDrawFrame]. void frameDidDraw(); /// Reports an error. /// /// The implementation is expected to halt benchmark execution as soon as possible. void _onError(dynamic error, StackTrace? stackTrace); } /// A variant of [WidgetsBinding] that collaborates with a [Recorder] to decide /// when to stop pumping frames. /// /// A normal [WidgetsBinding] typically always pumps frames whenever a widget /// instructs it to do so by calling [scheduleFrame] (transitively via /// `setState`). This binding will stop pumping new frames as soon as benchmark /// parameters are satisfactory (e.g. when the metric noise levels become low /// enough). class _RecordingWidgetsBinding extends BindingBase with GestureBinding, SchedulerBinding, ServicesBinding, PaintingBinding, SemanticsBinding, RendererBinding, WidgetsBinding { @override void initInstances() { super.initInstances(); _instance = this; } static _RecordingWidgetsBinding get instance => BindingBase.checkInstance(_instance); static _RecordingWidgetsBinding? _instance; /// Makes an instance of [_RecordingWidgetsBinding] the current binding. static _RecordingWidgetsBinding ensureInitialized() { if (_instance == null) { _RecordingWidgetsBinding(); } return _RecordingWidgetsBinding.instance; } // This will be not null when the benchmark is running. FrameRecorder? _recorder; bool _hasErrored = false; /// To short-circuit all frame lifecycle methods when the benchmark has /// stopped collecting data. bool _benchmarkStopped = false; void _beginRecording(FrameRecorder recorder, Widget widget) { if (_recorder != null) { throw Exception( 'Cannot call _RecordingWidgetsBinding._beginRecording more than once', ); } final FlutterExceptionHandler? originalOnError = FlutterError.onError; recorder.registerDidStop(() { _benchmarkStopped = true; }); // Fail hard and fast on errors. Benchmarks should not have any errors. FlutterError.onError = (FlutterErrorDetails details) { _haltBenchmarkWithError(details.exception, details.stack); originalOnError!(details); }; _recorder = recorder; runApp(widget); } void _haltBenchmarkWithError(dynamic error, StackTrace? stackTrace) { if (_hasErrored) { return; } _recorder!._onError(error, stackTrace); _hasErrored = true; } @override void handleBeginFrame(Duration? rawTimeStamp) { // Don't keep on truckin' if there's an error or the benchmark has stopped. if (_hasErrored || _benchmarkStopped) { return; } try { super.handleBeginFrame(rawTimeStamp); } catch (error, stackTrace) { _haltBenchmarkWithError(error, stackTrace); rethrow; } } @override void scheduleFrame() { // Don't keep on truckin' if there's an error or the benchmark has stopped. if (_hasErrored || _benchmarkStopped) { return; } super.scheduleFrame(); } @override void handleDrawFrame() { // Don't keep on truckin' if there's an error or the benchmark has stopped. if (_hasErrored || _benchmarkStopped) { return; } try { _recorder!.frameWillDraw(); super.handleDrawFrame(); _recorder!.frameDidDraw(); } catch (error, stackTrace) { _haltBenchmarkWithError(error, stackTrace); rethrow; } } } int _currentFrameNumber = 1; /// If [_calledStartMeasureFrame] is true, we have called [startMeasureFrame] /// but have not its pairing [endMeasureFrame] yet. /// /// This flag ensures that [startMeasureFrame] and [endMeasureFrame] are always /// called in pairs, with [startMeasureFrame] followed by [endMeasureFrame]. bool _calledStartMeasureFrame = false; /// Whether we are recording a measured frame. /// /// This flag ensures that we always stop measuring a frame if we /// have started one. Because we want to skip warm-up frames, this flag /// is necessary. bool _isMeasuringFrame = false; /// Adds a marker indication the beginning of frame rendering. /// /// This adds an event to the performance trace used to find measured frames in /// Chrome tracing data. The tracing data contains all frames, but some /// benchmarks are only interested in a subset of frames. For example, /// [WidgetBuildRecorder] only measures frames that build widgets, and ignores /// frames that clear the screen. /// /// Warm-up frames are not measured. If [profile.isWarmingUp] is true, /// this function does nothing. void startMeasureFrame(Profile profile) { if (_calledStartMeasureFrame) { throw Exception('`startMeasureFrame` called twice in a row.'); } _calledStartMeasureFrame = true; if (!profile.isWarmingUp) { // Tell the browser to mark the beginning of the frame. html.window.performance.mark('measured_frame_start#$_currentFrameNumber'); _isMeasuringFrame = true; } } /// Signals the end of a measured frame. /// /// See [startMeasureFrame] for details on what this instrumentation is used /// for. /// /// Warm-up frames are not measured. If [profile.isWarmingUp] was true /// when the corresponding [startMeasureFrame] was called, /// this function does nothing. void endMeasureFrame() { if (!_calledStartMeasureFrame) { throw Exception( '`startMeasureFrame` has not been called before calling `endMeasureFrame`'); } _calledStartMeasureFrame = false; if (_isMeasuringFrame) { // Tell the browser to mark the end of the frame, and measure the duration. html.window.performance.mark('measured_frame_end#$_currentFrameNumber'); html.window.performance.measure( 'measured_frame', 'measured_frame_start#$_currentFrameNumber'.toJS, 'measured_frame_end#$_currentFrameNumber', ); // Increment the current frame number. _currentFrameNumber += 1; _isMeasuringFrame = false; } } /// A function that receives a benchmark value from the framework. typedef EngineBenchmarkValueListener = void Function(num value); // Maps from a value label name to a listener. final Map<String, EngineBenchmarkValueListener> _engineBenchmarkListeners = <String, EngineBenchmarkValueListener>{}; /// Registers a [listener] for engine benchmark values labeled by [name]. /// /// If another listener is already registered, overrides it. void registerEngineBenchmarkValueListener( String name, EngineBenchmarkValueListener listener, ) { if (_engineBenchmarkListeners.containsKey(name)) { throw StateError( 'A listener for "$name" is already registered.\n' 'Call `stopListeningToEngineBenchmarkValues` to unregister the previous ' 'listener before registering a new one.', ); } if (_engineBenchmarkListeners.isEmpty) { // The first listener is being registered. Register the global listener. ui_web.benchmarkValueCallback = _dispatchEngineBenchmarkValue; } _engineBenchmarkListeners[name] = listener; } /// Stops listening to engine benchmark values under labeled by [name]. void stopListeningToEngineBenchmarkValues(String name) { _engineBenchmarkListeners.remove(name); if (_engineBenchmarkListeners.isEmpty) { // The last listener unregistered. Remove the global listener. ui_web.benchmarkValueCallback = null; } } // Dispatches a benchmark value reported by the engine to the relevant listener. // // If there are no listeners registered for [name], ignores the value. void _dispatchEngineBenchmarkValue(String name, double value) { final EngineBenchmarkValueListener? listener = _engineBenchmarkListeners[name]; if (listener != null) { listener(value); } }
packages/packages/web_benchmarks/lib/src/recorder.dart/0
{ "file_path": "packages/packages/web_benchmarks/lib/src/recorder.dart", "repo_id": "packages", "token_count": 12620 }
1,006
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; const ValueKey<String> textKey = ValueKey<String>('textKey'); const ValueKey<String> aboutPageKey = ValueKey<String>('aboutPageKey'); class HomePage extends StatefulWidget { const HomePage({super.key, required this.title}); final String title; @override State<HomePage> createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { int _counter = 0; void _incrementCounter() { setState(() { _counter++; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), actions: <Widget>[ IconButton( key: aboutPageKey, icon: const Icon(Icons.alternate_email), onPressed: () => Navigator.of(context).pushNamed('about'), ), ], ), body: Center( child: ListView.builder( itemExtent: 80, itemBuilder: (BuildContext context, int index) { if (index == 0) { return Column( key: textKey, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ const Text('You have pushed the button this many times:'), Text( '$_counter', style: Theme.of(context).textTheme.headlineMedium, ), ], ); } else { return SizedBox( height: 80, child: Padding( padding: const EdgeInsets.all(12), child: Card( elevation: 8, child: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( 'Line $index', style: Theme.of(context).textTheme.headlineSmall, ), Expanded(child: Container()), const Icon(Icons.camera), const Icon(Icons.face), ], ), ), ), ); } }, ), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: const Icon(Icons.add), ), ); } }
packages/packages/web_benchmarks/testing/test_app/lib/home_page.dart/0
{ "file_path": "packages/packages/web_benchmarks/testing/test_app/lib/home_page.dart", "repo_id": "packages", "token_count": 1391 }
1,007
buildFlags: _pluginToolsConfigGlobalKey: - "--no-tree-shake-icons" - "--dart-define=buildmode=testing"
packages/packages/webview_flutter/webview_flutter/example/.pluginToolsConfig.yaml/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter/example/.pluginToolsConfig.yaml", "repo_id": "packages", "token_count": 45 }
1,008
name: webview_flutter_example description: Demonstrates how to use the webview_flutter plugin. publish_to: none environment: sdk: ^3.2.3 flutter: ">=3.16.6" dependencies: flutter: sdk: flutter path_provider: ^2.0.6 webview_flutter: # 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_android: ^3.15.0 webview_flutter_wkwebview: ^3.12.0 dev_dependencies: build_runner: ^2.1.5 espresso: ^0.2.0 flutter_test: sdk: flutter integration_test: sdk: flutter webview_flutter_platform_interface: ^2.10.0 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/example/pubspec.yaml/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter/example/pubspec.yaml", "repo_id": "packages", "token_count": 390 }
1,009
// 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 static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.os.Build; import android.webkit.CookieManager; import android.webkit.ValueCallback; import android.webkit.WebView; import androidx.annotation.NonNull; import io.flutter.plugin.common.BinaryMessenger; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; public class CookieManagerTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); @Mock public CookieManager mockCookieManager; @Mock public BinaryMessenger mockBinaryMessenger; @Mock public CookieManagerHostApiImpl.CookieManagerProxy mockProxy; InstanceManager instanceManager; @Before public void setUp() { instanceManager = InstanceManager.create(identifier -> {}); } @After public void tearDown() { instanceManager.stopFinalizationListener(); } @Test public void getInstance() { final CookieManager mockCookieManager = mock(CookieManager.class); final long instanceIdentifier = 1; when(mockProxy.getInstance()).thenReturn(mockCookieManager); final CookieManagerHostApiImpl hostApi = new CookieManagerHostApiImpl(mockBinaryMessenger, instanceManager, mockProxy); hostApi.attachInstance(instanceIdentifier); assertEquals(instanceManager.getInstance(instanceIdentifier), mockCookieManager); } @Test public void setCookie() { final String url = "testString"; final String value = "testString2"; final long instanceIdentifier = 0; instanceManager.addDartCreatedInstance(mockCookieManager, instanceIdentifier); final CookieManagerHostApiImpl hostApi = new CookieManagerHostApiImpl(mockBinaryMessenger, instanceManager); hostApi.setCookie(instanceIdentifier, url, value); verify(mockCookieManager).setCookie(url, value); } @SuppressWarnings({"rawtypes", "unchecked"}) @Test public void clearCookies() { final long instanceIdentifier = 0; instanceManager.addDartCreatedInstance(mockCookieManager, instanceIdentifier); final CookieManagerHostApiImpl hostApi = new CookieManagerHostApiImpl( mockBinaryMessenger, instanceManager, new CookieManagerHostApiImpl.CookieManagerProxy(), (int version) -> version <= Build.VERSION_CODES.LOLLIPOP); final Boolean[] successResult = new Boolean[1]; hostApi.removeAllCookies( instanceIdentifier, new GeneratedAndroidWebView.Result<Boolean>() { @Override public void success(Boolean result) { successResult[0] = result; } @Override public void error(@NonNull Throwable error) {} }); final ArgumentCaptor<ValueCallback> valueCallbackArgumentCaptor = ArgumentCaptor.forClass(ValueCallback.class); verify(mockCookieManager).removeAllCookies(valueCallbackArgumentCaptor.capture()); final Boolean returnValue = true; valueCallbackArgumentCaptor.getValue().onReceiveValue(returnValue); assertEquals(successResult[0], returnValue); } @Test public void setAcceptThirdPartyCookies() { final WebView mockWebView = mock(WebView.class); final long webViewIdentifier = 4; instanceManager.addDartCreatedInstance(mockWebView, webViewIdentifier); final boolean accept = true; final long instanceIdentifier = 0; instanceManager.addDartCreatedInstance(mockCookieManager, instanceIdentifier); final CookieManagerHostApiImpl hostApi = new CookieManagerHostApiImpl( mockBinaryMessenger, instanceManager, new CookieManagerHostApiImpl.CookieManagerProxy(), (int version) -> version <= Build.VERSION_CODES.LOLLIPOP); hostApi.setAcceptThirdPartyCookies(instanceIdentifier, webViewIdentifier, accept); verify(mockCookieManager).setAcceptThirdPartyCookies(mockWebView, accept); } }
packages/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/CookieManagerTest.java/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/CookieManagerTest.java", "repo_id": "packages", "token_count": 1493 }
1,010
h1 { color: blue; }
packages/packages/webview_flutter/webview_flutter_android/example/assets/www/styles/style.css/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_android/example/assets/www/styles/style.css", "repo_id": "packages", "token_count": 13 }
1,011
// Mocks generated by Mockito 5.4.4 from annotations // in webview_flutter_android/test/android_webview_cookie_manager_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i5; import 'dart:ui' as _i4; import 'package:mockito/mockito.dart' as _i1; import 'package:webview_flutter_android/src/android_webview.dart' as _i2; import 'package:webview_flutter_android/src/android_webview_controller.dart' as _i6; import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart' as _i3; import 'test_android_webview.g.dart' as _i7; // 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, ); } class _FakePlatformWebViewControllerCreationParams_1 extends _i1.SmartFake implements _i3.PlatformWebViewControllerCreationParams { _FakePlatformWebViewControllerCreationParams_1( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeObject_2 extends _i1.SmartFake implements Object { _FakeObject_2( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeOffset_3 extends _i1.SmartFake implements _i4.Offset { _FakeOffset_3( 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 _i5.Future<void> setCookie( String? url, String? value, ) => (super.noSuchMethod( Invocation.method( #setCookie, [ url, value, ], ), returnValue: _i5.Future<void>.value(), returnValueForMissingStub: _i5.Future<void>.value(), ) as _i5.Future<void>); @override _i5.Future<bool> removeAllCookies() => (super.noSuchMethod( Invocation.method( #removeAllCookies, [], ), returnValue: _i5.Future<bool>.value(false), ) as _i5.Future<bool>); @override _i5.Future<void> setAcceptThirdPartyCookies( _i2.WebView? webView, bool? accept, ) => (super.noSuchMethod( Invocation.method( #setAcceptThirdPartyCookies, [ webView, accept, ], ), returnValue: _i5.Future<void>.value(), returnValueForMissingStub: _i5.Future<void>.value(), ) as _i5.Future<void>); @override _i2.CookieManager copy() => (super.noSuchMethod( Invocation.method( #copy, [], ), returnValue: _FakeCookieManager_0( this, Invocation.method( #copy, [], ), ), ) as _i2.CookieManager); } /// A class which mocks [AndroidWebViewController]. /// /// See the documentation for Mockito's code generation for more information. class MockAndroidWebViewController extends _i1.Mock implements _i6.AndroidWebViewController { MockAndroidWebViewController() { _i1.throwOnMissingStub(this); } @override int get webViewIdentifier => (super.noSuchMethod( Invocation.getter(#webViewIdentifier), returnValue: 0, ) as int); @override _i3.PlatformWebViewControllerCreationParams get params => (super.noSuchMethod( Invocation.getter(#params), returnValue: _FakePlatformWebViewControllerCreationParams_1( this, Invocation.getter(#params), ), ) as _i3.PlatformWebViewControllerCreationParams); @override _i5.Future<void> loadFile(String? absoluteFilePath) => (super.noSuchMethod( Invocation.method( #loadFile, [absoluteFilePath], ), returnValue: _i5.Future<void>.value(), returnValueForMissingStub: _i5.Future<void>.value(), ) as _i5.Future<void>); @override _i5.Future<void> loadFlutterAsset(String? key) => (super.noSuchMethod( Invocation.method( #loadFlutterAsset, [key], ), returnValue: _i5.Future<void>.value(), returnValueForMissingStub: _i5.Future<void>.value(), ) as _i5.Future<void>); @override _i5.Future<void> loadHtmlString( String? html, { String? baseUrl, }) => (super.noSuchMethod( Invocation.method( #loadHtmlString, [html], {#baseUrl: baseUrl}, ), returnValue: _i5.Future<void>.value(), returnValueForMissingStub: _i5.Future<void>.value(), ) as _i5.Future<void>); @override _i5.Future<void> loadRequest(_i3.LoadRequestParams? params) => (super.noSuchMethod( Invocation.method( #loadRequest, [params], ), returnValue: _i5.Future<void>.value(), returnValueForMissingStub: _i5.Future<void>.value(), ) as _i5.Future<void>); @override _i5.Future<String?> currentUrl() => (super.noSuchMethod( Invocation.method( #currentUrl, [], ), returnValue: _i5.Future<String?>.value(), ) as _i5.Future<String?>); @override _i5.Future<bool> canGoBack() => (super.noSuchMethod( Invocation.method( #canGoBack, [], ), returnValue: _i5.Future<bool>.value(false), ) as _i5.Future<bool>); @override _i5.Future<bool> canGoForward() => (super.noSuchMethod( Invocation.method( #canGoForward, [], ), returnValue: _i5.Future<bool>.value(false), ) as _i5.Future<bool>); @override _i5.Future<void> goBack() => (super.noSuchMethod( Invocation.method( #goBack, [], ), returnValue: _i5.Future<void>.value(), returnValueForMissingStub: _i5.Future<void>.value(), ) as _i5.Future<void>); @override _i5.Future<void> goForward() => (super.noSuchMethod( Invocation.method( #goForward, [], ), returnValue: _i5.Future<void>.value(), returnValueForMissingStub: _i5.Future<void>.value(), ) as _i5.Future<void>); @override _i5.Future<void> reload() => (super.noSuchMethod( Invocation.method( #reload, [], ), returnValue: _i5.Future<void>.value(), returnValueForMissingStub: _i5.Future<void>.value(), ) as _i5.Future<void>); @override _i5.Future<void> clearCache() => (super.noSuchMethod( Invocation.method( #clearCache, [], ), returnValue: _i5.Future<void>.value(), returnValueForMissingStub: _i5.Future<void>.value(), ) as _i5.Future<void>); @override _i5.Future<void> clearLocalStorage() => (super.noSuchMethod( Invocation.method( #clearLocalStorage, [], ), returnValue: _i5.Future<void>.value(), returnValueForMissingStub: _i5.Future<void>.value(), ) as _i5.Future<void>); @override _i5.Future<void> setPlatformNavigationDelegate( _i3.PlatformNavigationDelegate? handler) => (super.noSuchMethod( Invocation.method( #setPlatformNavigationDelegate, [handler], ), returnValue: _i5.Future<void>.value(), returnValueForMissingStub: _i5.Future<void>.value(), ) as _i5.Future<void>); @override _i5.Future<void> runJavaScript(String? javaScript) => (super.noSuchMethod( Invocation.method( #runJavaScript, [javaScript], ), returnValue: _i5.Future<void>.value(), returnValueForMissingStub: _i5.Future<void>.value(), ) as _i5.Future<void>); @override _i5.Future<Object> runJavaScriptReturningResult(String? javaScript) => (super.noSuchMethod( Invocation.method( #runJavaScriptReturningResult, [javaScript], ), returnValue: _i5.Future<Object>.value(_FakeObject_2( this, Invocation.method( #runJavaScriptReturningResult, [javaScript], ), )), ) as _i5.Future<Object>); @override _i5.Future<void> addJavaScriptChannel( _i3.JavaScriptChannelParams? javaScriptChannelParams) => (super.noSuchMethod( Invocation.method( #addJavaScriptChannel, [javaScriptChannelParams], ), returnValue: _i5.Future<void>.value(), returnValueForMissingStub: _i5.Future<void>.value(), ) as _i5.Future<void>); @override _i5.Future<void> removeJavaScriptChannel(String? javaScriptChannelName) => (super.noSuchMethod( Invocation.method( #removeJavaScriptChannel, [javaScriptChannelName], ), returnValue: _i5.Future<void>.value(), returnValueForMissingStub: _i5.Future<void>.value(), ) as _i5.Future<void>); @override _i5.Future<String?> getTitle() => (super.noSuchMethod( Invocation.method( #getTitle, [], ), returnValue: _i5.Future<String?>.value(), ) as _i5.Future<String?>); @override _i5.Future<void> scrollTo( int? x, int? y, ) => (super.noSuchMethod( Invocation.method( #scrollTo, [ x, y, ], ), returnValue: _i5.Future<void>.value(), returnValueForMissingStub: _i5.Future<void>.value(), ) as _i5.Future<void>); @override _i5.Future<void> scrollBy( int? x, int? y, ) => (super.noSuchMethod( Invocation.method( #scrollBy, [ x, y, ], ), returnValue: _i5.Future<void>.value(), returnValueForMissingStub: _i5.Future<void>.value(), ) as _i5.Future<void>); @override _i5.Future<_i4.Offset> getScrollPosition() => (super.noSuchMethod( Invocation.method( #getScrollPosition, [], ), returnValue: _i5.Future<_i4.Offset>.value(_FakeOffset_3( this, Invocation.method( #getScrollPosition, [], ), )), ) as _i5.Future<_i4.Offset>); @override _i5.Future<void> enableZoom(bool? enabled) => (super.noSuchMethod( Invocation.method( #enableZoom, [enabled], ), returnValue: _i5.Future<void>.value(), returnValueForMissingStub: _i5.Future<void>.value(), ) as _i5.Future<void>); @override _i5.Future<void> setBackgroundColor(_i4.Color? color) => (super.noSuchMethod( Invocation.method( #setBackgroundColor, [color], ), returnValue: _i5.Future<void>.value(), returnValueForMissingStub: _i5.Future<void>.value(), ) as _i5.Future<void>); @override _i5.Future<void> setJavaScriptMode(_i3.JavaScriptMode? javaScriptMode) => (super.noSuchMethod( Invocation.method( #setJavaScriptMode, [javaScriptMode], ), returnValue: _i5.Future<void>.value(), returnValueForMissingStub: _i5.Future<void>.value(), ) as _i5.Future<void>); @override _i5.Future<void> setUserAgent(String? userAgent) => (super.noSuchMethod( Invocation.method( #setUserAgent, [userAgent], ), returnValue: _i5.Future<void>.value(), returnValueForMissingStub: _i5.Future<void>.value(), ) as _i5.Future<void>); @override _i5.Future<void> setOnScrollPositionChange( void Function(_i3.ScrollPositionChange)? onScrollPositionChange) => (super.noSuchMethod( Invocation.method( #setOnScrollPositionChange, [onScrollPositionChange], ), returnValue: _i5.Future<void>.value(), returnValueForMissingStub: _i5.Future<void>.value(), ) as _i5.Future<void>); @override _i5.Future<void> setMediaPlaybackRequiresUserGesture(bool? require) => (super.noSuchMethod( Invocation.method( #setMediaPlaybackRequiresUserGesture, [require], ), returnValue: _i5.Future<void>.value(), returnValueForMissingStub: _i5.Future<void>.value(), ) as _i5.Future<void>); @override _i5.Future<void> setTextZoom(int? textZoom) => (super.noSuchMethod( Invocation.method( #setTextZoom, [textZoom], ), returnValue: _i5.Future<void>.value(), returnValueForMissingStub: _i5.Future<void>.value(), ) as _i5.Future<void>); @override _i5.Future<void> setOnShowFileSelector( _i5.Future<List<String>> Function(_i6.FileSelectorParams)? onShowFileSelector) => (super.noSuchMethod( Invocation.method( #setOnShowFileSelector, [onShowFileSelector], ), returnValue: _i5.Future<void>.value(), returnValueForMissingStub: _i5.Future<void>.value(), ) as _i5.Future<void>); @override _i5.Future<void> setOnPlatformPermissionRequest( void Function(_i3.PlatformWebViewPermissionRequest)? onPermissionRequest) => (super.noSuchMethod( Invocation.method( #setOnPlatformPermissionRequest, [onPermissionRequest], ), returnValue: _i5.Future<void>.value(), returnValueForMissingStub: _i5.Future<void>.value(), ) as _i5.Future<void>); @override _i5.Future<void> setGeolocationPermissionsPromptCallbacks({ _i6.OnGeolocationPermissionsShowPrompt? onShowPrompt, _i6.OnGeolocationPermissionsHidePrompt? onHidePrompt, }) => (super.noSuchMethod( Invocation.method( #setGeolocationPermissionsPromptCallbacks, [], { #onShowPrompt: onShowPrompt, #onHidePrompt: onHidePrompt, }, ), returnValue: _i5.Future<void>.value(), returnValueForMissingStub: _i5.Future<void>.value(), ) as _i5.Future<void>); @override _i5.Future<void> setCustomWidgetCallbacks({ required _i6.OnShowCustomWidgetCallback? onShowCustomWidget, required _i6.OnHideCustomWidgetCallback? onHideCustomWidget, }) => (super.noSuchMethod( Invocation.method( #setCustomWidgetCallbacks, [], { #onShowCustomWidget: onShowCustomWidget, #onHideCustomWidget: onHideCustomWidget, }, ), returnValue: _i5.Future<void>.value(), returnValueForMissingStub: _i5.Future<void>.value(), ) as _i5.Future<void>); @override _i5.Future<void> setOnConsoleMessage( void Function(_i3.JavaScriptConsoleMessage)? onConsoleMessage) => (super.noSuchMethod( Invocation.method( #setOnConsoleMessage, [onConsoleMessage], ), returnValue: _i5.Future<void>.value(), returnValueForMissingStub: _i5.Future<void>.value(), ) as _i5.Future<void>); @override _i5.Future<String?> getUserAgent() => (super.noSuchMethod( Invocation.method( #getUserAgent, [], ), returnValue: _i5.Future<String?>.value(), ) as _i5.Future<String?>); @override _i5.Future<void> setOnJavaScriptAlertDialog( _i5.Future<void> Function(_i3.JavaScriptAlertDialogRequest)? onJavaScriptAlertDialog) => (super.noSuchMethod( Invocation.method( #setOnJavaScriptAlertDialog, [onJavaScriptAlertDialog], ), returnValue: _i5.Future<void>.value(), returnValueForMissingStub: _i5.Future<void>.value(), ) as _i5.Future<void>); @override _i5.Future<void> setOnJavaScriptConfirmDialog( _i5.Future<bool> Function(_i3.JavaScriptConfirmDialogRequest)? onJavaScriptConfirmDialog) => (super.noSuchMethod( Invocation.method( #setOnJavaScriptConfirmDialog, [onJavaScriptConfirmDialog], ), returnValue: _i5.Future<void>.value(), returnValueForMissingStub: _i5.Future<void>.value(), ) as _i5.Future<void>); @override _i5.Future<void> setOnJavaScriptTextInputDialog( _i5.Future<String> Function(_i3.JavaScriptTextInputDialogRequest)? onJavaScriptTextInputDialog) => (super.noSuchMethod( Invocation.method( #setOnJavaScriptTextInputDialog, [onJavaScriptTextInputDialog], ), returnValue: _i5.Future<void>.value(), returnValueForMissingStub: _i5.Future<void>.value(), ) as _i5.Future<void>); } /// A class which mocks [TestInstanceManagerHostApi]. /// /// See the documentation for Mockito's code generation for more information. class MockTestInstanceManagerHostApi extends _i1.Mock implements _i7.TestInstanceManagerHostApi { MockTestInstanceManagerHostApi() { _i1.throwOnMissingStub(this); } @override void clear() => super.noSuchMethod( Invocation.method( #clear, [], ), returnValueForMissingStub: null, ); }
packages/packages/webview_flutter/webview_flutter_android/test/android_webview_cookie_manager_test.mocks.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_android/test/android_webview_cookie_manager_test.mocks.dart", "repo_id": "packages", "token_count": 8291 }
1,012
# webview\_flutter\_wkwebview The Apple WKWebView implementation of [`webview_flutter`][1]. ## Usage This package is [endorsed][2], which means you can simply use `webview_flutter` normally. This package will be automatically included in your app when you do, so you do not need to add it to your `pubspec.yaml`. However, if you `import` this package to use any of its APIs directly, you should add it to your `pubspec.yaml` as usual. ### External Native API The plugin also provides a native API accessible by the native code of iOS applications or packages. This API follows the convention of breaking changes of the Dart API, which means that any changes to the class that are not backwards compatible will only be made with a major version change of the plugin. Native code other than this external API does not follow breaking change conventions, so app or plugin clients should not use any other native APIs. The API can be accessed by importing the native plugin `webview_flutter_wkwebview`: Objective-C: ```objectivec @import webview_flutter_wkwebview; ``` Then you will have access to the native class `FWFWebViewFlutterWKWebViewExternalAPI`. ## Contributing This package uses [pigeon][3] to generate the communication layer between Flutter and the host platform (iOS). The communication interface is defined in the `pigeons/web_kit.dart` file. After editing the communication interface regenerate the communication layer by running `dart run pigeon --input pigeons/web_kit.dart`. Besides [pigeon][3] this package also uses [mockito][4] to generate mock objects for testing purposes. To generate the mock objects run the following command: ```bash dart run build_runner build --delete-conflicting-outputs ``` If you would like to contribute to the plugin, check out our [contribution guide][5]. [1]: https://pub.dev/packages/webview_flutter [2]: https://flutter.dev/docs/development/packages-and-plugins/developing-packages#endorsed-federated-plugin [3]: https://pub.dev/packages/pigeon [4]: https://pub.dev/packages/mockito [5]: https://github.com/flutter/packages/blob/main/CONTRIBUTING.md
packages/packages/webview_flutter/webview_flutter_wkwebview/README.md/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/README.md", "repo_id": "packages", "token_count": 590 }
1,013
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @import Flutter; @import XCTest; @import webview_flutter_wkwebview; #import <OCMock/OCMock.h> static bool feq(CGFloat a, CGFloat b) { return fabs(b - a) < FLT_EPSILON; } @interface FWFWebViewHostApiTests : XCTestCase @end @implementation FWFWebViewHostApiTests - (void)testCreateWithIdentifier { FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; FWFWebViewHostApiImpl *hostAPI = [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; [instanceManager addDartCreatedInstance:[[WKWebViewConfiguration alloc] init] withIdentifier:0]; FlutterError *error; [hostAPI createWithIdentifier:1 configurationIdentifier:0 error:&error]; WKWebView *webView = (WKWebView *)[instanceManager instanceForIdentifier:1]; XCTAssertTrue([webView isKindOfClass:[WKWebView class]]); XCTAssertNil(error); } - (void)testLoadRequest { FWFWebView *mockWebView = OCMClassMock([FWFWebView class]); FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; [instanceManager addDartCreatedInstance:mockWebView withIdentifier:0]; FWFWebViewHostApiImpl *hostAPI = [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; FlutterError *error; FWFNSUrlRequestData *requestData = [FWFNSUrlRequestData makeWithUrl:@"https://www.flutter.dev" httpMethod:@"get" httpBody:nil allHttpHeaderFields:@{@"a" : @"header"}]; [hostAPI loadRequestForWebViewWithIdentifier:0 request:requestData error:&error]; NSURL *url = [NSURL URLWithString:@"https://www.flutter.dev"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; request.HTTPMethod = @"get"; request.allHTTPHeaderFields = @{@"a" : @"header"}; OCMVerify([mockWebView loadRequest:request]); XCTAssertNil(error); } - (void)testLoadRequestWithInvalidUrl { FWFWebView *mockWebView = OCMClassMock([FWFWebView class]); FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; [instanceManager addDartCreatedInstance:mockWebView withIdentifier:0]; FWFWebViewHostApiImpl *hostAPI = [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; NSString *badURLString = @"%invalidUrl%"; FlutterError *error; FWFNSUrlRequestData *requestData = [FWFNSUrlRequestData makeWithUrl:badURLString httpMethod:nil httpBody:nil allHttpHeaderFields:@{}]; [hostAPI loadRequestForWebViewWithIdentifier:0 request:requestData error:&error]; // When linking against the iOS 17 SDK or later, NSURL uses a lenient parser, and won't // fail to parse URLs, so the test must allow for either outcome. if (error) { XCTAssertEqualObjects(error.code, @"FWFURLRequestParsingError"); XCTAssertEqualObjects(error.message, @"Failed instantiating an NSURLRequest."); XCTAssertEqualObjects(error.details, @"URL was: '%invalidUrl%'"); } else { NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:badURLString]]; OCMVerify([mockWebView loadRequest:request]); } } - (void)testSetCustomUserAgent { FWFWebView *mockWebView = OCMClassMock([FWFWebView class]); FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; [instanceManager addDartCreatedInstance:mockWebView withIdentifier:0]; FWFWebViewHostApiImpl *hostAPI = [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; FlutterError *error; [hostAPI setCustomUserAgentForWebViewWithIdentifier:0 userAgent:@"userA" error:&error]; OCMVerify([mockWebView setCustomUserAgent:@"userA"]); XCTAssertNil(error); } - (void)testURL { FWFWebView *mockWebView = OCMClassMock([FWFWebView class]); OCMStub([mockWebView URL]).andReturn([NSURL URLWithString:@"https://www.flutter.dev/"]); FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; [instanceManager addDartCreatedInstance:mockWebView withIdentifier:0]; FWFWebViewHostApiImpl *hostAPI = [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; FlutterError *error; XCTAssertEqualObjects([hostAPI URLForWebViewWithIdentifier:0 error:&error], @"https://www.flutter.dev/"); XCTAssertNil(error); } - (void)testCanGoBack { FWFWebView *mockWebView = OCMClassMock([FWFWebView class]); OCMStub([mockWebView canGoBack]).andReturn(YES); FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; [instanceManager addDartCreatedInstance:mockWebView withIdentifier:0]; FWFWebViewHostApiImpl *hostAPI = [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; FlutterError *error; XCTAssertEqualObjects([hostAPI canGoBackForWebViewWithIdentifier:0 error:&error], @YES); XCTAssertNil(error); } - (void)testSetUIDelegate { FWFWebView *mockWebView = OCMClassMock([FWFWebView class]); FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; [instanceManager addDartCreatedInstance:mockWebView withIdentifier:0]; FWFWebViewHostApiImpl *hostAPI = [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; id<WKUIDelegate> mockDelegate = OCMProtocolMock(@protocol(WKUIDelegate)); [instanceManager addDartCreatedInstance:mockDelegate withIdentifier:1]; FlutterError *error; [hostAPI setUIDelegateForWebViewWithIdentifier:0 delegateIdentifier:@1 error:&error]; OCMVerify([mockWebView setUIDelegate:mockDelegate]); XCTAssertNil(error); } - (void)testSetNavigationDelegate { FWFWebView *mockWebView = OCMClassMock([FWFWebView class]); FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; [instanceManager addDartCreatedInstance:mockWebView withIdentifier:0]; FWFWebViewHostApiImpl *hostAPI = [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; id<WKNavigationDelegate> mockDelegate = OCMProtocolMock(@protocol(WKNavigationDelegate)); [instanceManager addDartCreatedInstance:mockDelegate withIdentifier:1]; FlutterError *error; [hostAPI setNavigationDelegateForWebViewWithIdentifier:0 delegateIdentifier:@1 error:&error]; OCMVerify([mockWebView setNavigationDelegate:mockDelegate]); XCTAssertNil(error); } - (void)testEstimatedProgress { FWFWebView *mockWebView = OCMClassMock([FWFWebView class]); OCMStub([mockWebView estimatedProgress]).andReturn(34.0); FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; [instanceManager addDartCreatedInstance:mockWebView withIdentifier:0]; FWFWebViewHostApiImpl *hostAPI = [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; FlutterError *error; XCTAssertEqualObjects([hostAPI estimatedProgressForWebViewWithIdentifier:0 error:&error], @34.0); XCTAssertNil(error); } - (void)testloadHTMLString { FWFWebView *mockWebView = OCMClassMock([FWFWebView class]); FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; [instanceManager addDartCreatedInstance:mockWebView withIdentifier:0]; FWFWebViewHostApiImpl *hostAPI = [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; FlutterError *error; [hostAPI loadHTMLForWebViewWithIdentifier:0 HTMLString:@"myString" baseURL:@"myBaseUrl" error:&error]; OCMVerify([mockWebView loadHTMLString:@"myString" baseURL:[NSURL URLWithString:@"myBaseUrl"]]); XCTAssertNil(error); } - (void)testLoadFileURL { FWFWebView *mockWebView = OCMClassMock([FWFWebView class]); FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; [instanceManager addDartCreatedInstance:mockWebView withIdentifier:0]; FWFWebViewHostApiImpl *hostAPI = [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; FlutterError *error; [hostAPI loadFileForWebViewWithIdentifier:0 fileURL:@"myFolder/apple.txt" readAccessURL:@"myFolder" error:&error]; XCTAssertNil(error); OCMVerify([mockWebView loadFileURL:[NSURL fileURLWithPath:@"myFolder/apple.txt" isDirectory:NO] allowingReadAccessToURL:[NSURL fileURLWithPath:@"myFolder/" isDirectory:YES] ]); } - (void)testLoadFlutterAsset { FWFWebView *mockWebView = OCMClassMock([FWFWebView class]); FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; [instanceManager addDartCreatedInstance:mockWebView withIdentifier:0]; FWFAssetManager *mockAssetManager = OCMClassMock([FWFAssetManager class]); OCMStub([mockAssetManager lookupKeyForAsset:@"assets/index.html"]) .andReturn(@"myFolder/assets/index.html"); NSBundle *mockBundle = OCMClassMock([NSBundle class]); OCMStub([mockBundle URLForResource:@"myFolder/assets/index" withExtension:@"html"]) .andReturn([NSURL URLWithString:@"webview_flutter/myFolder/assets/index.html"]); FWFWebViewHostApiImpl *hostAPI = [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager bundle:mockBundle assetManager:mockAssetManager]; FlutterError *error; [hostAPI loadAssetForWebViewWithIdentifier:0 assetKey:@"assets/index.html" error:&error]; XCTAssertNil(error); OCMVerify([mockWebView loadFileURL:[NSURL URLWithString:@"webview_flutter/myFolder/assets/index.html"] allowingReadAccessToURL:[NSURL URLWithString:@"webview_flutter/myFolder/assets/"]]); } - (void)testCanGoForward { FWFWebView *mockWebView = OCMClassMock([FWFWebView class]); OCMStub([mockWebView canGoForward]).andReturn(NO); FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; [instanceManager addDartCreatedInstance:mockWebView withIdentifier:0]; FWFWebViewHostApiImpl *hostAPI = [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; FlutterError *error; XCTAssertEqualObjects([hostAPI canGoForwardForWebViewWithIdentifier:0 error:&error], @NO); XCTAssertNil(error); } - (void)testGoBack { FWFWebView *mockWebView = OCMClassMock([FWFWebView class]); FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; [instanceManager addDartCreatedInstance:mockWebView withIdentifier:0]; FWFWebViewHostApiImpl *hostAPI = [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; FlutterError *error; [hostAPI goBackForWebViewWithIdentifier:0 error:&error]; OCMVerify([mockWebView goBack]); XCTAssertNil(error); } - (void)testGoForward { FWFWebView *mockWebView = OCMClassMock([FWFWebView class]); FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; [instanceManager addDartCreatedInstance:mockWebView withIdentifier:0]; FWFWebViewHostApiImpl *hostAPI = [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; FlutterError *error; [hostAPI goForwardForWebViewWithIdentifier:0 error:&error]; OCMVerify([mockWebView goForward]); XCTAssertNil(error); } - (void)testReload { FWFWebView *mockWebView = OCMClassMock([FWFWebView class]); FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; [instanceManager addDartCreatedInstance:mockWebView withIdentifier:0]; FWFWebViewHostApiImpl *hostAPI = [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; FlutterError *error; [hostAPI reloadWebViewWithIdentifier:0 error:&error]; OCMVerify([mockWebView reload]); XCTAssertNil(error); } - (void)testTitle { FWFWebView *mockWebView = OCMClassMock([FWFWebView class]); OCMStub([mockWebView title]).andReturn(@"myTitle"); FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; [instanceManager addDartCreatedInstance:mockWebView withIdentifier:0]; FWFWebViewHostApiImpl *hostAPI = [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; FlutterError *error; XCTAssertEqualObjects([hostAPI titleForWebViewWithIdentifier:0 error:&error], @"myTitle"); XCTAssertNil(error); } - (void)testSetAllowsBackForwardNavigationGestures { FWFWebView *mockWebView = OCMClassMock([FWFWebView class]); FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; [instanceManager addDartCreatedInstance:mockWebView withIdentifier:0]; FWFWebViewHostApiImpl *hostAPI = [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; FlutterError *error; [hostAPI setAllowsBackForwardForWebViewWithIdentifier:0 isAllowed:YES error:&error]; OCMVerify([mockWebView setAllowsBackForwardNavigationGestures:YES]); XCTAssertNil(error); } - (void)testEvaluateJavaScript { FWFWebView *mockWebView = OCMClassMock([FWFWebView class]); OCMStub([mockWebView evaluateJavaScript:@"runJavaScript" completionHandler:([OCMArg invokeBlockWithArgs:@"result", [NSNull null], nil])]); FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; [instanceManager addDartCreatedInstance:mockWebView withIdentifier:0]; FWFWebViewHostApiImpl *hostAPI = [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; NSString __block *returnValue; FlutterError __block *returnError; [hostAPI evaluateJavaScriptForWebViewWithIdentifier:0 javaScriptString:@"runJavaScript" completion:^(id result, FlutterError *error) { returnValue = result; returnError = error; }]; XCTAssertEqualObjects(returnValue, @"result"); XCTAssertNil(returnError); } - (void)testEvaluateJavaScriptReturnsNSErrorData { FWFWebView *mockWebView = OCMClassMock([FWFWebView class]); OCMStub([mockWebView evaluateJavaScript:@"runJavaScript" completionHandler:([OCMArg invokeBlockWithArgs:[NSNull null], [NSError errorWithDomain:@"errorDomain" code:0 userInfo:@{ NSLocalizedDescriptionKey : @"description" }], nil])]); FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; [instanceManager addDartCreatedInstance:mockWebView withIdentifier:0]; FWFWebViewHostApiImpl *hostAPI = [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; NSString __block *returnValue; FlutterError __block *returnError; [hostAPI evaluateJavaScriptForWebViewWithIdentifier:0 javaScriptString:@"runJavaScript" completion:^(id result, FlutterError *error) { returnValue = result; returnError = error; }]; XCTAssertNil(returnValue); FWFNSErrorData *errorData = returnError.details; XCTAssertTrue([errorData isKindOfClass:[FWFNSErrorData class]]); XCTAssertEqual(errorData.code, 0); XCTAssertEqualObjects(errorData.domain, @"errorDomain"); XCTAssertEqualObjects(errorData.userInfo, @{NSLocalizedDescriptionKey : @"description"}); } - (void)testWebViewContentInsetBehaviorShouldBeNever { FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; FWFWebViewHostApiImpl *hostAPI = [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; [instanceManager addDartCreatedInstance:[[WKWebViewConfiguration alloc] init] withIdentifier:0]; FlutterError *error; [hostAPI createWithIdentifier:1 configurationIdentifier:0 error:&error]; FWFWebView *webView = (FWFWebView *)[instanceManager instanceForIdentifier:1]; XCTAssertEqual(webView.scrollView.contentInsetAdjustmentBehavior, UIScrollViewContentInsetAdjustmentNever); } - (void)testScrollViewsAutomaticallyAdjustsScrollIndicatorInsetsShouldbeNoOnIOS13 API_AVAILABLE( ios(13.0)) { FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; FWFWebViewHostApiImpl *hostAPI = [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; [instanceManager addDartCreatedInstance:[[WKWebViewConfiguration alloc] init] withIdentifier:0]; FlutterError *error; [hostAPI createWithIdentifier:1 configurationIdentifier:0 error:&error]; FWFWebView *webView = (FWFWebView *)[instanceManager instanceForIdentifier:1]; XCTAssertFalse(webView.scrollView.automaticallyAdjustsScrollIndicatorInsets); } - (void)testContentInsetsSumAlwaysZeroAfterSetFrame { FWFWebView *webView = [[FWFWebView alloc] initWithFrame:CGRectMake(0, 0, 300, 400) configuration:[[WKWebViewConfiguration alloc] init]]; webView.scrollView.contentInset = UIEdgeInsetsMake(0, 0, 300, 0); XCTAssertFalse(UIEdgeInsetsEqualToEdgeInsets(webView.scrollView.contentInset, UIEdgeInsetsZero)); webView.frame = CGRectMake(0, 0, 300, 200); XCTAssertTrue(UIEdgeInsetsEqualToEdgeInsets(webView.scrollView.contentInset, UIEdgeInsetsZero)); XCTAssertTrue(CGRectEqualToRect(webView.frame, CGRectMake(0, 0, 300, 200))); // Make sure the contentInset compensates the adjustedContentInset. UIScrollView *partialMockScrollView = OCMPartialMock(webView.scrollView); UIEdgeInsets insetToAdjust = UIEdgeInsetsMake(0, 0, 300, 0); OCMStub(partialMockScrollView.adjustedContentInset).andReturn(insetToAdjust); XCTAssertTrue(UIEdgeInsetsEqualToEdgeInsets(webView.scrollView.contentInset, UIEdgeInsetsZero)); webView.frame = CGRectMake(0, 0, 300, 100); XCTAssertTrue(feq(webView.scrollView.contentInset.bottom, -insetToAdjust.bottom)); XCTAssertTrue(CGRectEqualToRect(webView.frame, CGRectMake(0, 0, 300, 100))); } - (void)testSetInspectable API_AVAILABLE(ios(16.4), macos(13.3)) { FWFWebView *mockWebView = OCMClassMock([FWFWebView class]); FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; [instanceManager addDartCreatedInstance:mockWebView withIdentifier:0]; FWFWebViewHostApiImpl *hostAPI = [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; FlutterError *error; [hostAPI setInspectableForWebViewWithIdentifier:0 inspectable:YES error:&error]; OCMVerify([mockWebView setInspectable:YES]); XCTAssertNil(error); } - (void)testCustomUserAgent { FWFWebView *mockWebView = OCMClassMock([FWFWebView class]); NSString *userAgent = @"str"; OCMStub([mockWebView customUserAgent]).andReturn(userAgent); FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; [instanceManager addDartCreatedInstance:mockWebView withIdentifier:0]; FWFWebViewHostApiImpl *hostAPI = [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; FlutterError *error; XCTAssertEqualObjects([hostAPI customUserAgentForWebViewWithIdentifier:0 error:&error], userAgent); XCTAssertNil(error); } @end
packages/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerTests/FWFWebViewHostApiTests.m/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerTests/FWFWebViewHostApiTests.m", "repo_id": "packages", "token_count": 8692 }
1,014
// 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 #import <Foundation/Foundation.h> @protocol FlutterBinaryMessenger; @protocol FlutterMessageCodec; @class FlutterError; @class FlutterStandardTypedData; NS_ASSUME_NONNULL_BEGIN /// Mirror of NSKeyValueObservingOptions. /// /// See /// https://developer.apple.com/documentation/foundation/nskeyvalueobservingoptions?language=objc. typedef NS_ENUM(NSUInteger, FWFNSKeyValueObservingOptionsEnum) { FWFNSKeyValueObservingOptionsEnumNewValue = 0, FWFNSKeyValueObservingOptionsEnumOldValue = 1, FWFNSKeyValueObservingOptionsEnumInitialValue = 2, FWFNSKeyValueObservingOptionsEnumPriorNotification = 3, }; /// Wrapper for FWFNSKeyValueObservingOptionsEnum to allow for nullability. @interface FWFNSKeyValueObservingOptionsEnumBox : NSObject @property(nonatomic, assign) FWFNSKeyValueObservingOptionsEnum value; - (instancetype)initWithValue:(FWFNSKeyValueObservingOptionsEnum)value; @end /// Mirror of NSKeyValueChange. /// /// See https://developer.apple.com/documentation/foundation/nskeyvaluechange?language=objc. typedef NS_ENUM(NSUInteger, FWFNSKeyValueChangeEnum) { FWFNSKeyValueChangeEnumSetting = 0, FWFNSKeyValueChangeEnumInsertion = 1, FWFNSKeyValueChangeEnumRemoval = 2, FWFNSKeyValueChangeEnumReplacement = 3, }; /// Wrapper for FWFNSKeyValueChangeEnum to allow for nullability. @interface FWFNSKeyValueChangeEnumBox : NSObject @property(nonatomic, assign) FWFNSKeyValueChangeEnum value; - (instancetype)initWithValue:(FWFNSKeyValueChangeEnum)value; @end /// Mirror of NSKeyValueChangeKey. /// /// See https://developer.apple.com/documentation/foundation/nskeyvaluechangekey?language=objc. typedef NS_ENUM(NSUInteger, FWFNSKeyValueChangeKeyEnum) { FWFNSKeyValueChangeKeyEnumIndexes = 0, FWFNSKeyValueChangeKeyEnumKind = 1, FWFNSKeyValueChangeKeyEnumNewValue = 2, FWFNSKeyValueChangeKeyEnumNotificationIsPrior = 3, FWFNSKeyValueChangeKeyEnumOldValue = 4, FWFNSKeyValueChangeKeyEnumUnknown = 5, }; /// Wrapper for FWFNSKeyValueChangeKeyEnum to allow for nullability. @interface FWFNSKeyValueChangeKeyEnumBox : NSObject @property(nonatomic, assign) FWFNSKeyValueChangeKeyEnum value; - (instancetype)initWithValue:(FWFNSKeyValueChangeKeyEnum)value; @end /// Mirror of WKUserScriptInjectionTime. /// /// See https://developer.apple.com/documentation/webkit/wkuserscriptinjectiontime?language=objc. typedef NS_ENUM(NSUInteger, FWFWKUserScriptInjectionTimeEnum) { FWFWKUserScriptInjectionTimeEnumAtDocumentStart = 0, FWFWKUserScriptInjectionTimeEnumAtDocumentEnd = 1, }; /// Wrapper for FWFWKUserScriptInjectionTimeEnum to allow for nullability. @interface FWFWKUserScriptInjectionTimeEnumBox : NSObject @property(nonatomic, assign) FWFWKUserScriptInjectionTimeEnum value; - (instancetype)initWithValue:(FWFWKUserScriptInjectionTimeEnum)value; @end /// Mirror of WKAudiovisualMediaTypes. /// /// See /// [WKAudiovisualMediaTypes](https://developer.apple.com/documentation/webkit/wkaudiovisualmediatypes?language=objc). typedef NS_ENUM(NSUInteger, FWFWKAudiovisualMediaTypeEnum) { FWFWKAudiovisualMediaTypeEnumNone = 0, FWFWKAudiovisualMediaTypeEnumAudio = 1, FWFWKAudiovisualMediaTypeEnumVideo = 2, FWFWKAudiovisualMediaTypeEnumAll = 3, }; /// Wrapper for FWFWKAudiovisualMediaTypeEnum to allow for nullability. @interface FWFWKAudiovisualMediaTypeEnumBox : NSObject @property(nonatomic, assign) FWFWKAudiovisualMediaTypeEnum value; - (instancetype)initWithValue:(FWFWKAudiovisualMediaTypeEnum)value; @end /// Mirror of WKWebsiteDataTypes. /// /// See /// https://developer.apple.com/documentation/webkit/wkwebsitedatarecord/data_store_record_types?language=objc. typedef NS_ENUM(NSUInteger, FWFWKWebsiteDataTypeEnum) { FWFWKWebsiteDataTypeEnumCookies = 0, FWFWKWebsiteDataTypeEnumMemoryCache = 1, FWFWKWebsiteDataTypeEnumDiskCache = 2, FWFWKWebsiteDataTypeEnumOfflineWebApplicationCache = 3, FWFWKWebsiteDataTypeEnumLocalStorage = 4, FWFWKWebsiteDataTypeEnumSessionStorage = 5, FWFWKWebsiteDataTypeEnumWebSQLDatabases = 6, FWFWKWebsiteDataTypeEnumIndexedDBDatabases = 7, }; /// Wrapper for FWFWKWebsiteDataTypeEnum to allow for nullability. @interface FWFWKWebsiteDataTypeEnumBox : NSObject @property(nonatomic, assign) FWFWKWebsiteDataTypeEnum value; - (instancetype)initWithValue:(FWFWKWebsiteDataTypeEnum)value; @end /// Mirror of WKNavigationActionPolicy. /// /// See https://developer.apple.com/documentation/webkit/wknavigationactionpolicy?language=objc. typedef NS_ENUM(NSUInteger, FWFWKNavigationActionPolicyEnum) { FWFWKNavigationActionPolicyEnumAllow = 0, FWFWKNavigationActionPolicyEnumCancel = 1, }; /// Wrapper for FWFWKNavigationActionPolicyEnum to allow for nullability. @interface FWFWKNavigationActionPolicyEnumBox : NSObject @property(nonatomic, assign) FWFWKNavigationActionPolicyEnum value; - (instancetype)initWithValue:(FWFWKNavigationActionPolicyEnum)value; @end /// Mirror of WKNavigationResponsePolicy. /// /// See https://developer.apple.com/documentation/webkit/wknavigationactionpolicy?language=objc. typedef NS_ENUM(NSUInteger, FWFWKNavigationResponsePolicyEnum) { FWFWKNavigationResponsePolicyEnumAllow = 0, FWFWKNavigationResponsePolicyEnumCancel = 1, }; /// Wrapper for FWFWKNavigationResponsePolicyEnum to allow for nullability. @interface FWFWKNavigationResponsePolicyEnumBox : NSObject @property(nonatomic, assign) FWFWKNavigationResponsePolicyEnum value; - (instancetype)initWithValue:(FWFWKNavigationResponsePolicyEnum)value; @end /// Mirror of NSHTTPCookiePropertyKey. /// /// See https://developer.apple.com/documentation/foundation/nshttpcookiepropertykey. typedef NS_ENUM(NSUInteger, FWFNSHttpCookiePropertyKeyEnum) { FWFNSHttpCookiePropertyKeyEnumComment = 0, FWFNSHttpCookiePropertyKeyEnumCommentUrl = 1, FWFNSHttpCookiePropertyKeyEnumDiscard = 2, FWFNSHttpCookiePropertyKeyEnumDomain = 3, FWFNSHttpCookiePropertyKeyEnumExpires = 4, FWFNSHttpCookiePropertyKeyEnumMaximumAge = 5, FWFNSHttpCookiePropertyKeyEnumName = 6, FWFNSHttpCookiePropertyKeyEnumOriginUrl = 7, FWFNSHttpCookiePropertyKeyEnumPath = 8, FWFNSHttpCookiePropertyKeyEnumPort = 9, FWFNSHttpCookiePropertyKeyEnumSameSitePolicy = 10, FWFNSHttpCookiePropertyKeyEnumSecure = 11, FWFNSHttpCookiePropertyKeyEnumValue = 12, FWFNSHttpCookiePropertyKeyEnumVersion = 13, }; /// Wrapper for FWFNSHttpCookiePropertyKeyEnum to allow for nullability. @interface FWFNSHttpCookiePropertyKeyEnumBox : NSObject @property(nonatomic, assign) FWFNSHttpCookiePropertyKeyEnum value; - (instancetype)initWithValue:(FWFNSHttpCookiePropertyKeyEnum)value; @end /// An object that contains information about an action that causes navigation /// to occur. /// /// Wraps /// [WKNavigationType](https://developer.apple.com/documentation/webkit/wknavigationaction?language=objc). typedef NS_ENUM(NSUInteger, FWFWKNavigationType) { /// A link activation. /// /// See /// https://developer.apple.com/documentation/webkit/wknavigationtype/wknavigationtypelinkactivated?language=objc. FWFWKNavigationTypeLinkActivated = 0, /// A request to submit a form. /// /// See /// https://developer.apple.com/documentation/webkit/wknavigationtype/wknavigationtypeformsubmitted?language=objc. FWFWKNavigationTypeSubmitted = 1, /// A request for the frame’s next or previous item. /// /// See /// https://developer.apple.com/documentation/webkit/wknavigationtype/wknavigationtypebackforward?language=objc. FWFWKNavigationTypeBackForward = 2, /// A request to reload the webpage. /// /// See /// https://developer.apple.com/documentation/webkit/wknavigationtype/wknavigationtypereload?language=objc. FWFWKNavigationTypeReload = 3, /// A request to resubmit a form. /// /// See /// https://developer.apple.com/documentation/webkit/wknavigationtype/wknavigationtypeformresubmitted?language=objc. FWFWKNavigationTypeFormResubmitted = 4, /// A navigation request that originates for some other reason. /// /// See /// https://developer.apple.com/documentation/webkit/wknavigationtype/wknavigationtypeother?language=objc. FWFWKNavigationTypeOther = 5, /// An unknown navigation type. /// /// This does not represent an actual value provided by the platform and only /// indicates a value was provided that isn't currently supported. FWFWKNavigationTypeUnknown = 6, }; /// Wrapper for FWFWKNavigationType to allow for nullability. @interface FWFWKNavigationTypeBox : NSObject @property(nonatomic, assign) FWFWKNavigationType value; - (instancetype)initWithValue:(FWFWKNavigationType)value; @end /// Possible permission decisions for device resource access. /// /// See https://developer.apple.com/documentation/webkit/wkpermissiondecision?language=objc. typedef NS_ENUM(NSUInteger, FWFWKPermissionDecision) { /// Deny permission for the requested resource. /// /// See /// https://developer.apple.com/documentation/webkit/wkpermissiondecision/wkpermissiondecisiondeny?language=objc. FWFWKPermissionDecisionDeny = 0, /// Deny permission for the requested resource. /// /// See /// https://developer.apple.com/documentation/webkit/wkpermissiondecision/wkpermissiondecisiongrant?language=objc. FWFWKPermissionDecisionGrant = 1, /// Prompt the user for permission for the requested resource. /// /// See /// https://developer.apple.com/documentation/webkit/wkpermissiondecision/wkpermissiondecisionprompt?language=objc. FWFWKPermissionDecisionPrompt = 2, }; /// Wrapper for FWFWKPermissionDecision to allow for nullability. @interface FWFWKPermissionDecisionBox : NSObject @property(nonatomic, assign) FWFWKPermissionDecision value; - (instancetype)initWithValue:(FWFWKPermissionDecision)value; @end /// List of the types of media devices that can capture audio, video, or both. /// /// See https://developer.apple.com/documentation/webkit/wkmediacapturetype?language=objc. typedef NS_ENUM(NSUInteger, FWFWKMediaCaptureType) { /// A media device that can capture video. /// /// See /// https://developer.apple.com/documentation/webkit/wkmediacapturetype/wkmediacapturetypecamera?language=objc. FWFWKMediaCaptureTypeCamera = 0, /// A media device or devices that can capture audio and video. /// /// See /// https://developer.apple.com/documentation/webkit/wkmediacapturetype/wkmediacapturetypecameraandmicrophone?language=objc. FWFWKMediaCaptureTypeCameraAndMicrophone = 1, /// A media device that can capture audio. /// /// See /// https://developer.apple.com/documentation/webkit/wkmediacapturetype/wkmediacapturetypemicrophone?language=objc. FWFWKMediaCaptureTypeMicrophone = 2, /// An unknown media device. /// /// This does not represent an actual value provided by the platform and only /// indicates a value was provided that isn't currently supported. FWFWKMediaCaptureTypeUnknown = 3, }; /// Wrapper for FWFWKMediaCaptureType to allow for nullability. @interface FWFWKMediaCaptureTypeBox : NSObject @property(nonatomic, assign) FWFWKMediaCaptureType value; - (instancetype)initWithValue:(FWFWKMediaCaptureType)value; @end /// Responses to an authentication challenge. /// /// See /// https://developer.apple.com/documentation/foundation/nsurlsessionauthchallengedisposition?language=objc. typedef NS_ENUM(NSUInteger, FWFNSUrlSessionAuthChallengeDisposition) { /// Use the specified credential, which may be nil. /// /// See /// https://developer.apple.com/documentation/foundation/nsurlsessionauthchallengedisposition/nsurlsessionauthchallengeusecredential?language=objc. FWFNSUrlSessionAuthChallengeDispositionUseCredential = 0, /// Use the default handling for the challenge as though this delegate method /// were not implemented. /// /// See /// https://developer.apple.com/documentation/foundation/nsurlsessionauthchallengedisposition/nsurlsessionauthchallengeperformdefaulthandling?language=objc. FWFNSUrlSessionAuthChallengeDispositionPerformDefaultHandling = 1, /// Cancel the entire request. /// /// See /// https://developer.apple.com/documentation/foundation/nsurlsessionauthchallengedisposition/nsurlsessionauthchallengecancelauthenticationchallenge?language=objc. FWFNSUrlSessionAuthChallengeDispositionCancelAuthenticationChallenge = 2, /// Reject this challenge, and call the authentication delegate method again /// with the next authentication protection space. /// /// See /// https://developer.apple.com/documentation/foundation/nsurlsessionauthchallengedisposition/nsurlsessionauthchallengerejectprotectionspace?language=objc. FWFNSUrlSessionAuthChallengeDispositionRejectProtectionSpace = 3, }; /// Wrapper for FWFNSUrlSessionAuthChallengeDisposition to allow for nullability. @interface FWFNSUrlSessionAuthChallengeDispositionBox : NSObject @property(nonatomic, assign) FWFNSUrlSessionAuthChallengeDisposition value; - (instancetype)initWithValue:(FWFNSUrlSessionAuthChallengeDisposition)value; @end /// Specifies how long a credential will be kept. typedef NS_ENUM(NSUInteger, FWFNSUrlCredentialPersistence) { /// The credential should not be stored. /// /// See /// https://developer.apple.com/documentation/foundation/nsurlcredentialpersistence/nsurlcredentialpersistencenone?language=objc. FWFNSUrlCredentialPersistenceNone = 0, /// The credential should be stored only for this session. /// /// See /// https://developer.apple.com/documentation/foundation/nsurlcredentialpersistence/nsurlcredentialpersistenceforsession?language=objc. FWFNSUrlCredentialPersistenceSession = 1, /// The credential should be stored in the keychain. /// /// See /// https://developer.apple.com/documentation/foundation/nsurlcredentialpersistence/nsurlcredentialpersistencepermanent?language=objc. FWFNSUrlCredentialPersistencePermanent = 2, /// The credential should be stored permanently in the keychain, and in /// addition should be distributed to other devices based on the owning Apple /// ID. /// /// See /// https://developer.apple.com/documentation/foundation/nsurlcredentialpersistence/nsurlcredentialpersistencesynchronizable?language=objc. FWFNSUrlCredentialPersistenceSynchronizable = 3, }; /// Wrapper for FWFNSUrlCredentialPersistence to allow for nullability. @interface FWFNSUrlCredentialPersistenceBox : NSObject @property(nonatomic, assign) FWFNSUrlCredentialPersistence value; - (instancetype)initWithValue:(FWFNSUrlCredentialPersistence)value; @end @class FWFNSKeyValueObservingOptionsEnumData; @class FWFNSKeyValueChangeKeyEnumData; @class FWFWKUserScriptInjectionTimeEnumData; @class FWFWKAudiovisualMediaTypeEnumData; @class FWFWKWebsiteDataTypeEnumData; @class FWFWKNavigationActionPolicyEnumData; @class FWFNSHttpCookiePropertyKeyEnumData; @class FWFWKPermissionDecisionData; @class FWFWKMediaCaptureTypeData; @class FWFNSUrlRequestData; @class FWFNSHttpUrlResponseData; @class FWFWKUserScriptData; @class FWFWKNavigationActionData; @class FWFWKNavigationResponseData; @class FWFWKFrameInfoData; @class FWFNSErrorData; @class FWFWKScriptMessageData; @class FWFWKSecurityOriginData; @class FWFNSHttpCookieData; @class FWFObjectOrIdentifier; @class FWFAuthenticationChallengeResponse; @interface FWFNSKeyValueObservingOptionsEnumData : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithValue:(FWFNSKeyValueObservingOptionsEnum)value; @property(nonatomic, assign) FWFNSKeyValueObservingOptionsEnum value; @end @interface FWFNSKeyValueChangeKeyEnumData : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithValue:(FWFNSKeyValueChangeKeyEnum)value; @property(nonatomic, assign) FWFNSKeyValueChangeKeyEnum value; @end @interface FWFWKUserScriptInjectionTimeEnumData : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithValue:(FWFWKUserScriptInjectionTimeEnum)value; @property(nonatomic, assign) FWFWKUserScriptInjectionTimeEnum value; @end @interface FWFWKAudiovisualMediaTypeEnumData : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithValue:(FWFWKAudiovisualMediaTypeEnum)value; @property(nonatomic, assign) FWFWKAudiovisualMediaTypeEnum value; @end @interface FWFWKWebsiteDataTypeEnumData : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithValue:(FWFWKWebsiteDataTypeEnum)value; @property(nonatomic, assign) FWFWKWebsiteDataTypeEnum value; @end @interface FWFWKNavigationActionPolicyEnumData : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithValue:(FWFWKNavigationActionPolicyEnum)value; @property(nonatomic, assign) FWFWKNavigationActionPolicyEnum value; @end @interface FWFNSHttpCookiePropertyKeyEnumData : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithValue:(FWFNSHttpCookiePropertyKeyEnum)value; @property(nonatomic, assign) FWFNSHttpCookiePropertyKeyEnum value; @end @interface FWFWKPermissionDecisionData : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithValue:(FWFWKPermissionDecision)value; @property(nonatomic, assign) FWFWKPermissionDecision value; @end @interface FWFWKMediaCaptureTypeData : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithValue:(FWFWKMediaCaptureType)value; @property(nonatomic, assign) FWFWKMediaCaptureType value; @end /// Mirror of NSURLRequest. /// /// See https://developer.apple.com/documentation/foundation/nsurlrequest?language=objc. @interface FWFNSUrlRequestData : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithUrl:(NSString *)url httpMethod:(nullable NSString *)httpMethod httpBody:(nullable FlutterStandardTypedData *)httpBody allHttpHeaderFields:(NSDictionary<NSString *, NSString *> *)allHttpHeaderFields; @property(nonatomic, copy) NSString *url; @property(nonatomic, copy, nullable) NSString *httpMethod; @property(nonatomic, strong, nullable) FlutterStandardTypedData *httpBody; @property(nonatomic, copy) NSDictionary<NSString *, NSString *> *allHttpHeaderFields; @end /// Mirror of NSURLResponse. /// /// See https://developer.apple.com/documentation/foundation/nshttpurlresponse?language=objc. @interface FWFNSHttpUrlResponseData : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithStatusCode:(NSInteger)statusCode; @property(nonatomic, assign) NSInteger statusCode; @end /// Mirror of WKUserScript. /// /// See https://developer.apple.com/documentation/webkit/wkuserscript?language=objc. @interface FWFWKUserScriptData : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithSource:(NSString *)source injectionTime:(nullable FWFWKUserScriptInjectionTimeEnumData *)injectionTime isMainFrameOnly:(BOOL)isMainFrameOnly; @property(nonatomic, copy) NSString *source; @property(nonatomic, strong, nullable) FWFWKUserScriptInjectionTimeEnumData *injectionTime; @property(nonatomic, assign) BOOL isMainFrameOnly; @end /// Mirror of WKNavigationAction. /// /// See https://developer.apple.com/documentation/webkit/wknavigationaction. @interface FWFWKNavigationActionData : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithRequest:(FWFNSUrlRequestData *)request targetFrame:(FWFWKFrameInfoData *)targetFrame navigationType:(FWFWKNavigationType)navigationType; @property(nonatomic, strong) FWFNSUrlRequestData *request; @property(nonatomic, strong) FWFWKFrameInfoData *targetFrame; @property(nonatomic, assign) FWFWKNavigationType navigationType; @end /// Mirror of WKNavigationResponse. /// /// See https://developer.apple.com/documentation/webkit/wknavigationresponse. @interface FWFWKNavigationResponseData : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithResponse:(FWFNSHttpUrlResponseData *)response forMainFrame:(BOOL)forMainFrame; @property(nonatomic, strong) FWFNSHttpUrlResponseData *response; @property(nonatomic, assign) BOOL forMainFrame; @end /// Mirror of WKFrameInfo. /// /// See https://developer.apple.com/documentation/webkit/wkframeinfo?language=objc. @interface FWFWKFrameInfoData : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithIsMainFrame:(BOOL)isMainFrame request:(FWFNSUrlRequestData *)request; @property(nonatomic, assign) BOOL isMainFrame; @property(nonatomic, strong) FWFNSUrlRequestData *request; @end /// Mirror of NSError. /// /// See https://developer.apple.com/documentation/foundation/nserror?language=objc. @interface FWFNSErrorData : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithCode:(NSInteger)code domain:(NSString *)domain userInfo:(nullable NSDictionary<NSString *, id> *)userInfo; @property(nonatomic, assign) NSInteger code; @property(nonatomic, copy) NSString *domain; @property(nonatomic, copy, nullable) NSDictionary<NSString *, id> *userInfo; @end /// Mirror of WKScriptMessage. /// /// See https://developer.apple.com/documentation/webkit/wkscriptmessage?language=objc. @interface FWFWKScriptMessageData : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithName:(NSString *)name body:(nullable id)body; @property(nonatomic, copy) NSString *name; @property(nonatomic, strong, nullable) id body; @end /// Mirror of WKSecurityOrigin. /// /// See https://developer.apple.com/documentation/webkit/wksecurityorigin?language=objc. @interface FWFWKSecurityOriginData : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithHost:(NSString *)host port:(NSInteger)port protocol:(NSString *)protocol; @property(nonatomic, copy) NSString *host; @property(nonatomic, assign) NSInteger port; @property(nonatomic, copy) NSString *protocol; @end /// Mirror of NSHttpCookieData. /// /// See https://developer.apple.com/documentation/foundation/nshttpcookie?language=objc. @interface FWFNSHttpCookieData : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithPropertyKeys:(NSArray<FWFNSHttpCookiePropertyKeyEnumData *> *)propertyKeys propertyValues:(NSArray<id> *)propertyValues; @property(nonatomic, copy) NSArray<FWFNSHttpCookiePropertyKeyEnumData *> *propertyKeys; @property(nonatomic, copy) NSArray<id> *propertyValues; @end /// An object that can represent either a value supported by /// `StandardMessageCodec`, a data class in this pigeon file, or an identifier /// of an object stored in an `InstanceManager`. @interface FWFObjectOrIdentifier : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithValue:(nullable id)value isIdentifier:(BOOL)isIdentifier; @property(nonatomic, strong, nullable) id value; /// Whether value is an int that is used to retrieve an instance stored in an /// `InstanceManager`. @property(nonatomic, assign) BOOL isIdentifier; @end @interface FWFAuthenticationChallengeResponse : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithDisposition:(FWFNSUrlSessionAuthChallengeDisposition)disposition credentialIdentifier:(nullable NSNumber *)credentialIdentifier; @property(nonatomic, assign) FWFNSUrlSessionAuthChallengeDisposition disposition; @property(nonatomic, strong, nullable) NSNumber *credentialIdentifier; @end /// The codec used by FWFWKWebsiteDataStoreHostApi. NSObject<FlutterMessageCodec> *FWFWKWebsiteDataStoreHostApiGetCodec(void); /// Mirror of WKWebsiteDataStore. /// /// See https://developer.apple.com/documentation/webkit/wkwebsitedatastore?language=objc. @protocol FWFWKWebsiteDataStoreHostApi - (void)createFromWebViewConfigurationWithIdentifier:(NSInteger)identifier configurationIdentifier:(NSInteger)configurationIdentifier error:(FlutterError *_Nullable *_Nonnull)error; - (void)createDefaultDataStoreWithIdentifier:(NSInteger)identifier error:(FlutterError *_Nullable *_Nonnull)error; - (void)removeDataFromDataStoreWithIdentifier:(NSInteger)identifier ofTypes:(NSArray<FWFWKWebsiteDataTypeEnumData *> *)dataTypes modifiedSince:(double)modificationTimeInSecondsSinceEpoch completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion; @end extern void SetUpFWFWKWebsiteDataStoreHostApi( id<FlutterBinaryMessenger> binaryMessenger, NSObject<FWFWKWebsiteDataStoreHostApi> *_Nullable api); /// The codec used by FWFUIViewHostApi. NSObject<FlutterMessageCodec> *FWFUIViewHostApiGetCodec(void); /// Mirror of UIView. /// /// See https://developer.apple.com/documentation/uikit/uiview?language=objc. @protocol FWFUIViewHostApi - (void)setBackgroundColorForViewWithIdentifier:(NSInteger)identifier toValue:(nullable NSNumber *)value error:(FlutterError *_Nullable *_Nonnull)error; - (void)setOpaqueForViewWithIdentifier:(NSInteger)identifier isOpaque:(BOOL)opaque error:(FlutterError *_Nullable *_Nonnull)error; @end extern void SetUpFWFUIViewHostApi(id<FlutterBinaryMessenger> binaryMessenger, NSObject<FWFUIViewHostApi> *_Nullable api); /// The codec used by FWFUIScrollViewHostApi. NSObject<FlutterMessageCodec> *FWFUIScrollViewHostApiGetCodec(void); /// Mirror of UIScrollView. /// /// See https://developer.apple.com/documentation/uikit/uiscrollview?language=objc. @protocol FWFUIScrollViewHostApi - (void)createFromWebViewWithIdentifier:(NSInteger)identifier webViewIdentifier:(NSInteger)webViewIdentifier error:(FlutterError *_Nullable *_Nonnull)error; /// @return `nil` only when `error != nil`. - (nullable NSArray<NSNumber *> *) contentOffsetForScrollViewWithIdentifier:(NSInteger)identifier error:(FlutterError *_Nullable *_Nonnull)error; - (void)scrollByForScrollViewWithIdentifier:(NSInteger)identifier x:(double)x y:(double)y error:(FlutterError *_Nullable *_Nonnull)error; - (void)setContentOffsetForScrollViewWithIdentifier:(NSInteger)identifier toX:(double)x y:(double)y error:(FlutterError *_Nullable *_Nonnull)error; - (void)setDelegateForScrollViewWithIdentifier:(NSInteger)identifier uiScrollViewDelegateIdentifier:(nullable NSNumber *)uiScrollViewDelegateIdentifier error:(FlutterError *_Nullable *_Nonnull)error; @end extern void SetUpFWFUIScrollViewHostApi(id<FlutterBinaryMessenger> binaryMessenger, NSObject<FWFUIScrollViewHostApi> *_Nullable api); /// The codec used by FWFWKWebViewConfigurationHostApi. NSObject<FlutterMessageCodec> *FWFWKWebViewConfigurationHostApiGetCodec(void); /// Mirror of WKWebViewConfiguration. /// /// See https://developer.apple.com/documentation/webkit/wkwebviewconfiguration?language=objc. @protocol FWFWKWebViewConfigurationHostApi - (void)createWithIdentifier:(NSInteger)identifier error:(FlutterError *_Nullable *_Nonnull)error; - (void)createFromWebViewWithIdentifier:(NSInteger)identifier webViewIdentifier:(NSInteger)webViewIdentifier error:(FlutterError *_Nullable *_Nonnull)error; - (void)setAllowsInlineMediaPlaybackForConfigurationWithIdentifier:(NSInteger)identifier isAllowed:(BOOL)allow error: (FlutterError *_Nullable *_Nonnull) error; - (void)setLimitsNavigationsToAppBoundDomainsForConfigurationWithIdentifier:(NSInteger)identifier isLimited:(BOOL)limit error:(FlutterError *_Nullable *_Nonnull)error; - (void) setMediaTypesRequiresUserActionForConfigurationWithIdentifier:(NSInteger)identifier forTypes: (NSArray< FWFWKAudiovisualMediaTypeEnumData *> *)types error: (FlutterError *_Nullable *_Nonnull) error; @end extern void SetUpFWFWKWebViewConfigurationHostApi( id<FlutterBinaryMessenger> binaryMessenger, NSObject<FWFWKWebViewConfigurationHostApi> *_Nullable api); /// The codec used by FWFWKWebViewConfigurationFlutterApi. NSObject<FlutterMessageCodec> *FWFWKWebViewConfigurationFlutterApiGetCodec(void); /// Handles callbacks from a WKWebViewConfiguration instance. /// /// See https://developer.apple.com/documentation/webkit/wkwebviewconfiguration?language=objc. @interface FWFWKWebViewConfigurationFlutterApi : NSObject - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger; - (void)createWithIdentifier:(NSInteger)identifier completion:(void (^)(FlutterError *_Nullable))completion; @end /// The codec used by FWFWKUserContentControllerHostApi. NSObject<FlutterMessageCodec> *FWFWKUserContentControllerHostApiGetCodec(void); /// Mirror of WKUserContentController. /// /// See https://developer.apple.com/documentation/webkit/wkusercontentcontroller?language=objc. @protocol FWFWKUserContentControllerHostApi - (void)createFromWebViewConfigurationWithIdentifier:(NSInteger)identifier configurationIdentifier:(NSInteger)configurationIdentifier error:(FlutterError *_Nullable *_Nonnull)error; - (void)addScriptMessageHandlerForControllerWithIdentifier:(NSInteger)identifier handlerIdentifier:(NSInteger)handlerIdentifier ofName:(NSString *)name error:(FlutterError *_Nullable *_Nonnull)error; - (void)removeScriptMessageHandlerForControllerWithIdentifier:(NSInteger)identifier name:(NSString *)name error:(FlutterError *_Nullable *_Nonnull) error; - (void)removeAllScriptMessageHandlersForControllerWithIdentifier:(NSInteger)identifier error: (FlutterError *_Nullable *_Nonnull) error; - (void)addUserScriptForControllerWithIdentifier:(NSInteger)identifier userScript:(FWFWKUserScriptData *)userScript error:(FlutterError *_Nullable *_Nonnull)error; - (void)removeAllUserScriptsForControllerWithIdentifier:(NSInteger)identifier error:(FlutterError *_Nullable *_Nonnull)error; @end extern void SetUpFWFWKUserContentControllerHostApi( id<FlutterBinaryMessenger> binaryMessenger, NSObject<FWFWKUserContentControllerHostApi> *_Nullable api); /// The codec used by FWFWKPreferencesHostApi. NSObject<FlutterMessageCodec> *FWFWKPreferencesHostApiGetCodec(void); /// Mirror of WKUserPreferences. /// /// See https://developer.apple.com/documentation/webkit/wkpreferences?language=objc. @protocol FWFWKPreferencesHostApi - (void)createFromWebViewConfigurationWithIdentifier:(NSInteger)identifier configurationIdentifier:(NSInteger)configurationIdentifier error:(FlutterError *_Nullable *_Nonnull)error; - (void)setJavaScriptEnabledForPreferencesWithIdentifier:(NSInteger)identifier isEnabled:(BOOL)enabled error:(FlutterError *_Nullable *_Nonnull)error; @end extern void SetUpFWFWKPreferencesHostApi(id<FlutterBinaryMessenger> binaryMessenger, NSObject<FWFWKPreferencesHostApi> *_Nullable api); /// The codec used by FWFWKScriptMessageHandlerHostApi. NSObject<FlutterMessageCodec> *FWFWKScriptMessageHandlerHostApiGetCodec(void); /// Mirror of WKScriptMessageHandler. /// /// See https://developer.apple.com/documentation/webkit/wkscriptmessagehandler?language=objc. @protocol FWFWKScriptMessageHandlerHostApi - (void)createWithIdentifier:(NSInteger)identifier error:(FlutterError *_Nullable *_Nonnull)error; @end extern void SetUpFWFWKScriptMessageHandlerHostApi( id<FlutterBinaryMessenger> binaryMessenger, NSObject<FWFWKScriptMessageHandlerHostApi> *_Nullable api); /// The codec used by FWFWKScriptMessageHandlerFlutterApi. NSObject<FlutterMessageCodec> *FWFWKScriptMessageHandlerFlutterApiGetCodec(void); /// Handles callbacks from a WKScriptMessageHandler instance. /// /// See https://developer.apple.com/documentation/webkit/wkscriptmessagehandler?language=objc. @interface FWFWKScriptMessageHandlerFlutterApi : NSObject - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger; - (void)didReceiveScriptMessageForHandlerWithIdentifier:(NSInteger)identifier userContentControllerIdentifier:(NSInteger)userContentControllerIdentifier message:(FWFWKScriptMessageData *)message completion: (void (^)(FlutterError *_Nullable))completion; @end /// The codec used by FWFWKNavigationDelegateHostApi. NSObject<FlutterMessageCodec> *FWFWKNavigationDelegateHostApiGetCodec(void); /// Mirror of WKNavigationDelegate. /// /// See https://developer.apple.com/documentation/webkit/wknavigationdelegate?language=objc. @protocol FWFWKNavigationDelegateHostApi - (void)createWithIdentifier:(NSInteger)identifier error:(FlutterError *_Nullable *_Nonnull)error; @end extern void SetUpFWFWKNavigationDelegateHostApi( id<FlutterBinaryMessenger> binaryMessenger, NSObject<FWFWKNavigationDelegateHostApi> *_Nullable api); /// The codec used by FWFWKNavigationDelegateFlutterApi. NSObject<FlutterMessageCodec> *FWFWKNavigationDelegateFlutterApiGetCodec(void); /// Handles callbacks from a WKNavigationDelegate instance. /// /// See https://developer.apple.com/documentation/webkit/wknavigationdelegate?language=objc. @interface FWFWKNavigationDelegateFlutterApi : NSObject - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger; - (void)didFinishNavigationForDelegateWithIdentifier:(NSInteger)identifier webViewIdentifier:(NSInteger)webViewIdentifier URL:(nullable NSString *)url completion:(void (^)(FlutterError *_Nullable))completion; - (void)didStartProvisionalNavigationForDelegateWithIdentifier:(NSInteger)identifier webViewIdentifier:(NSInteger)webViewIdentifier URL:(nullable NSString *)url completion:(void (^)(FlutterError *_Nullable)) completion; - (void) decidePolicyForNavigationActionForDelegateWithIdentifier:(NSInteger)identifier webViewIdentifier:(NSInteger)webViewIdentifier navigationAction: (FWFWKNavigationActionData *)navigationAction completion: (void (^)(FWFWKNavigationActionPolicyEnumData *_Nullable, FlutterError *_Nullable))completion; - (void)decidePolicyForNavigationResponseForDelegateWithIdentifier:(NSInteger)identifier webViewIdentifier:(NSInteger)webViewIdentifier navigationResponse:(FWFWKNavigationResponseData *) navigationResponse completion: (void (^)( FWFWKNavigationResponsePolicyEnumBox *_Nullable, FlutterError *_Nullable))completion; - (void)didFailNavigationForDelegateWithIdentifier:(NSInteger)identifier webViewIdentifier:(NSInteger)webViewIdentifier error:(FWFNSErrorData *)error completion:(void (^)(FlutterError *_Nullable))completion; - (void)didFailProvisionalNavigationForDelegateWithIdentifier:(NSInteger)identifier webViewIdentifier:(NSInteger)webViewIdentifier error:(FWFNSErrorData *)error completion:(void (^)(FlutterError *_Nullable)) completion; - (void)webViewWebContentProcessDidTerminateForDelegateWithIdentifier:(NSInteger)identifier webViewIdentifier:(NSInteger)webViewIdentifier completion: (void (^)(FlutterError *_Nullable)) completion; - (void)didReceiveAuthenticationChallengeForDelegateWithIdentifier:(NSInteger)identifier webViewIdentifier:(NSInteger)webViewIdentifier challengeIdentifier:(NSInteger)challengeIdentifier completion: (void (^)( FWFAuthenticationChallengeResponse *_Nullable, FlutterError *_Nullable))completion; @end /// The codec used by FWFNSObjectHostApi. NSObject<FlutterMessageCodec> *FWFNSObjectHostApiGetCodec(void); /// Mirror of NSObject. /// /// See https://developer.apple.com/documentation/objectivec/nsobject. @protocol FWFNSObjectHostApi - (void)disposeObjectWithIdentifier:(NSInteger)identifier error:(FlutterError *_Nullable *_Nonnull)error; - (void)addObserverForObjectWithIdentifier:(NSInteger)identifier observerIdentifier:(NSInteger)observerIdentifier keyPath:(NSString *)keyPath options: (NSArray<FWFNSKeyValueObservingOptionsEnumData *> *)options error:(FlutterError *_Nullable *_Nonnull)error; - (void)removeObserverForObjectWithIdentifier:(NSInteger)identifier observerIdentifier:(NSInteger)observerIdentifier keyPath:(NSString *)keyPath error:(FlutterError *_Nullable *_Nonnull)error; @end extern void SetUpFWFNSObjectHostApi(id<FlutterBinaryMessenger> binaryMessenger, NSObject<FWFNSObjectHostApi> *_Nullable api); /// The codec used by FWFNSObjectFlutterApi. NSObject<FlutterMessageCodec> *FWFNSObjectFlutterApiGetCodec(void); /// Handles callbacks from an NSObject instance. /// /// See https://developer.apple.com/documentation/objectivec/nsobject. @interface FWFNSObjectFlutterApi : NSObject - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger; - (void)observeValueForObjectWithIdentifier:(NSInteger)identifier keyPath:(NSString *)keyPath objectIdentifier:(NSInteger)objectIdentifier changeKeys:(NSArray<FWFNSKeyValueChangeKeyEnumData *> *)changeKeys changeValues:(NSArray<FWFObjectOrIdentifier *> *)changeValues completion:(void (^)(FlutterError *_Nullable))completion; - (void)disposeObjectWithIdentifier:(NSInteger)identifier completion:(void (^)(FlutterError *_Nullable))completion; @end /// The codec used by FWFWKWebViewHostApi. NSObject<FlutterMessageCodec> *FWFWKWebViewHostApiGetCodec(void); /// Mirror of WKWebView. /// /// See https://developer.apple.com/documentation/webkit/wkwebview?language=objc. @protocol FWFWKWebViewHostApi - (void)createWithIdentifier:(NSInteger)identifier configurationIdentifier:(NSInteger)configurationIdentifier error:(FlutterError *_Nullable *_Nonnull)error; - (void)setUIDelegateForWebViewWithIdentifier:(NSInteger)identifier delegateIdentifier:(nullable NSNumber *)uiDelegateIdentifier error:(FlutterError *_Nullable *_Nonnull)error; - (void)setNavigationDelegateForWebViewWithIdentifier:(NSInteger)identifier delegateIdentifier: (nullable NSNumber *)navigationDelegateIdentifier error:(FlutterError *_Nullable *_Nonnull)error; - (nullable NSString *)URLForWebViewWithIdentifier:(NSInteger)identifier error:(FlutterError *_Nullable *_Nonnull)error; /// @return `nil` only when `error != nil`. - (nullable NSNumber *)estimatedProgressForWebViewWithIdentifier:(NSInteger)identifier error:(FlutterError *_Nullable *_Nonnull) error; - (void)loadRequestForWebViewWithIdentifier:(NSInteger)identifier request:(FWFNSUrlRequestData *)request error:(FlutterError *_Nullable *_Nonnull)error; - (void)loadHTMLForWebViewWithIdentifier:(NSInteger)identifier HTMLString:(NSString *)string baseURL:(nullable NSString *)baseUrl error:(FlutterError *_Nullable *_Nonnull)error; - (void)loadFileForWebViewWithIdentifier:(NSInteger)identifier fileURL:(NSString *)url readAccessURL:(NSString *)readAccessUrl error:(FlutterError *_Nullable *_Nonnull)error; - (void)loadAssetForWebViewWithIdentifier:(NSInteger)identifier assetKey:(NSString *)key error:(FlutterError *_Nullable *_Nonnull)error; /// @return `nil` only when `error != nil`. - (nullable NSNumber *)canGoBackForWebViewWithIdentifier:(NSInteger)identifier error:(FlutterError *_Nullable *_Nonnull)error; /// @return `nil` only when `error != nil`. - (nullable NSNumber *)canGoForwardForWebViewWithIdentifier:(NSInteger)identifier error: (FlutterError *_Nullable *_Nonnull)error; - (void)goBackForWebViewWithIdentifier:(NSInteger)identifier error:(FlutterError *_Nullable *_Nonnull)error; - (void)goForwardForWebViewWithIdentifier:(NSInteger)identifier error:(FlutterError *_Nullable *_Nonnull)error; - (void)reloadWebViewWithIdentifier:(NSInteger)identifier error:(FlutterError *_Nullable *_Nonnull)error; - (nullable NSString *)titleForWebViewWithIdentifier:(NSInteger)identifier error:(FlutterError *_Nullable *_Nonnull)error; - (void)setAllowsBackForwardForWebViewWithIdentifier:(NSInteger)identifier isAllowed:(BOOL)allow error:(FlutterError *_Nullable *_Nonnull)error; - (void)setCustomUserAgentForWebViewWithIdentifier:(NSInteger)identifier userAgent:(nullable NSString *)userAgent error:(FlutterError *_Nullable *_Nonnull)error; - (void)evaluateJavaScriptForWebViewWithIdentifier:(NSInteger)identifier javaScriptString:(NSString *)javaScriptString completion:(void (^)(id _Nullable, FlutterError *_Nullable))completion; - (void)setInspectableForWebViewWithIdentifier:(NSInteger)identifier inspectable:(BOOL)inspectable error:(FlutterError *_Nullable *_Nonnull)error; - (nullable NSString *)customUserAgentForWebViewWithIdentifier:(NSInteger)identifier error:(FlutterError *_Nullable *_Nonnull) error; @end extern void SetUpFWFWKWebViewHostApi(id<FlutterBinaryMessenger> binaryMessenger, NSObject<FWFWKWebViewHostApi> *_Nullable api); /// The codec used by FWFWKUIDelegateHostApi. NSObject<FlutterMessageCodec> *FWFWKUIDelegateHostApiGetCodec(void); /// Mirror of WKUIDelegate. /// /// See https://developer.apple.com/documentation/webkit/wkuidelegate?language=objc. @protocol FWFWKUIDelegateHostApi - (void)createWithIdentifier:(NSInteger)identifier error:(FlutterError *_Nullable *_Nonnull)error; @end extern void SetUpFWFWKUIDelegateHostApi(id<FlutterBinaryMessenger> binaryMessenger, NSObject<FWFWKUIDelegateHostApi> *_Nullable api); /// The codec used by FWFWKUIDelegateFlutterApi. NSObject<FlutterMessageCodec> *FWFWKUIDelegateFlutterApiGetCodec(void); /// Handles callbacks from a WKUIDelegate instance. /// /// See https://developer.apple.com/documentation/webkit/wkuidelegate?language=objc. @interface FWFWKUIDelegateFlutterApi : NSObject - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger; - (void)onCreateWebViewForDelegateWithIdentifier:(NSInteger)identifier webViewIdentifier:(NSInteger)webViewIdentifier configurationIdentifier:(NSInteger)configurationIdentifier navigationAction:(FWFWKNavigationActionData *)navigationAction completion:(void (^)(FlutterError *_Nullable))completion; /// Callback to Dart function `WKUIDelegate.requestMediaCapturePermission`. - (void)requestMediaCapturePermissionForDelegateWithIdentifier:(NSInteger)identifier webViewIdentifier:(NSInteger)webViewIdentifier origin:(FWFWKSecurityOriginData *)origin frame:(FWFWKFrameInfoData *)frame type:(FWFWKMediaCaptureTypeData *)type completion: (void (^)( FWFWKPermissionDecisionData *_Nullable, FlutterError *_Nullable))completion; /// Callback to Dart function `WKUIDelegate.runJavaScriptAlertPanel`. - (void)runJavaScriptAlertPanelForDelegateWithIdentifier:(NSInteger)identifier message:(NSString *)message frame:(FWFWKFrameInfoData *)frame completion: (void (^)(FlutterError *_Nullable))completion; /// Callback to Dart function `WKUIDelegate.runJavaScriptConfirmPanel`. - (void)runJavaScriptConfirmPanelForDelegateWithIdentifier:(NSInteger)identifier message:(NSString *)message frame:(FWFWKFrameInfoData *)frame completion: (void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion; /// Callback to Dart function `WKUIDelegate.runJavaScriptTextInputPanel`. - (void)runJavaScriptTextInputPanelForDelegateWithIdentifier:(NSInteger)identifier prompt:(NSString *)prompt defaultText:(NSString *)defaultText frame:(FWFWKFrameInfoData *)frame completion: (void (^)(NSString *_Nullable, FlutterError *_Nullable))completion; @end /// The codec used by FWFWKHttpCookieStoreHostApi. NSObject<FlutterMessageCodec> *FWFWKHttpCookieStoreHostApiGetCodec(void); /// Mirror of WKHttpCookieStore. /// /// See https://developer.apple.com/documentation/webkit/wkhttpcookiestore?language=objc. @protocol FWFWKHttpCookieStoreHostApi - (void)createFromWebsiteDataStoreWithIdentifier:(NSInteger)identifier dataStoreIdentifier:(NSInteger)websiteDataStoreIdentifier error:(FlutterError *_Nullable *_Nonnull)error; - (void)setCookieForStoreWithIdentifier:(NSInteger)identifier cookie:(FWFNSHttpCookieData *)cookie completion:(void (^)(FlutterError *_Nullable))completion; @end extern void SetUpFWFWKHttpCookieStoreHostApi(id<FlutterBinaryMessenger> binaryMessenger, NSObject<FWFWKHttpCookieStoreHostApi> *_Nullable api); /// The codec used by FWFNSUrlHostApi. NSObject<FlutterMessageCodec> *FWFNSUrlHostApiGetCodec(void); /// 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. @protocol FWFNSUrlHostApi - (nullable NSString *)absoluteStringForNSURLWithIdentifier:(NSInteger)identifier error: (FlutterError *_Nullable *_Nonnull)error; @end extern void SetUpFWFNSUrlHostApi(id<FlutterBinaryMessenger> binaryMessenger, NSObject<FWFNSUrlHostApi> *_Nullable api); /// The codec used by FWFNSUrlFlutterApi. NSObject<FlutterMessageCodec> *FWFNSUrlFlutterApiGetCodec(void); /// Flutter API for `NSUrl`. /// /// This class may handle instantiating and adding Dart instances that are /// attached to a native instance or receiving callback methods from an /// overridden native class. /// /// See https://developer.apple.com/documentation/foundation/nsurl?language=objc. @interface FWFNSUrlFlutterApi : NSObject - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger; - (void)createWithIdentifier:(NSInteger)identifier completion:(void (^)(FlutterError *_Nullable))completion; @end /// The codec used by FWFUIScrollViewDelegateHostApi. NSObject<FlutterMessageCodec> *FWFUIScrollViewDelegateHostApiGetCodec(void); /// 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. @protocol FWFUIScrollViewDelegateHostApi - (void)createWithIdentifier:(NSInteger)identifier error:(FlutterError *_Nullable *_Nonnull)error; @end extern void SetUpFWFUIScrollViewDelegateHostApi( id<FlutterBinaryMessenger> binaryMessenger, NSObject<FWFUIScrollViewDelegateHostApi> *_Nullable api); /// The codec used by FWFUIScrollViewDelegateFlutterApi. NSObject<FlutterMessageCodec> *FWFUIScrollViewDelegateFlutterApiGetCodec(void); /// Flutter API for `UIScrollViewDelegate`. /// /// See https://developer.apple.com/documentation/uikit/uiscrollviewdelegate?language=objc. @interface FWFUIScrollViewDelegateFlutterApi : NSObject - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger; - (void)scrollViewDidScrollWithIdentifier:(NSInteger)identifier UIScrollViewIdentifier:(NSInteger)uiScrollViewIdentifier x:(double)x y:(double)y completion:(void (^)(FlutterError *_Nullable))completion; @end /// The codec used by FWFNSUrlCredentialHostApi. NSObject<FlutterMessageCodec> *FWFNSUrlCredentialHostApiGetCodec(void); /// 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. @protocol FWFNSUrlCredentialHostApi /// Create a new native instance and add it to the `InstanceManager`. - (void)createWithUserWithIdentifier:(NSInteger)identifier user:(NSString *)user password:(NSString *)password persistence:(FWFNSUrlCredentialPersistence)persistence error:(FlutterError *_Nullable *_Nonnull)error; @end extern void SetUpFWFNSUrlCredentialHostApi(id<FlutterBinaryMessenger> binaryMessenger, NSObject<FWFNSUrlCredentialHostApi> *_Nullable api); /// The codec used by FWFNSUrlProtectionSpaceFlutterApi. NSObject<FlutterMessageCodec> *FWFNSUrlProtectionSpaceFlutterApiGetCodec(void); /// Flutter API for `NSUrlProtectionSpace`. /// /// This class may handle instantiating and adding Dart instances that are /// attached to a native instance or receiving callback methods from an /// overridden native class. /// /// See https://developer.apple.com/documentation/foundation/nsurlprotectionspace?language=objc. @interface FWFNSUrlProtectionSpaceFlutterApi : NSObject - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger; /// Create a new Dart instance and add it to the `InstanceManager`. - (void)createWithIdentifier:(NSInteger)identifier host:(nullable NSString *)host realm:(nullable NSString *)realm authenticationMethod:(nullable NSString *)authenticationMethod completion:(void (^)(FlutterError *_Nullable))completion; @end /// The codec used by FWFNSUrlAuthenticationChallengeFlutterApi. NSObject<FlutterMessageCodec> *FWFNSUrlAuthenticationChallengeFlutterApiGetCodec(void); /// Flutter API for `NSUrlAuthenticationChallenge`. /// /// This class may handle instantiating and adding Dart instances that are /// attached to a native instance or receiving callback methods from an /// overridden native class. /// /// See /// https://developer.apple.com/documentation/foundation/nsurlauthenticationchallenge?language=objc. @interface FWFNSUrlAuthenticationChallengeFlutterApi : NSObject - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger; /// Create a new Dart instance and add it to the `InstanceManager`. - (void)createWithIdentifier:(NSInteger)identifier protectionSpaceIdentifier:(NSInteger)protectionSpaceIdentifier completion:(void (^)(FlutterError *_Nullable))completion; @end NS_ASSUME_NONNULL_END
packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFGeneratedWebKitApis.h/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFGeneratedWebKitApis.h", "repo_id": "packages", "token_count": 25162 }
1,015
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "FWFScrollViewDelegateHostApi.h" #import "FWFWebViewHostApi.h" @interface FWFScrollViewDelegateFlutterApiImpl () // BinaryMessenger must be weak to prevent a circular reference with the host API it // references. @property(nonatomic, weak) id<FlutterBinaryMessenger> binaryMessenger; // InstanceManager must be weak to prevent a circular reference with the object it stores. @property(nonatomic, weak) FWFInstanceManager *instanceManager; @end @implementation FWFScrollViewDelegateFlutterApiImpl - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger instanceManager:(FWFInstanceManager *)instanceManager { self = [self initWithBinaryMessenger:binaryMessenger]; if (self) { _binaryMessenger = binaryMessenger; _instanceManager = instanceManager; } return self; } - (long)identifierForDelegate:(FWFScrollViewDelegate *)instance { return [self.instanceManager identifierWithStrongReferenceForInstance:instance]; } - (void)scrollViewDidScrollForDelegate:(FWFScrollViewDelegate *)instance uiScrollView:(UIScrollView *)scrollView completion:(void (^)(FlutterError *_Nullable))completion { [self scrollViewDidScrollWithIdentifier:[self identifierForDelegate:instance] UIScrollViewIdentifier:[self.instanceManager identifierWithStrongReferenceForInstance:scrollView] x:scrollView.contentOffset.x y:scrollView.contentOffset.y completion:completion]; } @end @implementation FWFScrollViewDelegate - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger instanceManager:(FWFInstanceManager *)instanceManager { self = [super initWithBinaryMessenger:binaryMessenger instanceManager:instanceManager]; if (self) { _scrollViewDelegateAPI = [[FWFScrollViewDelegateFlutterApiImpl alloc] initWithBinaryMessenger:binaryMessenger instanceManager:instanceManager]; } return self; } - (void)scrollViewDidScroll:(UIScrollView *)scrollView { [self.scrollViewDelegateAPI scrollViewDidScrollForDelegate:self uiScrollView:scrollView completion:^(FlutterError *error) { NSAssert(!error, @"%@", error); }]; } @end @interface FWFScrollViewDelegateHostApiImpl () // BinaryMessenger must be weak to prevent a circular reference with the host API it // references. @property(nonatomic, weak) id<FlutterBinaryMessenger> binaryMessenger; // InstanceManager must be weak to prevent a circular reference with the object it stores. @property(nonatomic, weak) FWFInstanceManager *instanceManager; @end @implementation FWFScrollViewDelegateHostApiImpl - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger instanceManager:(FWFInstanceManager *)instanceManager { self = [self init]; if (self) { _binaryMessenger = binaryMessenger; _instanceManager = instanceManager; } return self; } - (void)createWithIdentifier:(NSInteger)identifier error:(FlutterError *_Nullable *_Nonnull)error { FWFScrollViewDelegate *uiScrollViewDelegate = [[FWFScrollViewDelegate alloc] initWithBinaryMessenger:self.binaryMessenger instanceManager:self.instanceManager]; [self.instanceManager addDartCreatedInstance:uiScrollViewDelegate withIdentifier:identifier]; } @end
packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFScrollViewDelegateHostApi.m/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFScrollViewDelegateHostApi.m", "repo_id": "packages", "token_count": 1581 }
1,016
// 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 "FWFUserContentControllerHostApi.h" #import "FWFDataConverters.h" #import "FWFWebViewConfigurationHostApi.h" @interface FWFUserContentControllerHostApiImpl () // InstanceManager must be weak to prevent a circular reference with the object it stores. @property(nonatomic, weak) FWFInstanceManager *instanceManager; @end @implementation FWFUserContentControllerHostApiImpl - (instancetype)initWithInstanceManager:(FWFInstanceManager *)instanceManager { self = [self init]; if (self) { _instanceManager = instanceManager; } return self; } - (WKUserContentController *)userContentControllerForIdentifier:(NSInteger)identifier { return (WKUserContentController *)[self.instanceManager instanceForIdentifier:identifier]; } - (void)createFromWebViewConfigurationWithIdentifier:(NSInteger)identifier configurationIdentifier:(NSInteger)configurationIdentifier error:(FlutterError *_Nullable *_Nonnull)error { WKWebViewConfiguration *configuration = (WKWebViewConfiguration *)[self.instanceManager instanceForIdentifier:configurationIdentifier]; [self.instanceManager addDartCreatedInstance:configuration.userContentController withIdentifier:identifier]; } - (void)addScriptMessageHandlerForControllerWithIdentifier:(NSInteger)identifier handlerIdentifier:(NSInteger)handler ofName:(nonnull NSString *)name error: (FlutterError *_Nullable *_Nonnull)error { [[self userContentControllerForIdentifier:identifier] addScriptMessageHandler:(id<WKScriptMessageHandler>)[self.instanceManager instanceForIdentifier:handler] name:name]; } - (void)removeScriptMessageHandlerForControllerWithIdentifier:(NSInteger)identifier name:(nonnull NSString *)name error:(FlutterError *_Nullable *_Nonnull) error { [[self userContentControllerForIdentifier:identifier] removeScriptMessageHandlerForName:name]; } - (void)removeAllScriptMessageHandlersForControllerWithIdentifier:(NSInteger)identifier error: (FlutterError *_Nullable *_Nonnull) error { if (@available(iOS 14.0, *)) { [[self userContentControllerForIdentifier:identifier] removeAllScriptMessageHandlers]; } else { *error = [FlutterError errorWithCode:@"FWFUnsupportedVersionError" message:@"removeAllScriptMessageHandlers is only supported on versions 14+." details:nil]; } } - (void)addUserScriptForControllerWithIdentifier:(NSInteger)identifier userScript:(nonnull FWFWKUserScriptData *)userScript error:(FlutterError *_Nullable *_Nonnull)error { [[self userContentControllerForIdentifier:identifier] addUserScript:FWFNativeWKUserScriptFromScriptData(userScript)]; } - (void)removeAllUserScriptsForControllerWithIdentifier:(NSInteger)identifier error:(FlutterError *_Nullable *_Nonnull)error { [[self userContentControllerForIdentifier:identifier] removeAllUserScripts]; } @end
packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFUserContentControllerHostApi.m/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFUserContentControllerHostApi.m", "repo_id": "packages", "token_count": 1743 }
1,017
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import '../common/instance_manager.dart'; import '../common/weak_reference_utils.dart'; import 'foundation_api_impls.dart'; export 'foundation_api_impls.dart' show NSUrlCredentialPersistence, NSUrlSessionAuthChallengeDisposition; /// The values that can be returned in a change map. /// /// Wraps [NSKeyValueObservingOptions](https://developer.apple.com/documentation/foundation/nskeyvalueobservingoptions?language=objc). enum NSKeyValueObservingOptions { /// Indicates that the change map should provide the new attribute value, if applicable. /// /// See https://developer.apple.com/documentation/foundation/nskeyvalueobservingoptions/nskeyvalueobservingoptionnew?language=objc. newValue, /// Indicates that the change map should contain the old attribute value, if applicable. /// /// See https://developer.apple.com/documentation/foundation/nskeyvalueobservingoptions/nskeyvalueobservingoptionold?language=objc. oldValue, /// Indicates a notification should be sent to the observer immediately. /// /// See https://developer.apple.com/documentation/foundation/nskeyvalueobservingoptions/nskeyvalueobservingoptioninitial?language=objc. initialValue, /// Whether separate notifications should be sent to the observer before and after each change. /// /// See https://developer.apple.com/documentation/foundation/nskeyvalueobservingoptions/nskeyvalueobservingoptionprior?language=objc. priorNotification, } /// The kinds of changes that can be observed. /// /// Wraps [NSKeyValueChange](https://developer.apple.com/documentation/foundation/nskeyvaluechange?language=objc). enum NSKeyValueChange { /// Indicates that the value of the observed key path was set to a new value. /// /// See https://developer.apple.com/documentation/foundation/nskeyvaluechange/nskeyvaluechangesetting?language=objc. setting, /// Indicates that an object has been inserted into the to-many relationship that is being observed. /// /// See https://developer.apple.com/documentation/foundation/nskeyvaluechange/nskeyvaluechangeinsertion?language=objc. insertion, /// Indicates that an object has been removed from the to-many relationship that is being observed. /// /// See https://developer.apple.com/documentation/foundation/nskeyvaluechange/nskeyvaluechangeremoval?language=objc. removal, /// Indicates that an object has been replaced in the to-many relationship that is being observed. /// /// See https://developer.apple.com/documentation/foundation/nskeyvaluechange/nskeyvaluechangereplacement?language=objc. replacement, } /// The keys that can appear in the change map. /// /// Wraps [NSKeyValueChangeKey](https://developer.apple.com/documentation/foundation/nskeyvaluechangekey?language=objc). enum NSKeyValueChangeKey { /// Indicates changes made in a collection. /// /// See https://developer.apple.com/documentation/foundation/nskeyvaluechangeindexeskey?language=objc. indexes, /// Indicates what sort of change has occurred. /// /// See https://developer.apple.com/documentation/foundation/nskeyvaluechangekindkey?language=objc. kind, /// Indicates the new value for the attribute. /// /// See https://developer.apple.com/documentation/foundation/nskeyvaluechangenewkey?language=objc. newValue, /// Indicates a notification is sent prior to a change. /// /// See https://developer.apple.com/documentation/foundation/nskeyvaluechangenotificationispriorkey?language=objc. notificationIsPrior, /// Indicates the value of this key is the value before the attribute was changed. /// /// See https://developer.apple.com/documentation/foundation/nskeyvaluechangeoldkey?language=objc. oldValue, /// An unknown change key. /// /// This does not represent an actual value provided by the platform and only /// indicates a value was provided that isn't currently supported. unknown, } /// The supported keys in a cookie attributes dictionary. /// /// Wraps [NSHTTPCookiePropertyKey](https://developer.apple.com/documentation/foundation/nshttpcookiepropertykey). enum NSHttpCookiePropertyKey { /// A String object containing the comment for the cookie. /// /// See https://developer.apple.com/documentation/foundation/nshttpcookiecomment. comment, /// A String object containing the comment URL for the cookie. /// /// See https://developer.apple.com/documentation/foundation/nshttpcookiecommenturl. commentUrl, /// A String object stating whether the cookie should be discarded at the end of the session. /// /// See https://developer.apple.com/documentation/foundation/nshttpcookiediscard. discard, /// A String object specifying the expiration date for the cookie. /// /// See https://developer.apple.com/documentation/foundation/nshttpcookiedomain. domain, /// A String object specifying the expiration date for the cookie. /// /// See https://developer.apple.com/documentation/foundation/nshttpcookieexpires. expires, /// A String object containing an integer value stating how long in seconds the cookie should be kept, at most. /// /// See https://developer.apple.com/documentation/foundation/nshttpcookiemaximumage. maximumAge, /// A String object containing the name of the cookie (required). /// /// See https://developer.apple.com/documentation/foundation/nshttpcookiename. name, /// A String object containing the URL that set this cookie. /// /// See https://developer.apple.com/documentation/foundation/nshttpcookieoriginurl. originUrl, /// A String object containing the path for the cookie. /// /// See https://developer.apple.com/documentation/foundation/nshttpcookiepath. path, /// A String object containing comma-separated integer values specifying the ports for the cookie. /// /// See https://developer.apple.com/documentation/foundation/nshttpcookieport. port, /// A String indicating the same-site policy for the cookie. /// /// This is only supported on iOS version 13+. This value will be ignored on /// versions < 13. /// /// See https://developer.apple.com/documentation/foundation/nshttpcookiesamesitepolicy. sameSitePolicy, /// A String object indicating that the cookie should be transmitted only over secure channels. /// /// See https://developer.apple.com/documentation/foundation/nshttpcookiesecure. secure, /// A String object containing the value of the cookie. /// /// See https://developer.apple.com/documentation/foundation/nshttpcookievalue. value, /// A String object that specifies the version of the cookie. /// /// See https://developer.apple.com/documentation/foundation/nshttpcookieversion. version, } /// A URL load request that is independent of protocol or URL scheme. /// /// Wraps [NSUrlRequest](https://developer.apple.com/documentation/foundation/nsurlrequest?language=objc). @immutable class NSUrlRequest { /// Constructs an [NSUrlRequest]. const NSUrlRequest({ required this.url, this.httpMethod, this.httpBody, this.allHttpHeaderFields = const <String, String>{}, }); /// The URL being requested. final String url; /// The HTTP request method. /// /// The default HTTP method is “GET”. final String? httpMethod; /// Data sent as the message body of a request, as in an HTTP POST request. final Uint8List? httpBody; /// All of the HTTP header fields for a request. final Map<String, String> allHttpHeaderFields; } /// Keys that may exist in the user info map of `NSError`. class NSErrorUserInfoKey { NSErrorUserInfoKey._(); /// The corresponding value is a localized string representation of the error /// that, if present, will be returned by [NSError.localizedDescription]. /// /// See https://developer.apple.com/documentation/foundation/nslocalizeddescriptionkey. static const String NSLocalizedDescription = 'NSLocalizedDescription'; /// The URL which caused a load to fail. /// /// See https://developer.apple.com/documentation/foundation/nsurlerrorfailingurlstringerrorkey?language=objc. static const String NSURLErrorFailingURLStringError = 'NSErrorFailingURLStringKey'; } /// The metadata associated with the response to an HTTP protocol URL load /// request. /// /// Wraps [NSHttpUrlResponse](https://developer.apple.com/documentation/foundation/nshttpurlresponse?language=objc). @immutable class NSHttpUrlResponse { /// Constructs an [NSHttpUrlResponse]. const NSHttpUrlResponse({ required this.statusCode, }); /// The response’s HTTP status code. final int statusCode; } /// Information about an error condition. /// /// Wraps [NSError](https://developer.apple.com/documentation/foundation/nserror?language=objc). @immutable class NSError { /// Constructs an [NSError]. const NSError({ required this.code, required this.domain, this.userInfo = const <String, Object?>{}, }); /// The error code. /// /// Error codes are [domain]-specific. final int code; /// A string containing the error domain. final String domain; /// Map of arbitrary data. /// /// See [NSErrorUserInfoKey] for possible keys (non-exhaustive). /// /// This currently only supports values that are a String. final Map<String, Object?> userInfo; /// A string containing the localized description of the error. String? get localizedDescription => userInfo[NSErrorUserInfoKey.NSLocalizedDescription] as String?; @override String toString() { if (localizedDescription?.isEmpty ?? true) { return 'Error $domain:$code:$userInfo'; } return '$localizedDescription ($domain:$code:$userInfo)'; } } /// A representation of an HTTP cookie. /// /// Wraps [NSHTTPCookie](https://developer.apple.com/documentation/foundation/nshttpcookie). @immutable class NSHttpCookie { /// Initializes an HTTP cookie object using the provided properties. const NSHttpCookie.withProperties(this.properties); /// Properties of the new cookie object. final Map<NSHttpCookiePropertyKey, Object> properties; } /// An object that represents the location of a resource, such as an item on a /// remote server or the path to a local file. /// /// See https://developer.apple.com/documentation/foundation/nsurl?language=objc. class NSUrl extends NSObject { /// Instantiates a [NSUrl] without creating and attaching to an instance /// of the associated native class. /// /// This should only be used outside of tests by subclasses created by this /// library or to create a copy for an [InstanceManager]. @protected NSUrl.detached({super.binaryMessenger, super.instanceManager}) : _nsUrlHostApi = NSUrlHostApiImpl( binaryMessenger: binaryMessenger, instanceManager: instanceManager, ), super.detached(); final NSUrlHostApiImpl _nsUrlHostApi; /// The URL string for the receiver as an absolute URL. (read-only) /// /// Represents [NSURL.absoluteString](https://developer.apple.com/documentation/foundation/nsurl/1409868-absolutestring?language=objc). Future<String?> getAbsoluteString() { return _nsUrlHostApi.getAbsoluteStringFromInstances(this); } @override NSObject copy() { return NSUrl.detached( binaryMessenger: _nsUrlHostApi.binaryMessenger, instanceManager: _nsUrlHostApi.instanceManager, ); } } /// The root class of most Objective-C class hierarchies. @immutable class NSObject with Copyable { /// Constructs a [NSObject] without creating the associated /// Objective-C object. /// /// This should only be used by subclasses created by this library or to /// create copies. NSObject.detached({ this.observeValue, BinaryMessenger? binaryMessenger, InstanceManager? instanceManager, }) : _api = NSObjectHostApiImpl( binaryMessenger: binaryMessenger, instanceManager: instanceManager, ) { // Ensures FlutterApis for the Foundation library are set up. FoundationFlutterApis.instance.ensureSetUp(); } /// Release the reference to the Objective-C object. static void dispose(NSObject instance) { instance._api.instanceManager.removeWeakReference(instance); } /// Global instance of [InstanceManager]. static final InstanceManager globalInstanceManager = InstanceManager(onWeakReferenceRemoved: (int instanceId) { NSObjectHostApiImpl().dispose(instanceId); }); final NSObjectHostApiImpl _api; /// Informs the observing object when the value at the specified key path has /// changed. /// /// {@template webview_flutter_wkwebview.foundation.callbacks} /// For the associated Objective-C object to be automatically garbage /// collected, it is required that this Function doesn't contain a strong /// reference to the encapsulating class instance. Consider using /// `WeakReference` when referencing an object not received as a parameter. /// Otherwise, use [NSObject.dispose] to release the associated Objective-C /// object manually. /// /// See [withWeakReferenceTo]. /// {@endtemplate} final void Function( String keyPath, NSObject object, Map<NSKeyValueChangeKey, Object?> change, )? observeValue; /// Registers the observer object to receive KVO notifications. Future<void> addObserver( NSObject observer, { required String keyPath, required Set<NSKeyValueObservingOptions> options, }) { assert(options.isNotEmpty); return _api.addObserverForInstances( this, observer, keyPath, options, ); } /// Stops the observer object from receiving change notifications for the property. Future<void> removeObserver(NSObject observer, {required String keyPath}) { return _api.removeObserverForInstances(this, observer, keyPath); } @override NSObject copy() { return NSObject.detached( observeValue: observeValue, binaryMessenger: _api.binaryMessenger, instanceManager: _api.instanceManager, ); } } /// An authentication credential consisting of information specific to the type /// of credential and the type of persistent storage to use, if any. /// /// See https://developer.apple.com/documentation/foundation/nsurlcredential?language=objc. class NSUrlCredential extends NSObject { /// Creates a URL credential instance for internet password authentication /// with a given user name and password, using a given persistence setting. NSUrlCredential.withUser({ required String user, required String password, required NSUrlCredentialPersistence persistence, @visibleForTesting super.binaryMessenger, @visibleForTesting super.instanceManager, }) : _urlCredentialApi = NSUrlCredentialHostApiImpl( binaryMessenger: binaryMessenger, instanceManager: instanceManager), super.detached() { // Ensures Flutter Apis are setup. FoundationFlutterApis.instance.ensureSetUp(); _urlCredentialApi.createWithUserFromInstances( this, user, password, persistence, ); } /// Instantiates a [NSUrlCredential] without creating and attaching to an /// instance of the associated native class. /// /// This should only be used outside of tests by subclasses created by this /// library or to create a copy for an [InstanceManager]. @protected NSUrlCredential.detached({super.binaryMessenger, super.instanceManager}) : _urlCredentialApi = NSUrlCredentialHostApiImpl( binaryMessenger: binaryMessenger, instanceManager: instanceManager), super.detached(); final NSUrlCredentialHostApiImpl _urlCredentialApi; @override NSObject copy() { return NSUrlCredential.detached( binaryMessenger: _urlCredentialApi.binaryMessenger, instanceManager: _urlCredentialApi.instanceManager, ); } } /// A server or an area on a server, commonly referred to as a realm, that /// requires authentication. /// /// See https://developer.apple.com/documentation/foundation/nsurlprotectionspace?language=objc. class NSUrlProtectionSpace extends NSObject { /// Instantiates a [NSUrlProtectionSpace] without creating and attaching to an /// instance of the associated native class. /// /// This should only be used outside of tests by subclasses created by this /// library or to create a copy for an [InstanceManager]. @protected NSUrlProtectionSpace.detached({ required this.host, required this.realm, required this.authenticationMethod, super.binaryMessenger, super.instanceManager, }) : super.detached(); /// The receiver’s host. final String? host; /// The receiver’s authentication realm. final String? realm; /// The authentication method used by the receiver. final String? authenticationMethod; @override NSUrlProtectionSpace copy() { return NSUrlProtectionSpace.detached( host: host, realm: realm, authenticationMethod: authenticationMethod, ); } } /// The authentication method used by the receiver. class NSUrlAuthenticationMethod { /// Use the default authentication method for a protocol. static const String default_ = 'NSURLAuthenticationMethodDefault'; /// Use HTML form authentication for this protection space. static const String htmlForm = 'NSURLAuthenticationMethodHTMLForm'; /// Use HTTP basic authentication for this protection space. static const String httpBasic = 'NSURLAuthenticationMethodHTTPBasic'; /// Use HTTP digest authentication for this protection space. static const String httpDigest = 'NSURLAuthenticationMethodHTTPDigest'; } /// A challenge from a server requiring authentication from the client. /// /// See https://developer.apple.com/documentation/foundation/nsurlauthenticationchallenge?language=objc. class NSUrlAuthenticationChallenge extends NSObject { /// Instantiates a [NSUrlAuthenticationChallenge] without creating and /// attaching to an instance of the associated native class. /// /// This should only be used outside of tests by subclasses created by this /// library or to create a copy for an [InstanceManager]. @protected NSUrlAuthenticationChallenge.detached({ required this.protectionSpace, super.binaryMessenger, super.instanceManager, }) : super.detached(); /// The receiver’s protection space. late final NSUrlProtectionSpace protectionSpace; @override NSUrlAuthenticationChallenge copy() { return NSUrlAuthenticationChallenge.detached( protectionSpace: protectionSpace, ); } }
packages/packages/webview_flutter/webview_flutter_wkwebview/lib/src/foundation/foundation.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/lib/src/foundation/foundation.dart", "repo_id": "packages", "token_count": 5479 }
1,018
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:pigeon/pigeon.dart'; @ConfigurePigeon( PigeonOptions( dartOut: 'lib/src/common/web_kit.g.dart', dartTestOut: 'test/src/common/test_web_kit.g.dart', objcHeaderOut: 'ios/Classes/FWFGeneratedWebKitApis.h', objcSourceOut: 'ios/Classes/FWFGeneratedWebKitApis.m', objcOptions: ObjcOptions( headerIncludePath: 'ios/Classes/FWFGeneratedWebKitApis.h', prefix: 'FWF', ), copyrightHeader: 'pigeons/copyright.txt', ), ) /// Mirror of NSKeyValueObservingOptions. /// /// See https://developer.apple.com/documentation/foundation/nskeyvalueobservingoptions?language=objc. enum NSKeyValueObservingOptionsEnum { newValue, oldValue, initialValue, priorNotification, } // TODO(bparrishMines): Enums need be wrapped in a data class because they can't // be used as primitive arguments. See https://github.com/flutter/flutter/issues/87307 class NSKeyValueObservingOptionsEnumData { late NSKeyValueObservingOptionsEnum value; } /// Mirror of NSKeyValueChange. /// /// See https://developer.apple.com/documentation/foundation/nskeyvaluechange?language=objc. enum NSKeyValueChangeEnum { setting, insertion, removal, replacement, } // TODO(bparrishMines): Enums need be wrapped in a data class because they can't // be used as primitive arguments. See https://github.com/flutter/flutter/issues/87307 class NSKeyValueChangeEnumData { late NSKeyValueChangeEnum value; } /// Mirror of NSKeyValueChangeKey. /// /// See https://developer.apple.com/documentation/foundation/nskeyvaluechangekey?language=objc. enum NSKeyValueChangeKeyEnum { indexes, kind, newValue, notificationIsPrior, oldValue, unknown, } // TODO(bparrishMines): Enums need be wrapped in a data class because they can't // be used as primitive arguments. See https://github.com/flutter/flutter/issues/87307 class NSKeyValueChangeKeyEnumData { late NSKeyValueChangeKeyEnum value; } /// Mirror of WKUserScriptInjectionTime. /// /// See https://developer.apple.com/documentation/webkit/wkuserscriptinjectiontime?language=objc. enum WKUserScriptInjectionTimeEnum { atDocumentStart, atDocumentEnd, } // TODO(bparrishMines): Enums need be wrapped in a data class because they can't // be used as primitive arguments. See https://github.com/flutter/flutter/issues/87307 class WKUserScriptInjectionTimeEnumData { late WKUserScriptInjectionTimeEnum value; } /// Mirror of WKAudiovisualMediaTypes. /// /// See [WKAudiovisualMediaTypes](https://developer.apple.com/documentation/webkit/wkaudiovisualmediatypes?language=objc). enum WKAudiovisualMediaTypeEnum { none, audio, video, all, } // TODO(bparrishMines): Enums need be wrapped in a data class because they can't // be used as primitive arguments. See https://github.com/flutter/flutter/issues/87307 class WKAudiovisualMediaTypeEnumData { late WKAudiovisualMediaTypeEnum value; } /// Mirror of WKWebsiteDataTypes. /// /// See https://developer.apple.com/documentation/webkit/wkwebsitedatarecord/data_store_record_types?language=objc. enum WKWebsiteDataTypeEnum { cookies, memoryCache, diskCache, offlineWebApplicationCache, localStorage, sessionStorage, webSQLDatabases, indexedDBDatabases, } // TODO(bparrishMines): Enums need be wrapped in a data class because they can't // be used as primitive arguments. See https://github.com/flutter/flutter/issues/87307 class WKWebsiteDataTypeEnumData { late WKWebsiteDataTypeEnum value; } /// Mirror of WKNavigationActionPolicy. /// /// See https://developer.apple.com/documentation/webkit/wknavigationactionpolicy?language=objc. enum WKNavigationActionPolicyEnum { allow, cancel, } // TODO(bparrishMines): Enums need be wrapped in a data class because they can't // be used as primitive arguments. See https://github.com/flutter/flutter/issues/87307 class WKNavigationActionPolicyEnumData { late WKNavigationActionPolicyEnum value; } /// Mirror of WKNavigationResponsePolicy. /// /// See https://developer.apple.com/documentation/webkit/wknavigationactionpolicy?language=objc. enum WKNavigationResponsePolicyEnum { allow, cancel, } /// Mirror of NSHTTPCookiePropertyKey. /// /// See https://developer.apple.com/documentation/foundation/nshttpcookiepropertykey. enum NSHttpCookiePropertyKeyEnum { comment, commentUrl, discard, domain, expires, maximumAge, name, originUrl, path, port, sameSitePolicy, secure, value, version, } // TODO(bparrishMines): Enums need be wrapped in a data class because they can't // be used as primitive arguments. See https://github.com/flutter/flutter/issues/87307 class NSHttpCookiePropertyKeyEnumData { late NSHttpCookiePropertyKeyEnum value; } /// An object that contains information about an action that causes navigation /// to occur. /// /// Wraps [WKNavigationType](https://developer.apple.com/documentation/webkit/wknavigationaction?language=objc). enum WKNavigationType { /// A link activation. /// /// See https://developer.apple.com/documentation/webkit/wknavigationtype/wknavigationtypelinkactivated?language=objc. linkActivated, /// A request to submit a form. /// /// See https://developer.apple.com/documentation/webkit/wknavigationtype/wknavigationtypeformsubmitted?language=objc. submitted, /// A request for the frame’s next or previous item. /// /// See https://developer.apple.com/documentation/webkit/wknavigationtype/wknavigationtypebackforward?language=objc. backForward, /// A request to reload the webpage. /// /// See https://developer.apple.com/documentation/webkit/wknavigationtype/wknavigationtypereload?language=objc. reload, /// A request to resubmit a form. /// /// See https://developer.apple.com/documentation/webkit/wknavigationtype/wknavigationtypeformresubmitted?language=objc. formResubmitted, /// A navigation request that originates for some other reason. /// /// See https://developer.apple.com/documentation/webkit/wknavigationtype/wknavigationtypeother?language=objc. other, /// An unknown navigation type. /// /// This does not represent an actual value provided by the platform and only /// indicates a value was provided that isn't currently supported. unknown, } /// Possible permission decisions for device resource access. /// /// See https://developer.apple.com/documentation/webkit/wkpermissiondecision?language=objc. enum WKPermissionDecision { /// Deny permission for the requested resource. /// /// See https://developer.apple.com/documentation/webkit/wkpermissiondecision/wkpermissiondecisiondeny?language=objc. deny, /// Deny permission for the requested resource. /// /// See https://developer.apple.com/documentation/webkit/wkpermissiondecision/wkpermissiondecisiongrant?language=objc. grant, /// Prompt the user for permission for the requested resource. /// /// See https://developer.apple.com/documentation/webkit/wkpermissiondecision/wkpermissiondecisionprompt?language=objc. prompt, } // TODO(bparrishMines): Enums need be wrapped in a data class because they can't // be used as primitive arguments. See https://github.com/flutter/flutter/issues/87307 class WKPermissionDecisionData { late WKPermissionDecision value; } /// List of the types of media devices that can capture audio, video, or both. /// /// See https://developer.apple.com/documentation/webkit/wkmediacapturetype?language=objc. enum WKMediaCaptureType { /// A media device that can capture video. /// /// See https://developer.apple.com/documentation/webkit/wkmediacapturetype/wkmediacapturetypecamera?language=objc. camera, /// A media device or devices that can capture audio and video. /// /// See https://developer.apple.com/documentation/webkit/wkmediacapturetype/wkmediacapturetypecameraandmicrophone?language=objc. cameraAndMicrophone, /// A media device that can capture audio. /// /// See https://developer.apple.com/documentation/webkit/wkmediacapturetype/wkmediacapturetypemicrophone?language=objc. microphone, /// An unknown media device. /// /// This does not represent an actual value provided by the platform and only /// indicates a value was provided that isn't currently supported. unknown, } // TODO(bparrishMines): Enums need be wrapped in a data class because they can't // be used as primitive arguments. See https://github.com/flutter/flutter/issues/87307 class WKMediaCaptureTypeData { late WKMediaCaptureType value; } /// Responses to an authentication challenge. /// /// See https://developer.apple.com/documentation/foundation/nsurlsessionauthchallengedisposition?language=objc. enum NSUrlSessionAuthChallengeDisposition { /// Use the specified credential, which may be nil. /// /// See https://developer.apple.com/documentation/foundation/nsurlsessionauthchallengedisposition/nsurlsessionauthchallengeusecredential?language=objc. useCredential, /// Use the default handling for the challenge as though this delegate method /// were not implemented. /// /// See https://developer.apple.com/documentation/foundation/nsurlsessionauthchallengedisposition/nsurlsessionauthchallengeperformdefaulthandling?language=objc. performDefaultHandling, /// Cancel the entire request. /// /// See https://developer.apple.com/documentation/foundation/nsurlsessionauthchallengedisposition/nsurlsessionauthchallengecancelauthenticationchallenge?language=objc. cancelAuthenticationChallenge, /// Reject this challenge, and call the authentication delegate method again /// with the next authentication protection space. /// /// See https://developer.apple.com/documentation/foundation/nsurlsessionauthchallengedisposition/nsurlsessionauthchallengerejectprotectionspace?language=objc. rejectProtectionSpace, } /// Specifies how long a credential will be kept. enum NSUrlCredentialPersistence { /// The credential should not be stored. /// /// See https://developer.apple.com/documentation/foundation/nsurlcredentialpersistence/nsurlcredentialpersistencenone?language=objc. none, /// The credential should be stored only for this session. /// /// See https://developer.apple.com/documentation/foundation/nsurlcredentialpersistence/nsurlcredentialpersistenceforsession?language=objc. session, /// The credential should be stored in the keychain. /// /// See https://developer.apple.com/documentation/foundation/nsurlcredentialpersistence/nsurlcredentialpersistencepermanent?language=objc. permanent, /// The credential should be stored permanently in the keychain, and in /// addition should be distributed to other devices based on the owning Apple /// ID. /// /// See https://developer.apple.com/documentation/foundation/nsurlcredentialpersistence/nsurlcredentialpersistencesynchronizable?language=objc. synchronizable, } /// Mirror of NSURLRequest. /// /// See https://developer.apple.com/documentation/foundation/nsurlrequest?language=objc. class NSUrlRequestData { late String url; late String? httpMethod; late Uint8List? httpBody; late Map<String?, String?> allHttpHeaderFields; } /// Mirror of NSURLResponse. /// /// See https://developer.apple.com/documentation/foundation/nshttpurlresponse?language=objc. class NSHttpUrlResponseData { late int statusCode; } /// Mirror of WKUserScript. /// /// See https://developer.apple.com/documentation/webkit/wkuserscript?language=objc. class WKUserScriptData { late String source; late WKUserScriptInjectionTimeEnumData? injectionTime; late bool isMainFrameOnly; } /// Mirror of WKNavigationAction. /// /// See https://developer.apple.com/documentation/webkit/wknavigationaction. class WKNavigationActionData { late NSUrlRequestData request; late WKFrameInfoData targetFrame; late WKNavigationType navigationType; } /// Mirror of WKNavigationResponse. /// /// See https://developer.apple.com/documentation/webkit/wknavigationresponse. class WKNavigationResponseData { late NSHttpUrlResponseData response; late bool forMainFrame; } /// Mirror of WKFrameInfo. /// /// See https://developer.apple.com/documentation/webkit/wkframeinfo?language=objc. class WKFrameInfoData { late bool isMainFrame; late NSUrlRequestData request; } /// Mirror of NSError. /// /// See https://developer.apple.com/documentation/foundation/nserror?language=objc. class NSErrorData { late int code; late String domain; late Map<String?, Object?>? userInfo; } /// Mirror of WKScriptMessage. /// /// See https://developer.apple.com/documentation/webkit/wkscriptmessage?language=objc. class WKScriptMessageData { late String name; late Object? body; } /// Mirror of WKSecurityOrigin. /// /// See https://developer.apple.com/documentation/webkit/wksecurityorigin?language=objc. class WKSecurityOriginData { late String host; late int port; late String protocol; } /// Mirror of NSHttpCookieData. /// /// See https://developer.apple.com/documentation/foundation/nshttpcookie?language=objc. class NSHttpCookieData { // TODO(bparrishMines): Change to a map when Objective-C data classes conform // to `NSCopying`. See https://github.com/flutter/flutter/issues/103383. // `NSDictionary`s are unable to use data classes as keys because they don't // conform to `NSCopying`. This splits the map of properties into a list of // keys and values with the ordered maintained. late List<NSHttpCookiePropertyKeyEnumData?> propertyKeys; late List<Object?> propertyValues; } /// An object that can represent either a value supported by /// `StandardMessageCodec`, a data class in this pigeon file, or an identifier /// of an object stored in an `InstanceManager`. class ObjectOrIdentifier { late Object? value; /// Whether value is an int that is used to retrieve an instance stored in an /// `InstanceManager`. late bool isIdentifier; } class AuthenticationChallengeResponse { late NSUrlSessionAuthChallengeDisposition disposition; late int? credentialIdentifier; } /// Mirror of WKWebsiteDataStore. /// /// See https://developer.apple.com/documentation/webkit/wkwebsitedatastore?language=objc. @HostApi(dartHostTestHandler: 'TestWKWebsiteDataStoreHostApi') abstract class WKWebsiteDataStoreHostApi { @ObjCSelector( 'createFromWebViewConfigurationWithIdentifier:configurationIdentifier:', ) void createFromWebViewConfiguration( int identifier, int configurationIdentifier, ); @ObjCSelector('createDefaultDataStoreWithIdentifier:') void createDefaultDataStore(int identifier); @ObjCSelector( 'removeDataFromDataStoreWithIdentifier:ofTypes:modifiedSince:', ) @async bool removeDataOfTypes( int identifier, List<WKWebsiteDataTypeEnumData> dataTypes, double modificationTimeInSecondsSinceEpoch, ); } /// Mirror of UIView. /// /// See https://developer.apple.com/documentation/uikit/uiview?language=objc. @HostApi(dartHostTestHandler: 'TestUIViewHostApi') abstract class UIViewHostApi { @ObjCSelector('setBackgroundColorForViewWithIdentifier:toValue:') void setBackgroundColor(int identifier, int? value); @ObjCSelector('setOpaqueForViewWithIdentifier:isOpaque:') void setOpaque(int identifier, bool opaque); } /// Mirror of UIScrollView. /// /// See https://developer.apple.com/documentation/uikit/uiscrollview?language=objc. @HostApi(dartHostTestHandler: 'TestUIScrollViewHostApi') abstract class UIScrollViewHostApi { @ObjCSelector('createFromWebViewWithIdentifier:webViewIdentifier:') void createFromWebView(int identifier, int webViewIdentifier); @ObjCSelector('contentOffsetForScrollViewWithIdentifier:') List<double?> getContentOffset(int identifier); @ObjCSelector('scrollByForScrollViewWithIdentifier:x:y:') void scrollBy(int identifier, double x, double y); @ObjCSelector('setContentOffsetForScrollViewWithIdentifier:toX:y:') void setContentOffset(int identifier, double x, double y); @ObjCSelector( 'setDelegateForScrollViewWithIdentifier:uiScrollViewDelegateIdentifier:') void setDelegate(int identifier, int? uiScrollViewDelegateIdentifier); } /// Mirror of WKWebViewConfiguration. /// /// See https://developer.apple.com/documentation/webkit/wkwebviewconfiguration?language=objc. @HostApi(dartHostTestHandler: 'TestWKWebViewConfigurationHostApi') abstract class WKWebViewConfigurationHostApi { @ObjCSelector('createWithIdentifier:') void create(int identifier); @ObjCSelector('createFromWebViewWithIdentifier:webViewIdentifier:') void createFromWebView(int identifier, int webViewIdentifier); @ObjCSelector( 'setAllowsInlineMediaPlaybackForConfigurationWithIdentifier:isAllowed:', ) void setAllowsInlineMediaPlayback(int identifier, bool allow); @ObjCSelector( 'setLimitsNavigationsToAppBoundDomainsForConfigurationWithIdentifier:isLimited:', ) void setLimitsNavigationsToAppBoundDomains(int identifier, bool limit); @ObjCSelector( 'setMediaTypesRequiresUserActionForConfigurationWithIdentifier:forTypes:', ) void setMediaTypesRequiringUserActionForPlayback( int identifier, List<WKAudiovisualMediaTypeEnumData> types, ); } /// Handles callbacks from a WKWebViewConfiguration instance. /// /// See https://developer.apple.com/documentation/webkit/wkwebviewconfiguration?language=objc. @FlutterApi() abstract class WKWebViewConfigurationFlutterApi { @ObjCSelector('createWithIdentifier:') void create(int identifier); } /// Mirror of WKUserContentController. /// /// See https://developer.apple.com/documentation/webkit/wkusercontentcontroller?language=objc. @HostApi(dartHostTestHandler: 'TestWKUserContentControllerHostApi') abstract class WKUserContentControllerHostApi { @ObjCSelector( 'createFromWebViewConfigurationWithIdentifier:configurationIdentifier:', ) void createFromWebViewConfiguration( int identifier, int configurationIdentifier, ); @ObjCSelector( 'addScriptMessageHandlerForControllerWithIdentifier:handlerIdentifier:ofName:', ) void addScriptMessageHandler( int identifier, int handlerIdentifier, String name, ); @ObjCSelector('removeScriptMessageHandlerForControllerWithIdentifier:name:') void removeScriptMessageHandler(int identifier, String name); @ObjCSelector('removeAllScriptMessageHandlersForControllerWithIdentifier:') void removeAllScriptMessageHandlers(int identifier); @ObjCSelector('addUserScriptForControllerWithIdentifier:userScript:') void addUserScript(int identifier, WKUserScriptData userScript); @ObjCSelector('removeAllUserScriptsForControllerWithIdentifier:') void removeAllUserScripts(int identifier); } /// Mirror of WKUserPreferences. /// /// See https://developer.apple.com/documentation/webkit/wkpreferences?language=objc. @HostApi(dartHostTestHandler: 'TestWKPreferencesHostApi') abstract class WKPreferencesHostApi { @ObjCSelector( 'createFromWebViewConfigurationWithIdentifier:configurationIdentifier:', ) void createFromWebViewConfiguration( int identifier, int configurationIdentifier, ); @ObjCSelector('setJavaScriptEnabledForPreferencesWithIdentifier:isEnabled:') void setJavaScriptEnabled(int identifier, bool enabled); } /// Mirror of WKScriptMessageHandler. /// /// See https://developer.apple.com/documentation/webkit/wkscriptmessagehandler?language=objc. @HostApi(dartHostTestHandler: 'TestWKScriptMessageHandlerHostApi') abstract class WKScriptMessageHandlerHostApi { @ObjCSelector('createWithIdentifier:') void create(int identifier); } /// Handles callbacks from a WKScriptMessageHandler instance. /// /// See https://developer.apple.com/documentation/webkit/wkscriptmessagehandler?language=objc. @FlutterApi() abstract class WKScriptMessageHandlerFlutterApi { @ObjCSelector( 'didReceiveScriptMessageForHandlerWithIdentifier:userContentControllerIdentifier:message:', ) void didReceiveScriptMessage( int identifier, int userContentControllerIdentifier, WKScriptMessageData message, ); } /// Mirror of WKNavigationDelegate. /// /// See https://developer.apple.com/documentation/webkit/wknavigationdelegate?language=objc. @HostApi(dartHostTestHandler: 'TestWKNavigationDelegateHostApi') abstract class WKNavigationDelegateHostApi { @ObjCSelector('createWithIdentifier:') void create(int identifier); } /// Handles callbacks from a WKNavigationDelegate instance. /// /// See https://developer.apple.com/documentation/webkit/wknavigationdelegate?language=objc. @FlutterApi() abstract class WKNavigationDelegateFlutterApi { @ObjCSelector( 'didFinishNavigationForDelegateWithIdentifier:webViewIdentifier:URL:', ) void didFinishNavigation( int identifier, int webViewIdentifier, String? url, ); @ObjCSelector( 'didStartProvisionalNavigationForDelegateWithIdentifier:webViewIdentifier:URL:', ) void didStartProvisionalNavigation( int identifier, int webViewIdentifier, String? url, ); @ObjCSelector( 'decidePolicyForNavigationActionForDelegateWithIdentifier:webViewIdentifier:navigationAction:', ) @async WKNavigationActionPolicyEnumData decidePolicyForNavigationAction( int identifier, int webViewIdentifier, WKNavigationActionData navigationAction, ); @ObjCSelector( 'decidePolicyForNavigationResponseForDelegateWithIdentifier:webViewIdentifier:navigationResponse:', ) @async WKNavigationResponsePolicyEnum decidePolicyForNavigationResponse( int identifier, int webViewIdentifier, WKNavigationResponseData navigationResponse, ); @ObjCSelector( 'didFailNavigationForDelegateWithIdentifier:webViewIdentifier:error:', ) void didFailNavigation( int identifier, int webViewIdentifier, NSErrorData error, ); @ObjCSelector( 'didFailProvisionalNavigationForDelegateWithIdentifier:webViewIdentifier:error:', ) void didFailProvisionalNavigation( int identifier, int webViewIdentifier, NSErrorData error, ); @ObjCSelector( 'webViewWebContentProcessDidTerminateForDelegateWithIdentifier:webViewIdentifier:', ) void webViewWebContentProcessDidTerminate( int identifier, int webViewIdentifier, ); @async @ObjCSelector( 'didReceiveAuthenticationChallengeForDelegateWithIdentifier:webViewIdentifier:challengeIdentifier:', ) AuthenticationChallengeResponse didReceiveAuthenticationChallenge( int identifier, int webViewIdentifier, int challengeIdentifier, ); } /// Mirror of NSObject. /// /// See https://developer.apple.com/documentation/objectivec/nsobject. @HostApi(dartHostTestHandler: 'TestNSObjectHostApi') abstract class NSObjectHostApi { @ObjCSelector('disposeObjectWithIdentifier:') void dispose(int identifier); @ObjCSelector( 'addObserverForObjectWithIdentifier:observerIdentifier:keyPath:options:', ) void addObserver( int identifier, int observerIdentifier, String keyPath, List<NSKeyValueObservingOptionsEnumData> options, ); @ObjCSelector( 'removeObserverForObjectWithIdentifier:observerIdentifier:keyPath:', ) void removeObserver(int identifier, int observerIdentifier, String keyPath); } /// Handles callbacks from an NSObject instance. /// /// See https://developer.apple.com/documentation/objectivec/nsobject. @FlutterApi() abstract class NSObjectFlutterApi { @ObjCSelector( 'observeValueForObjectWithIdentifier:keyPath:objectIdentifier:changeKeys:changeValues:', ) void observeValue( int identifier, String keyPath, int objectIdentifier, // TODO(bparrishMines): Change to a map when Objective-C data classes conform // to `NSCopying`. See https://github.com/flutter/flutter/issues/103383. // `NSDictionary`s are unable to use data classes as keys because they don't // conform to `NSCopying`. This splits the map of properties into a list of // keys and values with the ordered maintained. List<NSKeyValueChangeKeyEnumData?> changeKeys, List<ObjectOrIdentifier> changeValues, ); @ObjCSelector('disposeObjectWithIdentifier:') void dispose(int identifier); } /// Mirror of WKWebView. /// /// See https://developer.apple.com/documentation/webkit/wkwebview?language=objc. @HostApi(dartHostTestHandler: 'TestWKWebViewHostApi') abstract class WKWebViewHostApi { @ObjCSelector('createWithIdentifier:configurationIdentifier:') void create(int identifier, int configurationIdentifier); @ObjCSelector('setUIDelegateForWebViewWithIdentifier:delegateIdentifier:') void setUIDelegate(int identifier, int? uiDelegateIdentifier); @ObjCSelector( 'setNavigationDelegateForWebViewWithIdentifier:delegateIdentifier:', ) void setNavigationDelegate(int identifier, int? navigationDelegateIdentifier); @ObjCSelector('URLForWebViewWithIdentifier:') String? getUrl(int identifier); @ObjCSelector('estimatedProgressForWebViewWithIdentifier:') double getEstimatedProgress(int identifier); @ObjCSelector('loadRequestForWebViewWithIdentifier:request:') void loadRequest(int identifier, NSUrlRequestData request); @ObjCSelector('loadHTMLForWebViewWithIdentifier:HTMLString:baseURL:') void loadHtmlString(int identifier, String string, String? baseUrl); @ObjCSelector('loadFileForWebViewWithIdentifier:fileURL:readAccessURL:') void loadFileUrl(int identifier, String url, String readAccessUrl); @ObjCSelector('loadAssetForWebViewWithIdentifier:assetKey:') void loadFlutterAsset(int identifier, String key); @ObjCSelector('canGoBackForWebViewWithIdentifier:') bool canGoBack(int identifier); @ObjCSelector('canGoForwardForWebViewWithIdentifier:') bool canGoForward(int identifier); @ObjCSelector('goBackForWebViewWithIdentifier:') void goBack(int identifier); @ObjCSelector('goForwardForWebViewWithIdentifier:') void goForward(int identifier); @ObjCSelector('reloadWebViewWithIdentifier:') void reload(int identifier); @ObjCSelector('titleForWebViewWithIdentifier:') String? getTitle(int identifier); @ObjCSelector('setAllowsBackForwardForWebViewWithIdentifier:isAllowed:') void setAllowsBackForwardNavigationGestures(int identifier, bool allow); @ObjCSelector('setCustomUserAgentForWebViewWithIdentifier:userAgent:') void setCustomUserAgent(int identifier, String? userAgent); @ObjCSelector('evaluateJavaScriptForWebViewWithIdentifier:javaScriptString:') @async Object? evaluateJavaScript(int identifier, String javaScriptString); @ObjCSelector('setInspectableForWebViewWithIdentifier:inspectable:') void setInspectable(int identifier, bool inspectable); @ObjCSelector('customUserAgentForWebViewWithIdentifier:') String? getCustomUserAgent(int identifier); } /// Mirror of WKUIDelegate. /// /// See https://developer.apple.com/documentation/webkit/wkuidelegate?language=objc. @HostApi(dartHostTestHandler: 'TestWKUIDelegateHostApi') abstract class WKUIDelegateHostApi { @ObjCSelector('createWithIdentifier:') void create(int identifier); } /// Handles callbacks from a WKUIDelegate instance. /// /// See https://developer.apple.com/documentation/webkit/wkuidelegate?language=objc. @FlutterApi() abstract class WKUIDelegateFlutterApi { @ObjCSelector( 'onCreateWebViewForDelegateWithIdentifier:webViewIdentifier:configurationIdentifier:navigationAction:', ) void onCreateWebView( int identifier, int webViewIdentifier, int configurationIdentifier, WKNavigationActionData navigationAction, ); /// Callback to Dart function `WKUIDelegate.requestMediaCapturePermission`. @ObjCSelector( 'requestMediaCapturePermissionForDelegateWithIdentifier:webViewIdentifier:origin:frame:type:', ) @async WKPermissionDecisionData requestMediaCapturePermission( int identifier, int webViewIdentifier, WKSecurityOriginData origin, WKFrameInfoData frame, WKMediaCaptureTypeData type, ); /// Callback to Dart function `WKUIDelegate.runJavaScriptAlertPanel`. @ObjCSelector( 'runJavaScriptAlertPanelForDelegateWithIdentifier:message:frame:', ) @async void runJavaScriptAlertPanel( int identifier, String message, WKFrameInfoData frame, ); /// Callback to Dart function `WKUIDelegate.runJavaScriptConfirmPanel`. @ObjCSelector( 'runJavaScriptConfirmPanelForDelegateWithIdentifier:message:frame:', ) @async bool runJavaScriptConfirmPanel( int identifier, String message, WKFrameInfoData frame, ); /// Callback to Dart function `WKUIDelegate.runJavaScriptTextInputPanel`. @ObjCSelector( 'runJavaScriptTextInputPanelForDelegateWithIdentifier:prompt:defaultText:frame:', ) @async String runJavaScriptTextInputPanel( int identifier, String prompt, String defaultText, WKFrameInfoData frame, ); } /// Mirror of WKHttpCookieStore. /// /// See https://developer.apple.com/documentation/webkit/wkhttpcookiestore?language=objc. @HostApi(dartHostTestHandler: 'TestWKHttpCookieStoreHostApi') abstract class WKHttpCookieStoreHostApi { @ObjCSelector('createFromWebsiteDataStoreWithIdentifier:dataStoreIdentifier:') void createFromWebsiteDataStore( int identifier, int websiteDataStoreIdentifier, ); @ObjCSelector('setCookieForStoreWithIdentifier:cookie:') @async void setCookie(int identifier, NSHttpCookieData cookie); } /// 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. @HostApi(dartHostTestHandler: 'TestNSUrlHostApi') abstract class NSUrlHostApi { @ObjCSelector('absoluteStringForNSURLWithIdentifier:') String? getAbsoluteString(int identifier); } /// Flutter API for `NSUrl`. /// /// This class may handle instantiating and adding Dart instances that are /// attached to a native instance or receiving callback methods from an /// overridden native class. /// /// See https://developer.apple.com/documentation/foundation/nsurl?language=objc. @FlutterApi() abstract class NSUrlFlutterApi { @ObjCSelector('createWithIdentifier:') void create(int identifier); } /// 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. @HostApi(dartHostTestHandler: 'TestUIScrollViewDelegateHostApi') abstract class UIScrollViewDelegateHostApi { @ObjCSelector('createWithIdentifier:') void create(int identifier); } /// Flutter API for `UIScrollViewDelegate`. /// /// See https://developer.apple.com/documentation/uikit/uiscrollviewdelegate?language=objc. @FlutterApi() abstract class UIScrollViewDelegateFlutterApi { @ObjCSelector( 'scrollViewDidScrollWithIdentifier:UIScrollViewIdentifier:x:y:', ) void scrollViewDidScroll( int identifier, int uiScrollViewIdentifier, double x, double y, ); } /// 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. @HostApi(dartHostTestHandler: 'TestNSUrlCredentialHostApi') abstract class NSUrlCredentialHostApi { /// Create a new native instance and add it to the `InstanceManager`. @ObjCSelector( 'createWithUserWithIdentifier:user:password:persistence:', ) void createWithUser( int identifier, String user, String password, NSUrlCredentialPersistence persistence, ); } /// Flutter API for `NSUrlProtectionSpace`. /// /// This class may handle instantiating and adding Dart instances that are /// attached to a native instance or receiving callback methods from an /// overridden native class. /// /// See https://developer.apple.com/documentation/foundation/nsurlprotectionspace?language=objc. @FlutterApi() abstract class NSUrlProtectionSpaceFlutterApi { /// Create a new Dart instance and add it to the `InstanceManager`. @ObjCSelector('createWithIdentifier:host:realm:authenticationMethod:') void create( int identifier, String? host, String? realm, String? authenticationMethod, ); } /// Flutter API for `NSUrlAuthenticationChallenge`. /// /// This class may handle instantiating and adding Dart instances that are /// attached to a native instance or receiving callback methods from an /// overridden native class. /// /// See https://developer.apple.com/documentation/foundation/nsurlauthenticationchallenge?language=objc. @FlutterApi() abstract class NSUrlAuthenticationChallengeFlutterApi { /// Create a new Dart instance and add it to the `InstanceManager`. @ObjCSelector('createWithIdentifier:protectionSpaceIdentifier:') void create(int identifier, int protectionSpaceIdentifier); }
packages/packages/webview_flutter/webview_flutter_wkwebview/pigeons/web_kit.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/pigeons/web_kit.dart", "repo_id": "packages", "token_count": 10293 }
1,019
// Mocks generated by Mockito 5.4.4 from annotations // in webview_flutter_wkwebview/test/webkit_webview_controller_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i6; import 'dart:math' as _i3; import 'dart:ui' as _i7; import 'package:mockito/mockito.dart' as _i1; import 'package:webview_flutter_wkwebview/src/foundation/foundation.dart' as _i2; import 'package:webview_flutter_wkwebview/src/ui_kit/ui_kit.dart' as _i4; import 'package:webview_flutter_wkwebview/src/web_kit/web_kit.dart' as _i5; // 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 _FakeNSObject_0 extends _i1.SmartFake implements _i2.NSObject { _FakeNSObject_0( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakePoint_1<T extends num> extends _i1.SmartFake implements _i3.Point<T> { _FakePoint_1( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeUIScrollView_2 extends _i1.SmartFake implements _i4.UIScrollView { _FakeUIScrollView_2( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeUIScrollViewDelegate_3 extends _i1.SmartFake implements _i4.UIScrollViewDelegate { _FakeUIScrollViewDelegate_3( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeWKPreferences_4 extends _i1.SmartFake implements _i5.WKPreferences { _FakeWKPreferences_4( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeWKUserContentController_5 extends _i1.SmartFake implements _i5.WKUserContentController { _FakeWKUserContentController_5( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeWKHttpCookieStore_6 extends _i1.SmartFake implements _i5.WKHttpCookieStore { _FakeWKHttpCookieStore_6( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeWKWebsiteDataStore_7 extends _i1.SmartFake implements _i5.WKWebsiteDataStore { _FakeWKWebsiteDataStore_7( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeWKWebViewConfiguration_8 extends _i1.SmartFake implements _i5.WKWebViewConfiguration { _FakeWKWebViewConfiguration_8( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeWKWebView_9 extends _i1.SmartFake implements _i5.WKWebView { _FakeWKWebView_9( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeWKScriptMessageHandler_10 extends _i1.SmartFake implements _i5.WKScriptMessageHandler { _FakeWKScriptMessageHandler_10( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } /// A class which mocks [NSUrl]. /// /// See the documentation for Mockito's code generation for more information. class MockNSUrl extends _i1.Mock implements _i2.NSUrl { MockNSUrl() { _i1.throwOnMissingStub(this); } @override _i6.Future<String?> getAbsoluteString() => (super.noSuchMethod( Invocation.method( #getAbsoluteString, [], ), returnValue: _i6.Future<String?>.value(), ) as _i6.Future<String?>); @override _i2.NSObject copy() => (super.noSuchMethod( Invocation.method( #copy, [], ), returnValue: _FakeNSObject_0( this, Invocation.method( #copy, [], ), ), ) as _i2.NSObject); @override _i6.Future<void> addObserver( _i2.NSObject? observer, { required String? keyPath, required Set<_i2.NSKeyValueObservingOptions>? options, }) => (super.noSuchMethod( Invocation.method( #addObserver, [observer], { #keyPath: keyPath, #options: options, }, ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); @override _i6.Future<void> removeObserver( _i2.NSObject? observer, { required String? keyPath, }) => (super.noSuchMethod( Invocation.method( #removeObserver, [observer], {#keyPath: keyPath}, ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); } /// A class which mocks [UIScrollView]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable class MockUIScrollView extends _i1.Mock implements _i4.UIScrollView { MockUIScrollView() { _i1.throwOnMissingStub(this); } @override _i6.Future<_i3.Point<double>> getContentOffset() => (super.noSuchMethod( Invocation.method( #getContentOffset, [], ), returnValue: _i6.Future<_i3.Point<double>>.value(_FakePoint_1<double>( this, Invocation.method( #getContentOffset, [], ), )), ) as _i6.Future<_i3.Point<double>>); @override _i6.Future<void> scrollBy(_i3.Point<double>? offset) => (super.noSuchMethod( Invocation.method( #scrollBy, [offset], ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); @override _i6.Future<void> setContentOffset(_i3.Point<double>? offset) => (super.noSuchMethod( Invocation.method( #setContentOffset, [offset], ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); @override _i6.Future<void> setDelegate(_i4.UIScrollViewDelegate? delegate) => (super.noSuchMethod( Invocation.method( #setDelegate, [delegate], ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); @override _i4.UIScrollView copy() => (super.noSuchMethod( Invocation.method( #copy, [], ), returnValue: _FakeUIScrollView_2( this, Invocation.method( #copy, [], ), ), ) as _i4.UIScrollView); @override _i6.Future<void> setBackgroundColor(_i7.Color? color) => (super.noSuchMethod( Invocation.method( #setBackgroundColor, [color], ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); @override _i6.Future<void> setOpaque(bool? opaque) => (super.noSuchMethod( Invocation.method( #setOpaque, [opaque], ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); @override _i6.Future<void> addObserver( _i2.NSObject? observer, { required String? keyPath, required Set<_i2.NSKeyValueObservingOptions>? options, }) => (super.noSuchMethod( Invocation.method( #addObserver, [observer], { #keyPath: keyPath, #options: options, }, ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); @override _i6.Future<void> removeObserver( _i2.NSObject? observer, { required String? keyPath, }) => (super.noSuchMethod( Invocation.method( #removeObserver, [observer], {#keyPath: keyPath}, ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); } /// A class which mocks [UIScrollViewDelegate]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable class MockUIScrollViewDelegate extends _i1.Mock implements _i4.UIScrollViewDelegate { MockUIScrollViewDelegate() { _i1.throwOnMissingStub(this); } @override _i4.UIScrollViewDelegate copy() => (super.noSuchMethod( Invocation.method( #copy, [], ), returnValue: _FakeUIScrollViewDelegate_3( this, Invocation.method( #copy, [], ), ), ) as _i4.UIScrollViewDelegate); @override _i6.Future<void> addObserver( _i2.NSObject? observer, { required String? keyPath, required Set<_i2.NSKeyValueObservingOptions>? options, }) => (super.noSuchMethod( Invocation.method( #addObserver, [observer], { #keyPath: keyPath, #options: options, }, ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); @override _i6.Future<void> removeObserver( _i2.NSObject? observer, { required String? keyPath, }) => (super.noSuchMethod( Invocation.method( #removeObserver, [observer], {#keyPath: keyPath}, ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); } /// A class which mocks [WKPreferences]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable class MockWKPreferences extends _i1.Mock implements _i5.WKPreferences { MockWKPreferences() { _i1.throwOnMissingStub(this); } @override _i6.Future<void> setJavaScriptEnabled(bool? enabled) => (super.noSuchMethod( Invocation.method( #setJavaScriptEnabled, [enabled], ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); @override _i5.WKPreferences copy() => (super.noSuchMethod( Invocation.method( #copy, [], ), returnValue: _FakeWKPreferences_4( this, Invocation.method( #copy, [], ), ), ) as _i5.WKPreferences); @override _i6.Future<void> addObserver( _i2.NSObject? observer, { required String? keyPath, required Set<_i2.NSKeyValueObservingOptions>? options, }) => (super.noSuchMethod( Invocation.method( #addObserver, [observer], { #keyPath: keyPath, #options: options, }, ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); @override _i6.Future<void> removeObserver( _i2.NSObject? observer, { required String? keyPath, }) => (super.noSuchMethod( Invocation.method( #removeObserver, [observer], {#keyPath: keyPath}, ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); } /// A class which mocks [WKUserContentController]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable class MockWKUserContentController extends _i1.Mock implements _i5.WKUserContentController { MockWKUserContentController() { _i1.throwOnMissingStub(this); } @override _i6.Future<void> addScriptMessageHandler( _i5.WKScriptMessageHandler? handler, String? name, ) => (super.noSuchMethod( Invocation.method( #addScriptMessageHandler, [ handler, name, ], ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); @override _i6.Future<void> removeScriptMessageHandler(String? name) => (super.noSuchMethod( Invocation.method( #removeScriptMessageHandler, [name], ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); @override _i6.Future<void> removeAllScriptMessageHandlers() => (super.noSuchMethod( Invocation.method( #removeAllScriptMessageHandlers, [], ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); @override _i6.Future<void> addUserScript(_i5.WKUserScript? userScript) => (super.noSuchMethod( Invocation.method( #addUserScript, [userScript], ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); @override _i6.Future<void> removeAllUserScripts() => (super.noSuchMethod( Invocation.method( #removeAllUserScripts, [], ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); @override _i5.WKUserContentController copy() => (super.noSuchMethod( Invocation.method( #copy, [], ), returnValue: _FakeWKUserContentController_5( this, Invocation.method( #copy, [], ), ), ) as _i5.WKUserContentController); @override _i6.Future<void> addObserver( _i2.NSObject? observer, { required String? keyPath, required Set<_i2.NSKeyValueObservingOptions>? options, }) => (super.noSuchMethod( Invocation.method( #addObserver, [observer], { #keyPath: keyPath, #options: options, }, ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); @override _i6.Future<void> removeObserver( _i2.NSObject? observer, { required String? keyPath, }) => (super.noSuchMethod( Invocation.method( #removeObserver, [observer], {#keyPath: keyPath}, ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); } /// A class which mocks [WKWebsiteDataStore]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable class MockWKWebsiteDataStore extends _i1.Mock implements _i5.WKWebsiteDataStore { MockWKWebsiteDataStore() { _i1.throwOnMissingStub(this); } @override _i5.WKHttpCookieStore get httpCookieStore => (super.noSuchMethod( Invocation.getter(#httpCookieStore), returnValue: _FakeWKHttpCookieStore_6( this, Invocation.getter(#httpCookieStore), ), ) as _i5.WKHttpCookieStore); @override _i6.Future<bool> removeDataOfTypes( Set<_i5.WKWebsiteDataType>? dataTypes, DateTime? since, ) => (super.noSuchMethod( Invocation.method( #removeDataOfTypes, [ dataTypes, since, ], ), returnValue: _i6.Future<bool>.value(false), ) as _i6.Future<bool>); @override _i5.WKWebsiteDataStore copy() => (super.noSuchMethod( Invocation.method( #copy, [], ), returnValue: _FakeWKWebsiteDataStore_7( this, Invocation.method( #copy, [], ), ), ) as _i5.WKWebsiteDataStore); @override _i6.Future<void> addObserver( _i2.NSObject? observer, { required String? keyPath, required Set<_i2.NSKeyValueObservingOptions>? options, }) => (super.noSuchMethod( Invocation.method( #addObserver, [observer], { #keyPath: keyPath, #options: options, }, ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); @override _i6.Future<void> removeObserver( _i2.NSObject? observer, { required String? keyPath, }) => (super.noSuchMethod( Invocation.method( #removeObserver, [observer], {#keyPath: keyPath}, ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); } /// A class which mocks [WKWebView]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable class MockWKWebView extends _i1.Mock implements _i5.WKWebView { MockWKWebView() { _i1.throwOnMissingStub(this); } @override _i5.WKWebViewConfiguration get configuration => (super.noSuchMethod( Invocation.getter(#configuration), returnValue: _FakeWKWebViewConfiguration_8( this, Invocation.getter(#configuration), ), ) as _i5.WKWebViewConfiguration); @override _i4.UIScrollView get scrollView => (super.noSuchMethod( Invocation.getter(#scrollView), returnValue: _FakeUIScrollView_2( this, Invocation.getter(#scrollView), ), ) as _i4.UIScrollView); @override _i6.Future<void> setUIDelegate(_i5.WKUIDelegate? delegate) => (super.noSuchMethod( Invocation.method( #setUIDelegate, [delegate], ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); @override _i6.Future<void> setNavigationDelegate(_i5.WKNavigationDelegate? delegate) => (super.noSuchMethod( Invocation.method( #setNavigationDelegate, [delegate], ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); @override _i6.Future<String?> getUrl() => (super.noSuchMethod( Invocation.method( #getUrl, [], ), returnValue: _i6.Future<String?>.value(), ) as _i6.Future<String?>); @override _i6.Future<double> getEstimatedProgress() => (super.noSuchMethod( Invocation.method( #getEstimatedProgress, [], ), returnValue: _i6.Future<double>.value(0.0), ) as _i6.Future<double>); @override _i6.Future<void> loadRequest(_i2.NSUrlRequest? request) => (super.noSuchMethod( Invocation.method( #loadRequest, [request], ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); @override _i6.Future<void> loadHtmlString( String? string, { String? baseUrl, }) => (super.noSuchMethod( Invocation.method( #loadHtmlString, [string], {#baseUrl: baseUrl}, ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); @override _i6.Future<void> loadFileUrl( String? url, { required String? readAccessUrl, }) => (super.noSuchMethod( Invocation.method( #loadFileUrl, [url], {#readAccessUrl: readAccessUrl}, ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); @override _i6.Future<void> loadFlutterAsset(String? key) => (super.noSuchMethod( Invocation.method( #loadFlutterAsset, [key], ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); @override _i6.Future<bool> canGoBack() => (super.noSuchMethod( Invocation.method( #canGoBack, [], ), returnValue: _i6.Future<bool>.value(false), ) as _i6.Future<bool>); @override _i6.Future<bool> canGoForward() => (super.noSuchMethod( Invocation.method( #canGoForward, [], ), returnValue: _i6.Future<bool>.value(false), ) as _i6.Future<bool>); @override _i6.Future<void> goBack() => (super.noSuchMethod( Invocation.method( #goBack, [], ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); @override _i6.Future<void> goForward() => (super.noSuchMethod( Invocation.method( #goForward, [], ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); @override _i6.Future<void> reload() => (super.noSuchMethod( Invocation.method( #reload, [], ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); @override _i6.Future<String?> getTitle() => (super.noSuchMethod( Invocation.method( #getTitle, [], ), returnValue: _i6.Future<String?>.value(), ) as _i6.Future<String?>); @override _i6.Future<void> setAllowsBackForwardNavigationGestures(bool? allow) => (super.noSuchMethod( Invocation.method( #setAllowsBackForwardNavigationGestures, [allow], ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); @override _i6.Future<void> setCustomUserAgent(String? userAgent) => (super.noSuchMethod( Invocation.method( #setCustomUserAgent, [userAgent], ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); @override _i6.Future<Object?> evaluateJavaScript(String? javaScriptString) => (super.noSuchMethod( Invocation.method( #evaluateJavaScript, [javaScriptString], ), returnValue: _i6.Future<Object?>.value(), ) as _i6.Future<Object?>); @override _i6.Future<void> setInspectable(bool? inspectable) => (super.noSuchMethod( Invocation.method( #setInspectable, [inspectable], ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); @override _i6.Future<String?> getCustomUserAgent() => (super.noSuchMethod( Invocation.method( #getCustomUserAgent, [], ), returnValue: _i6.Future<String?>.value(), ) as _i6.Future<String?>); @override _i5.WKWebView copy() => (super.noSuchMethod( Invocation.method( #copy, [], ), returnValue: _FakeWKWebView_9( this, Invocation.method( #copy, [], ), ), ) as _i5.WKWebView); @override _i6.Future<void> setBackgroundColor(_i7.Color? color) => (super.noSuchMethod( Invocation.method( #setBackgroundColor, [color], ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); @override _i6.Future<void> setOpaque(bool? opaque) => (super.noSuchMethod( Invocation.method( #setOpaque, [opaque], ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); @override _i6.Future<void> addObserver( _i2.NSObject? observer, { required String? keyPath, required Set<_i2.NSKeyValueObservingOptions>? options, }) => (super.noSuchMethod( Invocation.method( #addObserver, [observer], { #keyPath: keyPath, #options: options, }, ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); @override _i6.Future<void> removeObserver( _i2.NSObject? observer, { required String? keyPath, }) => (super.noSuchMethod( Invocation.method( #removeObserver, [observer], {#keyPath: keyPath}, ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); } /// A class which mocks [WKWebViewConfiguration]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable class MockWKWebViewConfiguration extends _i1.Mock implements _i5.WKWebViewConfiguration { MockWKWebViewConfiguration() { _i1.throwOnMissingStub(this); } @override _i5.WKUserContentController get userContentController => (super.noSuchMethod( Invocation.getter(#userContentController), returnValue: _FakeWKUserContentController_5( this, Invocation.getter(#userContentController), ), ) as _i5.WKUserContentController); @override _i5.WKPreferences get preferences => (super.noSuchMethod( Invocation.getter(#preferences), returnValue: _FakeWKPreferences_4( this, Invocation.getter(#preferences), ), ) as _i5.WKPreferences); @override _i5.WKWebsiteDataStore get websiteDataStore => (super.noSuchMethod( Invocation.getter(#websiteDataStore), returnValue: _FakeWKWebsiteDataStore_7( this, Invocation.getter(#websiteDataStore), ), ) as _i5.WKWebsiteDataStore); @override _i6.Future<void> setAllowsInlineMediaPlayback(bool? allow) => (super.noSuchMethod( Invocation.method( #setAllowsInlineMediaPlayback, [allow], ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); @override _i6.Future<void> setLimitsNavigationsToAppBoundDomains(bool? limit) => (super.noSuchMethod( Invocation.method( #setLimitsNavigationsToAppBoundDomains, [limit], ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); @override _i6.Future<void> setMediaTypesRequiringUserActionForPlayback( Set<_i5.WKAudiovisualMediaType>? types) => (super.noSuchMethod( Invocation.method( #setMediaTypesRequiringUserActionForPlayback, [types], ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); @override _i5.WKWebViewConfiguration copy() => (super.noSuchMethod( Invocation.method( #copy, [], ), returnValue: _FakeWKWebViewConfiguration_8( this, Invocation.method( #copy, [], ), ), ) as _i5.WKWebViewConfiguration); @override _i6.Future<void> addObserver( _i2.NSObject? observer, { required String? keyPath, required Set<_i2.NSKeyValueObservingOptions>? options, }) => (super.noSuchMethod( Invocation.method( #addObserver, [observer], { #keyPath: keyPath, #options: options, }, ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); @override _i6.Future<void> removeObserver( _i2.NSObject? observer, { required String? keyPath, }) => (super.noSuchMethod( Invocation.method( #removeObserver, [observer], {#keyPath: keyPath}, ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); } /// A class which mocks [WKScriptMessageHandler]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable class MockWKScriptMessageHandler extends _i1.Mock implements _i5.WKScriptMessageHandler { MockWKScriptMessageHandler() { _i1.throwOnMissingStub(this); } @override void Function( _i5.WKUserContentController, _i5.WKScriptMessage, ) get didReceiveScriptMessage => (super.noSuchMethod( Invocation.getter(#didReceiveScriptMessage), returnValue: ( _i5.WKUserContentController userContentController, _i5.WKScriptMessage message, ) {}, ) as void Function( _i5.WKUserContentController, _i5.WKScriptMessage, )); @override _i5.WKScriptMessageHandler copy() => (super.noSuchMethod( Invocation.method( #copy, [], ), returnValue: _FakeWKScriptMessageHandler_10( this, Invocation.method( #copy, [], ), ), ) as _i5.WKScriptMessageHandler); @override _i6.Future<void> addObserver( _i2.NSObject? observer, { required String? keyPath, required Set<_i2.NSKeyValueObservingOptions>? options, }) => (super.noSuchMethod( Invocation.method( #addObserver, [observer], { #keyPath: keyPath, #options: options, }, ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); @override _i6.Future<void> removeObserver( _i2.NSObject? observer, { required String? keyPath, }) => (super.noSuchMethod( Invocation.method( #removeObserver, [observer], {#keyPath: keyPath}, ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); }
packages/packages/webview_flutter/webview_flutter_wkwebview/test/webkit_webview_controller_test.mocks.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/test/webkit_webview_controller_test.mocks.dart", "repo_id": "packages", "token_count": 14843 }
1,020
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // ignore_for_file: public_member_api_docs import 'dart:io'; import 'package:flutter/material.dart'; import 'package:xdg_directories/xdg_directories.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( title: 'XDG Directories Demo', home: MyHomePage(title: 'XDG Directories Demo'), color: Colors.blue, ); } } class MyHomePage extends StatefulWidget { const MyHomePage({super.key, required this.title}); final String title; @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { final Set<String> userDirectoryNames = getUserDirectoryNames(); String selectedUserDirectory = ''; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: ListView( padding: const EdgeInsets.only(left: 20), shrinkWrap: true, children: <Widget>[ const SizedBox( height: 20, ), ListView.builder( shrinkWrap: true, itemCount: userDirectoryNames.length, itemBuilder: (BuildContext context, int index) => Text( '${userDirectoryNames.elementAt(index)}: \n${getUserDirectory(userDirectoryNames.elementAt(index))?.path}\n', ), ), Text('Data Home: \n${dataHome.path}\n'), Text('Config Home: \n${configHome.path}\n'), Text( 'Data Directories: \n${dataDirs.map((Directory directory) => directory.path).toList().join('\n')}\n'), Text( 'Config Directories: \n${configDirs.map((Directory directory) => directory.path).toList().join('\n')}\n'), Text('Cache Home: \n${cacheHome.path}\n'), Text('Runtime Directory: \n${runtimeDir?.path}\n'), const SizedBox( height: 100, ), ], ), ), ); } }
packages/packages/xdg_directories/example/lib/main.dart/0
{ "file_path": "packages/packages/xdg_directories/example/lib/main.dart", "repo_id": "packages", "token_count": 991 }
1,021
# Packages that deliberately use their own analysis_options.yaml. # # Please consult with #hackers-ecosystem before adding anything to this list, # as the goal is to have consistent analysis options across all packages. # # All entries here shoud include a comment explaining why they use different # options. # DO NOT move or delete this file without updating # https://github.com/dart-lang/sdk/blob/main/tools/bots/flutter/analyze_flutter_packages.sh # and # https://github.com/flutter/flutter/blob/main/dev/bots/test.dart # which reference this file from source, but out-of-repo. # Contact stuartmorgan or devoncarew for assistance if necessary. # Opts out of unawaited_futures, matching flutter/flutter's disabling due # to interactions with animation. - animations # Deliberately uses flutter_lints, as that's what it is demonstrating. - flutter_lints/example # Adopts some flutter_tools rules regarding public api docs due to being an # extension of the tool and using tools base code. - flutter_migrate # Has some test files that are intentionally broken to conduct dart fix tests. # Also opts out of unawaited_futures, matching flutter/flutter. - go_router # Has some constructions that are currently handled poorly by dart format. - rfw/example # Disables docs requirements, as it is test code. - web_benchmarks/testing/test_app
packages/script/configs/custom_analysis.yaml/0
{ "file_path": "packages/script/configs/custom_analysis.yaml", "repo_id": "packages", "token_count": 375 }
1,022
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io' as io; import 'package:platform/platform.dart'; import 'process_runner.dart'; import 'repository_package.dart'; /// Runs either `dart pub get` or `flutter pub get` in [package], depending on /// the package type. /// /// If [alwaysUseFlutter] is true, it will use `flutter pub get` regardless. /// This can be useful, for instance, to get the `flutter`-default behavior /// of fetching example packages as well. /// /// If [streamOutput] is false, output will only be printed if the command /// fails. Future<bool> runPubGet( RepositoryPackage package, ProcessRunner processRunner, Platform platform, {bool alwaysUseFlutter = false, bool streamOutput = true}) async { // Running `dart pub get` on a Flutter package can fail if a non-Flutter Dart // is first in the path, so use `flutter pub get` for any Flutter package. final bool useFlutter = alwaysUseFlutter || package.requiresFlutter(); final String command = useFlutter ? (platform.isWindows ? 'flutter.bat' : 'flutter') : 'dart'; final List<String> args = <String>['pub', 'get']; final int exitCode; if (streamOutput) { exitCode = await processRunner.runAndStream(command, args, workingDir: package.directory); } else { final io.ProcessResult result = await processRunner.run(command, args, workingDir: package.directory); exitCode = result.exitCode; if (exitCode != 0) { print('${result.stdout}\n${result.stderr}\n'); } } return exitCode == 0; }
packages/script/tool/lib/src/common/pub_utils.dart/0
{ "file_path": "packages/script/tool/lib/src/common/pub_utils.dart", "repo_id": "packages", "token_count": 524 }
1,023
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'common/core.dart'; import 'common/gradle.dart'; import 'common/output_utils.dart'; import 'common/package_looping_command.dart'; import 'common/plugin_utils.dart'; import 'common/repository_package.dart'; /// Run 'gradlew lint'. /// /// See https://developer.android.com/studio/write/lint. class LintAndroidCommand extends PackageLoopingCommand { /// Creates an instance of the linter command. LintAndroidCommand( super.packagesDir, { super.processRunner, super.platform, }); @override final String name = 'lint-android'; @override final String description = 'Runs "gradlew lint" on Android plugins.\n\n' 'Requires the examples to have been build at least once before running.'; @override Future<PackageResult> runForPackage(RepositoryPackage package) async { if (!pluginSupportsPlatform(platformAndroid, package, requiredMode: PlatformSupport.inline)) { return PackageResult.skip( 'Plugin does not have an Android implementation.'); } for (final RepositoryPackage example in package.getExamples()) { final GradleProject project = GradleProject(example, processRunner: processRunner, platform: platform); if (!project.isConfigured()) { final int exitCode = await processRunner.runAndStream( flutterCommand, <String>['build', 'apk', '--config-only'], workingDir: example.directory, ); if (exitCode != 0) { printError('Unable to configure Gradle project.'); return PackageResult.fail(<String>['Unable to configure Gradle.']); } } final String packageName = package.directory.basename; // Only lint one build mode to avoid extra work. // Only lint the plugin project itself, to avoid failing due to errors in // dependencies. // // TODO(stuartmorgan): Consider adding an XML parser to read and summarize // all results. Currently, only the first three errors will be shown // inline, and the rest have to be checked via the CI-uploaded artifact. final int exitCode = await project.runCommand('$packageName:lintDebug'); if (exitCode != 0) { return PackageResult.fail(); } } return PackageResult.success(); } }
packages/script/tool/lib/src/lint_android_command.dart/0
{ "file_path": "packages/script/tool/lib/src/lint_android_command.dart", "repo_id": "packages", "token_count": 835 }
1,024
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:file/file.dart'; import 'package:http/http.dart' as http; import 'package:meta/meta.dart'; import 'package:path/path.dart' as p; import 'package:pub_semver/pub_semver.dart'; import 'common/git_version_finder.dart'; import 'common/output_utils.dart'; import 'common/package_looping_command.dart'; import 'common/package_state_utils.dart'; import 'common/pub_version_finder.dart'; import 'common/repository_package.dart'; /// Categories of version change types. enum NextVersionType { /// A breaking change. BREAKING_MAJOR, /// A minor change (e.g., added feature). MINOR, /// A bugfix change. PATCH, /// The release of an existing pre-1.0 version. V1_RELEASE, } /// The state of a package's version relative to the comparison base. enum _CurrentVersionState { /// The version is unchanged. unchanged, /// The version has increased, and the transition is valid. validIncrease, /// The version has decrease, and the transition is a valid revert. validRevert, /// The version has changed, and the transition is invalid. invalidChange, /// The package is new. newPackage, /// There was an error determining the version state. unknown, } /// Returns the set of allowed next non-prerelease versions, with their change /// type, for [version]. /// /// [newVersion] is used to check whether this is a pre-1.0 version bump, as /// those have different semver rules. @visibleForTesting Map<Version, NextVersionType> getAllowedNextVersions( Version version, { required Version newVersion, }) { final Map<Version, NextVersionType> allowedNextVersions = <Version, NextVersionType>{ version.nextMajor: NextVersionType.BREAKING_MAJOR, version.nextMinor: NextVersionType.MINOR, version.nextPatch: NextVersionType.PATCH, }; if (version.major < 1 && newVersion.major < 1) { int nextBuildNumber = -1; if (version.build.isEmpty) { nextBuildNumber = 1; } else { final int currentBuildNumber = version.build.first as int; nextBuildNumber = currentBuildNumber + 1; } final Version nextBuildVersion = Version( version.major, version.minor, version.patch, build: nextBuildNumber.toString(), ); allowedNextVersions.clear(); allowedNextVersions[version.nextMajor] = NextVersionType.V1_RELEASE; allowedNextVersions[version.nextMinor] = NextVersionType.BREAKING_MAJOR; allowedNextVersions[version.nextPatch] = NextVersionType.MINOR; allowedNextVersions[nextBuildVersion] = NextVersionType.PATCH; } return allowedNextVersions; } /// A command to validate version changes to packages. class VersionCheckCommand extends PackageLoopingCommand { /// Creates an instance of the version check command. VersionCheckCommand( super.packagesDir, { super.processRunner, super.platform, super.gitDir, http.Client? httpClient, }) : _pubVersionFinder = PubVersionFinder(httpClient: httpClient ?? http.Client()) { argParser.addFlag( _againstPubFlag, help: 'Whether the version check should run against the version on pub.\n' 'Defaults to false, which means the version check only run against ' 'the previous version in code.', ); argParser.addOption(_prLabelsArg, help: 'A comma-separated list of labels associated with this PR, ' 'if applicable.\n\n' 'If supplied, this may be to allow overrides to some version ' 'checks.'); argParser.addFlag(_checkForMissingChanges, help: 'Validates that changes to packages include CHANGELOG and ' 'version changes unless they meet an established exemption.\n\n' 'If used with --$_prLabelsArg, this is should only be ' 'used in pre-submit CI checks, to prevent post-submit breakage ' 'when labels are no longer applicable.', hide: true); argParser.addFlag(_ignorePlatformInterfaceBreaks, help: 'Bypasses the check that platform interfaces do not contain ' 'breaking changes.\n\n' 'This is only intended for use in post-submit CI checks, to ' 'prevent post-submit breakage when overriding the check with ' 'labels. Pre-submit checks should always use ' '--$_prLabelsArg instead.', hide: true); } static const String _againstPubFlag = 'against-pub'; static const String _prLabelsArg = 'pr-labels'; static const String _checkForMissingChanges = 'check-for-missing-changes'; static const String _ignorePlatformInterfaceBreaks = 'ignore-platform-interface-breaks'; /// The label that must be on a PR to allow a breaking /// change to a platform interface. static const String _breakingChangeOverrideLabel = 'override: allow breaking change'; /// The label that must be on a PR to allow skipping a version change for a PR /// that would normally require one. static const String _missingVersionChangeOverrideLabel = 'override: no versioning needed'; /// The label that must be on a PR to allow skipping a CHANGELOG change for a /// PR that would normally require one. static const String _missingChangelogChangeOverrideLabel = 'override: no changelog needed'; final PubVersionFinder _pubVersionFinder; late final GitVersionFinder _gitVersionFinder; late final String _mergeBase; late final List<String> _changedFiles; late final Set<String> _prLabels = _getPRLabels(); @override final String name = 'version-check'; @override List<String> get aliases => <String>['check-version']; @override final String description = 'Checks if the versions of packages have been incremented per pub specification.\n' 'Also checks if the latest version in CHANGELOG matches the version in pubspec.\n\n' 'This command requires "pub" and "flutter" to be in your path.'; @override bool get hasLongOutput => false; @override Future<void> initializeRun() async { _gitVersionFinder = await retrieveVersionFinder(); _mergeBase = await _gitVersionFinder.getBaseSha(); _changedFiles = await _gitVersionFinder.getChangedFiles(); } @override Future<PackageResult> runForPackage(RepositoryPackage package) async { final Pubspec? pubspec = _tryParsePubspec(package); if (pubspec == null) { // No remaining checks make sense, so fail immediately. return PackageResult.fail(<String>['Invalid pubspec.yaml.']); } if (pubspec.publishTo == 'none') { return PackageResult.skip('Found "publish_to: none".'); } final Version? currentPubspecVersion = pubspec.version; if (currentPubspecVersion == null) { printError('${indentation}No version found in pubspec.yaml. A package ' 'that intentionally has no version should be marked ' '"publish_to: none".'); // No remaining checks make sense, so fail immediately. return PackageResult.fail(<String>['No pubspec.yaml version.']); } final List<String> errors = <String>[]; bool versionChanged; final _CurrentVersionState versionState = await _getVersionState(package, pubspec: pubspec); switch (versionState) { case _CurrentVersionState.unchanged: versionChanged = false; case _CurrentVersionState.validIncrease: case _CurrentVersionState.validRevert: case _CurrentVersionState.newPackage: versionChanged = true; case _CurrentVersionState.invalidChange: versionChanged = true; errors.add('Disallowed version change.'); case _CurrentVersionState.unknown: versionChanged = false; errors.add('Unable to determine previous version.'); } if (!(await _validateChangelogVersion(package, pubspec: pubspec, pubspecVersionState: versionState))) { errors.add('CHANGELOG.md failed validation.'); } // If there are no other issues, make sure that there isn't a missing // change to the version and/or CHANGELOG. if (getBoolArg(_checkForMissingChanges) && !versionChanged && errors.isEmpty) { final String? error = await _checkForMissingChangeError(package); if (error != null) { errors.add(error); } } return errors.isEmpty ? PackageResult.success() : PackageResult.fail(errors); } @override Future<void> completeRun() async { _pubVersionFinder.httpClient.close(); } /// Returns the previous published version of [package]. /// /// [packageName] must be the actual name of the package as published (i.e., /// the name from pubspec.yaml, not the on disk name if different.) Future<Version?> _fetchPreviousVersionFromPub(String packageName) async { final PubVersionFinderResponse pubVersionFinderResponse = await _pubVersionFinder.getPackageVersion(packageName: packageName); switch (pubVersionFinderResponse.result) { case PubVersionFinderResult.success: return pubVersionFinderResponse.versions.first; case PubVersionFinderResult.fail: printError(''' ${indentation}Error fetching version on pub for $packageName. ${indentation}HTTP Status ${pubVersionFinderResponse.httpResponse.statusCode} ${indentation}HTTP response: ${pubVersionFinderResponse.httpResponse.body} '''); return null; case PubVersionFinderResult.noPackageFound: return Version.none; } } /// Returns the version of [package] from git at the base comparison hash. Future<Version?> _getPreviousVersionFromGit(RepositoryPackage package) async { final File pubspecFile = package.pubspecFile; final String relativePath = path.relative(pubspecFile.absolute.path, from: (await gitDir).path); // Use Posix-style paths for git. final String gitPath = path.style == p.Style.windows ? p.posix.joinAll(path.split(relativePath)) : relativePath; return _gitVersionFinder.getPackageVersion(gitPath, gitRef: _mergeBase); } /// Returns the state of the verison of [package] relative to the comparison /// base (git or pub, depending on flags). Future<_CurrentVersionState> _getVersionState( RepositoryPackage package, { required Pubspec pubspec, }) async { // This method isn't called unless `version` is non-null. final Version currentVersion = pubspec.version!; Version? previousVersion; String previousVersionSource; if (getBoolArg(_againstPubFlag)) { previousVersionSource = 'pub'; previousVersion = await _fetchPreviousVersionFromPub(pubspec.name); if (previousVersion == null) { return _CurrentVersionState.unknown; } if (previousVersion != Version.none) { print( '$indentation${pubspec.name}: Current largest version on pub: $previousVersion'); } } else { previousVersionSource = _mergeBase; previousVersion = await _getPreviousVersionFromGit(package) ?? Version.none; } if (previousVersion == Version.none) { print('${indentation}Unable to find previous version ' '${getBoolArg(_againstPubFlag) ? 'on pub server' : 'at git base'}.'); logWarning( '${indentation}If this package is not new, something has gone wrong.'); return _CurrentVersionState.newPackage; } if (previousVersion == currentVersion) { print('${indentation}No version change.'); return _CurrentVersionState.unchanged; } // Check for reverts when doing local validation. if (!getBoolArg(_againstPubFlag) && currentVersion < previousVersion) { // Since this skips validation, try to ensure that it really is likely // to be a revert rather than a typo by checking that the transition // from the lower version to the new version would have been valid. if (_shouldAllowVersionChange( oldVersion: currentVersion, newVersion: previousVersion)) { logWarning('${indentation}New version is lower than previous version. ' 'This is assumed to be a revert.'); return _CurrentVersionState.validRevert; } } final Map<Version, NextVersionType> allowedNextVersions = getAllowedNextVersions(previousVersion, newVersion: currentVersion); if (_shouldAllowVersionChange( oldVersion: previousVersion, newVersion: currentVersion)) { print('$indentation$previousVersion -> $currentVersion'); } else { printError('${indentation}Incorrectly updated version.\n' '${indentation}HEAD: $currentVersion, $previousVersionSource: $previousVersion.\n' '${indentation}Allowed versions: $allowedNextVersions'); return _CurrentVersionState.invalidChange; } // Check whether the version (or for a pre-release, the version that // pre-release would eventually be released as) is a breaking change, and // if so, validate it. final Version targetReleaseVersion = currentVersion.isPreRelease ? currentVersion.nextPatch : currentVersion; if (allowedNextVersions[targetReleaseVersion] == NextVersionType.BREAKING_MAJOR && !_validateBreakingChange(package)) { printError('${indentation}Breaking change detected.\n' '${indentation}Breaking changes to platform interfaces are not ' 'allowed without explicit justification.\n' '${indentation}See ' 'https://github.com/flutter/flutter/wiki/Contributing-to-Plugins-and-Packages ' 'for more information.'); return _CurrentVersionState.invalidChange; } return _CurrentVersionState.validIncrease; } /// Checks whether or not [package]'s CHANGELOG's versioning is correct, /// both that it matches [pubspec] and that NEXT is used correctly, printing /// the results of its checks. /// /// Returns false if the CHANGELOG fails validation. Future<bool> _validateChangelogVersion( RepositoryPackage package, { required Pubspec pubspec, required _CurrentVersionState pubspecVersionState, }) async { // This method isn't called unless `version` is non-null. final Version fromPubspec = pubspec.version!; // get first version from CHANGELOG final File changelog = package.changelogFile; final List<String> lines = changelog.readAsLinesSync(); String? firstLineWithText; final Iterator<String> iterator = lines.iterator; while (iterator.moveNext()) { if (iterator.current.trim().isNotEmpty) { firstLineWithText = iterator.current.trim(); break; } } // Remove all leading mark down syntax from the version line. String? versionString = firstLineWithText?.split(' ').last; final String badNextErrorMessage = '${indentation}When bumping the version ' 'for release, the NEXT section should be incorporated into the new ' "version's release notes."; // Skip validation for the special NEXT version that's used to accumulate // changes that don't warrant publishing on their own. final bool hasNextSection = versionString == 'NEXT'; if (hasNextSection) { // NEXT should not be present in a commit that increases the version. if (pubspecVersionState == _CurrentVersionState.validIncrease || pubspecVersionState == _CurrentVersionState.invalidChange) { printError(badNextErrorMessage); return false; } print( '${indentation}Found NEXT; validating next version in the CHANGELOG.'); // Ensure that the version in pubspec hasn't changed without updating // CHANGELOG. That means the next version entry in the CHANGELOG should // pass the normal validation. versionString = null; while (iterator.moveNext()) { if (iterator.current.trim().startsWith('## ')) { versionString = iterator.current.trim().split(' ').last; break; } } } if (versionString == null) { printError('${indentation}Unable to find a version in CHANGELOG.md'); print('${indentation}The current version should be on a line starting ' 'with "## ", either on the first non-empty line or after a "## NEXT" ' 'section.'); return false; } final Version fromChangeLog; try { fromChangeLog = Version.parse(versionString); } on FormatException { printError('"$versionString" could not be parsed as a version.'); return false; } if (fromPubspec != fromChangeLog) { printError(''' ${indentation}Versions in CHANGELOG.md and pubspec.yaml do not match. ${indentation}The version in pubspec.yaml is $fromPubspec. ${indentation}The first version listed in CHANGELOG.md is $fromChangeLog. '''); return false; } // If NEXT wasn't the first section, it should not exist at all. if (!hasNextSection) { final RegExp nextRegex = RegExp(r'^#+\s*NEXT\s*$'); if (lines.any((String line) => nextRegex.hasMatch(line))) { printError(badNextErrorMessage); return false; } } return true; } Pubspec? _tryParsePubspec(RepositoryPackage package) { try { final Pubspec pubspec = package.parsePubspec(); return pubspec; } on Exception catch (exception) { printError('${indentation}Failed to parse `pubspec.yaml`: $exception}'); return null; } } /// Checks whether the current breaking change to [package] should be allowed, /// logging extra information for auditing when allowing unusual cases. bool _validateBreakingChange(RepositoryPackage package) { // Only platform interfaces have breaking change restrictions. if (!package.isPlatformInterface) { return true; } if (getBoolArg(_ignorePlatformInterfaceBreaks)) { logWarning( '${indentation}Allowing breaking change to ${package.displayName} ' 'due to --$_ignorePlatformInterfaceBreaks'); return true; } if (_prLabels.contains(_breakingChangeOverrideLabel)) { logWarning( '${indentation}Allowing breaking change to ${package.displayName} ' 'due to the "$_breakingChangeOverrideLabel" label.'); return true; } return false; } /// Returns the labels associated with this PR, if any, or an empty set /// if that flag is not provided. Set<String> _getPRLabels() { final String labels = getStringArg(_prLabelsArg); if (labels.isEmpty) { return <String>{}; } return labels.split(',').map((String label) => label.trim()).toSet(); } /// Returns true if the given version transition should be allowed. bool _shouldAllowVersionChange( {required Version oldVersion, required Version newVersion}) { // Get the non-pre-release next version mapping. final Map<Version, NextVersionType> allowedNextVersions = getAllowedNextVersions(oldVersion, newVersion: newVersion); if (allowedNextVersions.containsKey(newVersion)) { return true; } // Allow a pre-release version of a version that would be a valid // transition. if (newVersion.isPreRelease) { final Version targetReleaseVersion = newVersion.nextPatch; if (allowedNextVersions.containsKey(targetReleaseVersion)) { return true; } } return false; } /// Returns an error string if the changes to this package should have /// resulted in a version change, or shoud have resulted in a CHANGELOG change /// but didn't. /// /// This should only be called if the version did not change. Future<String?> _checkForMissingChangeError(RepositoryPackage package) async { // Find the relative path to the current package, as it would appear at the // beginning of a path reported by getChangedFiles() (which always uses // Posix paths). final Directory gitRoot = packagesDir.fileSystem.directory((await gitDir).path); final String relativePackagePath = getRelativePosixPath(package.directory, from: gitRoot); final PackageChangeState state = await checkPackageChangeState(package, changedPaths: _changedFiles, relativePackagePath: relativePackagePath, git: await retrieveVersionFinder()); if (!state.hasChanges) { return null; } if (state.needsVersionChange) { if (_prLabels.contains(_missingVersionChangeOverrideLabel)) { logWarning('Ignoring lack of version change due to the ' '"$_missingVersionChangeOverrideLabel" label.'); } else { printError( 'No version change found, but the change to this package could ' 'not be verified to be exempt\n' 'from version changes according to repository policy.\n' 'If this is a false positive, please comment in ' 'the PR to explain why the PR\n' 'is exempt, and add (or ask your reviewer to add) the ' '"$_missingVersionChangeOverrideLabel" label.'); return 'Missing version change'; } } if (!state.hasChangelogChange && state.needsChangelogChange) { if (_prLabels.contains(_missingChangelogChangeOverrideLabel)) { logWarning('Ignoring lack of CHANGELOG update due to the ' '"$_missingChangelogChangeOverrideLabel" label.'); } else { printError('No CHANGELOG change found.\n' 'If this PR needs an exemption from the standard policy of listing ' 'all changes in the CHANGELOG,\n' 'comment in the PR to explain why the PR is exempt, and add (or ' 'ask your reviewer to add) the\n' '"$_missingChangelogChangeOverrideLabel" label.\n' 'Otherwise, please add a NEXT entry in the CHANGELOG as described in ' 'the contributing guide.'); return 'Missing CHANGELOG change'; } } return null; } }
packages/script/tool/lib/src/version_check_command.dart/0
{ "file_path": "packages/script/tool/lib/src/version_check_command.dart", "repo_id": "packages", "token_count": 7551 }
1,025
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:file/file.dart'; import 'package:file/memory.dart'; import 'package:pubspec_parse/pubspec_parse.dart'; import 'package:test/test.dart'; import '../util.dart'; void main() { late FileSystem fileSystem; late Directory packagesDir; setUp(() { fileSystem = MemoryFileSystem(); packagesDir = createPackagesDirectory(fileSystem: fileSystem); }); group('displayName', () { test('prints packageDir-relative paths by default', () async { expect( RepositoryPackage(packagesDir.childDirectory('foo')).displayName, 'foo', ); expect( RepositoryPackage(packagesDir .childDirectory('foo') .childDirectory('bar') .childDirectory('baz')) .displayName, 'foo/bar/baz', ); }); test('handles third_party/packages/', () async { expect( RepositoryPackage(packagesDir.parent .childDirectory('third_party') .childDirectory('packages') .childDirectory('foo') .childDirectory('bar') .childDirectory('baz')) .displayName, 'foo/bar/baz', ); }); test('always uses Posix-style paths', () async { final Directory windowsPackagesDir = createPackagesDirectory( fileSystem: MemoryFileSystem(style: FileSystemStyle.windows)); expect( RepositoryPackage(windowsPackagesDir.childDirectory('foo')).displayName, 'foo', ); expect( RepositoryPackage(windowsPackagesDir .childDirectory('foo') .childDirectory('bar') .childDirectory('baz')) .displayName, 'foo/bar/baz', ); }); test('elides group name in grouped federated plugin structure', () async { expect( RepositoryPackage(packagesDir .childDirectory('a_plugin') .childDirectory('a_plugin_platform_interface')) .displayName, 'a_plugin_platform_interface', ); expect( RepositoryPackage(packagesDir .childDirectory('a_plugin') .childDirectory('a_plugin_platform_web')) .displayName, 'a_plugin_platform_web', ); }); // The app-facing package doesn't get elided to avoid potential confusion // with the group folder itself. test('does not elide group name for app-facing packages', () async { expect( RepositoryPackage(packagesDir .childDirectory('a_plugin') .childDirectory('a_plugin')) .displayName, 'a_plugin/a_plugin', ); }); }); group('getExamples', () { test('handles a single Flutter example', () async { final RepositoryPackage plugin = createFakePlugin('a_plugin', packagesDir); final List<RepositoryPackage> examples = plugin.getExamples().toList(); expect(examples.length, 1); expect(examples[0].isExample, isTrue); expect(examples[0].path, getExampleDir(plugin).path); }); test('handles multiple Flutter examples', () async { final RepositoryPackage plugin = createFakePlugin('a_plugin', packagesDir, examples: <String>['example1', 'example2']); final List<RepositoryPackage> examples = plugin.getExamples().toList(); expect(examples.length, 2); expect(examples[0].isExample, isTrue); expect(examples[1].isExample, isTrue); expect(examples[0].path, getExampleDir(plugin).childDirectory('example1').path); expect(examples[1].path, getExampleDir(plugin).childDirectory('example2').path); }); test('handles a single non-Flutter example', () async { final RepositoryPackage package = createFakePackage('a_package', packagesDir); final List<RepositoryPackage> examples = package.getExamples().toList(); expect(examples.length, 1); expect(examples[0].isExample, isTrue); expect(examples[0].path, getExampleDir(package).path); }); test('handles multiple non-Flutter examples', () async { final RepositoryPackage package = createFakePackage( 'a_package', packagesDir, examples: <String>['example1', 'example2']); final List<RepositoryPackage> examples = package.getExamples().toList(); expect(examples.length, 2); expect(examples[0].isExample, isTrue); expect(examples[1].isExample, isTrue); expect(examples[0].path, getExampleDir(package).childDirectory('example1').path); expect(examples[1].path, getExampleDir(package).childDirectory('example2').path); }); }); group('federated plugin queries', () { test('all return false for a simple plugin', () { final RepositoryPackage plugin = createFakePlugin('a_plugin', packagesDir); expect(plugin.isFederated, false); expect(plugin.isAppFacing, false); expect(plugin.isPlatformInterface, false); expect(plugin.isFederated, false); expect(plugin.isExample, isFalse); }); test('handle app-facing packages', () { final RepositoryPackage plugin = createFakePlugin('a_plugin', packagesDir.childDirectory('a_plugin')); expect(plugin.isFederated, true); expect(plugin.isAppFacing, true); expect(plugin.isPlatformInterface, false); expect(plugin.isPlatformImplementation, false); expect(plugin.isExample, isFalse); }); test('handle platform interface packages', () { final RepositoryPackage plugin = createFakePlugin( 'a_plugin_platform_interface', packagesDir.childDirectory('a_plugin')); expect(plugin.isFederated, true); expect(plugin.isAppFacing, false); expect(plugin.isPlatformInterface, true); expect(plugin.isPlatformImplementation, false); expect(plugin.isExample, isFalse); }); test('handle platform implementation packages', () { // A platform interface can end with anything, not just one of the known // platform names, because of cases like webview_flutter_wkwebview. final RepositoryPackage plugin = createFakePlugin( 'a_plugin_foo', packagesDir.childDirectory('a_plugin')); expect(plugin.isFederated, true); expect(plugin.isAppFacing, false); expect(plugin.isPlatformInterface, false); expect(plugin.isPlatformImplementation, true); expect(plugin.isExample, isFalse); }); }); group('pubspec', () { test('file', () async { final RepositoryPackage plugin = createFakePlugin('a_plugin', packagesDir); final File pubspecFile = plugin.pubspecFile; expect(pubspecFile.path, plugin.directory.childFile('pubspec.yaml').path); }); test('parsing', () async { final RepositoryPackage plugin = createFakePlugin('a_plugin', packagesDir, examples: <String>['example1', 'example2']); final Pubspec pubspec = plugin.parsePubspec(); expect(pubspec.name, 'a_plugin'); }); }); group('requiresFlutter', () { test('returns true for Flutter package', () async { final RepositoryPackage package = createFakePackage('a_package', packagesDir, isFlutter: true); expect(package.requiresFlutter(), true); }); test('returns true for a dev dependency on Flutter', () async { final RepositoryPackage package = createFakePackage('a_package', packagesDir); final File pubspecFile = package.pubspecFile; final Pubspec pubspec = package.parsePubspec(); pubspec.devDependencies['flutter'] = SdkDependency('flutter'); pubspecFile.writeAsStringSync(pubspec.toString()); expect(package.requiresFlutter(), true); }); test('returns false for non-Flutter package', () async { final RepositoryPackage package = createFakePackage('a_package', packagesDir); expect(package.requiresFlutter(), false); }); }); }
packages/script/tool/test/common/repository_package_test.dart/0
{ "file_path": "packages/script/tool/test/common/repository_package_test.dart", "repo_id": "packages", "token_count": 3165 }
1,026
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:args/command_runner.dart'; import 'package:file/file.dart'; import 'package:file/memory.dart'; import 'package:flutter_plugin_tools/src/make_deps_path_based_command.dart'; import 'package:mockito/mockito.dart'; import 'package:pubspec_parse/pubspec_parse.dart'; import 'package:test/test.dart'; import 'common/package_command_test.mocks.dart'; import 'mocks.dart'; import 'util.dart'; void main() { FileSystem fileSystem; late Directory packagesDir; late Directory thirdPartyPackagesDir; late CommandRunner<void> runner; late RecordingProcessRunner processRunner; setUp(() { fileSystem = MemoryFileSystem(); packagesDir = createPackagesDirectory(fileSystem: fileSystem); thirdPartyPackagesDir = packagesDir.parent .childDirectory('third_party') .childDirectory('packages'); 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 MakeDepsPathBasedCommand command = MakeDepsPathBasedCommand(packagesDir, gitDir: gitDir); runner = CommandRunner<void>( 'make-deps-path-based_command', 'Test for $MakeDepsPathBasedCommand'); runner.addCommand(command); }); /// Adds dummy 'dependencies:' entries for each package in [dependencies] /// to [package]. void addDependencies(RepositoryPackage package, Iterable<String> dependencies, {String constraint = '<2.0.0'}) { final List<String> lines = package.pubspecFile.readAsLinesSync(); final int dependenciesStartIndex = lines.indexOf('dependencies:'); assert(dependenciesStartIndex != -1); lines.insertAll(dependenciesStartIndex + 1, <String>[ for (final String dependency in dependencies) ' $dependency: $constraint', ]); package.pubspecFile.writeAsStringSync(lines.join('\n')); } /// Adds a 'dev_dependencies:' section with entries for each package in /// [dependencies] to [package]. void addDevDependenciesSection( RepositoryPackage package, Iterable<String> devDependencies, {String constraint = '<2.0.0'}) { final String originalContent = package.pubspecFile.readAsStringSync(); package.pubspecFile.writeAsStringSync(''' $originalContent dev_dependencies: ${devDependencies.map((String dep) => ' $dep: $constraint').join('\n')} '''); } Map<String, String> getDependencyOverrides(RepositoryPackage package) { final Pubspec pubspec = package.parsePubspec(); return pubspec.dependencyOverrides.map((String name, Dependency dep) => MapEntry<String, String>( name, (dep is PathDependency) ? dep.path : dep.toString())); } test('no-ops for no plugins', () async { createFakePackage('foo', packagesDir, isFlutter: true); final RepositoryPackage packageBar = createFakePackage('bar', packagesDir, isFlutter: true); addDependencies(packageBar, <String>['foo']); final String originalPubspecContents = packageBar.pubspecFile.readAsStringSync(); final List<String> output = await runCapturingPrint(runner, <String>['make-deps-path-based']); expect( output, containsAllInOrder(<Matcher>[ contains('No target dependencies'), ]), ); // The 'foo' reference should not have been modified. expect(packageBar.pubspecFile.readAsStringSync(), originalPubspecContents); }); test('includes explanatory comment', () async { final RepositoryPackage packageA = createFakePackage('package_a', packagesDir, isFlutter: true); createFakePackage('package_b', packagesDir, isFlutter: true); addDependencies(packageA, <String>[ 'package_b', ]); await runCapturingPrint(runner, <String>['make-deps-path-based', '--target-dependencies=package_b']); expect( packageA.pubspecFile.readAsLinesSync(), containsAllInOrder(<String>[ '# FOR TESTING AND INITIAL REVIEW ONLY. DO NOT MERGE.', '# See https://github.com/flutter/flutter/wiki/Contributing-to-Plugins-and-Packages#changing-federated-plugins', 'dependency_overrides:', ])); }); test('rewrites "dependencies" references', () async { final RepositoryPackage simplePackage = createFakePackage('foo', packagesDir, isFlutter: true); final Directory pluginGroup = packagesDir.childDirectory('bar'); createFakePackage('bar_platform_interface', pluginGroup, isFlutter: true); final RepositoryPackage pluginImplementation = createFakePlugin('bar_android', pluginGroup); final RepositoryPackage pluginAppFacing = createFakePlugin('bar', pluginGroup); addDependencies(simplePackage, <String>[ 'bar', 'bar_android', 'bar_platform_interface', ]); addDependencies(pluginAppFacing, <String>[ 'bar_platform_interface', 'bar_android', ]); addDependencies(pluginImplementation, <String>[ 'bar_platform_interface', ]); final List<String> output = await runCapturingPrint(runner, <String>[ 'make-deps-path-based', '--target-dependencies=bar,bar_platform_interface' ]); expect( output, containsAll(<String>[ 'Rewriting references to: bar, bar_platform_interface...', ' Modified packages/bar/bar/pubspec.yaml', ' Modified packages/bar/bar_android/pubspec.yaml', ' Modified packages/foo/pubspec.yaml', ])); expect( output, isNot(contains( ' Modified packages/bar/bar_platform_interface/pubspec.yaml'))); final Map<String, String?> simplePackageOverrides = getDependencyOverrides(simplePackage); expect(simplePackageOverrides.length, 2); expect(simplePackageOverrides['bar'], '../bar/bar'); expect(simplePackageOverrides['bar_platform_interface'], '../bar/bar_platform_interface'); final Map<String, String?> appFacingPackageOverrides = getDependencyOverrides(pluginAppFacing); expect(appFacingPackageOverrides.length, 1); expect(appFacingPackageOverrides['bar_platform_interface'], '../../bar/bar_platform_interface'); }); test('rewrites "dev_dependencies" references', () async { createFakePackage('foo', packagesDir); final RepositoryPackage builderPackage = createFakePackage('foo_builder', packagesDir); addDevDependenciesSection(builderPackage, <String>[ 'foo', ]); final List<String> output = await runCapturingPrint( runner, <String>['make-deps-path-based', '--target-dependencies=foo']); expect( output, containsAll(<String>[ 'Rewriting references to: foo...', ' Modified packages/foo_builder/pubspec.yaml', ])); final Map<String, String?> overrides = getDependencyOverrides(builderPackage); expect(overrides.length, 1); expect(overrides['foo'], '../foo'); }); test('rewrites examples when rewriting the main package', () async { final Directory pluginGroup = packagesDir.childDirectory('bar'); createFakePackage('bar_platform_interface', pluginGroup, isFlutter: true); final RepositoryPackage pluginImplementation = createFakePlugin('bar_android', pluginGroup); final RepositoryPackage pluginAppFacing = createFakePlugin('bar', pluginGroup); addDependencies(pluginAppFacing, <String>[ 'bar_platform_interface', 'bar_android', ]); addDependencies(pluginImplementation, <String>[ 'bar_platform_interface', ]); await runCapturingPrint(runner, <String>['make-deps-path-based', '--target-dependencies=bar_android']); final Map<String, String?> exampleOverrides = getDependencyOverrides(pluginAppFacing.getExamples().first); expect(exampleOverrides.length, 1); expect(exampleOverrides['bar_android'], '../../../bar/bar_android'); }); test('example overrides include both local and main-package dependencies', () async { final Directory pluginGroup = packagesDir.childDirectory('bar'); createFakePackage('bar_platform_interface', pluginGroup, isFlutter: true); createFakePlugin('bar_android', pluginGroup); final RepositoryPackage pluginAppFacing = createFakePlugin('bar', pluginGroup); createFakePackage('another_package', packagesDir); addDependencies(pluginAppFacing, <String>[ 'bar_platform_interface', 'bar_android', ]); addDependencies(pluginAppFacing.getExamples().first, <String>[ 'another_package', ]); await runCapturingPrint(runner, <String>[ 'make-deps-path-based', '--target-dependencies=bar_android,another_package' ]); final Map<String, String?> exampleOverrides = getDependencyOverrides(pluginAppFacing.getExamples().first); expect(exampleOverrides.length, 2); expect(exampleOverrides['another_package'], '../../../another_package'); expect(exampleOverrides['bar_android'], '../../../bar/bar_android'); }); test( 'alphabetizes overrides from different sections to avoid lint warnings in analysis', () async { createFakePackage('a', packagesDir); createFakePackage('b', packagesDir); createFakePackage('c', packagesDir); final RepositoryPackage targetPackage = createFakePackage('target', packagesDir); addDependencies(targetPackage, <String>['a', 'c']); addDevDependenciesSection(targetPackage, <String>['b']); final List<String> output = await runCapturingPrint(runner, <String>['make-deps-path-based', '--target-dependencies=c,a,b']); expect( output, containsAllInOrder(<String>[ 'Rewriting references to: c, a, b...', ' Modified packages/target/pubspec.yaml', ])); // This matches with a regex in order to all for either flow style or // expanded style output. expect( targetPackage.pubspecFile.readAsStringSync(), matches(RegExp(r'dependency_overrides:.*a:.*b:.*c:.*', multiLine: true, dotAll: true))); }); test('finds third_party packages', () async { createFakePackage('bar', thirdPartyPackagesDir, isFlutter: true); final RepositoryPackage firstPartyPackge = createFakePlugin('foo', packagesDir); addDependencies(firstPartyPackge, <String>[ 'bar', ]); final List<String> output = await runCapturingPrint( runner, <String>['make-deps-path-based', '--target-dependencies=bar']); expect( output, containsAll(<String>[ 'Rewriting references to: bar...', ' Modified packages/foo/pubspec.yaml', ])); final Map<String, String?> simplePackageOverrides = getDependencyOverrides(firstPartyPackge); expect(simplePackageOverrides.length, 1); expect(simplePackageOverrides['bar'], '../../third_party/packages/bar'); }); // This test case ensures that running CI using this command on an interim // PR that itself used this command won't fail on the rewrite step. test('running a second time no-ops without failing', () async { final RepositoryPackage simplePackage = createFakePackage('foo', packagesDir, isFlutter: true); final Directory pluginGroup = packagesDir.childDirectory('bar'); createFakePackage('bar_platform_interface', pluginGroup, isFlutter: true); final RepositoryPackage pluginImplementation = createFakePlugin('bar_android', pluginGroup); final RepositoryPackage pluginAppFacing = createFakePlugin('bar', pluginGroup); addDependencies(simplePackage, <String>[ 'bar', 'bar_android', 'bar_platform_interface', ]); addDependencies(pluginAppFacing, <String>[ 'bar_platform_interface', 'bar_android', ]); addDependencies(pluginImplementation, <String>[ 'bar_platform_interface', ]); await runCapturingPrint(runner, <String>[ 'make-deps-path-based', '--target-dependencies=bar,bar_platform_interface' ]); final String simplePackageUpdatedContent = simplePackage.pubspecFile.readAsStringSync(); final String appFacingPackageUpdatedContent = pluginAppFacing.pubspecFile.readAsStringSync(); final String implementationPackageUpdatedContent = pluginImplementation.pubspecFile.readAsStringSync(); final List<String> output = await runCapturingPrint(runner, <String>[ 'make-deps-path-based', '--target-dependencies=bar,bar_platform_interface' ]); expect( output, containsAll(<String>[ 'Rewriting references to: bar, bar_platform_interface...', ' Modified packages/bar/bar/pubspec.yaml', ' Modified packages/bar/bar_android/pubspec.yaml', ' Modified packages/foo/pubspec.yaml', ])); expect(simplePackageUpdatedContent, simplePackage.pubspecFile.readAsStringSync()); expect(appFacingPackageUpdatedContent, pluginAppFacing.pubspecFile.readAsStringSync()); expect(implementationPackageUpdatedContent, pluginImplementation.pubspecFile.readAsStringSync()); }); group('target-dependencies-with-non-breaking-updates', () { test('no-ops for no published changes', () async { final RepositoryPackage package = createFakePackage('foo', packagesDir); final String changedFileOutput = <File>[ package.pubspecFile, ].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: package.pubspecFile.readAsStringSync())), ]; final List<String> output = await runCapturingPrint(runner, <String>[ 'make-deps-path-based', '--target-dependencies-with-non-breaking-updates' ]); expect( output, containsAllInOrder(<Matcher>[ contains('No target dependencies'), ]), ); }); test('no-ops for no deleted packages', () async { final String changedFileOutput = <File>[ // A change for a file that's not on disk simulates a deletion. packagesDir.childDirectory('foo').childFile('pubspec.yaml'), ].map((File file) => file.path).join('\n'); processRunner.mockProcessesForExecutable['git-diff'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(stdout: changedFileOutput)), ]; final List<String> output = await runCapturingPrint(runner, <String>[ 'make-deps-path-based', '--target-dependencies-with-non-breaking-updates' ]); expect( output, containsAllInOrder(<Matcher>[ contains('Skipping foo; deleted.'), contains('No target dependencies'), ]), ); }); test('includes bugfix version changes as targets', () async { const String newVersion = '1.0.1'; final RepositoryPackage package = createFakePackage('foo', packagesDir, version: newVersion); final File pubspecFile = package.pubspecFile; final String changedFileOutput = <File>[ pubspecFile, ].map((File file) => file.path).join('\n'); processRunner.mockProcessesForExecutable['git-diff'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(stdout: changedFileOutput)), ]; final String gitPubspecContents = pubspecFile.readAsStringSync().replaceAll(newVersion, '1.0.0'); // Simulate no change to the version in the interface's pubspec.yaml. processRunner.mockProcessesForExecutable['git-show'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(stdout: gitPubspecContents)), ]; final List<String> output = await runCapturingPrint(runner, <String>[ 'make-deps-path-based', '--target-dependencies-with-non-breaking-updates' ]); expect( output, containsAllInOrder(<Matcher>[ contains('Rewriting references to: foo...'), ]), ); }); test('includes minor version changes to 1.0+ as targets', () async { const String newVersion = '1.1.0'; final RepositoryPackage package = createFakePackage('foo', packagesDir, version: newVersion); final File pubspecFile = package.pubspecFile; final String changedFileOutput = <File>[ pubspecFile, ].map((File file) => file.path).join('\n'); processRunner.mockProcessesForExecutable['git-diff'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(stdout: changedFileOutput)), ]; final String gitPubspecContents = pubspecFile.readAsStringSync().replaceAll(newVersion, '1.0.0'); // Simulate no change to the version in the interface's pubspec.yaml. processRunner.mockProcessesForExecutable['git-show'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(stdout: gitPubspecContents)), ]; final List<String> output = await runCapturingPrint(runner, <String>[ 'make-deps-path-based', '--target-dependencies-with-non-breaking-updates' ]); expect( output, containsAllInOrder(<Matcher>[ contains('Rewriting references to: foo...'), ]), ); }); test('does not include major version changes as targets', () async { const String newVersion = '2.0.0'; final RepositoryPackage package = createFakePackage('foo', packagesDir, version: newVersion); final File pubspecFile = package.pubspecFile; final String changedFileOutput = <File>[ pubspecFile, ].map((File file) => file.path).join('\n'); processRunner.mockProcessesForExecutable['git-diff'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(stdout: changedFileOutput)), ]; final String gitPubspecContents = pubspecFile.readAsStringSync().replaceAll(newVersion, '1.0.0'); // Simulate no change to the version in the interface's pubspec.yaml. processRunner.mockProcessesForExecutable['git-show'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(stdout: gitPubspecContents)), ]; final List<String> output = await runCapturingPrint(runner, <String>[ 'make-deps-path-based', '--target-dependencies-with-non-breaking-updates' ]); expect( output, containsAllInOrder(<Matcher>[ contains('No target dependencies'), ]), ); }); test('does not include minor version changes to 0.x as targets', () async { const String newVersion = '0.8.0'; final RepositoryPackage package = createFakePackage('foo', packagesDir, version: newVersion); final File pubspecFile = package.pubspecFile; final String changedFileOutput = <File>[ pubspecFile, ].map((File file) => file.path).join('\n'); processRunner.mockProcessesForExecutable['git-diff'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(stdout: changedFileOutput)), ]; final String gitPubspecContents = pubspecFile.readAsStringSync().replaceAll(newVersion, '0.7.0'); // Simulate no change to the version in the interface's pubspec.yaml. processRunner.mockProcessesForExecutable['git-show'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(stdout: gitPubspecContents)), ]; final List<String> output = await runCapturingPrint(runner, <String>[ 'make-deps-path-based', '--target-dependencies-with-non-breaking-updates' ]); expect( output, containsAllInOrder(<Matcher>[ contains('No target dependencies'), ]), ); }); test('does not update references with an older major version', () async { const String newVersion = '2.0.1'; final RepositoryPackage targetPackage = createFakePackage('foo', packagesDir, version: newVersion); final RepositoryPackage referencingPackage = createFakePackage('bar', packagesDir); // For a dependency on ^1.0.0, the 2.0.0->2.0.1 update should not apply. addDependencies(referencingPackage, <String>['foo'], constraint: '^1.0.0'); final File pubspecFile = targetPackage.pubspecFile; final String changedFileOutput = <File>[ pubspecFile, ].map((File file) => file.path).join('\n'); processRunner.mockProcessesForExecutable['git-diff'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(stdout: changedFileOutput)), ]; final String gitPubspecContents = pubspecFile.readAsStringSync().replaceAll(newVersion, '2.0.0'); processRunner.mockProcessesForExecutable['git-show'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(stdout: gitPubspecContents)), ]; final List<String> output = await runCapturingPrint(runner, <String>[ 'make-deps-path-based', '--target-dependencies-with-non-breaking-updates' ]); final Pubspec referencingPubspec = referencingPackage.parsePubspec(); expect( output, containsAllInOrder(<Matcher>[ contains('Rewriting references to: foo'), ]), ); expect(referencingPubspec.dependencyOverrides.isEmpty, true); }); test('does update references with a matching version range', () async { const String newVersion = '2.0.1'; final RepositoryPackage targetPackage = createFakePackage('foo', packagesDir, version: newVersion); final RepositoryPackage referencingPackage = createFakePackage('bar', packagesDir); // For a dependency on ^1.0.0, the 2.0.0->2.0.1 update should not apply. addDependencies(referencingPackage, <String>['foo'], constraint: '^2.0.0'); final File pubspecFile = targetPackage.pubspecFile; final String changedFileOutput = <File>[ pubspecFile, ].map((File file) => file.path).join('\n'); processRunner.mockProcessesForExecutable['git-diff'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(stdout: changedFileOutput)), ]; final String gitPubspecContents = pubspecFile.readAsStringSync().replaceAll(newVersion, '2.0.0'); processRunner.mockProcessesForExecutable['git-show'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(stdout: gitPubspecContents)), ]; final List<String> output = await runCapturingPrint(runner, <String>[ 'make-deps-path-based', '--target-dependencies-with-non-breaking-updates' ]); final Pubspec referencingPubspec = referencingPackage.parsePubspec(); expect( output, containsAllInOrder(<Matcher>[ contains('Rewriting references to: foo'), ]), ); expect(referencingPubspec.dependencyOverrides['foo'] is PathDependency, true); }); test('skips anything outside of the packages directory', () async { final Directory toolDir = packagesDir.parent.childDirectory('tool'); const String newVersion = '1.1.0'; final RepositoryPackage package = createFakePackage( 'flutter_plugin_tools', toolDir, version: newVersion); // Simulate a minor version change so it would be a target. final File pubspecFile = package.pubspecFile; final String changedFileOutput = <File>[ pubspecFile, ].map((File file) => file.path).join('\n'); processRunner.mockProcessesForExecutable['git-diff'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(stdout: changedFileOutput)), ]; final String gitPubspecContents = pubspecFile.readAsStringSync().replaceAll(newVersion, '1.0.0'); processRunner.mockProcessesForExecutable['git-show'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(stdout: gitPubspecContents)), ]; final List<String> output = await runCapturingPrint(runner, <String>[ 'make-deps-path-based', '--target-dependencies-with-non-breaking-updates' ]); expect( output, containsAllInOrder(<Matcher>[ contains( 'Skipping /tool/flutter_plugin_tools/pubspec.yaml; not in packages directory.'), contains('No target dependencies'), ]), ); }); }); }
packages/script/tool/test/make_deps_path_based_command_test.dart/0
{ "file_path": "packages/script/tool/test/make_deps_path_based_command_test.dart", "repo_id": "packages", "token_count": 9375 }
1,027
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import '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/xcode_analyze_command.dart'; import 'package:test/test.dart'; import 'mocks.dart'; import 'util.dart'; // TODO(stuartmorgan): Rework these tests to use a mock Xcode instead of // doing all the process mocking and validation. void main() { group('test xcode_analyze_command', () { late FileSystem fileSystem; late MockPlatform mockPlatform; late Directory packagesDir; late CommandRunner<void> runner; late RecordingProcessRunner processRunner; setUp(() { fileSystem = MemoryFileSystem(); mockPlatform = MockPlatform(isMacOS: true); packagesDir = createPackagesDirectory(fileSystem: fileSystem); processRunner = RecordingProcessRunner(); final XcodeAnalyzeCommand command = XcodeAnalyzeCommand(packagesDir, processRunner: processRunner, platform: mockPlatform); runner = CommandRunner<void>( 'xcode_analyze_command', 'Test for xcode_analyze_command'); runner.addCommand(command); }); test('Fails if no platforms are provided', () async { Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['xcode-analyze'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('At least one platform flag must be provided'), ]), ); }); group('iOS', () { test('skip if iOS is not supported', () async { createFakePlugin('plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformMacOS: const PlatformDetails(PlatformSupport.inline), }); final List<String> output = await runCapturingPrint(runner, <String>['xcode-analyze', '--ios']); expect(output, contains(contains('Not implemented for target platform(s).'))); expect(processRunner.recordedCalls, orderedEquals(<ProcessCall>[])); }); test('skip if iOS is implemented in a federated package', () async { createFakePlugin('plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformIOS: const PlatformDetails(PlatformSupport.federated) }); final List<String> output = await runCapturingPrint(runner, <String>['xcode-analyze', '--ios']); expect(output, contains(contains('Not implemented for target platform(s).'))); expect(processRunner.recordedCalls, orderedEquals(<ProcessCall>[])); }); test('runs for iOS plugin', () async { final RepositoryPackage plugin = createFakePlugin('plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformIOS: const PlatformDetails(PlatformSupport.inline) }); final Directory pluginExampleDirectory = getExampleDir(plugin); final List<String> output = await runCapturingPrint(runner, <String>[ 'xcode-analyze', '--ios', ]); expect( output, containsAllInOrder(<Matcher>[ contains('Running for plugin'), contains('plugin/example (iOS) passed analysis.') ])); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( 'xcrun', const <String>[ 'xcodebuild', 'analyze', '-workspace', 'ios/Runner.xcworkspace', '-scheme', 'Runner', '-configuration', 'Debug', '-destination', 'generic/platform=iOS Simulator', 'GCC_TREAT_WARNINGS_AS_ERRORS=YES', ], pluginExampleDirectory.path), ])); }); test('passes min iOS deployment version when requested', () async { final RepositoryPackage plugin = createFakePlugin('plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformIOS: const PlatformDetails(PlatformSupport.inline) }); final Directory pluginExampleDirectory = getExampleDir(plugin); final List<String> output = await runCapturingPrint(runner, <String>['xcode-analyze', '--ios', '--ios-min-version=14.0']); expect( output, containsAllInOrder(<Matcher>[ contains('Running for plugin'), contains('plugin/example (iOS) passed analysis.') ])); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( 'xcrun', const <String>[ 'xcodebuild', 'analyze', '-workspace', 'ios/Runner.xcworkspace', '-scheme', 'Runner', '-configuration', 'Debug', '-destination', 'generic/platform=iOS Simulator', 'IPHONEOS_DEPLOYMENT_TARGET=14.0', 'GCC_TREAT_WARNINGS_AS_ERRORS=YES', ], pluginExampleDirectory.path), ])); }); test('fails if xcrun fails', () async { createFakePlugin('plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformIOS: const PlatformDetails(PlatformSupport.inline) }); processRunner.mockProcessesForExecutable['xcrun'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(exitCode: 1)) ]; Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>[ 'xcode-analyze', '--ios', ], errorHandler: (Error e) { commandError = e; }, ); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('The following packages had errors:'), contains(' plugin'), ])); }); }); group('macOS', () { test('skip if macOS is not supported', () async { createFakePlugin( 'plugin', packagesDir, ); final List<String> output = await runCapturingPrint( runner, <String>['xcode-analyze', '--macos']); expect(output, contains(contains('Not implemented for target platform(s).'))); expect(processRunner.recordedCalls, orderedEquals(<ProcessCall>[])); }); test('skip if macOS is implemented in a federated package', () async { createFakePlugin('plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformMacOS: const PlatformDetails(PlatformSupport.federated), }); final List<String> output = await runCapturingPrint( runner, <String>['xcode-analyze', '--macos']); expect(output, contains(contains('Not implemented for target platform(s).'))); expect(processRunner.recordedCalls, orderedEquals(<ProcessCall>[])); }); test('runs for macOS plugin', () async { final RepositoryPackage plugin = createFakePlugin('plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformMacOS: const PlatformDetails(PlatformSupport.inline), }); final Directory pluginExampleDirectory = getExampleDir(plugin); final List<String> output = await runCapturingPrint(runner, <String>[ 'xcode-analyze', '--macos', ]); expect(output, contains(contains('plugin/example (macOS) passed analysis.'))); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( 'xcrun', const <String>[ 'xcodebuild', 'analyze', '-workspace', 'macos/Runner.xcworkspace', '-scheme', 'Runner', '-configuration', 'Debug', 'GCC_TREAT_WARNINGS_AS_ERRORS=YES', ], pluginExampleDirectory.path), ])); }); test('passes min macOS deployment version when requested', () async { final RepositoryPackage plugin = createFakePlugin('plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformMacOS: const PlatformDetails(PlatformSupport.inline), }); final Directory pluginExampleDirectory = getExampleDir(plugin); final List<String> output = await runCapturingPrint(runner, <String>['xcode-analyze', '--macos', '--macos-min-version=12.0']); expect(output, contains(contains('plugin/example (macOS) passed analysis.'))); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( 'xcrun', const <String>[ 'xcodebuild', 'analyze', '-workspace', 'macos/Runner.xcworkspace', '-scheme', 'Runner', '-configuration', 'Debug', 'MACOSX_DEPLOYMENT_TARGET=12.0', 'GCC_TREAT_WARNINGS_AS_ERRORS=YES', ], pluginExampleDirectory.path), ])); }); test('fails if xcrun fails', () async { createFakePlugin('plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformMacOS: const PlatformDetails(PlatformSupport.inline), }); processRunner.mockProcessesForExecutable['xcrun'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(exitCode: 1)) ]; Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['xcode-analyze', '--macos'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('The following packages had errors:'), contains(' plugin'), ]), ); }); }); group('combined', () { test('runs both iOS and macOS when supported', () async { final RepositoryPackage plugin = createFakePlugin('plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformIOS: const PlatformDetails(PlatformSupport.inline), platformMacOS: const PlatformDetails(PlatformSupport.inline), }); final Directory pluginExampleDirectory = getExampleDir(plugin); final List<String> output = await runCapturingPrint(runner, <String>[ 'xcode-analyze', '--ios', '--macos', ]); expect( output, containsAll(<Matcher>[ contains('plugin/example (iOS) passed analysis.'), contains('plugin/example (macOS) passed analysis.'), ])); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( 'xcrun', const <String>[ 'xcodebuild', 'analyze', '-workspace', 'ios/Runner.xcworkspace', '-scheme', 'Runner', '-configuration', 'Debug', '-destination', 'generic/platform=iOS Simulator', 'GCC_TREAT_WARNINGS_AS_ERRORS=YES', ], pluginExampleDirectory.path), ProcessCall( 'xcrun', const <String>[ 'xcodebuild', 'analyze', '-workspace', 'macos/Runner.xcworkspace', '-scheme', 'Runner', '-configuration', 'Debug', 'GCC_TREAT_WARNINGS_AS_ERRORS=YES', ], pluginExampleDirectory.path), ])); }); test('runs only macOS for a macOS plugin', () async { final RepositoryPackage plugin = createFakePlugin('plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformMacOS: const PlatformDetails(PlatformSupport.inline), }); final Directory pluginExampleDirectory = getExampleDir(plugin); final List<String> output = await runCapturingPrint(runner, <String>[ 'xcode-analyze', '--ios', '--macos', ]); expect( output, containsAllInOrder(<Matcher>[ contains('plugin/example (macOS) passed analysis.'), ])); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( 'xcrun', const <String>[ 'xcodebuild', 'analyze', '-workspace', 'macos/Runner.xcworkspace', '-scheme', 'Runner', '-configuration', 'Debug', 'GCC_TREAT_WARNINGS_AS_ERRORS=YES', ], pluginExampleDirectory.path), ])); }); test('runs only iOS for a iOS plugin', () async { final RepositoryPackage plugin = createFakePlugin('plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformIOS: const PlatformDetails(PlatformSupport.inline) }); final Directory pluginExampleDirectory = getExampleDir(plugin); final List<String> output = await runCapturingPrint(runner, <String>[ 'xcode-analyze', '--ios', '--macos', ]); expect( output, containsAllInOrder( <Matcher>[contains('plugin/example (iOS) passed analysis.')])); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( 'xcrun', const <String>[ 'xcodebuild', 'analyze', '-workspace', 'ios/Runner.xcworkspace', '-scheme', 'Runner', '-configuration', 'Debug', '-destination', 'generic/platform=iOS Simulator', 'GCC_TREAT_WARNINGS_AS_ERRORS=YES', ], pluginExampleDirectory.path), ])); }); test('skips when neither are supported', () async { createFakePlugin('plugin', packagesDir); final List<String> output = await runCapturingPrint(runner, <String>[ 'xcode-analyze', '--ios', '--macos', ]); expect( output, containsAllInOrder(<Matcher>[ contains('SKIPPING: Not implemented for target platform(s).'), ])); expect(processRunner.recordedCalls, orderedEquals(<ProcessCall>[])); }); }); }); }
packages/script/tool/test/xcode_analyze_command_test.dart/0
{ "file_path": "packages/script/tool/test/xcode_analyze_command_test.dart", "repo_id": "packages", "token_count": 8123 }
1,028
import * as admin from 'firebase-admin'; admin.initializeApp(); export { shareImage } from './share';
photobooth/functions/src/index.ts/0
{ "file_path": "photobooth/functions/src/index.ts", "repo_id": "photobooth", "token_count": 30 }
1,029
export 'widgets/widgets.dart';
photobooth/lib/footer/footer.dart/0
{ "file_path": "photobooth/lib/footer/footer.dart", "repo_id": "photobooth", "token_count": 12 }
1,030
export 'animated_android.dart'; export 'animated_dash.dart'; export 'animated_dino.dart'; export 'animated_sparky.dart';
photobooth/lib/photobooth/widgets/animated_characters/animated_characters.dart/0
{ "file_path": "photobooth/lib/photobooth/widgets/animated_characters/animated_characters.dart", "repo_id": "photobooth", "token_count": 47 }
1,031
part of 'share_bloc.dart'; enum ShareStatus { initial, loading, success, failure } enum ShareUrl { none, twitter, facebook } extension ShareStatusX on ShareStatus { bool get isLoading => this == ShareStatus.loading; bool get isSuccess => this == ShareStatus.success; bool get isFailure => this == ShareStatus.failure; } class ShareState extends Equatable { const ShareState({ this.compositeStatus = ShareStatus.initial, this.uploadStatus = ShareStatus.initial, this.file, this.bytes, this.explicitShareUrl = '', this.facebookShareUrl = '', this.twitterShareUrl = '', this.isDownloadRequested = false, this.isUploadRequested = false, this.shareUrl = ShareUrl.none, }); final ShareStatus compositeStatus; final ShareStatus uploadStatus; final XFile? file; final Uint8List? bytes; final String explicitShareUrl; final String twitterShareUrl; final String facebookShareUrl; final bool isUploadRequested; final bool isDownloadRequested; final ShareUrl shareUrl; @override List<Object?> get props => [ compositeStatus, uploadStatus, file, bytes, twitterShareUrl, facebookShareUrl, isUploadRequested, isDownloadRequested, shareUrl, ]; ShareState copyWith({ ShareStatus? compositeStatus, ShareStatus? uploadStatus, XFile? file, Uint8List? bytes, String? explicitShareUrl, String? twitterShareUrl, String? facebookShareUrl, bool? isUploadRequested, bool? isDownloadRequested, ShareUrl? shareUrl, }) { return ShareState( compositeStatus: compositeStatus ?? this.compositeStatus, uploadStatus: uploadStatus ?? this.uploadStatus, file: file ?? this.file, bytes: bytes ?? this.bytes, explicitShareUrl: explicitShareUrl ?? this.explicitShareUrl, twitterShareUrl: twitterShareUrl ?? this.twitterShareUrl, facebookShareUrl: facebookShareUrl ?? this.facebookShareUrl, isUploadRequested: isUploadRequested ?? this.isUploadRequested, isDownloadRequested: isDownloadRequested ?? this.isDownloadRequested, shareUrl: shareUrl ?? this.shareUrl, ); } }
photobooth/lib/share/bloc/share_state.dart/0
{ "file_path": "photobooth/lib/share/bloc/share_state.dart", "repo_id": "photobooth", "token_count": 764 }
1,032
import 'package:flutter/material.dart'; import 'package:io_photobooth/l10n/l10n.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; class ShareHeading extends StatelessWidget { const ShareHeading({super.key}); @override Widget build(BuildContext context) { final theme = Theme.of(context); final l10n = context.l10n; return SelectableText( l10n.sharePageHeading, style: theme.textTheme.displayLarge?.copyWith( color: PhotoboothColors.white, ), textAlign: TextAlign.center, ); } } class ShareSuccessHeading extends StatelessWidget { const ShareSuccessHeading({super.key}); @override Widget build(BuildContext context) { final theme = Theme.of(context); final l10n = context.l10n; return SelectableText( l10n.sharePageSuccessHeading, style: theme.textTheme.displayLarge?.copyWith( color: PhotoboothColors.white, ), textAlign: TextAlign.center, ); } } class ShareErrorHeading extends StatelessWidget { const ShareErrorHeading({super.key}); @override Widget build(BuildContext context) { final theme = Theme.of(context); final l10n = context.l10n; return SelectableText( l10n.sharePageErrorHeading, style: theme.textTheme.displayLarge?.copyWith( color: PhotoboothColors.white, ), textAlign: TextAlign.center, ); } }
photobooth/lib/share/widgets/share_heading.dart/0
{ "file_path": "photobooth/lib/share/widgets/share_heading.dart", "repo_id": "photobooth", "token_count": 544 }
1,033
import 'package:flutter/material.dart'; import 'package:io_photobooth/l10n/l10n.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; class ClearStickersCancelButton extends StatelessWidget { const ClearStickersCancelButton({super.key}); @override Widget build(BuildContext context) { final l10n = context.l10n; return OutlinedButton( style: OutlinedButton.styleFrom( foregroundColor: PhotoboothColors.black, side: const BorderSide(color: PhotoboothColors.black), ), onPressed: () => Navigator.of(context).pop(false), child: Text( l10n.clearStickersDialogCancelButtonText, ), ); } }
photobooth/lib/stickers/widgets/clear_stickers/clear_stickers_cancel_button.dart/0
{ "file_path": "photobooth/lib/stickers/widgets/clear_stickers/clear_stickers_cancel_button.dart", "repo_id": "photobooth", "token_count": 259 }
1,034
@TestOn('chrome') library; import 'dart:js'; import 'package:analytics/src/analytics_web.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; class MockJsObject extends Mock implements JsObject {} void main() { group('trackEvent', () { late JsObject context; setUp(() { context = MockJsObject(); testContext = context; }); test('calls ga on window with correct args', () { const category = 'category'; const action = 'action'; const label = 'label'; expect( () => trackEvent( category: category, action: action, label: label, ), returnsNormally, ); verify( () => context.callMethod( 'ga', <dynamic>['send', 'event', category, action, label], ), ).called(1); }); }); }
photobooth/packages/analytics/test/analytics_web_test.dart/0
{ "file_path": "photobooth/packages/analytics/test/analytics_web_test.dart", "repo_id": "photobooth", "token_count": 382 }
1,035
export 'camera_exception.dart'; export 'camera_image.dart'; export 'camera_options.dart'; export 'media_device_info.dart';
photobooth/packages/camera/camera_platform_interface/lib/src/types/types.dart/0
{ "file_path": "photobooth/packages/camera/camera_platform_interface/lib/src/types/types.dart", "repo_id": "photobooth", "token_count": 43 }
1,036
import 'package:flutter/material.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; import 'package:platform_helper/platform_helper.dart'; /// Show a modal as bottom sheet when mobile or portrait. Else displays a dialog Future<T?> showAppModal<T>({ required BuildContext context, required Widget portraitChild, required Widget landscapeChild, PlatformHelper? platformHelper, }) { final isMobile = (platformHelper ?? PlatformHelper()).isMobile; final orientation = MediaQuery.of(context).orientation; if (isMobile || orientation == Orientation.portrait) { return showModalBottomSheet( context: context, isScrollControlled: true, backgroundColor: PhotoboothColors.transparent, builder: (_) => portraitChild, ); } else { return showAppDialog( context: context, child: landscapeChild, ); } }
photobooth/packages/photobooth_ui/lib/src/helpers/modal_helper.dart/0
{ "file_path": "photobooth/packages/photobooth_ui/lib/src/helpers/modal_helper.dart", "repo_id": "photobooth", "token_count": 283 }
1,037
import 'dart:async'; import 'package:flame/components.dart' hide Timer; import 'package:flame/sprite.dart'; import 'package:flame/widgets.dart'; import 'package:flutter/material.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; /// {@template sprites} /// Object which contains meta data for a collection of sprites. /// {@endtemplate} class Sprites { /// {@macro sprites} const Sprites({ required this.asset, required this.size, required this.frames, this.stepTime = 0.1, }); /// The sprite sheet asset name. /// This should be the name of the file within /// the `assets/images` directory. final String asset; /// The size an individual sprite within the sprite sheet final Size size; /// The number of frames within the sprite sheet. final int frames; /// Number of seconds per frame. Defaults to 0.1. final double stepTime; } /// The animation mode which determines when the animation plays. enum AnimationMode { /// Animations plays on a loop loop, /// Animations plays immediately once oneTime } /// {@template animated_sprite} /// A widget which renders an animated sprite /// given a collection of sprites. /// {@endtemplate} class AnimatedSprite extends StatefulWidget { /// {@macro animated_sprite} const AnimatedSprite({ required this.sprites, this.mode = AnimationMode.loop, this.showLoadingIndicator = true, this.loadingIndicatorColor = PhotoboothColors.orange, super.key, }); /// The collection of sprites which will be animated. final Sprites sprites; /// The mode of animation (`trigger`, `loop` or `oneTime`). final AnimationMode mode; /// Where should display a loading indicator while loading the sprite final bool showLoadingIndicator; /// Color for loading indicator final Color loadingIndicatorColor; @override State<AnimatedSprite> createState() => _AnimatedSpriteState(); } enum _AnimatedSpriteStatus { loading, loaded, failure } extension on _AnimatedSpriteStatus { /// Returns true for `_AnimatedSpriteStatus.loaded`. bool get isLoaded => this == _AnimatedSpriteStatus.loaded; } class _AnimatedSpriteState extends State<AnimatedSprite> { late SpriteSheet _spriteSheet; late SpriteAnimation _animation; Timer? _timer; var _status = _AnimatedSpriteStatus.loading; var _isPlaying = false; @override void initState() { super.initState(); _loadAnimation(); } @override void dispose() { _timer?.cancel(); super.dispose(); } Future<void> _loadAnimation() async { try { _spriteSheet = SpriteSheet( image: await Flame.images.load(widget.sprites.asset), srcSize: Vector2(widget.sprites.size.width, widget.sprites.size.height), ); _animation = _spriteSheet.createAnimation( row: 0, stepTime: widget.sprites.stepTime, to: widget.sprites.frames, loop: widget.mode == AnimationMode.loop, ); setState(() { _status = _AnimatedSpriteStatus.loaded; if (widget.mode == AnimationMode.loop || widget.mode == AnimationMode.oneTime) { _isPlaying = true; } }); } catch (_) { setState(() => _status = _AnimatedSpriteStatus.failure); } } @override Widget build(BuildContext context) { return AppAnimatedCrossFade( firstChild: widget.showLoadingIndicator ? SizedBox.fromSize( size: const Size(20, 20), child: AppCircularProgressIndicator( strokeWidth: 2, color: widget.loadingIndicatorColor, ), ) : const SizedBox(), secondChild: SizedBox.expand( child: _status.isLoaded ? SpriteAnimationWidget(animation: _animation, playing: _isPlaying) : const SizedBox(), ), crossFadeState: _status.isLoaded ? CrossFadeState.showSecond : CrossFadeState.showFirst, ); } }
photobooth/packages/photobooth_ui/lib/src/widgets/animated_sprite.dart/0
{ "file_path": "photobooth/packages/photobooth_ui/lib/src/widgets/animated_sprite.dart", "repo_id": "photobooth", "token_count": 1450 }
1,038
export 'links_helper_test.dart'; export 'set_display_size.dart';
photobooth/packages/photobooth_ui/test/src/helpers/helpers.dart/0
{ "file_path": "photobooth/packages/photobooth_ui/test/src/helpers/helpers.dart", "repo_id": "photobooth", "token_count": 25 }
1,039
// 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('AppTooltip', () { testWidgets('renders Tooltip by default', (tester) async { const target = Key('__key__'); await tester.pumpWidget( MaterialApp( home: Material( child: AppTooltip( message: 'message', child: SizedBox(key: target), ), ), ), ); expect(find.byType(Tooltip), findsOneWidget); expect(find.byKey(target), findsOneWidget); expect(find.text('message'), findsNothing); }); testWidgets('renders tooltip message when visible is true', (tester) async { const target = Key('__key__'); await tester.pumpWidget( const MaterialApp( home: Material( child: AppTooltip.custom( visible: true, message: 'message', child: SizedBox(key: target), ), ), ), ); expect(find.byType(Tooltip), findsNothing); expect(find.byKey(target), findsOneWidget); expect(find.text('message'), findsOneWidget); }); testWidgets('does not render tooltip message when visible is false', (tester) async { const target = Key('__key__'); await tester.pumpWidget( const MaterialApp( home: Material( child: AppTooltip.custom( visible: false, message: 'message', child: SizedBox(key: target), ), ), ), ); expect(find.byType(Tooltip), findsOneWidget); expect(find.byKey(target), findsOneWidget); expect(find.text('message'), findsNothing); }); }); }
photobooth/packages/photobooth_ui/test/src/widgets/app_tooltip_test.dart/0
{ "file_path": "photobooth/packages/photobooth_ui/test/src/widgets/app_tooltip_test.dart", "repo_id": "photobooth", "token_count": 855 }
1,040
// ignore_for_file: prefer_const_constructors import 'package:io_photobooth/share/share.dart'; import 'package:test/test.dart'; void main() { group('ShareEvent', () { group('ShareViewLoaded', () { test('support value equality', () { final instanceA = ShareViewLoaded(); final instanceB = ShareViewLoaded(); expect(instanceA, equals(instanceB)); }); }); group('ShareOnTwitterTapped', () { test('support value equality', () { final instanceA = ShareOnTwitterTapped(); final instanceB = ShareOnTwitterTapped(); expect(instanceA, equals(instanceB)); }); }); group('ShareOnFacebookTapped', () { test('support value equality', () { final instanceA = ShareOnFacebookTapped(); final instanceB = ShareOnFacebookTapped(); expect(instanceA, equals(instanceB)); }); }); }); }
photobooth/test/share/bloc/share_event_test.dart/0
{ "file_path": "photobooth/test/share/bloc/share_event_test.dart", "repo_id": "photobooth", "token_count": 343 }
1,041
// ignore_for_file: prefer_const_constructors import 'dart:convert'; import 'dart:typed_data'; import 'package:bloc_test/bloc_test.dart'; import 'package:camera/camera.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:io_photobooth/assets.g.dart'; import 'package:io_photobooth/footer/footer.dart'; import 'package:io_photobooth/photobooth/photobooth.dart'; import 'package:io_photobooth/share/share.dart'; import 'package:io_photobooth/stickers/stickers.dart'; import 'package:mocktail/mocktail.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; import 'package:photos_repository/photos_repository.dart'; import 'package:platform_helper/platform_helper.dart'; import '../../helpers/helpers.dart'; class FakeStickersEvent extends Fake implements StickersEvent {} class FakeStickersState extends Fake implements StickersState {} class MockStickersBloc extends MockBloc<StickersEvent, StickersState> implements StickersBloc {} class FakePhotoboothEvent extends Fake implements PhotoboothEvent {} class FakePhotoboothState extends Fake implements PhotoboothState {} class MockPhotoboothBloc extends MockBloc<PhotoboothEvent, PhotoboothState> implements PhotoboothBloc {} class FakeShareEvent extends Fake implements ShareEvent {} class FakeShareState extends Fake implements ShareState {} class MockShareBloc extends MockBloc<ShareEvent, ShareState> implements ShareBloc {} class FakeDragUpdate extends Fake implements DragUpdate {} class MockPlatformHelper extends Mock implements PlatformHelper {} class MockPhotosRepository extends Mock implements PhotosRepository {} void main() { TestWidgetsFlutterBinding.ensureInitialized(); const width = 1; const height = 1; final data = 'data:image/png,${base64.encode(transparentImage)}'; final image = CameraImage(width: width, height: height, data: data); setUpAll(() { registerFallbackValue(FakeStickersEvent()); registerFallbackValue(FakeStickersState()); registerFallbackValue(FakePhotoboothEvent()); registerFallbackValue(FakePhotoboothState()); registerFallbackValue(FakeShareEvent()); registerFallbackValue(FakeShareState()); }); group('StickersPage', () { late PhotoboothBloc photoboothBloc; setUp(() { photoboothBloc = MockPhotoboothBloc(); when(() => photoboothBloc.state).thenReturn( PhotoboothState( image: image, ), ); }); test('is routable', () { expect(StickersPage.route(), isA<MaterialPageRoute<void>>()); }); testWidgets('renders PreviewImage', (tester) async { await tester.pumpApp( BlocProvider.value( value: photoboothBloc, child: StickersPage(), ), ); expect(find.byType(PreviewImage), findsOneWidget); }); testWidgets('renders StickersView', (tester) async { await tester.pumpApp( BlocProvider.value( value: photoboothBloc, child: StickersPage(), ), ); expect(find.byType(StickersView), findsOneWidget); }); }); group('StickersView', () { late PhotoboothBloc photoboothBloc; late StickersBloc stickersBloc; setUp(() { photoboothBloc = MockPhotoboothBloc(); when(() => photoboothBloc.state).thenReturn( PhotoboothState(image: image), ); stickersBloc = MockStickersBloc(); when(() => stickersBloc.state).thenReturn(StickersState()); }); testWidgets('renders PhotoboothBackground', (tester) async { await tester.pumpApp( MultiBlocProvider( providers: [ BlocProvider.value(value: photoboothBloc), BlocProvider.value(value: stickersBloc), ], child: StickersView(), ), ); expect(find.byType(PhotoboothBackground), findsOneWidget); }); testWidgets('renders PreviewImage', (tester) async { await tester.pumpApp( MultiBlocProvider( providers: [ BlocProvider.value(value: photoboothBloc), BlocProvider.value(value: stickersBloc), ], child: StickersView(), ), ); expect(find.byType(PreviewImage), findsOneWidget); }); testWidgets('renders OpenStickersButton', (tester) async { await tester.pumpApp( MultiBlocProvider( providers: [ BlocProvider.value(value: photoboothBloc), BlocProvider.value(value: stickersBloc), ], child: StickersView(), ), ); expect(find.byType(OpenStickersButton), findsOneWidget); }); testWidgets('renders FlutterIconLink', (tester) async { await tester.pumpApp( MultiBlocProvider( providers: [ BlocProvider.value(value: photoboothBloc), BlocProvider.value(value: stickersBloc), ], child: StickersView(), ), ); expect(find.byType(FlutterIconLink), findsOneWidget); }); testWidgets('renders FirebaseIconLink', (tester) async { await tester.pumpApp( MultiBlocProvider( providers: [ BlocProvider.value(value: photoboothBloc), BlocProvider.value(value: stickersBloc), ], child: StickersView(), ), ); expect(find.byType(FirebaseIconLink), findsOneWidget); }); testWidgets('adds StickersDrawerToggled when OpenStickersButton tapped', (tester) async { await tester.pumpApp( MultiBlocProvider( providers: [ BlocProvider.value(value: photoboothBloc), BlocProvider.value(value: stickersBloc), ], child: StickersView(), ), ); tester .widget<OpenStickersButton>(find.byType(OpenStickersButton)) .onPressed(); verify(() => stickersBloc.add(StickersDrawerToggled())).called(1); }); testWidgets( 'does not display pulse animation ' 'once has been clicked', (tester) async { await tester.pumpApp( MultiBlocProvider( providers: [ BlocProvider.value(value: photoboothBloc), BlocProvider.value(value: stickersBloc), ], child: StickersView(), ), ); expect(find.byType(AnimatedPulse), findsOneWidget); tester .widget<AppTooltipButton>( find.byKey(Key('stickersView_openStickersButton_appTooltipButton')), ) .onPressed(); await tester.pumpAndSettle(); expect(find.byType(AnimatedPulse), findsNothing); }); testWidgets( 'does not display DraggableResizableAsset when stickers is empty', (tester) async { await tester.pumpApp( MultiBlocProvider( providers: [ BlocProvider.value(value: photoboothBloc), BlocProvider.value(value: stickersBloc), ], child: StickersView(), ), ); expect(find.byType(DraggableResizable), findsNothing); }); testWidgets('displays DraggableResizableAsset when stickers is populated', (tester) async { when(() => photoboothBloc.state).thenReturn( PhotoboothState( stickers: [ PhotoAsset(id: '0', asset: Assets.props.first), PhotoAsset(id: '1', asset: Assets.props.last) ], image: image, ), ); await tester.pumpApp( MultiBlocProvider( providers: [ BlocProvider.value(value: photoboothBloc), BlocProvider.value(value: stickersBloc), ], child: StickersView(), ), ); expect(find.byType(DraggableResizable), findsNWidgets(2)); }); testWidgets('adds PhotoStickerDragged when sticker dragged', (tester) async { when(() => photoboothBloc.state).thenReturn( PhotoboothState( stickers: [PhotoAsset(id: '0', asset: Assets.props.first)], image: image, ), ); await tester.pumpApp( MultiBlocProvider( providers: [ BlocProvider.value(value: photoboothBloc), BlocProvider.value(value: stickersBloc), ], child: StickersView(), ), ); tester .widget<DraggableResizable>(find.byType(DraggableResizable)) .onUpdate ?.call(FakeDragUpdate()); verify( () => photoboothBloc.add(any(that: isA<PhotoStickerDragged>())), ); }); testWidgets('tapping on retake + close does nothing', (tester) async { const initialPage = Key('__target__'); await tester.pumpApp( Builder( builder: (context) { return ElevatedButton( key: initialPage, onPressed: () => Navigator.of(context).push( MaterialPageRoute<void>( builder: (_) => MultiBlocProvider( providers: [ BlocProvider.value(value: photoboothBloc), BlocProvider.value(value: stickersBloc), ], child: StickersView(), ), ), ), child: const SizedBox(), ); }, ), ); await tester.tap(find.byType(ElevatedButton)); await tester.pumpAndSettle(); expect(find.byType(StickersView), findsOneWidget); expect(find.byKey(initialPage), findsNothing); final retakeButtonFinder = find.byKey( const Key('stickersPage_retake_appTooltipButton'), ); tester.widget<AppTooltipButton>(retakeButtonFinder).onPressed(); await tester.pumpAndSettle(); tester.widget<IconButton>(find.byType(IconButton)).onPressed!(); await tester.pumpAndSettle(); verifyNever(() => photoboothBloc.add(const PhotoClearAllTapped())); await tester.pumpAndSettle(); expect(find.byType(StickersView), findsOneWidget); expect(find.byKey(initialPage), findsNothing); }); testWidgets('tapping on retake + cancel does nothing', (tester) async { const initialPage = Key('__target__'); await tester.pumpApp( Builder( builder: (context) { return ElevatedButton( key: initialPage, onPressed: () => Navigator.of(context).push( MaterialPageRoute<void>( builder: (_) => MultiBlocProvider( providers: [ BlocProvider.value(value: photoboothBloc), BlocProvider.value(value: stickersBloc), ], child: StickersView(), ), ), ), child: const SizedBox(), ); }, ), ); await tester.tap(find.byType(ElevatedButton)); await tester.pumpAndSettle(); expect(find.byType(StickersView), findsOneWidget); expect(find.byKey(initialPage), findsNothing); final retakeButtonFinder = find.byKey( const Key('stickersPage_retake_appTooltipButton'), ); tester.widget<AppTooltipButton>(retakeButtonFinder).onPressed(); await tester.pumpAndSettle(); tester.widget<OutlinedButton>(find.byType(OutlinedButton)).onPressed!(); await tester.pumpAndSettle(); verifyNever(() => photoboothBloc.add(const PhotoClearAllTapped())); await tester.pumpAndSettle(); expect(find.byType(StickersView), findsOneWidget); expect(find.byKey(initialPage), findsNothing); }); testWidgets( 'tapping on retake + confirm replaces route with PhotoboothPage' ' and clears props', (tester) async { await tester.pumpApp( BlocProvider.value(value: stickersBloc, child: StickersView()), photoboothBloc: photoboothBloc, ); expect(find.byType(StickersView), findsOneWidget); expect(find.byType(PhotoboothPage), findsNothing); final retakeButtonFinder = find.byKey( const Key('stickersPage_retake_appTooltipButton'), ); tester.widget<AppTooltipButton>(retakeButtonFinder).onPressed(); await tester.pumpAndSettle(); tester.widget<ElevatedButton>(find.byType(ElevatedButton)).onPressed!(); await tester.pumpAndSettle(); verify(() => photoboothBloc.add(const PhotoClearAllTapped())).called(1); await tester.pumpAndSettle(); expect(find.byType(StickersView), findsNothing); expect(find.byType(PhotoboothPage), findsOneWidget); }); testWidgets('tapping next + cancel does not route to SharePage', (tester) async { await tester.pumpApp( BlocProvider.value(value: stickersBloc, child: StickersView()), photoboothBloc: photoboothBloc, ); tester .widget<InkWell>(find.byKey(const Key('stickersPage_next_inkWell'))) .onTap!(); await tester.pump(); tester.widget<OutlinedButton>(find.byType(OutlinedButton)).onPressed!(); await tester.pump(); await tester.pump(); expect(find.byType(StickersView), findsOneWidget); expect(find.byType(SharePage), findsNothing); }); testWidgets('tapping next + close does not route to SharePage', (tester) async { await tester.pumpApp( BlocProvider.value(value: stickersBloc, child: StickersView()), photoboothBloc: photoboothBloc, ); tester .widget<InkWell>(find.byKey(const Key('stickersPage_next_inkWell'))) .onTap!(); await tester.pump(); tester.widget<IconButton>(find.byType(IconButton)).onPressed!(); await tester.pump(); await tester.pump(); expect(find.byType(StickersView), findsOneWidget); expect(find.byType(SharePage), findsNothing); }); testWidgets('tapping next + confirm routes to SharePage', (tester) async { final photosRepository = MockPhotosRepository(); when( () => photosRepository.composite( width: any(named: 'width'), height: any(named: 'height'), data: any(named: 'data'), layers: [], aspectRatio: any(named: 'aspectRatio'), ), ).thenAnswer((_) async => Uint8List(0)); await tester.pumpApp( BlocProvider.value(value: stickersBloc, child: StickersView()), photoboothBloc: photoboothBloc, photosRepository: photosRepository, ); tester .widget<InkWell>(find.byKey(const Key('stickersPage_next_inkWell'))) .onTap!(); await tester.pump(); tester.widget<ElevatedButton>(find.byType(ElevatedButton)).onPressed!(); await tester.pump(); await tester.pump(); expect(find.byType(StickersPage), findsNothing); expect(find.byType(SharePage), findsOneWidget); }); testWidgets('does not display ClearStickersButton when stickers is empty', (tester) async { when(() => stickersBloc.state).thenReturn( StickersState(isDrawerActive: true), ); await tester.pumpApp( MultiBlocProvider( providers: [ BlocProvider.value(value: photoboothBloc), BlocProvider.value(value: stickersBloc), ], child: StickersView(), ), ); expect(find.byType(ClearStickersButton), findsNothing); }); testWidgets('displays ClearStickersButton when stickers is not empty', (tester) async { when(() => photoboothBloc.state).thenReturn( PhotoboothState( stickers: [PhotoAsset(id: '0', asset: Assets.props.first)], image: image, ), ); when(() => stickersBloc.state).thenReturn( StickersState(isDrawerActive: true), ); await tester.pumpApp( MultiBlocProvider( providers: [ BlocProvider.value(value: photoboothBloc), BlocProvider.value(value: stickersBloc), ], child: StickersView(), ), ); expect(find.byType(ClearStickersButton), findsOneWidget); }); testWidgets('shows ClearStickersDialog when ClearStickersButton is tapped', (tester) async { when(() => photoboothBloc.state).thenReturn( PhotoboothState( stickers: [PhotoAsset(id: '0', asset: Assets.props.first)], image: image, ), ); when(() => stickersBloc.state).thenReturn( StickersState(isDrawerActive: true), ); await tester.pumpApp( MultiBlocProvider( providers: [ BlocProvider.value(value: photoboothBloc), BlocProvider.value(value: stickersBloc), ], child: StickersView(), ), ); final clearStickersButton = tester.widget<ClearStickersButton>( find.byType(ClearStickersButton), ); clearStickersButton.onPressed(); await tester.pump(); expect(find.byType(ClearStickersDialog), findsOneWidget); }); testWidgets( 'PhotoClearStickersTapped when ClearStickersConfirmButton is tapped', (tester) async { when(() => photoboothBloc.state).thenReturn( PhotoboothState( stickers: [PhotoAsset(id: '0', asset: Assets.props.first)], image: image, ), ); await tester.pumpApp( MultiBlocProvider( providers: [ BlocProvider.value(value: photoboothBloc), BlocProvider.value(value: stickersBloc), ], child: StickersView(), ), ); final clearStickersButton = tester.widget<ClearStickersButton>( find.byType(ClearStickersButton), ); clearStickersButton.onPressed(); await tester.pumpAndSettle(); expect(find.byType(ClearStickersDialog), findsOneWidget); final confirmButton = find.byType(ClearStickersConfirmButton); await tester.ensureVisible(confirmButton); await tester.tap(confirmButton); await tester.pumpAndSettle(); verify(() => photoboothBloc.add(PhotoClearStickersTapped())).called(1); }); testWidgets('adds PhotoTapped when background photo is tapped', (tester) async { when(() => photoboothBloc.state).thenReturn( PhotoboothState( stickers: [PhotoAsset(id: '0', asset: Assets.props.first)], image: image, ), ); await tester.pumpApp( MultiBlocProvider( providers: [ BlocProvider.value(value: photoboothBloc), BlocProvider.value(value: stickersBloc), ], child: StickersView(), ), ); final background = tester.widget<GestureDetector>( find.byKey(const Key('stickersView_background_gestureDetector')), ); background.onTap?.call(); verify(() => photoboothBloc.add(PhotoTapped())).called(1); }); testWidgets( 'adds PhotoDeleteSelectedStickerTapped ' 'when sticker selected is removed', (tester) async { when(() => photoboothBloc.state).thenReturn( PhotoboothState( stickers: [PhotoAsset(id: '0', asset: Assets.props.first)], image: image, ), ); await tester.pumpApp( MultiBlocProvider( providers: [ BlocProvider.value(value: photoboothBloc), BlocProvider.value(value: stickersBloc), ], child: StickersView(), ), ); tester .widget<DraggableResizable>(find.byType(DraggableResizable)) .onDelete ?.call(); verify( () => photoboothBloc.add( any(that: isA<PhotoDeleteSelectedStickerTapped>()), ), ).called(1); }); testWidgets( 'renders StickersCaption when shouldDisplayPropsReminder is true', (tester) async { when(() => stickersBloc.state).thenReturn(StickersState()); await tester.pumpApp( MultiBlocProvider( providers: [ BlocProvider.value(value: photoboothBloc), BlocProvider.value(value: stickersBloc), ], child: StickersView(), ), ); expect( find.byKey(const Key('stickersPage_propsReminder_appTooltip')), findsOneWidget, ); }); testWidgets( 'does not render StickersCaption when ' 'shouldDisplayPropsReminder is false', (tester) async { when(() => stickersBloc.state).thenReturn( StickersState(shouldDisplayPropsReminder: false), ); await tester.pumpApp( MultiBlocProvider( providers: [ BlocProvider.value(value: photoboothBloc), BlocProvider.value(value: stickersBloc), ], child: StickersView(), ), ); expect( find.byKey(const Key('stickersPage_propsReminder_appTooltip')), findsNothing, ); }); }); }
photobooth/test/stickers/view/stickers_page_test.dart/0
{ "file_path": "photobooth/test/stickers/view/stickers_page_test.dart", "repo_id": "photobooth", "token_count": 9383 }
1,042
include: package:very_good_analysis/analysis_options.2.4.0.yaml analyzer: exclude: - lib/**/*.gen.dart linter: rules: public_member_api_docs: false
pinball/analysis_options.yaml/0
{ "file_path": "pinball/analysis_options.yaml", "repo_id": "pinball", "token_count": 64 }
1,043
import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:pinball_audio/pinball_audio.dart'; import 'package:pinball_flame/pinball_flame.dart'; class BumperNoiseBehavior extends ContactBehavior { @override void beginContact(Object other, Contact contact) { super.beginContact(other, contact); readProvider<PinballAudioPlayer>().play(PinballAudio.bumper); } }
pinball/lib/game/behaviors/bumper_noise_behavior.dart/0
{ "file_path": "pinball/lib/game/behaviors/bumper_noise_behavior.dart", "repo_id": "pinball", "token_count": 128 }
1,044
import 'package:flame/components.dart'; import 'package:flame_bloc/flame_bloc.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; /// Reset [SpaceshipRamp] state when GameState.rounds changes. class RampResetBehavior extends Component with FlameBlocListenable<GameBloc, GameState> { @override bool listenWhen(GameState previousState, GameState newState) { return previousState.rounds != newState.rounds; } @override void onNewState(GameState state) { readBloc<SpaceshipRampCubit, SpaceshipRampState>().onReset(); } }
pinball/lib/game/components/android_acres/behaviors/ramp_reset_behavior.dart/0
{ "file_path": "pinball/lib/game/components/android_acres/behaviors/ramp_reset_behavior.dart", "repo_id": "pinball", "token_count": 223 }
1,045
export 'android_acres/android_acres.dart'; export 'backbox/backbox.dart'; export 'bottom_group.dart'; export 'dino_desert/dino_desert.dart'; export 'drain/drain.dart'; export 'flutter_forest/flutter_forest.dart'; export 'game_bloc_status_listener.dart'; export 'google_gallery/google_gallery.dart'; export 'launcher.dart'; export 'multiballs/multiballs.dart'; export 'multipliers/multipliers.dart'; export 'sparky_scorch/sparky_scorch.dart';
pinball/lib/game/components/components.dart/0
{ "file_path": "pinball/lib/game/components/components.dart", "repo_id": "pinball", "token_count": 171 }
1,046
import 'package:flame/components.dart'; import 'package:flame_bloc/flame_bloc.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; /// Toggle each [Multiball] when there is a bonus ball. class MultiballsBehavior extends Component with ParentIsA<Multiballs>, FlameBlocListenable<GameBloc, GameState> { @override bool listenWhen(GameState? previousState, GameState newState) { final hasChanged = previousState?.bonusHistory != newState.bonusHistory; final lastBonusIsMultiball = newState.bonusHistory.isNotEmpty && (newState.bonusHistory.last == GameBonus.dashNest || newState.bonusHistory.last == GameBonus.googleWord); return hasChanged && lastBonusIsMultiball; } @override void onNewState(GameState state) { parent.children.whereType<Multiball>().forEach((multiball) { multiball.bloc.onAnimate(); }); } }
pinball/lib/game/components/multiballs/behaviors/multiballs_behavior.dart/0
{ "file_path": "pinball/lib/game/components/multiballs/behaviors/multiballs_behavior.dart", "repo_id": "pinball", "token_count": 344 }
1,047
import 'package:flutter/material.dart'; import 'package:pinball_ui/pinball_ui.dart'; /// {@template mobile_dpad} /// Widget rendering 4 directional input arrows. /// {@endtemplate} class MobileDpad extends StatelessWidget { /// {@template mobile_dpad} const MobileDpad({ Key? key, required this.onTapUp, required this.onTapDown, required this.onTapLeft, required this.onTapRight, }) : super(key: key); static const _size = 180.0; /// Called when dpad up is pressed final VoidCallback onTapUp; /// Called when dpad down is pressed final VoidCallback onTapDown; /// Called when dpad left is pressed final VoidCallback onTapLeft; /// Called when dpad right is pressed final VoidCallback onTapRight; @override Widget build(BuildContext context) { return SizedBox( width: _size, height: _size, child: Column( children: [ Row( children: [ const Spacer(), PinballDpadButton( direction: PinballDpadDirection.up, onTap: onTapUp, ), const Spacer(), ], ), Row( children: [ PinballDpadButton( direction: PinballDpadDirection.left, onTap: onTapLeft, ), const Spacer(), PinballDpadButton( direction: PinballDpadDirection.right, onTap: onTapRight, ), ], ), Row( children: [ const Spacer(), PinballDpadButton( direction: PinballDpadDirection.down, onTap: onTapDown, ), const Spacer(), ], ), ], ), ); } }
pinball/lib/game/view/widgets/mobile_dpad.dart/0
{ "file_path": "pinball/lib/game/view/widgets/mobile_dpad.dart", "repo_id": "pinball", "token_count": 905 }
1,048
import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:pinball/l10n/l10n.dart'; import 'package:pinball_ui/pinball_ui.dart'; /// Inflates [MoreInformationDialog] using [showDialog]. Future<void> showMoreInformationDialog(BuildContext context) { final gameWidgetWidth = MediaQuery.of(context).size.height * 9 / 16; return showDialog<void>( context: context, barrierColor: PinballColors.transparent, barrierDismissible: true, builder: (_) { return Center( child: SizedBox( height: gameWidgetWidth * 0.87, width: gameWidgetWidth, child: const MoreInformationDialog(), ), ); }, ); } /// {@template more_information_dialog} /// Dialog used to show informational links /// {@endtemplate} class MoreInformationDialog extends StatelessWidget { /// {@macro more_information_dialog} const MoreInformationDialog({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Material( color: PinballColors.transparent, child: _LinkBoxDecoration( child: Column( children: const [ SizedBox(height: 16), _LinkBoxHeader(), Expanded( child: _LinkBoxBody(), ), ], ), ), ); } } class _LinkBoxHeader extends StatelessWidget { const _LinkBoxHeader({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final l10n = context.l10n; return Column( children: [ Text( l10n.linkBoxTitle, style: Theme.of(context).textTheme.headline3!.copyWith( color: PinballColors.blue, fontWeight: FontWeight.bold, ), overflow: TextOverflow.ellipsis, ), const SizedBox(height: 12), const SizedBox( width: 200, child: Divider(color: PinballColors.white, thickness: 2), ), ], ); } } class _LinkBoxDecoration extends StatelessWidget { const _LinkBoxDecoration({ Key? key, required this.child, }) : super(key: key); final Widget child; @override Widget build(BuildContext context) { return DecoratedBox( decoration: const CrtBackground().copyWith( borderRadius: const BorderRadius.all(Radius.circular(12)), border: Border.all( color: PinballColors.white, width: 5, ), ), child: child, ); } } class _LinkBoxBody extends StatelessWidget { const _LinkBoxBody({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final l10n = context.l10n; return Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ const _MadeWithFlutterAndFirebase(), _TextLink( text: l10n.linkBoxOpenSourceCode, link: _MoreInformationUrl.openSourceCode, ), _TextLink( text: l10n.linkBoxGoogleIOText, link: _MoreInformationUrl.googleIOEvent, ), _TextLink( text: l10n.linkBoxFlutterGames, link: _MoreInformationUrl.flutterGamesWebsite, ), _TextLink( text: l10n.linkBoxHowItsMade, link: _MoreInformationUrl.howItsMadeArticle, ), _TextLink( text: l10n.linkBoxTermsOfService, link: _MoreInformationUrl.termsOfService, ), _TextLink( text: l10n.linkBoxPrivacyPolicy, link: _MoreInformationUrl.privacyPolicy, ), ], ); } } class _TextLink extends StatelessWidget { const _TextLink({ Key? key, required this.text, required this.link, }) : super(key: key); final String text; final String link; @override Widget build(BuildContext context) { final theme = Theme.of(context); return InkWell( onTap: () => openLink(link), child: Text( text, style: theme.textTheme.headline5!.copyWith( color: PinballColors.white, ), overflow: TextOverflow.ellipsis, ), ); } } class _MadeWithFlutterAndFirebase extends StatelessWidget { const _MadeWithFlutterAndFirebase({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final l10n = context.l10n; final theme = Theme.of(context); return RichText( textAlign: TextAlign.center, text: TextSpan( text: l10n.linkBoxMadeWithText, style: theme.textTheme.headline5!.copyWith(color: PinballColors.white), children: <TextSpan>[ TextSpan( text: l10n.linkBoxFlutterLinkText, recognizer: TapGestureRecognizer() ..onTap = () => openLink(_MoreInformationUrl.flutterWebsite), style: const TextStyle( decoration: TextDecoration.underline, ), ), const TextSpan(text: ' & '), TextSpan( text: l10n.linkBoxFirebaseLinkText, recognizer: TapGestureRecognizer() ..onTap = () => openLink(_MoreInformationUrl.firebaseWebsite), style: theme.textTheme.headline5!.copyWith( decoration: TextDecoration.underline, ), ), ], ), ); } } abstract class _MoreInformationUrl { static const flutterWebsite = 'https://flutter.dev'; static const firebaseWebsite = 'https://firebase.google.com'; static const openSourceCode = 'https://github.com/flutter/pinball'; static const googleIOEvent = 'https://events.google.com/io/'; static const flutterGamesWebsite = 'http://flutter.dev/games'; static const howItsMadeArticle = 'https://medium.com/flutter/i-o-pinball-powered-by-flutter-and-firebase-d22423f3f5d'; static const termsOfService = 'https://policies.google.com/terms'; static const privacyPolicy = 'https://policies.google.com/privacy'; }
pinball/lib/more_information/more_information_dialog.dart/0
{ "file_path": "pinball/lib/more_information/more_information_dialog.dart", "repo_id": "pinball", "token_count": 2573 }
1,049
import 'package:firebase_auth/firebase_auth.dart'; /// {@template authentication_exception} /// Exception for authentication repository failures. /// {@endtemplate} class AuthenticationException implements Exception { /// {@macro authentication_exception} const AuthenticationException(this.error, this.stackTrace); /// The error that was caught. final Object error; /// The Stacktrace associated with the [error]. final StackTrace stackTrace; } /// {@template authentication_repository} /// Repository to manage user authentication. /// {@endtemplate} class AuthenticationRepository { /// {@macro authentication_repository} AuthenticationRepository(this._firebaseAuth); final FirebaseAuth _firebaseAuth; /// Sign in the existing user anonymously using [FirebaseAuth]. If the /// authentication process can't be completed, it will throw an /// [AuthenticationException]. Future<void> authenticateAnonymously() async { try { await _firebaseAuth.signInAnonymously(); } on Exception catch (error, stackTrace) { throw AuthenticationException(error, stackTrace); } } }
pinball/packages/authentication_repository/lib/src/authentication_repository.dart/0
{ "file_path": "pinball/packages/authentication_repository/lib/src/authentication_repository.dart", "repo_id": "pinball", "token_count": 307 }
1,050