text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.camerax; import androidx.annotation.NonNull; import androidx.camera.video.Recorder; import androidx.camera.video.VideoCapture; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.VideoCaptureFlutterApi; public class VideoCaptureFlutterApiImpl extends VideoCaptureFlutterApi { public VideoCaptureFlutterApiImpl( @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { super(binaryMessenger); this.instanceManager = instanceManager; } private final InstanceManager instanceManager; void create(@NonNull VideoCapture<Recorder> videoCapture, Reply<Void> reply) { create(instanceManager.addHostCreatedInstance(videoCapture), reply); } }
packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/VideoCaptureFlutterApiImpl.java/0
{ "file_path": "packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/VideoCaptureFlutterApiImpl.java", "repo_id": "packages", "token_count": 273 }
925
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.camerax; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.app.Activity; import io.flutter.embedding.engine.systemchannels.PlatformChannel.DeviceOrientation; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugins.camerax.DeviceOrientationManager.DeviceOrientationChangeCallback; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.DeviceOrientationManagerFlutterApi.Reply; import org.junit.Rule; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.ArgumentMatchers; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; public class DeviceOrientationManagerWrapperTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); @Mock DeviceOrientationManager mockDeviceOrientationManager; @Mock public BinaryMessenger mockBinaryMessenger; @Mock public InstanceManager mockInstanceManager; @Test public void deviceOrientationManagerWrapper_handlesDeviceOrientationChangesAsExpected() { final DeviceOrientationManagerHostApiImpl hostApi = new DeviceOrientationManagerHostApiImpl(mockBinaryMessenger, mockInstanceManager); final CameraXProxy mockCameraXProxy = mock(CameraXProxy.class); final Activity mockActivity = mock(Activity.class); final Boolean isFrontFacing = true; final int sensorOrientation = 90; DeviceOrientationManagerFlutterApiImpl flutterApi = mock(DeviceOrientationManagerFlutterApiImpl.class); hostApi.deviceOrientationManagerFlutterApiImpl = flutterApi; hostApi.cameraXProxy = mockCameraXProxy; hostApi.setActivity(mockActivity); when(mockCameraXProxy.createDeviceOrientationManager( eq(mockActivity), eq(isFrontFacing), eq(sensorOrientation), any(DeviceOrientationChangeCallback.class))) .thenReturn(mockDeviceOrientationManager); final ArgumentCaptor<DeviceOrientationChangeCallback> deviceOrientationChangeCallbackCaptor = ArgumentCaptor.forClass(DeviceOrientationChangeCallback.class); hostApi.startListeningForDeviceOrientationChange( isFrontFacing, Long.valueOf(sensorOrientation)); // Test callback method defined in Flutter API is called when device orientation changes. verify(mockCameraXProxy) .createDeviceOrientationManager( eq(mockActivity), eq(isFrontFacing), eq(sensorOrientation), deviceOrientationChangeCallbackCaptor.capture()); DeviceOrientationChangeCallback deviceOrientationChangeCallback = deviceOrientationChangeCallbackCaptor.getValue(); deviceOrientationChangeCallback.onChange(DeviceOrientation.PORTRAIT_DOWN); verify(flutterApi) .sendDeviceOrientationChangedEvent( eq(DeviceOrientation.PORTRAIT_DOWN.toString()), ArgumentMatchers.<Reply<Void>>any()); // Test that the DeviceOrientationManager starts listening for device orientation changes. verify(mockDeviceOrientationManager).start(); // Test that the DeviceOrientationManager can stop listening for device orientation changes. hostApi.stopListeningForDeviceOrientationChange(); verify(mockDeviceOrientationManager).stop(); } @Test public void getDefaultDisplayRotation_returnsExpectedRotation() { final DeviceOrientationManagerHostApiImpl hostApi = new DeviceOrientationManagerHostApiImpl(mockBinaryMessenger, mockInstanceManager); final int defaultRotation = 180; hostApi.deviceOrientationManager = mockDeviceOrientationManager; when(mockDeviceOrientationManager.getDefaultRotation()).thenReturn(defaultRotation); assertEquals(hostApi.getDefaultDisplayRotation(), Long.valueOf(defaultRotation)); } }
packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/DeviceOrientationManagerWrapperTest.java/0
{ "file_path": "packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/DeviceOrientationManagerWrapperTest.java", "repo_id": "packages", "token_count": 1382 }
926
// 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' show BinaryMessenger, PlatformException; import 'package:meta/meta.dart' show immutable; import 'android_camera_camerax_flutter_api_impls.dart'; import 'camerax_library.g.dart'; import 'focus_metering_action.dart'; import 'focus_metering_result.dart'; import 'instance_manager.dart'; import 'java_object.dart'; import 'system_services.dart'; /// The interface that provides asynchronous operations like zoom and focus & /// metering, which affects output of all [UseCase]s currently bound to the /// corresponding [Camera] instance. /// /// See https://developer.android.com/reference/androidx/camera/core/CameraControl. @immutable class CameraControl extends JavaObject { /// Constructs a [CameraControl] that is not automatically attached to a native object. CameraControl.detached( {BinaryMessenger? binaryMessenger, InstanceManager? instanceManager}) : super.detached( binaryMessenger: binaryMessenger, instanceManager: instanceManager) { _api = _CameraControlHostApiImpl( binaryMessenger: binaryMessenger, instanceManager: instanceManager); AndroidCameraXCameraFlutterApis.instance.ensureSetUp(); } late final _CameraControlHostApiImpl _api; /// Enables or disables the torch of related [Camera] instance. /// /// If the torch mode was unable to be changed, an error message will be /// added to [SystemServices.cameraErrorStreamController]. Future<void> enableTorch(bool torch) async { return _api.enableTorchFromInstance(this, torch); } /// Sets zoom of related [Camera] by ratio. /// /// Ratio should be between what the `minZoomRatio` and `maxZoomRatio` of the /// [ZoomState] of the [CameraInfo] instance that is retrievable from the same /// [Camera] instance; otherwise, an error message will be added to /// [SystemServices.cameraErrorStreamController]. Future<void> setZoomRatio(double ratio) async { return _api.setZoomRatioFromInstance(this, ratio); } /// Starts a focus and metering action configured by the [FocusMeteringAction]. /// /// Will trigger an auto focus action and enable auto focus/auto exposure/ /// auto white balance metering regions. /// /// Only one [FocusMeteringAction] is allowed to run at a time; if multiple /// are executed in a row, only the latest one will work and other actions /// will be canceled. /// /// Returns null if focus and metering could not be started. Future<FocusMeteringResult?> startFocusAndMetering( FocusMeteringAction action) { return _api.startFocusAndMeteringFromInstance(this, action); } /// Cancels current [FocusMeteringAction] and clears auto focus/auto exposure/ /// auto white balance regions. Future<void> cancelFocusAndMetering() => _api.cancelFocusAndMeteringFromInstance(this); /// Sets the exposure compensation value for related [Camera] and returns the /// new target exposure value. /// /// The exposure compensation value set on the camera must be within the range /// of the current [ExposureState]'s `exposureCompensationRange` for the call /// to succeed. /// /// Only one [setExposureCompensationIndex] is allowed to run at a time; if /// multiple are executed in a row, only the latest setting will be kept in /// the camera. /// /// Returns null if the exposure compensation index failed to be set. Future<int?> setExposureCompensationIndex(int index) async { return _api.setExposureCompensationIndexFromInstance(this, index); } } /// Host API implementation of [CameraControl]. class _CameraControlHostApiImpl extends CameraControlHostApi { /// Constructs a [_CameraControlHostApiImpl]. /// /// An [instanceManager] is typically passed when a copy of an instance /// contained by an [InstanceManager] is being created. _CameraControlHostApiImpl( {this.binaryMessenger, InstanceManager? instanceManager}) : super(binaryMessenger: binaryMessenger) { this.instanceManager = instanceManager ?? JavaObject.globalInstanceManager; } /// Receives binary data across the Flutter platform barrier. /// /// If it is null, the default BinaryMessenger will be used which routes to /// the host platform. final BinaryMessenger? binaryMessenger; /// Maintains instances stored to communicate with native language objects. late final InstanceManager instanceManager; /// Enables or disables the torch for the specified [CameraControl] instance. Future<void> enableTorchFromInstance( CameraControl instance, bool torch) async { final int identifier = instanceManager.getIdentifier(instance)!; try { await enableTorch(identifier, torch); } on PlatformException catch (e) { SystemServices.cameraErrorStreamController .add(e.message ?? 'The camera was unable to change torch modes.'); } } /// Sets zoom of specified [CameraControl] instance by ratio. Future<void> setZoomRatioFromInstance( CameraControl instance, double ratio) async { final int identifier = instanceManager.getIdentifier(instance)!; try { await setZoomRatio(identifier, ratio); } on PlatformException catch (e) { SystemServices.cameraErrorStreamController.add(e.message ?? 'Zoom ratio was unable to be set. If ratio was not out of range, newer value may have been set; otherwise, the camera may be closed.'); } } /// Starts a focus and metering action configured by the [FocusMeteringAction] /// for the specified [CameraControl] instance. Future<FocusMeteringResult?> startFocusAndMeteringFromInstance( CameraControl instance, FocusMeteringAction action) async { final int cameraControlIdentifier = instanceManager.getIdentifier(instance)!; final int actionIdentifier = instanceManager.getIdentifier(action)!; try { final int? focusMeteringResultId = await startFocusAndMetering( cameraControlIdentifier, actionIdentifier); if (focusMeteringResultId == null) { SystemServices.cameraErrorStreamController.add( 'Starting focus and metering was canceled due to the camera being closed or a new request being submitted.'); return Future<FocusMeteringResult?>.value(); } return instanceManager.getInstanceWithWeakReference<FocusMeteringResult>( focusMeteringResultId); } on PlatformException catch (e) { SystemServices.cameraErrorStreamController .add(e.message ?? 'Starting focus and metering failed.'); // Surfacing error to differentiate an operation cancellation from an // illegal argument exception at a plugin layer. rethrow; } } /// Cancels current [FocusMeteringAction] and clears AF/AE/AWB regions for the /// specified [CameraControl] instance. Future<void> cancelFocusAndMeteringFromInstance( CameraControl instance) async { final int identifier = instanceManager.getIdentifier(instance)!; await cancelFocusAndMetering(identifier); } /// Sets exposure compensation index for specified [CameraControl] instance /// and returns the new target exposure value. Future<int?> setExposureCompensationIndexFromInstance( CameraControl instance, int index) async { final int identifier = instanceManager.getIdentifier(instance)!; try { final int? exposureCompensationIndex = await setExposureCompensationIndex(identifier, index); if (exposureCompensationIndex == null) { SystemServices.cameraErrorStreamController.add( 'Setting exposure compensation index was canceled due to the camera being closed or a new request being submitted.'); return Future<int?>.value(); } return exposureCompensationIndex; } on PlatformException catch (e) { SystemServices.cameraErrorStreamController.add(e.message ?? 'Setting the camera exposure compensation index failed.'); // Surfacing error to plugin layer to maintain consistency of // setExposureOffset implementation across platform implementations. rethrow; } } } /// Flutter API implementation of [CameraControl]. class CameraControlFlutterApiImpl extends CameraControlFlutterApi { /// Constructs a [CameraControlFlutterApiImpl]. /// /// If [binaryMessenger] is null, the default [BinaryMessenger] will be used, /// which routes to the host platform. /// /// An [instanceManager] is typically passed when a copy of an instance /// contained by an [InstanceManager] is being created. If left null, it /// will default to the global instance defined in [JavaObject]. CameraControlFlutterApiImpl({ BinaryMessenger? binaryMessenger, InstanceManager? instanceManager, }) : _binaryMessenger = binaryMessenger, _instanceManager = instanceManager ?? JavaObject.globalInstanceManager; /// Receives binary data across the Flutter platform barrier. final BinaryMessenger? _binaryMessenger; /// Maintains instances stored to communicate with native language objects. final InstanceManager _instanceManager; @override void create(int identifier) { _instanceManager.addHostCreatedInstance( CameraControl.detached( binaryMessenger: _binaryMessenger, instanceManager: _instanceManager), identifier, onCopy: (CameraControl original) { return CameraControl.detached( binaryMessenger: _binaryMessenger, instanceManager: _instanceManager); }, ); } }
packages/packages/camera/camera_android_camerax/lib/src/camera_control.dart/0
{ "file_path": "packages/packages/camera/camera_android_camerax/lib/src/camera_control.dart", "repo_id": "packages", "token_count": 2834 }
927
// 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. /// Maintains instances used to communicate with the native objects they /// represent. /// /// Added instances are stored as weak references and their copies are stored /// as strong references to maintain access to their variables and callback /// methods. Both are stored with the same identifier. /// /// When a weak referenced instance becomes inaccessible, /// [onWeakReferenceRemoved] is called with its associated identifier. /// /// If an instance is retrieved and has the possibility to be used, /// (e.g. calling [getInstanceWithWeakReference]) a copy of the strong reference /// is added as a weak reference with the same identifier. This prevents a /// scenario where the weak referenced instance was released and then later /// returned by the host platform. class InstanceManager { /// Constructs an [InstanceManager]. InstanceManager({required void Function(int) onWeakReferenceRemoved}) { this.onWeakReferenceRemoved = (int identifier) { _weakInstances.remove(identifier); onWeakReferenceRemoved(identifier); }; _finalizer = Finalizer<int>(this.onWeakReferenceRemoved); } // Identifiers are locked to a specific range to avoid collisions with objects // created simultaneously by the host platform. // Host uses identifiers >= 2^16 and Dart is expected to use values n where, // 0 <= n < 2^16. static const int _maxDartCreatedIdentifier = 65536; // Expando is used because it doesn't prevent its keys from becoming // inaccessible. This allows the manager to efficiently retrieve an identifier // of an instance without holding a strong reference to that instance. // // It also doesn't use `==` to search for identifiers, which would lead to an // infinite loop when comparing an object to its copy. (i.e. which was caused // by calling instanceManager.getIdentifier() inside of `==` while this was a // HashMap). final Expando<int> _identifiers = Expando<int>(); final Map<int, WeakReference<Object>> _weakInstances = <int, WeakReference<Object>>{}; final Map<int, Object> _strongInstances = <int, Object>{}; final Map<int, Function> _copyCallbacks = <int, Function>{}; late final Finalizer<int> _finalizer; int _nextIdentifier = 0; /// Called when a weak referenced instance is removed by [removeWeakReference] /// or becomes inaccessible. late final void Function(int) onWeakReferenceRemoved; /// Adds a new instance that was instantiated by Dart. /// /// In other words, Dart wants to add a new instance that will represent /// an object that will be instantiated on the host platform. /// /// Throws assertion error if the instance has already been added. /// /// Returns the randomly generated id of the [instance] added. int addDartCreatedInstance<T extends Object>( T instance, { required T Function(T original) onCopy, }) { final int identifier = _nextUniqueIdentifier(); _addInstanceWithIdentifier(instance, identifier, onCopy: onCopy); return identifier; } /// Removes the instance, if present, and call [onWeakReferenceRemoved] with /// its identifier. /// /// Returns the identifier associated with the removed instance. Otherwise, /// `null` if the instance was not found in this manager. /// /// This does not remove the the strong referenced instance associated with /// [instance]. This can be done with [remove]. int? removeWeakReference(Object instance) { final int? identifier = getIdentifier(instance); if (identifier == null) { return null; } _identifiers[instance] = null; _finalizer.detach(instance); onWeakReferenceRemoved(identifier); return identifier; } /// Removes [identifier] and its associated strongly referenced instance, if /// present, from the manager. /// /// Returns the strong referenced instance associated with [identifier] before /// it was removed. Returns `null` if [identifier] was not associated with /// any strong reference. /// /// This does not remove the the weak referenced instance associtated with /// [identifier]. This can be done with [removeWeakReference]. T? remove<T extends Object>(int identifier) { _copyCallbacks.remove(identifier); return _strongInstances.remove(identifier) as T?; } /// Retrieves the instance associated with identifier. /// /// The value returned is chosen from the following order: /// /// 1. A weakly referenced instance associated with identifier. /// 2. If the only instance associated with identifier is a strongly /// referenced instance, a copy of the instance is added as a weak reference /// with the same identifier. Returning the newly created copy. /// 3. If no instance is associated with identifier, returns null. /// /// This method also expects the host `InstanceManager` to have a strong /// reference to the instance the identifier is associated with. T? getInstanceWithWeakReference<T extends Object>(int identifier) { final T? weakInstance = _weakInstances[identifier]?.target as T?; if (weakInstance == null) { final T? strongInstance = _strongInstances[identifier] as T?; if (strongInstance != null) { final Function copyCallback = _copyCallbacks[identifier]!; // This avoid_dynamic_calls is safe since the type of strongInstance // matches the argument type for _addInstanceWithIdentifier, which is // the only place _copyCallbacks is populated. // ignore: avoid_dynamic_calls final T copy = copyCallback(strongInstance) as T; _identifiers[copy] = identifier; _weakInstances[identifier] = WeakReference<Object>(copy); _finalizer.attach(copy, identifier, detach: copy); return copy; } return strongInstance; } return weakInstance; } /// Retrieves the identifier associated with instance. int? getIdentifier(Object instance) { return _identifiers[instance]; } /// Adds a new instance that was instantiated by the host platform. /// /// In other words, the host platform wants to add a new instance that /// represents an object on the host platform. Stored with [identifier]. /// /// Throws assertion error if the instance or its identifier has already been /// added. /// /// Returns unique identifier of the [instance] added. void addHostCreatedInstance<T extends Object>( T instance, int identifier, { required T Function(T original) onCopy, }) { _addInstanceWithIdentifier(instance, identifier, onCopy: onCopy); } void _addInstanceWithIdentifier<T extends Object>( T instance, int identifier, { required T Function(T original) onCopy, }) { assert(!containsIdentifier(identifier)); assert(getIdentifier(instance) == null); assert(identifier >= 0); _identifiers[instance] = identifier; _weakInstances[identifier] = WeakReference<Object>(instance); _finalizer.attach(instance, identifier, detach: instance); final Object copy = onCopy(instance); _identifiers[copy] = identifier; _strongInstances[identifier] = copy; _copyCallbacks[identifier] = onCopy; } /// Whether this manager contains the given [identifier]. bool containsIdentifier(int identifier) { return _weakInstances.containsKey(identifier) || _strongInstances.containsKey(identifier); } int _nextUniqueIdentifier() { late int identifier; do { identifier = _nextIdentifier; _nextIdentifier = (_nextIdentifier + 1) % _maxDartCreatedIdentifier; } while (containsIdentifier(identifier)); return identifier; } }
packages/packages/camera/camera_android_camerax/lib/src/instance_manager.dart/0
{ "file_path": "packages/packages/camera/camera_android_camerax/lib/src/instance_manager.dart", "repo_id": "packages", "token_count": 2197 }
928
// Mocks generated by Mockito 5.4.4 from annotations // in camera_android_camerax/test/camera_info_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i5; import 'package:camera_android_camerax/src/camera_state.dart' as _i4; import 'package:camera_android_camerax/src/live_data.dart' as _i3; import 'package:camera_android_camerax/src/observer.dart' as _i6; import 'package:camera_android_camerax/src/zoom_state.dart' as _i7; import 'package:mockito/mockito.dart' as _i1; import 'test_camerax_library.g.dart' as _i2; // ignore_for_file: type=lint // ignore_for_file: avoid_redundant_argument_values // ignore_for_file: avoid_setters_without_getters // ignore_for_file: comment_references // ignore_for_file: deprecated_member_use // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types // ignore_for_file: subtype_of_sealed_class /// A class which mocks [TestCameraInfoHostApi]. /// /// See the documentation for Mockito's code generation for more information. class MockTestCameraInfoHostApi extends _i1.Mock implements _i2.TestCameraInfoHostApi { MockTestCameraInfoHostApi() { _i1.throwOnMissingStub(this); } @override int getSensorRotationDegrees(int? identifier) => (super.noSuchMethod( Invocation.method( #getSensorRotationDegrees, [identifier], ), returnValue: 0, ) as int); @override int getCameraState(int? identifier) => (super.noSuchMethod( Invocation.method( #getCameraState, [identifier], ), returnValue: 0, ) as int); @override int getExposureState(int? identifier) => (super.noSuchMethod( Invocation.method( #getExposureState, [identifier], ), returnValue: 0, ) as int); @override int getZoomState(int? identifier) => (super.noSuchMethod( Invocation.method( #getZoomState, [identifier], ), returnValue: 0, ) as int); } /// A class which mocks [TestInstanceManagerHostApi]. /// /// See the documentation for Mockito's code generation for more information. class MockTestInstanceManagerHostApi extends _i1.Mock implements _i2.TestInstanceManagerHostApi { MockTestInstanceManagerHostApi() { _i1.throwOnMissingStub(this); } @override void clear() => super.noSuchMethod( Invocation.method( #clear, [], ), returnValueForMissingStub: null, ); } /// A class which mocks [LiveData]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable class MockLiveCameraState extends _i1.Mock implements _i3.LiveData<_i4.CameraState> { MockLiveCameraState() { _i1.throwOnMissingStub(this); } @override _i5.Future<void> observe(_i6.Observer<_i4.CameraState>? observer) => (super.noSuchMethod( Invocation.method( #observe, [observer], ), returnValue: _i5.Future<void>.value(), returnValueForMissingStub: _i5.Future<void>.value(), ) as _i5.Future<void>); @override _i5.Future<void> removeObservers() => (super.noSuchMethod( Invocation.method( #removeObservers, [], ), returnValue: _i5.Future<void>.value(), returnValueForMissingStub: _i5.Future<void>.value(), ) as _i5.Future<void>); } /// A class which mocks [LiveData]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable class MockLiveZoomState extends _i1.Mock implements _i3.LiveData<_i7.ZoomState> { MockLiveZoomState() { _i1.throwOnMissingStub(this); } @override _i5.Future<void> observe(_i6.Observer<_i7.ZoomState>? observer) => (super.noSuchMethod( Invocation.method( #observe, [observer], ), returnValue: _i5.Future<void>.value(), returnValueForMissingStub: _i5.Future<void>.value(), ) as _i5.Future<void>); @override _i5.Future<void> removeObservers() => (super.noSuchMethod( Invocation.method( #removeObservers, [], ), returnValue: _i5.Future<void>.value(), returnValueForMissingStub: _i5.Future<void>.value(), ) as _i5.Future<void>); }
packages/packages/camera/camera_android_camerax/test/camera_info_test.mocks.dart/0
{ "file_path": "packages/packages/camera/camera_android_camerax/test/camera_info_test.mocks.dart", "repo_id": "packages", "token_count": 1911 }
929
// Mocks generated by Mockito 5.4.4 from annotations // in camera_android_camerax/test/fallback_strategy_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'package:camera_android_camerax/src/camerax_library.g.dart' as _i3; import 'package:mockito/mockito.dart' as _i1; import 'test_camerax_library.g.dart' as _i2; // ignore_for_file: type=lint // ignore_for_file: avoid_redundant_argument_values // ignore_for_file: avoid_setters_without_getters // ignore_for_file: comment_references // ignore_for_file: deprecated_member_use // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types // ignore_for_file: subtype_of_sealed_class /// A class which mocks [TestFallbackStrategyHostApi]. /// /// See the documentation for Mockito's code generation for more information. class MockTestFallbackStrategyHostApi extends _i1.Mock implements _i2.TestFallbackStrategyHostApi { MockTestFallbackStrategyHostApi() { _i1.throwOnMissingStub(this); } @override void create( int? identifier, _i3.VideoQuality? quality, _i3.VideoResolutionFallbackRule? fallbackRule, ) => super.noSuchMethod( Invocation.method( #create, [ identifier, quality, fallbackRule, ], ), returnValueForMissingStub: null, ); } /// A class which mocks [TestInstanceManagerHostApi]. /// /// See the documentation for Mockito's code generation for more information. class MockTestInstanceManagerHostApi extends _i1.Mock implements _i2.TestInstanceManagerHostApi { MockTestInstanceManagerHostApi() { _i1.throwOnMissingStub(this); } @override void clear() => super.noSuchMethod( Invocation.method( #clear, [], ), returnValueForMissingStub: null, ); }
packages/packages/camera/camera_android_camerax/test/fallback_strategy_test.mocks.dart/0
{ "file_path": "packages/packages/camera/camera_android_camerax/test/fallback_strategy_test.mocks.dart", "repo_id": "packages", "token_count": 806 }
930
// 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:camera_android_camerax/src/camera_state.dart'; import 'package:camera_android_camerax/src/camerax_library.g.dart'; import 'package:camera_android_camerax/src/instance_manager.dart'; import 'package:camera_android_camerax/src/observer.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'observer_test.mocks.dart'; import 'test_camerax_library.g.dart'; @GenerateMocks(<Type>[TestObserverHostApi, TestInstanceManagerHostApi]) void main() { TestWidgetsFlutterBinding.ensureInitialized(); // Mocks the call to clear the native InstanceManager. TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); group('Observer', () { tearDown(() { TestObserverHostApi.setup(null); }); test('HostApi create makes call to create Observer instance', () { final MockTestObserverHostApi mockApi = MockTestObserverHostApi(); TestObserverHostApi.setup(mockApi); final InstanceManager instanceManager = InstanceManager( onWeakReferenceRemoved: (_) {}, ); final Observer<dynamic> instance = Observer<dynamic>( instanceManager: instanceManager, onChanged: (Object value) {}, ); verify(mockApi.create( instanceManager.getIdentifier(instance), )); }); test( 'HostAPI create makes Observer instance that throws assertion error if onChanged receives unexpected parameter type', () { final MockTestObserverHostApi mockApi = MockTestObserverHostApi(); TestObserverHostApi.setup(mockApi); final Observer<String> cameraStateObserver = Observer<String>.detached(onChanged: (Object value) {}); expect( () => cameraStateObserver.onChanged( CameraState.detached(type: CameraStateType.pendingOpen)), throwsAssertionError); }); test( 'FlutterAPI onChanged makes call with expected parameter to Observer instance onChanged callback', () { final InstanceManager instanceManager = InstanceManager( onWeakReferenceRemoved: (_) {}, ); const int instanceIdentifier = 0; late final Object? callbackParameter; final Observer<CameraState> instance = Observer<CameraState>.detached( onChanged: (Object value) { callbackParameter = value; }, instanceManager: instanceManager, ); instanceManager.addHostCreatedInstance( instance, instanceIdentifier, onCopy: (Observer<CameraState> original) => Observer<CameraState>.detached( onChanged: original.onChanged, instanceManager: instanceManager, ), ); final ObserverFlutterApiImpl flutterApi = ObserverFlutterApiImpl( instanceManager: instanceManager, ); const CameraStateType cameraStateType = CameraStateType.closed; final CameraState value = CameraState.detached( instanceManager: instanceManager, type: cameraStateType, ); const int valueIdentifier = 11; instanceManager.addHostCreatedInstance( value, valueIdentifier, onCopy: (_) => CameraState.detached( instanceManager: instanceManager, type: cameraStateType, ), ); flutterApi.onChanged( instanceIdentifier, valueIdentifier, ); expect(callbackParameter, value); }); }); }
packages/packages/camera/camera_android_camerax/test/observer_test.dart/0
{ "file_path": "packages/packages/camera/camera_android_camerax/test/observer_test.dart", "repo_id": "packages", "token_count": 1374 }
931
// 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'; import 'package:camera_android_camerax/src/aspect_ratio_strategy.dart'; import 'package:camera_android_camerax/src/instance_manager.dart'; import 'package:camera_android_camerax/src/resolution_selector.dart'; import 'package:camera_android_camerax/src/resolution_strategy.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'resolution_selector_test.mocks.dart'; import 'test_camerax_library.g.dart'; @GenerateMocks(<Type>[ AspectRatioStrategy, ResolutionStrategy, TestResolutionSelectorHostApi, TestInstanceManagerHostApi, ]) void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('ResolutionSelector', () { tearDown(() { TestResolutionSelectorHostApi.setup(null); TestInstanceManagerHostApi.setup(null); }); test( 'detached constructor does not make call to create expected AspectRatioStrategy instance', () async { final MockTestResolutionSelectorHostApi mockApi = MockTestResolutionSelectorHostApi(); TestResolutionSelectorHostApi.setup(mockApi); TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); final InstanceManager instanceManager = InstanceManager( onWeakReferenceRemoved: (_) {}, ); const int preferredAspectRatio = 1; const int fallbackRule = 1; AspectRatioStrategy.detached( preferredAspectRatio: preferredAspectRatio, fallbackRule: fallbackRule, instanceManager: instanceManager, ); ResolutionSelector.detached( resolutionStrategy: MockResolutionStrategy(), aspectRatioStrategy: MockAspectRatioStrategy(), instanceManager: instanceManager, ); verifyNever(mockApi.create( argThat(isA<int>()), argThat(isA<int>()), argThat(isA<int>()), )); }); test('HostApi create creates expected ResolutionSelector instance', () { final MockTestResolutionSelectorHostApi mockApi = MockTestResolutionSelectorHostApi(); TestResolutionSelectorHostApi.setup(mockApi); TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); final InstanceManager instanceManager = InstanceManager( onWeakReferenceRemoved: (_) {}, ); final ResolutionStrategy resolutionStrategy = ResolutionStrategy.detached( boundSize: const Size(50, 30), fallbackRule: ResolutionStrategy.fallbackRuleClosestLower, instanceManager: instanceManager, ); const int resolutionStrategyIdentifier = 14; instanceManager.addHostCreatedInstance( resolutionStrategy, resolutionStrategyIdentifier, onCopy: (ResolutionStrategy original) => ResolutionStrategy.detached( boundSize: original.boundSize, fallbackRule: original.fallbackRule, instanceManager: instanceManager, ), ); final AspectRatioStrategy aspectRatioStrategy = AspectRatioStrategy.detached( preferredAspectRatio: AspectRatio.ratio4To3, fallbackRule: AspectRatioStrategy.fallbackRuleAuto, instanceManager: instanceManager, ); const int aspectRatioStrategyIdentifier = 15; instanceManager.addHostCreatedInstance( aspectRatioStrategy, aspectRatioStrategyIdentifier, onCopy: (AspectRatioStrategy original) => AspectRatioStrategy.detached( preferredAspectRatio: original.preferredAspectRatio, fallbackRule: original.fallbackRule, instanceManager: instanceManager, ), ); final ResolutionSelector instance = ResolutionSelector( resolutionStrategy: resolutionStrategy, aspectRatioStrategy: aspectRatioStrategy, instanceManager: instanceManager, ); verify(mockApi.create( instanceManager.getIdentifier(instance), resolutionStrategyIdentifier, aspectRatioStrategyIdentifier, )); }); }); }
packages/packages/camera/camera_android_camerax/test/resolution_selector_test.dart/0
{ "file_path": "packages/packages/camera/camera_android_camerax/test/resolution_selector_test.dart", "repo_id": "packages", "token_count": 1600 }
932
name: camera_windows description: A Flutter plugin for getting information about and controlling the camera on Windows. repository: https://github.com/flutter/packages/tree/main/packages/camera/camera_windows issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+camera%22 version: 0.2.1+9 environment: sdk: ^3.1.0 flutter: ">=3.13.0" flutter: plugin: implements: camera platforms: windows: pluginClass: CameraWindows dartPluginClass: CameraWindows dependencies: camera_platform_interface: ^2.3.1 cross_file: ^0.3.1 flutter: sdk: flutter stream_transform: ^2.0.0 dev_dependencies: async: ^2.5.0 flutter_test: sdk: flutter topics: - camera
packages/packages/camera/camera_windows/pubspec.yaml/0
{ "file_path": "packages/packages/camera/camera_windows/pubspec.yaml", "repo_id": "packages", "token_count": 294 }
933
// 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:dynamic_layouts/dynamic_layouts.dart'; import 'package:flutter/material.dart'; void main() { runApp(const StaggeredExample()); } /// A staggered layout example. Clicking the upper-right button will change /// between a grid with a fixed cross axis count and one with a main axis /// extent. class StaggeredExample extends StatefulWidget { /// Creates a [StaggeredExample]. const StaggeredExample({super.key}); @override State<StaggeredExample> createState() => _StaggeredExampleState(); } class _StaggeredExampleState extends State<StaggeredExample> { final List<Widget> children = List<Widget>.generate( 50, (int index) => _DynamicSizedTile(index: index), ); bool fixedCrossAxisCount = true; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Staggered Layout Example'), actions: <Widget>[ Padding( padding: const EdgeInsets.only(right: 50.0), child: TextButton( onPressed: () { setState(() { fixedCrossAxisCount = !fixedCrossAxisCount; }); }, child: Text( fixedCrossAxisCount ? 'FIXED' : 'MAX', style: const TextStyle(color: Colors.white), ), ), ), ], ), floatingActionButton: FloatingActionButton( onPressed: () { setState(() { children.add(_DynamicSizedTile(index: children.length)); }); }, child: const Icon(Icons.plus_one), ), body: fixedCrossAxisCount ? DynamicGridView.staggered( crossAxisCount: 4, children: <Widget>[...children], ) : DynamicGridView.staggered( maxCrossAxisExtent: 100, children: <Widget>[...children], ), ); } } class _DynamicSizedTile extends StatelessWidget { const _DynamicSizedTile({required this.index}); final int index; @override Widget build(BuildContext context) { return Container( height: index % 3 * 50 + 20, color: Colors.amber[(index % 8 + 1) * 100], child: Text('Index $index'), ); } }
packages/packages/dynamic_layouts/example/lib/staggered_layout_example.dart/0
{ "file_path": "packages/packages/dynamic_layouts/example/lib/staggered_layout_example.dart", "repo_id": "packages", "token_count": 1038 }
934
// 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:math' as math; import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'base_grid_layout.dart'; /// A sliver that places multiple box children in a two dimensional arrangement. /// /// [RenderDynamicSliverGrid] places its children in arbitrary positions determined by /// the [DynamicSliverGridLayout] provided by the [gridDelegate]. /// /// {@macro dynamicLayouts.garbageCollection} class RenderDynamicSliverGrid extends RenderSliverGrid { /// Creates a sliver that contains multiple box children whose size and /// position are managed by a delegate. /// /// The [childManager] and [gridDelegate] arguments must not be null. RenderDynamicSliverGrid({ required super.childManager, required super.gridDelegate, }); @override void performLayout() { final SliverConstraints constraints = this.constraints; childManager.didStartLayout(); childManager.setDidUnderflow(false); final double scrollOffset = constraints.scrollOffset + constraints.cacheOrigin; assert(scrollOffset >= 0.0); final double remainingExtent = constraints.remainingCacheExtent; assert(remainingExtent >= 0.0); final double targetEndScrollOffset = scrollOffset + remainingExtent; final DynamicSliverGridLayout layout = gridDelegate.getLayout(constraints) as DynamicSliverGridLayout; int leadingGarbage = 0; int trailingGarbage = 0; bool reachedEnd = false; // This algorithm in principle is straight-forward: find the first child // that overlaps the given scrollOffset, creating more children at the top // of the grid if necessary, then walk through the grid updating and laying // out each child and adding more at the end if necessary until we have // enough children to cover the entire viewport. // // It is complicated by one minor issue, which is that any time you update // or create a child, it's possible that some of the children that // haven't yet been laid out will be removed, leaving the list in an // inconsistent state, and requiring that missing nodes be recreated. // // To keep this mess tractable, this algorithm starts from what is currently // the first child, if any, and then walks up and/or down from there, so // that the nodes that might get removed are always at the edges of what has // already been laid out. // Make sure we have at least one child to start from. if (firstChild == null && !addInitialChild()) { // There are no children. geometry = SliverGeometry.zero; childManager.didFinishLayout(); return; } // We have at least one child. assert(firstChild != null); // These variables track the range of children that we have laid out. Within // this range, the children have consecutive indices. Outside this range, // it's possible for a child to get removed without notice. RenderBox? leadingChildWithLayout, trailingChildWithLayout; RenderBox? earliestUsefulChild = firstChild; // A firstChild with null layout offset is likely a result of children // reordering. // // We rely on firstChild to have accurate layout offset. In the case of null // layout offset, we have to find the first child that has valid layout // offset. if (childScrollOffset(firstChild!) == null) { int leadingChildrenWithoutLayoutOffset = 0; while (earliestUsefulChild != null && childScrollOffset(earliestUsefulChild) == null) { earliestUsefulChild = childAfter(earliestUsefulChild); leadingChildrenWithoutLayoutOffset += 1; } // We should be able to destroy children with null layout offset safely, // because they are likely outside of viewport collectGarbage(leadingChildrenWithoutLayoutOffset, 0); // If we cannot find a valid layout offset, start from the initial child. if (firstChild == null && !addInitialChild()) { // There are no children. geometry = SliverGeometry.zero; childManager.didFinishLayout(); return; } } // Find the last child that is at or before the scrollOffset. earliestUsefulChild = firstChild; assert(earliestUsefulChild != null); for (int index = indexOf(earliestUsefulChild!) - 1; childScrollOffset(earliestUsefulChild!)! > scrollOffset; --index) { final double earliestScrollOffset = childScrollOffset(earliestUsefulChild)!; // We have to add children before the earliestUsefulChild. SliverGridGeometry gridGeometry = layout.getGeometryForChildIndex(index); earliestUsefulChild = insertAndLayoutLeadingChild( gridGeometry.getBoxConstraints(constraints), parentUsesSize: true, ); // There are no more preceding children. if (earliestUsefulChild == null) { final SliverGridParentData childParentData = firstChild!.parentData! as SliverGridParentData; childParentData.layoutOffset = gridGeometry.scrollOffset; childParentData.crossAxisOffset = gridGeometry.crossAxisOffset; if (scrollOffset == 0.0) { // insertAndLayoutLeadingChild only lays out the children before // firstChild. In this case, nothing has been laid out. We have // to lay out firstChild manually. gridGeometry = layout.getGeometryForChildIndex(0); firstChild!.layout(gridGeometry.getBoxConstraints(constraints), parentUsesSize: true); earliestUsefulChild = firstChild; leadingChildWithLayout = earliestUsefulChild; trailingChildWithLayout ??= earliestUsefulChild; break; } else { // We ran out of children before reaching the scroll offset. // We must inform our parent that this sliver cannot fulfill // its contract and that we need a scroll offset correction. geometry = SliverGeometry( scrollOffsetCorrection: -scrollOffset, ); return; } } final double firstChildScrollOffset = earliestScrollOffset - paintExtentOf(firstChild!); // firstChildScrollOffset may contain double precision error if (firstChildScrollOffset < -precisionErrorTolerance) { // Let's assume there is no child before the first child. We will // correct it on the next layout if it is not. geometry = SliverGeometry( scrollOffsetCorrection: -firstChildScrollOffset, ); final SliverGridParentData childParentData = firstChild!.parentData! as SliverGridParentData; childParentData.layoutOffset = gridGeometry.scrollOffset; childParentData.crossAxisOffset = gridGeometry.crossAxisOffset; return; } final SliverGridParentData childParentData = earliestUsefulChild.parentData! as SliverGridParentData; gridGeometry = layout.updateGeometryForChildIndex( indexOf(earliestUsefulChild), earliestUsefulChild.size); childParentData.layoutOffset = gridGeometry.scrollOffset; childParentData.crossAxisOffset = gridGeometry.crossAxisOffset; assert(earliestUsefulChild == firstChild); leadingChildWithLayout = earliestUsefulChild; trailingChildWithLayout ??= earliestUsefulChild; } assert(childScrollOffset(firstChild!)! > -precisionErrorTolerance); // If the scroll offset is at zero, we should make sure we are // actually at the beginning of the list. if (scrollOffset < precisionErrorTolerance) { // We iterate from the firstChild in case the leading child has a 0 paint // extent. int indexOfFirstChild = indexOf(firstChild!); while (indexOfFirstChild > 0) { final double earliestScrollOffset = childScrollOffset(firstChild!)!; // We correct one child at a time. If there are more children before // the earliestUsefulChild, we will correct it once the scroll offset // reaches zero again. SliverGridGeometry gridGeometry = layout.getGeometryForChildIndex(indexOfFirstChild - 1); earliestUsefulChild = insertAndLayoutLeadingChild( gridGeometry.getBoxConstraints(constraints), parentUsesSize: true, ); assert(earliestUsefulChild != null); final double firstChildScrollOffset = earliestScrollOffset - paintExtentOf(firstChild!); final SliverGridParentData childParentData = firstChild!.parentData! as SliverGridParentData; gridGeometry = layout.updateGeometryForChildIndex( indexOfFirstChild - 1, firstChild!.size); childParentData.layoutOffset = gridGeometry.scrollOffset; childParentData.crossAxisOffset = gridGeometry.crossAxisOffset; // We only need to correct if the leading child actually has a // paint extent. if (firstChildScrollOffset < -precisionErrorTolerance) { geometry = SliverGeometry( scrollOffsetCorrection: -firstChildScrollOffset, ); return; } indexOfFirstChild = indexOf(firstChild!); } } // At this point, earliestUsefulChild is the first child, and is a child // whose scrollOffset is at or before the scrollOffset, and // leadingChildWithLayout and trailingChildWithLayout are either null or // cover a range of render boxes that we have laid out with the first being // the same as earliestUsefulChild and the last being either at or after the // scroll offset. assert(earliestUsefulChild == firstChild); assert(childScrollOffset(earliestUsefulChild!)! <= scrollOffset); // Make sure we've laid out at least one child. if (leadingChildWithLayout == null) { final int index = indexOf(earliestUsefulChild!); SliverGridGeometry gridGeometry = layout.getGeometryForChildIndex(index); earliestUsefulChild.layout( gridGeometry.getBoxConstraints(constraints), parentUsesSize: true, ); leadingChildWithLayout = earliestUsefulChild; trailingChildWithLayout = earliestUsefulChild; gridGeometry = layout.updateGeometryForChildIndex(index, earliestUsefulChild.size); final SliverGridParentData childParentData = earliestUsefulChild.parentData! as SliverGridParentData; childParentData.layoutOffset = gridGeometry.scrollOffset; childParentData.crossAxisOffset = gridGeometry.crossAxisOffset; } // Here, earliestUsefulChild is still the first child, it's got a // scrollOffset that is at or before our actual scrollOffset, and it has // been laid out, and is in fact our leadingChildWithLayout. It's possible // that some children beyond that one have also been laid out. bool inLayoutRange = true; RenderBox? child = earliestUsefulChild; int index = indexOf(child!); double endScrollOffset = childScrollOffset(child)! + paintExtentOf(child); bool advance() { // returns true if we advanced, false if we have no more children // This function is used in two different places below, to avoid code duplication. late SliverGridGeometry gridGeometry; assert(child != null); if (child == trailingChildWithLayout) { inLayoutRange = false; } child = childAfter(child!); if (child == null) { inLayoutRange = false; } index += 1; if (!inLayoutRange) { if (child == null || indexOf(child!) != index) { // We are missing a child. Insert it (and lay it out) if possible. gridGeometry = layout .getGeometryForChildIndex(indexOf(trailingChildWithLayout!) + 1); child = insertAndLayoutChild( gridGeometry.getBoxConstraints(constraints), after: trailingChildWithLayout, parentUsesSize: true, ); if (child == null) { // We have run out of children. return false; } } else { // Lay out the child. assert(indexOf(child!) == index); gridGeometry = layout.getGeometryForChildIndex(index); child!.layout( gridGeometry.getBoxConstraints(constraints), parentUsesSize: true, ); } trailingChildWithLayout = child; } assert(child != null); final SliverGridParentData childParentData = child!.parentData! as SliverGridParentData; gridGeometry = layout.updateGeometryForChildIndex(index, child!.size); childParentData.layoutOffset = gridGeometry.scrollOffset; childParentData.crossAxisOffset = gridGeometry.crossAxisOffset; assert(childParentData.index == index); // The current child may not extend past a previously laid out child. endScrollOffset = math.max( endScrollOffset, childScrollOffset(child!)! + paintExtentOf(child!), ); return true; } // Find the first child that ends after the scroll offset. while (endScrollOffset < scrollOffset) { leadingGarbage += 1; if (!advance()) { assert(leadingGarbage == childCount); assert(child == null); // we want to make sure we keep the last child around so we know the end // scroll offset collectGarbage(leadingGarbage - 1, 0); assert(firstChild == lastChild); final double extent = childScrollOffset(lastChild!)! + paintExtentOf(lastChild!); geometry = SliverGeometry( scrollExtent: extent, maxPaintExtent: extent, ); return; } } // Now find the first child that ends after our end. while (endScrollOffset < targetEndScrollOffset || !layout.reachedTargetScrollOffset(targetEndScrollOffset)) { if (!advance()) { reachedEnd = true; break; } } // Finally count up all the remaining children and label them as garbage. if (child != null) { child = childAfter(child!); while (child != null) { trailingGarbage += 1; child = childAfter(child!); } } // At this point everything should be good to go, we just have to clean up // the garbage and report the geometry. // We only collect trailing garbage because // // 1 - dynamic tile placement is dependent on the preceding tile, // potentially, the SliverGridLayout could cache the placement of each // tile to refer back to, but that would mean tiles could not change in // size or be added/removed without having to recompute the whole layout. // // 2 - Currently, Flutter only supports collecting garbage in sequential // order. Dynamic layout patterns can break this assumption. In order to // truly collect garbage efficiently, support for non-sequential garbage // collection is necessary. // TODO(all): https://github.com/flutter/flutter/issues/112234 collectGarbage(0, trailingGarbage); assert(debugAssertChildListIsNonEmptyAndContiguous()); final double estimatedMaxScrollOffset; if (reachedEnd) { estimatedMaxScrollOffset = endScrollOffset; } else { estimatedMaxScrollOffset = childManager.estimateMaxScrollOffset( constraints, firstIndex: indexOf(firstChild!), lastIndex: indexOf(lastChild!), leadingScrollOffset: childScrollOffset(firstChild!), trailingScrollOffset: endScrollOffset, ); assert(estimatedMaxScrollOffset >= endScrollOffset - childScrollOffset(firstChild!)!); } final double paintExtent = calculatePaintOffset( constraints, from: childScrollOffset(firstChild!)!, to: endScrollOffset, ); final double cacheExtent = calculateCacheOffset( constraints, from: childScrollOffset(firstChild!)!, to: endScrollOffset, ); final double targetEndScrollOffsetForPaint = constraints.scrollOffset + constraints.remainingPaintExtent; geometry = SliverGeometry( scrollExtent: estimatedMaxScrollOffset, paintExtent: paintExtent, cacheExtent: cacheExtent, maxPaintExtent: estimatedMaxScrollOffset, // Conservative to avoid flickering away the clip during scroll. hasVisualOverflow: endScrollOffset > targetEndScrollOffsetForPaint || constraints.scrollOffset > 0.0, ); // We may have started the layout while scrolled to the end, which would not // expose a new child. if (estimatedMaxScrollOffset == endScrollOffset) { childManager.setDidUnderflow(true); } childManager.didFinishLayout(); } }
packages/packages/dynamic_layouts/lib/src/render_dynamic_grid.dart/0
{ "file_path": "packages/packages/dynamic_layouts/lib/src/render_dynamic_grid.dart", "repo_id": "packages", "token_count": 5885 }
935
group 'com.example.espresso' version '1.0' buildscript { repositories { google() mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:7.4.1' } } rootProject.allprojects { repositories { google() mavenCentral() } } apply plugin: 'com.android.library' android { // Conditional for compatibility with AGP <4.2. if (project.android.hasProperty("namespace")) { namespace 'com.example.espresso' } compileSdk 34 defaultConfig { minSdkVersion 16 testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } lintOptions { checkAllWarnings true warningsAsErrors true disable 'AndroidGradlePluginVersion', 'InvalidPackage', 'GradleDependency' baseline file("lint-baseline.xml") } testOptions { unitTests.includeAndroidResources = true unitTests.returnDefaultValues = true unitTests.all { testLogging { events "passed", "skipped", "failed", "standardOut", "standardError" outputs.upToDateWhen {false} showStandardStreams = true } } } } dependencies { implementation 'com.google.guava:guava:31.1-android' implementation 'com.squareup.okhttp3:okhttp:4.11.0' implementation 'com.google.code.gson:gson:2.10.1' androidTestImplementation 'org.hamcrest:hamcrest:2.2' testImplementation 'junit:junit:4.13.2' testImplementation "com.google.truth:truth:1.1.3" api 'androidx.test:runner:1.1.1' api 'androidx.test.espresso:espresso-core:3.5.1' // Core library api 'androidx.test:core:1.0.0' // AndroidJUnitRunner and JUnit Rules api 'androidx.test:runner:1.1.0' api 'androidx.test:rules:1.1.0' // Assertions api 'androidx.test.ext:junit:1.1.5' api 'androidx.test.ext:truth:1.5.0' api 'com.google.truth:truth:1.1.3' // Espresso dependencies api 'androidx.test.espresso:espresso-core:3.5.1' api 'androidx.test.espresso:espresso-contrib:3.5.1' api 'androidx.test.espresso:espresso-intents:3.5.1' api 'androidx.test.espresso:espresso-accessibility:3.5.1' api 'androidx.test.espresso:espresso-web:3.5.1' api 'androidx.test.espresso.idling:idling-concurrent:3.5.1' // The following Espresso dependency can be either "implementation" // or "androidTestImplementation", depending on whether you want the // dependency to appear on your APK's compile classpath or the test APK // classpath. api 'androidx.test.espresso:espresso-idling-resource:3.5.1' }
packages/packages/espresso/android/build.gradle/0
{ "file_path": "packages/packages/espresso/android/build.gradle", "repo_id": "packages", "token_count": 1179 }
936
// 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 androidx.test.espresso.flutter.api; import android.graphics.Rect; import androidx.test.espresso.flutter.model.WidgetInfo; import com.google.common.annotations.Beta; import java.util.concurrent.Future; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** Defines the testing protocol/semantics between Espresso and Flutter. */ @Beta public interface FlutterTestingProtocol { /** Returns a future that waits until the Flutter testing protocol is in a usable state. */ public Future<Void> connect(); /** * Performs a synthetic action on the Flutter widget that matches the given {@code widgetMatcher}. * * <p>If failed to perform the given {@code action}, returns a {@code Future} containing an {@code * ExecutionException} that wraps the following exception: * * <ul> * <li>{@code AmbiguousWidgetMatcherException} if the given {@code widgetMatcher} matched * multiple widgets in the hierarchy when only one widget was expected. * <li>{@code NoMatchingWidgetException} if the given {@code widgetMatcher} did not match any * widget in the Flutter UI hierarchy. * <li>{@code ConnectException} if connection error occurred. * </ul> * * @param widgetMatcher the matcher to match a Flutter widget. If {@code null}, {@code action} is * not performed on a specific widget. * @param action the action to be performed on the widget. * @return a {@code Future} representing pending completion of performing the action, or yields an * exception if the action was failed to perform. */ Future<Void> perform(@Nullable WidgetMatcher widgetMatcher, @Nonnull SyntheticAction action); /** * Returns a Java representation of the Flutter widget that matches the given widget matcher. * * <p>If failed to find a matching widget, returns a {@code Future} containing an {@code * ExecutionException} that wraps the following exception: * * <ul> * <li>{@code AmbiguousWidgetMatcherException} if the given {@code widgetMatcher} matched * multiple widgets in the hierarchy when only one widget was expected. * <li>{@code NoMatchingWidgetException} if the given {@code widgetMatcher} did not match any * widget in the Flutter UI hierarchy. * <li>{@code ConnectException} if connection error occurred. * </ul> * * @param widgetMatcher the matcher to match a Flutter widget. Cannot be {@code null}. * @return a {@code Future} representing pending completion of the matching operation. */ Future<WidgetInfo> matchWidget(@Nonnull WidgetMatcher widgetMatcher); /** * Returns the local (as relative to its outer Flutter View) rectangle area of a widget that * matches the given widget matcher. * * @param widgetMatcher the matcher to match a Flutter widget. Cannot be {@code null}. * @return a rectangle area where the matched widget lives, in the unit of dp (Density-independent * Pixel). */ Future<Rect> getLocalRect(@Nonnull WidgetMatcher widgetMatcher); /** Waits until the Flutter frame is in a stable state. */ Future<Void> waitUntilIdle(); /** Releases all the resources associated with this testing protocol connection. */ void close(); }
packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/api/FlutterTestingProtocol.java/0
{ "file_path": "packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/api/FlutterTestingProtocol.java", "repo_id": "packages", "token_count": 1010 }
937
// 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 androidx.test.espresso.flutter.internal.jsonrpc.message; import com.google.gson.JsonObject; import java.util.Objects; /** * A class for holding the error object in {@code JsonRpcResponse}. * * <p>See https://www.jsonrpc.org/specification#error_object for detailed specification. */ public class ErrorObject { private final int code; private final String message; private final JsonObject data; public ErrorObject(int code, String message) { this(code, message, null); } public ErrorObject(int code, String message, JsonObject data) { this.code = code; this.message = message; this.data = data; } /** Gets the error code. */ public int getCode() { return code; } /** Gets the error message. */ public String getMessage() { return message; } /** Gets the additional information about the error. Could be null. */ public JsonObject getData() { return data; } @Override public boolean equals(Object obj) { if (obj instanceof ErrorObject) { ErrorObject errorObject = (ErrorObject) obj; return errorObject.code == this.code && Objects.equals(errorObject.message, this.message) && Objects.equals(errorObject.data, this.data); } else { return false; } } @Override public int hashCode() { int hash = code; hash = hash * 31 + Objects.hashCode(message); hash = hash * 31 + Objects.hashCode(data); return hash; } }
packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/ErrorObject.java/0
{ "file_path": "packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/ErrorObject.java", "repo_id": "packages", "token_count": 536 }
938
// 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 androidx.test.espresso.flutter.internal.protocol.impl; import static com.google.common.base.Preconditions.checkNotNull; import android.util.Log; import androidx.test.espresso.flutter.model.WidgetInfo; import androidx.test.espresso.flutter.model.WidgetInfoBuilder; /** A factory that creates {@link WidgetInfo} instances. */ final class WidgetInfoFactory { private static final String TAG = WidgetInfoFactory.class.getSimpleName(); private enum WidgetRuntimeType { TEXT("Text"), RICH_TEXT("RichText"), UNKNOWN("Unknown"); private WidgetRuntimeType(String typeString) { this.type = typeString; } private final String type; @Override public String toString() { return type; } public static WidgetRuntimeType getType(String typeString) { for (WidgetRuntimeType widgetType : WidgetRuntimeType.values()) { if (widgetType.type.equals(typeString)) { return widgetType; } } return UNKNOWN; } } /** * Creates a {@code WidgetInfo} instance based on the given diagnostics info. * * <p>The current implementation is ugly. As the widget's properties are serialized out as JSON * strings, we have to inspect the content based on the widget type. * * @throws FlutterProtocolException when the given {@code widgetDiagnostics} is invalid. */ public static WidgetInfo createWidgetInfo(GetWidgetDiagnosticsResponse widgetDiagnostics) { checkNotNull(widgetDiagnostics, "The widget diagnostics instance is null."); WidgetInfoBuilder widgetInfo = new WidgetInfoBuilder(); if (widgetDiagnostics.getRuntimeType() == null) { throw new FlutterProtocolException( String.format( "The widget diagnostics info must contain the runtime type of the widget. Illegal" + " widget diagnostics info: %s.", widgetDiagnostics)); } widgetInfo.setRuntimeType(widgetDiagnostics.getRuntimeType()); // Ugly, but let's figure out a better way as this evolves. switch (WidgetRuntimeType.getType(widgetDiagnostics.getRuntimeType())) { case TEXT: // Flutter Text Widget's "data" field stores the text info. if (widgetDiagnostics.getPropertyByName("data") != null) { String text = widgetDiagnostics.getPropertyByName("data").getValue(); widgetInfo.setText(text); } break; case RICH_TEXT: if (widgetDiagnostics.getPropertyByName("text") != null) { String richText = widgetDiagnostics.getPropertyByName("text").getValue(); widgetInfo.setText(richText); } break; default: // Let's be silent when we know little about the widget's type. // The widget's fields will be mostly empty but it can be used for checking the existence // of the widget. Log.i( TAG, String.format( "Unknown widget type: %s. Widget diagnostics info: %s.", widgetDiagnostics.getRuntimeType(), widgetDiagnostics)); } return widgetInfo.build(); } }
packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/WidgetInfoFactory.java/0
{ "file_path": "packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/WidgetInfoFactory.java", "repo_id": "packages", "token_count": 1179 }
939
def localProperties = new Properties() def localPropertiesFile = rootProject.file('local.properties') if (localPropertiesFile.exists()) { localPropertiesFile.withReader('UTF-8') { reader -> localProperties.load(reader) } } def flutterRoot = localProperties.getProperty('flutter.sdk') if (flutterRoot == null) { throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.") } def flutterVersionCode = localProperties.getProperty('flutter.versionCode') if (flutterVersionCode == null) { flutterVersionCode = '1' } def flutterVersionName = localProperties.getProperty('flutter.versionName') if (flutterVersionName == null) { flutterVersionName = '1.0' } apply plugin: 'com.android.application' apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" android { compileSdk flutter.compileSdkVersion // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). namespace "com.example.espresso_example" defaultConfig { minSdkVersion flutter.minSdkVersion targetSdkVersion 29 versionCode flutterVersionCode.toInteger() versionName flutterVersionName testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" multiDexEnabled true } buildTypes { release { // TODO: Add your own signing config for the release build. // Signing with the debug keys for now, so `flutter run --release` works. signingConfig signingConfigs.debug } } lint { disable 'InvalidPackage' } } flutter { source '../..' } dependencies { testImplementation 'junit:junit:4.13.2' // Multidex implementation "androidx.multidex:multidex:2.0.1" // Core library api 'androidx.test:core:1.2.0' // AndroidJUnitRunner and JUnit Rules androidTestImplementation 'androidx.test:runner:1.2.0' androidTestImplementation 'androidx.test:rules:1.1.0' // Assertions androidTestImplementation 'androidx.test.ext:junit:1.0.0' androidTestImplementation 'androidx.test.ext:truth:1.0.0' androidTestImplementation 'com.google.truth:truth:1.1.3' // Espresso dependencies androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0' androidTestImplementation 'androidx.test.espresso:espresso-contrib:3.1.0' androidTestImplementation 'androidx.test.espresso:espresso-intents:3.1.0' androidTestImplementation 'androidx.test.espresso:espresso-accessibility:3.1.0' androidTestImplementation 'androidx.test.espresso:espresso-web:3.1.0' androidTestImplementation 'androidx.test.espresso.idling:idling-concurrent:3.1.0' // The following Espresso dependency can be either "implementation" // or "androidTestImplementation", depending on whether you want the // dependency to appear on your APK's compile classpath or the test APK // classpath. androidTestImplementation 'androidx.test.espresso:espresso-idling-resource:3.1.0' }
packages/packages/espresso/example/android/app/build.gradle/0
{ "file_path": "packages/packages/espresso/example/android/app/build.gradle", "repo_id": "packages", "token_count": 1109 }
940
org.gradle.jvmargs=-Xmx4G android.useAndroidX=true android.enableJetifier=true
packages/packages/espresso/example/android/gradle.properties/0
{ "file_path": "packages/packages/espresso/example/android/gradle.properties", "repo_id": "packages", "token_count": 30 }
941
org.gradle.jvmargs=-Xmx1536M android.useAndroidX=true android.enableJetifier=true
packages/packages/extension_google_sign_in_as_googleapis_auth/example/android/gradle.properties/0
{ "file_path": "packages/packages/extension_google_sign_in_as_googleapis_auth/example/android/gradle.properties", "repo_id": "packages", "token_count": 31 }
942
// 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 dev.flutter.packages.file_selector_android_example; import android.content.ContentProvider; import android.content.ContentValues; import android.content.res.AssetFileDescriptor; import android.database.Cursor; import android.database.MatrixCursor; import android.net.Uri; import android.provider.OpenableColumns; import androidx.annotation.NonNull; import androidx.annotation.Nullable; public class TestContentProvider extends ContentProvider { @Override public boolean onCreate() { return true; } @Nullable @Override public Cursor query( @NonNull Uri uri, @Nullable String[] strings, @Nullable String s, @Nullable String[] strings1, @Nullable String s1) { MatrixCursor cursor = new MatrixCursor(new String[] {OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE}); cursor.addRow( new Object[] { "dummy.png", getContext().getResources().openRawResourceFd(R.raw.ic_launcher).getLength() }); return cursor; } @Nullable @Override public String getType(@NonNull Uri uri) { return "image/png"; } @Nullable @Override public AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode) { return getContext().getResources().openRawResourceFd(R.raw.ic_launcher); } @Nullable @Override public Uri insert(@NonNull Uri uri, @Nullable ContentValues contentValues) { return null; } @Override public int delete(@NonNull Uri uri, @Nullable String s, @Nullable String[] strings) { return 0; } @Override public int update( @NonNull Uri uri, @Nullable ContentValues contentValues, @Nullable String s, @Nullable String[] strings) { return 0; } }
packages/packages/file_selector/file_selector_android/example/android/app/src/main/java/dev/flutter/packages/file_selector_android_example/TestContentProvider.java/0
{ "file_path": "packages/packages/file_selector/file_selector_android/example/android/app/src/main/java/dev/flutter/packages/file_selector_android_example/TestContentProvider.java", "repo_id": "packages", "token_count": 651 }
943
// Mocks generated by Mockito 5.4.4 from annotations // in file_selector_android/test/file_selector_android_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i3; import 'package:file_selector_android/src/file_selector_api.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 [FileSelectorApi]. /// /// See the documentation for Mockito's code generation for more information. class MockFileSelectorApi extends _i1.Mock implements _i2.FileSelectorApi { MockFileSelectorApi() { _i1.throwOnMissingStub(this); } @override _i3.Future<_i2.FileResponse?> openFile( String? arg_initialDirectory, _i2.FileTypes? arg_allowedTypes, ) => (super.noSuchMethod( Invocation.method( #openFile, [ arg_initialDirectory, arg_allowedTypes, ], ), returnValue: _i3.Future<_i2.FileResponse?>.value(), ) as _i3.Future<_i2.FileResponse?>); @override _i3.Future<List<_i2.FileResponse?>> openFiles( String? arg_initialDirectory, _i2.FileTypes? arg_allowedTypes, ) => (super.noSuchMethod( Invocation.method( #openFiles, [ arg_initialDirectory, arg_allowedTypes, ], ), returnValue: _i3.Future<List<_i2.FileResponse?>>.value(<_i2.FileResponse?>[]), ) as _i3.Future<List<_i2.FileResponse?>>); @override _i3.Future<String?> getDirectoryPath(String? arg_initialDirectory) => (super.noSuchMethod( Invocation.method( #getDirectoryPath, [arg_initialDirectory], ), returnValue: _i3.Future<String?>.value(), ) as _i3.Future<String?>); }
packages/packages/file_selector/file_selector_android/test/file_selector_android_test.mocks.dart/0
{ "file_path": "packages/packages/file_selector/file_selector_android/test/file_selector_android_test.mocks.dart", "repo_id": "packages", "token_count": 991 }
944
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart' show immutable; /// Configuration options for any file selector dialog. @immutable class FileDialogOptions { /// Creates a new options set with the given settings. const FileDialogOptions({this.initialDirectory, this.confirmButtonText}); /// The initial directory the dialog should open with. final String? initialDirectory; /// The label for the button that confirms selection. final String? confirmButtonText; } /// Configuration options for a save dialog. @immutable class SaveDialogOptions extends FileDialogOptions { /// Creates a new options set with the given settings. const SaveDialogOptions( {super.initialDirectory, super.confirmButtonText, this.suggestedName}); /// The suggested name of the file to save or open. final String? suggestedName; }
packages/packages/file_selector/file_selector_platform_interface/lib/src/types/file_dialog_options.dart/0
{ "file_path": "packages/packages/file_selector/file_selector_platform_interface/lib/src/types/file_dialog_options.dart", "repo_id": "packages", "token_count": 249 }
945
name: file_selector_windows description: Windows implementation of the file_selector plugin. repository: https://github.com/flutter/packages/tree/main/packages/file_selector/file_selector_windows issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+file_selector%22 version: 0.9.3+1 environment: sdk: ^3.1.0 flutter: ">=3.13.0" flutter: plugin: implements: file_selector platforms: windows: dartPluginClass: FileSelectorWindows pluginClass: FileSelectorWindows dependencies: cross_file: ^0.3.1 file_selector_platform_interface: ^2.6.0 flutter: sdk: flutter dev_dependencies: build_runner: ^2.3.0 flutter_test: sdk: flutter mockito: 5.4.4 pigeon: ^10.0.0 topics: - files - file-selection - file-selector
packages/packages/file_selector/file_selector_windows/pubspec.yaml/0
{ "file_path": "packages/packages/file_selector/file_selector_windows/pubspec.yaml", "repo_id": "packages", "token_count": 334 }
946
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "file_selector_plugin.h" #include <flutter/method_call.h> #include <flutter/method_result_functions.h> #include <flutter/plugin_registrar_windows.h> #include <flutter/standard_method_codec.h> #include <gmock/gmock.h> #include <gtest/gtest.h> #include <windows.h> #include <functional> #include <memory> #include <string> #include <variant> #include "file_dialog_controller.h" #include "string_utils.h" #include "test/test_file_dialog_controller.h" #include "test/test_utils.h" namespace file_selector_windows { namespace test { namespace { using flutter::CustomEncodableValue; using flutter::EncodableList; using flutter::EncodableValue; } // namespace TEST(FileSelectorPlugin, TestOpenSimple) { const HWND fake_window = reinterpret_cast<HWND>(1337); ScopedTestShellItem fake_selected_file; IShellItemArrayPtr fake_result_array; ::SHCreateShellItemArrayFromShellItem(fake_selected_file.file(), IID_PPV_ARGS(&fake_result_array)); bool shown = false; MockShow show_validator = [&shown, fake_result_array, fake_window]( const TestFileDialogController& dialog, HWND parent) { shown = true; EXPECT_EQ(parent, fake_window); // Validate options. FILEOPENDIALOGOPTIONS options; dialog.GetOptions(&options); EXPECT_EQ(options & FOS_ALLOWMULTISELECT, 0U); EXPECT_EQ(options & FOS_PICKFOLDERS, 0U); return MockShowResult(fake_result_array); }; FileSelectorPlugin plugin( [fake_window] { return fake_window; }, std::make_unique<TestFileDialogControllerFactory>(show_validator)); ErrorOr<FileDialogResult> result = plugin.ShowOpenDialog( SelectionOptions(/* allow multiple = */ false, /* select folders = */ false, EncodableList()), nullptr, nullptr); EXPECT_TRUE(shown); ASSERT_FALSE(result.has_error()); const EncodableList& paths = result.value().paths(); ASSERT_EQ(paths.size(), 1); EXPECT_EQ(std::get<std::string>(paths[0]), Utf8FromUtf16(fake_selected_file.path())); EXPECT_EQ(result.value().type_group_index(), nullptr); } TEST(FileSelectorPlugin, TestOpenWithArguments) { const HWND fake_window = reinterpret_cast<HWND>(1337); ScopedTestShellItem fake_selected_file; IShellItemArrayPtr fake_result_array; ::SHCreateShellItemArrayFromShellItem(fake_selected_file.file(), IID_PPV_ARGS(&fake_result_array)); bool shown = false; MockShow show_validator = [&shown, fake_result_array, fake_window]( const TestFileDialogController& dialog, HWND parent) { shown = true; EXPECT_EQ(parent, fake_window); // Validate arguments. EXPECT_EQ(dialog.GetDialogFolderPath(), L"C:\\Program Files"); // Make sure that the folder was called via SetFolder, not SetDefaultFolder. EXPECT_EQ(dialog.GetSetFolderPath(), L"C:\\Program Files"); EXPECT_EQ(dialog.GetOkButtonLabel(), L"Open it!"); return MockShowResult(fake_result_array); }; FileSelectorPlugin plugin( [fake_window] { return fake_window; }, std::make_unique<TestFileDialogControllerFactory>(show_validator)); // This directory must exist. std::string initial_directory("C:\\Program Files"); std::string confirm_button("Open it!"); ErrorOr<FileDialogResult> result = plugin.ShowOpenDialog( SelectionOptions(/* allow multiple = */ false, /* select folders = */ false, EncodableList()), &initial_directory, &confirm_button); EXPECT_TRUE(shown); ASSERT_FALSE(result.has_error()); const EncodableList& paths = result.value().paths(); ASSERT_EQ(paths.size(), 1); EXPECT_EQ(std::get<std::string>(paths[0]), Utf8FromUtf16(fake_selected_file.path())); EXPECT_EQ(result.value().type_group_index(), nullptr); } TEST(FileSelectorPlugin, TestOpenMultiple) { const HWND fake_window = reinterpret_cast<HWND>(1337); ScopedTestFileIdList fake_selected_file_1; ScopedTestFileIdList fake_selected_file_2; LPCITEMIDLIST fake_selected_files[] = { fake_selected_file_1.file(), fake_selected_file_2.file(), }; IShellItemArrayPtr fake_result_array; ::SHCreateShellItemArrayFromIDLists(2, fake_selected_files, &fake_result_array); bool shown = false; MockShow show_validator = [&shown, fake_result_array, fake_window]( const TestFileDialogController& dialog, HWND parent) { shown = true; EXPECT_EQ(parent, fake_window); // Validate options. FILEOPENDIALOGOPTIONS options; dialog.GetOptions(&options); EXPECT_NE(options & FOS_ALLOWMULTISELECT, 0U); EXPECT_EQ(options & FOS_PICKFOLDERS, 0U); return MockShowResult(fake_result_array); }; FileSelectorPlugin plugin( [fake_window] { return fake_window; }, std::make_unique<TestFileDialogControllerFactory>(show_validator)); ErrorOr<FileDialogResult> result = plugin.ShowOpenDialog( SelectionOptions(/* allow multiple = */ true, /* select folders = */ false, EncodableList()), nullptr, nullptr); EXPECT_TRUE(shown); ASSERT_FALSE(result.has_error()); const EncodableList& paths = result.value().paths(); ASSERT_EQ(paths.size(), 2); EXPECT_EQ(std::get<std::string>(paths[0]), Utf8FromUtf16(fake_selected_file_1.path())); EXPECT_EQ(std::get<std::string>(paths[1]), Utf8FromUtf16(fake_selected_file_2.path())); EXPECT_EQ(result.value().type_group_index(), nullptr); } TEST(FileSelectorPlugin, TestOpenWithFilter) { const HWND fake_window = reinterpret_cast<HWND>(1337); ScopedTestShellItem fake_selected_file; IShellItemArrayPtr fake_result_array; ::SHCreateShellItemArrayFromShellItem(fake_selected_file.file(), IID_PPV_ARGS(&fake_result_array)); const EncodableValue text_group = CustomEncodableValue(TypeGroup("Text", EncodableList({ EncodableValue("txt"), EncodableValue("json"), }))); const EncodableValue image_group = CustomEncodableValue(TypeGroup("Images", EncodableList({ EncodableValue("png"), EncodableValue("gif"), EncodableValue("jpeg"), }))); const EncodableValue any_group = CustomEncodableValue(TypeGroup("Any", EncodableList())); bool shown = false; MockShow show_validator = [&shown, fake_result_array, fake_window]( const TestFileDialogController& dialog, HWND parent) { shown = true; EXPECT_EQ(parent, fake_window); // Validate filter. const std::vector<DialogFilter>& filters = dialog.GetFileTypes(); EXPECT_EQ(filters.size(), 3U); if (filters.size() == 3U) { EXPECT_EQ(filters[0].name, L"Text"); EXPECT_EQ(filters[0].spec, L"*.txt;*.json"); EXPECT_EQ(filters[1].name, L"Images"); EXPECT_EQ(filters[1].spec, L"*.png;*.gif;*.jpeg"); EXPECT_EQ(filters[2].name, L"Any"); EXPECT_EQ(filters[2].spec, L"*.*"); } return MockShowResult(fake_result_array); }; FileSelectorPlugin plugin( [fake_window] { return fake_window; }, std::make_unique<TestFileDialogControllerFactory>(show_validator)); ErrorOr<FileDialogResult> result = plugin.ShowOpenDialog(SelectionOptions(/* allow multiple = */ false, /* select folders = */ false, EncodableList({ text_group, image_group, any_group, })), nullptr, nullptr); EXPECT_TRUE(shown); ASSERT_FALSE(result.has_error()); const EncodableList& paths = result.value().paths(); ASSERT_EQ(paths.size(), 1); EXPECT_EQ(std::get<std::string>(paths[0]), Utf8FromUtf16(fake_selected_file.path())); // The test dialog controller always reports the last group as // selected, so that should be what the plugin returns. ASSERT_NE(result.value().type_group_index(), nullptr); EXPECT_EQ(*(result.value().type_group_index()), 2); } TEST(FileSelectorPlugin, TestOpenCancel) { const HWND fake_window = reinterpret_cast<HWND>(1337); bool shown = false; MockShow show_validator = [&shown, fake_window]( const TestFileDialogController& dialog, HWND parent) { shown = true; return MockShowResult(); }; FileSelectorPlugin plugin( [fake_window] { return fake_window; }, std::make_unique<TestFileDialogControllerFactory>(show_validator)); ErrorOr<FileDialogResult> result = plugin.ShowOpenDialog( SelectionOptions(/* allow multiple = */ false, /* select folders = */ false, EncodableList()), nullptr, nullptr); EXPECT_TRUE(shown); ASSERT_FALSE(result.has_error()); const EncodableList& paths = result.value().paths(); EXPECT_EQ(paths.size(), 0); EXPECT_EQ(result.value().type_group_index(), nullptr); } TEST(FileSelectorPlugin, TestSaveSimple) { const HWND fake_window = reinterpret_cast<HWND>(1337); ScopedTestShellItem fake_selected_file; bool shown = false; MockShow show_validator = [&shown, fake_result = fake_selected_file.file(), fake_window]( const TestFileDialogController& dialog, HWND parent) { shown = true; EXPECT_EQ(parent, fake_window); // Validate options. FILEOPENDIALOGOPTIONS options; dialog.GetOptions(&options); EXPECT_EQ(options & FOS_ALLOWMULTISELECT, 0U); EXPECT_EQ(options & FOS_PICKFOLDERS, 0U); return MockShowResult(fake_result); }; FileSelectorPlugin plugin( [fake_window] { return fake_window; }, std::make_unique<TestFileDialogControllerFactory>(show_validator)); ErrorOr<FileDialogResult> result = plugin.ShowSaveDialog( SelectionOptions(/* allow multiple = */ false, /* select folders = */ false, EncodableList()), nullptr, nullptr, nullptr); EXPECT_TRUE(shown); ASSERT_FALSE(result.has_error()); const EncodableList& paths = result.value().paths(); ASSERT_EQ(paths.size(), 1); EXPECT_EQ(std::get<std::string>(paths[0]), Utf8FromUtf16(fake_selected_file.path())); EXPECT_EQ(result.value().type_group_index(), nullptr); } TEST(FileSelectorPlugin, TestSaveWithArguments) { const HWND fake_window = reinterpret_cast<HWND>(1337); ScopedTestShellItem fake_selected_file; bool shown = false; MockShow show_validator = [&shown, fake_result = fake_selected_file.file(), fake_window]( const TestFileDialogController& dialog, HWND parent) { shown = true; EXPECT_EQ(parent, fake_window); // Validate arguments. EXPECT_EQ(dialog.GetDialogFolderPath(), L"C:\\Program Files"); // Make sure that the folder was called via SetFolder, not // SetDefaultFolder. EXPECT_EQ(dialog.GetSetFolderPath(), L"C:\\Program Files"); EXPECT_EQ(dialog.GetFileName(), L"a name"); EXPECT_EQ(dialog.GetOkButtonLabel(), L"Save it!"); return MockShowResult(fake_result); }; FileSelectorPlugin plugin( [fake_window] { return fake_window; }, std::make_unique<TestFileDialogControllerFactory>(show_validator)); // This directory must exist. std::string initial_directory("C:\\Program Files"); std::string suggested_name("a name"); std::string confirm_button("Save it!"); ErrorOr<FileDialogResult> result = plugin.ShowSaveDialog( SelectionOptions(/* allow multiple = */ false, /* select folders = */ false, EncodableList()), &initial_directory, &suggested_name, &confirm_button); EXPECT_TRUE(shown); ASSERT_FALSE(result.has_error()); const EncodableList& paths = result.value().paths(); ASSERT_EQ(paths.size(), 1); EXPECT_EQ(std::get<std::string>(paths[0]), Utf8FromUtf16(fake_selected_file.path())); EXPECT_EQ(result.value().type_group_index(), nullptr); } TEST(FileSelectorPlugin, TestSaveWithFilter) { const HWND fake_window = reinterpret_cast<HWND>(1337); ScopedTestShellItem fake_selected_file; const EncodableValue text_group = CustomEncodableValue(TypeGroup("Text", EncodableList({ EncodableValue("txt"), EncodableValue("json"), }))); const EncodableValue image_group = CustomEncodableValue(TypeGroup("Images", EncodableList({ EncodableValue("png"), EncodableValue("gif"), EncodableValue("jpeg"), }))); bool shown = false; MockShow show_validator = [&shown, fake_result = fake_selected_file.file(), fake_window]( const TestFileDialogController& dialog, HWND parent) { shown = true; EXPECT_EQ(parent, fake_window); // Validate filter. const std::vector<DialogFilter>& filters = dialog.GetFileTypes(); EXPECT_EQ(filters.size(), 2U); if (filters.size() == 2U) { EXPECT_EQ(filters[0].name, L"Text"); EXPECT_EQ(filters[0].spec, L"*.txt;*.json"); EXPECT_EQ(filters[1].name, L"Images"); EXPECT_EQ(filters[1].spec, L"*.png;*.gif;*.jpeg"); } return MockShowResult(fake_result); }; FileSelectorPlugin plugin( [fake_window] { return fake_window; }, std::make_unique<TestFileDialogControllerFactory>(show_validator)); ErrorOr<FileDialogResult> result = plugin.ShowSaveDialog(SelectionOptions(/* allow multiple = */ false, /* select folders = */ false, EncodableList({ text_group, image_group, })), nullptr, nullptr, nullptr); EXPECT_TRUE(shown); ASSERT_FALSE(result.has_error()); const EncodableList& paths = result.value().paths(); ASSERT_EQ(paths.size(), 1); EXPECT_EQ(std::get<std::string>(paths[0]), Utf8FromUtf16(fake_selected_file.path())); // The test dialog controller always reports the last group as // selected, so that should be what the plugin returns. ASSERT_NE(result.value().type_group_index(), nullptr); EXPECT_EQ(*(result.value().type_group_index()), 1); } TEST(FileSelectorPlugin, TestSaveCancel) { const HWND fake_window = reinterpret_cast<HWND>(1337); bool shown = false; MockShow show_validator = [&shown, fake_window]( const TestFileDialogController& dialog, HWND parent) { shown = true; return MockShowResult(); }; FileSelectorPlugin plugin( [fake_window] { return fake_window; }, std::make_unique<TestFileDialogControllerFactory>(show_validator)); ErrorOr<FileDialogResult> result = plugin.ShowSaveDialog( SelectionOptions(/* allow multiple = */ false, /* select folders = */ false, EncodableList()), nullptr, nullptr, nullptr); EXPECT_TRUE(shown); ASSERT_FALSE(result.has_error()); const EncodableList& paths = result.value().paths(); EXPECT_EQ(paths.size(), 0); EXPECT_EQ(result.value().type_group_index(), nullptr); } TEST(FileSelectorPlugin, TestGetDirectorySimple) { const HWND fake_window = reinterpret_cast<HWND>(1337); IShellItemPtr fake_selected_directory; // This must be a directory that actually exists. ::SHCreateItemFromParsingName(L"C:\\Program Files", nullptr, IID_PPV_ARGS(&fake_selected_directory)); IShellItemArrayPtr fake_result_array; ::SHCreateShellItemArrayFromShellItem(fake_selected_directory, IID_PPV_ARGS(&fake_result_array)); bool shown = false; MockShow show_validator = [&shown, fake_result_array, fake_window]( const TestFileDialogController& dialog, HWND parent) { shown = true; EXPECT_EQ(parent, fake_window); // Validate options. FILEOPENDIALOGOPTIONS options; dialog.GetOptions(&options); EXPECT_EQ(options & FOS_ALLOWMULTISELECT, 0U); EXPECT_NE(options & FOS_PICKFOLDERS, 0U); return MockShowResult(fake_result_array); }; FileSelectorPlugin plugin( [fake_window] { return fake_window; }, std::make_unique<TestFileDialogControllerFactory>(show_validator)); ErrorOr<FileDialogResult> result = plugin.ShowOpenDialog( SelectionOptions(/* allow multiple = */ false, /* select folders = */ true, EncodableList()), nullptr, nullptr); EXPECT_TRUE(shown); ASSERT_FALSE(result.has_error()); const EncodableList& paths = result.value().paths(); ASSERT_EQ(paths.size(), 1); EXPECT_EQ(std::get<std::string>(paths[0]), "C:\\Program Files"); EXPECT_EQ(result.value().type_group_index(), nullptr); } TEST(FileSelectorPlugin, TestGetDirectoryMultiple) { const HWND fake_window = reinterpret_cast<HWND>(1337); // These are actual files, but since the plugin implementation doesn't // validate the types of items returned from the system dialog, they are fine // to use for unit tests. ScopedTestFileIdList fake_selected_dir_1; ScopedTestFileIdList fake_selected_dir_2; LPCITEMIDLIST fake_selected_dirs[] = { fake_selected_dir_1.file(), fake_selected_dir_2.file(), }; IShellItemArrayPtr fake_result_array; ::SHCreateShellItemArrayFromIDLists(2, fake_selected_dirs, &fake_result_array); bool shown = false; MockShow show_validator = [&shown, fake_result_array, fake_window]( const TestFileDialogController& dialog, HWND parent) { shown = true; EXPECT_EQ(parent, fake_window); // Validate options. FILEOPENDIALOGOPTIONS options; dialog.GetOptions(&options); EXPECT_NE(options & FOS_ALLOWMULTISELECT, 0U); EXPECT_NE(options & FOS_PICKFOLDERS, 0U); return MockShowResult(fake_result_array); }; FileSelectorPlugin plugin( [fake_window] { return fake_window; }, std::make_unique<TestFileDialogControllerFactory>(show_validator)); ErrorOr<FileDialogResult> result = plugin.ShowOpenDialog( SelectionOptions(/* allow multiple = */ true, /* select folders = */ true, EncodableList()), nullptr, nullptr); EXPECT_TRUE(shown); ASSERT_FALSE(result.has_error()); const EncodableList& paths = result.value().paths(); ASSERT_EQ(paths.size(), 2); EXPECT_EQ(std::get<std::string>(paths[0]), Utf8FromUtf16(fake_selected_dir_1.path())); EXPECT_EQ(std::get<std::string>(paths[1]), Utf8FromUtf16(fake_selected_dir_2.path())); EXPECT_EQ(result.value().type_group_index(), nullptr); } TEST(FileSelectorPlugin, TestGetDirectoryCancel) { const HWND fake_window = reinterpret_cast<HWND>(1337); bool shown = false; MockShow show_validator = [&shown, fake_window]( const TestFileDialogController& dialog, HWND parent) { shown = true; return MockShowResult(); }; FileSelectorPlugin plugin( [fake_window] { return fake_window; }, std::make_unique<TestFileDialogControllerFactory>(show_validator)); ErrorOr<FileDialogResult> result = plugin.ShowOpenDialog( SelectionOptions(/* allow multiple = */ false, /* select folders = */ true, EncodableList()), nullptr, nullptr); EXPECT_TRUE(shown); ASSERT_FALSE(result.has_error()); const EncodableList& paths = result.value().paths(); EXPECT_EQ(paths.size(), 0); EXPECT_EQ(result.value().type_group_index(), nullptr); } } // namespace test } // namespace file_selector_windows
packages/packages/file_selector/file_selector_windows/windows/test/file_selector_plugin_test.cpp/0
{ "file_path": "packages/packages/file_selector/file_selector_windows/windows/test/file_selector_plugin_test.cpp", "repo_id": "packages", "token_count": 9095 }
947
org.gradle.jvmargs=-Xmx1536M android.useAndroidX=true android.enableJetifier=true
packages/packages/flutter_adaptive_scaffold/example/android/gradle.properties/0
{ "file_path": "packages/packages/flutter_adaptive_scaffold/example/android/gradle.properties", "repo_id": "packages", "token_count": 31 }
948
// 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' show HttpOverrides; import 'package:flutter/foundation.dart'; import 'package:flutter/painting.dart'; import 'package:flutter_image/network.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:quiver/testing/async.dart'; String _imageUrl(String fileName) { return 'http://localhost:11111/$fileName'; } void main() { AutomatedTestWidgetsFlutterBinding(); HttpOverrides.global = null; group('NetworkImageWithRetry', () { group('succeeds', () { setUp(() { FlutterError.onError = (FlutterErrorDetails error) { fail('$error'); }; }); tearDown(() { FlutterError.onError = FlutterError.dumpErrorToConsole; }); test('loads image from network', () async { final NetworkImageWithRetry subject = NetworkImageWithRetry( _imageUrl('immediate_success.png'), ); assertThatImageLoadingSucceeds(subject); }); test('loads image from network with an extra header', () async { final NetworkImageWithRetry subject = NetworkImageWithRetry( _imageUrl('extra_header.png'), headers: const <String, Object>{'ExtraHeader': 'special'}, ); assertThatImageLoadingSucceeds(subject); }); test('succeeds on successful retry', () async { final NetworkImageWithRetry subject = NetworkImageWithRetry( _imageUrl('error.png'), fetchStrategy: (Uri uri, FetchFailure? failure) async { if (failure == null) { return FetchInstructions.attempt( uri: uri, timeout: const Duration(minutes: 1), ); } else { expect(failure.attemptCount, lessThan(2)); return FetchInstructions.attempt( uri: Uri.parse(_imageUrl('immediate_success.png')), timeout: const Duration(minutes: 1), ); } }, ); assertThatImageLoadingSucceeds(subject); }); }); group('fails', () { final List<FlutterErrorDetails> errorLog = <FlutterErrorDetails>[]; FakeAsync fakeAsync = FakeAsync(); setUp(() { FlutterError.onError = errorLog.add; }); tearDown(() { fakeAsync = FakeAsync(); errorLog.clear(); FlutterError.onError = FlutterError.dumpErrorToConsole; }); test('retries 6 times then gives up', () async { final VoidCallback maxAttemptCountReached = expectAsync0(() {}); int attemptCount = 0; Future<void> onAttempt() async { expect(attemptCount, lessThan(7)); if (attemptCount == 6) { maxAttemptCountReached(); } await Future<void>.delayed(Duration.zero); fakeAsync.elapse(const Duration(seconds: 60)); attemptCount++; } final NetworkImageWithRetry subject = NetworkImageWithRetry( _imageUrl('error.png'), fetchStrategy: (Uri uri, FetchFailure? failure) { Timer.run(onAttempt); return fakeAsync.run((FakeAsync fakeAsync) { return NetworkImageWithRetry.defaultFetchStrategy(uri, failure); }) as Future<FetchInstructions>; }, ); assertThatImageLoadingFails(subject, errorLog); }); test('gives up immediately on non-retriable errors (HTTP 404)', () async { int attemptCount = 0; Future<void> onAttempt() async { expect(attemptCount, lessThan(2)); await Future<void>.delayed(Duration.zero); fakeAsync.elapse(const Duration(seconds: 60)); attemptCount++; } final NetworkImageWithRetry subject = NetworkImageWithRetry( _imageUrl('does_not_exist.png'), fetchStrategy: (Uri uri, FetchFailure? failure) { Timer.run(onAttempt); return fakeAsync.run((FakeAsync fakeAsync) { return NetworkImageWithRetry.defaultFetchStrategy(uri, failure); }) as Future<FetchInstructions>; }, ); assertThatImageLoadingFails(subject, errorLog); }); }); }); } void assertThatImageLoadingFails( NetworkImageWithRetry subject, List<FlutterErrorDetails> errorLog, ) { final ImageStreamCompleter completer = subject.loadImage( subject, PaintingBinding.instance.instantiateImageCodecWithSize, ); completer.addListener(ImageStreamListener( (ImageInfo image, bool synchronousCall) {}, onError: expectAsync2((Object error, StackTrace? _) { expect(errorLog.single.exception, isInstanceOf<FetchFailure>()); expect(error, isInstanceOf<FetchFailure>()); expect(error, equals(errorLog.single.exception)); }), )); } void assertThatImageLoadingSucceeds( NetworkImageWithRetry subject, ) { final ImageStreamCompleter completer = subject.loadImage( subject, PaintingBinding.instance.instantiateImageCodecWithSize, ); completer.addListener(ImageStreamListener( expectAsync2((ImageInfo image, bool synchronousCall) { expect(image.image.height, 1); expect(image.image.width, 1); }), )); }
packages/packages/flutter_image/test/network_test.dart/0
{ "file_path": "packages/packages/flutter_image/test/network_test.dart", "repo_id": "packages", "token_count": 2245 }
949
#include "Generated.xcconfig"
packages/packages/flutter_markdown/example/ios/Flutter/Release.xcconfig/0
{ "file_path": "packages/packages/flutter_markdown/example/ios/Flutter/Release.xcconfig", "repo_id": "packages", "token_count": 12 }
950
// 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'; // ignore_for_file: public_member_api_docs abstract class MarkdownDemoWidget extends Widget { const MarkdownDemoWidget({super.key}); // The title property should be a short name to uniquely identify the example // demo. The title will be displayed at the top of the card in the home screen // to identify the demo and as the banner title on the demo screen. String get title; // The description property should be a short explanation to provide // additional information to clarify the actions performed by the demo. This // should be a terse explanation of no more than three sentences. String get description; // The data property is the sample Markdown source text data to be displayed // in the Formatted and Raw tabs of the demo screen. This data will be used by // the demo widget that implements MarkdownDemoWidget to format the Markdown // data to be displayed in the Formatted tab. The raw source text of data is // used by the Raw tab of the demo screen. The data can be as short or as long // as needed for demonstration purposes. Future<String> get data; // The notes property is a detailed explanation of the syntax, concepts, // comments, notes, or other additional information useful in explaining the // demo. The notes are displayed in the Notes tab of the demo screen. Notes // supports Markdown data to allow for rich text formatting. Future<String> get notes; }
packages/packages/flutter_markdown/example/lib/shared/markdown_demo_widget.dart/0
{ "file_path": "packages/packages/flutter_markdown/example/lib/shared/markdown_demo_widget.dart", "repo_id": "packages", "token_count": 399 }
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 'dart:convert'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:markdown/markdown.dart' as md; import '../flutter_markdown.dart'; import '_functions_io.dart' if (dart.library.html) '_functions_web.dart'; /// Signature for callbacks used by [MarkdownWidget] when /// [MarkdownWidget.selectable] is set to true and the user changes selection. /// /// The callback will return the entire block of text available for selection, /// along with the current [selection] and the [cause] of the selection change. /// This is a wrapper of [SelectionChangedCallback] with additional context /// [text] for the caller to process. /// /// Used by [MarkdownWidget.onSelectionChanged] typedef MarkdownOnSelectionChangedCallback = void Function( String? text, TextSelection selection, SelectionChangedCause? cause); /// Signature for callbacks used by [MarkdownWidget] when the user taps a link. /// The callback will return the link text, destination, and title from the /// Markdown link tag in the document. /// /// Used by [MarkdownWidget.onTapLink]. typedef MarkdownTapLinkCallback = void Function( String text, String? href, String title); /// Signature for custom image widget. /// /// Used by [MarkdownWidget.imageBuilder] typedef MarkdownImageBuilder = Widget Function( Uri uri, String? title, String? alt); /// Signature for custom checkbox widget. /// /// Used by [MarkdownWidget.checkboxBuilder] typedef MarkdownCheckboxBuilder = Widget Function(bool value); /// Signature for custom bullet widget. /// /// Used by [MarkdownWidget.bulletBuilder] typedef MarkdownBulletBuilder = Widget Function(int index, BulletStyle style); /// Enumeration sent to the user when calling [MarkdownBulletBuilder] /// /// Use this to differentiate the bullet styling when building your own. enum BulletStyle { /// An ordered list. orderedList, /// An unordered list. unorderedList, } /// Creates a format [TextSpan] given a string. /// /// Used by [MarkdownWidget] to highlight the contents of `pre` elements. abstract class SyntaxHighlighter { // ignore: one_member_abstracts /// Returns the formatted [TextSpan] for the given string. TextSpan format(String source); } /// An interface for an element builder. abstract class MarkdownElementBuilder { /// For block syntax has to return true. /// /// By default returns false. bool isBlockElement() => false; /// Called when an Element has been reached, before its children have been /// visited. void visitElementBefore(md.Element element) {} /// Called when a text node has been reached. /// /// If [MarkdownWidget.styleSheet] has a style of this tag, will passing /// to [preferredStyle]. /// /// If you needn't build a widget, return null. Widget? visitText(md.Text text, TextStyle? preferredStyle) => null; /// Called when an Element has been reached, after its children have been /// visited. /// /// If [MarkdownWidget.styleSheet] has a style with this tag, it will be /// passed as [preferredStyle]. /// /// If parent element has [TextStyle] set, it will be passed as /// [parentStyle]. /// /// If a widget build isn't needed, return null. Widget? visitElementAfterWithContext( BuildContext context, md.Element element, TextStyle? preferredStyle, TextStyle? parentStyle, ) { return visitElementAfter(element, preferredStyle); } /// Called when an Element has been reached, after its children have been /// visited. /// /// If [MarkdownWidget.styleSheet] has a style of this tag, will passing /// to [preferredStyle]. /// /// If you needn't build a widget, return null. @Deprecated('Use visitElementAfterWithContext() instead.') Widget? visitElementAfter(md.Element element, TextStyle? preferredStyle) => null; } /// Enum to specify which theme being used when creating [MarkdownStyleSheet] /// /// [material] - create MarkdownStyleSheet based on MaterialTheme /// [cupertino] - create MarkdownStyleSheet based on CupertinoTheme /// [platform] - create MarkdownStyleSheet based on the Platform where the /// is running on. Material on Android and Cupertino on iOS enum MarkdownStyleSheetBaseTheme { /// Creates a MarkdownStyleSheet based on MaterialTheme. material, /// Creates a MarkdownStyleSheet based on CupertinoTheme. cupertino, /// Creates a MarkdownStyleSheet whose theme is based on the current platform. platform, } /// Enumeration of alignment strategies for the cross axis of list items. enum MarkdownListItemCrossAxisAlignment { /// Uses [CrossAxisAlignment.baseline] for the row the bullet and the list /// item are placed in. /// /// This alignment will ensure that the bullet always lines up with /// the list text on the baseline. /// /// However, note that this alignment does not support intrinsic height /// measurements because [RenderFlex] does not support it for /// [CrossAxisAlignment.baseline]. /// See https://github.com/flutter/flutter_markdown/issues/311 for cases, /// where this might be a problem for you. /// /// See also: /// * [start], which allows for intrinsic height measurements. baseline, /// Uses [CrossAxisAlignment.start] for the row the bullet and the list item /// are placed in. /// /// This alignment will ensure that intrinsic height measurements work. /// /// However, note that this alignment might not line up the bullet with the /// list text in the way you would expect in certain scenarios. /// See https://github.com/flutter/flutter_markdown/issues/169 for example /// cases that do not produce expected results. /// /// See also: /// * [baseline], which will position the bullet and list item on the /// baseline. start, } /// A base class for widgets that parse and display Markdown. /// /// Supports all standard Markdown from the original /// [Markdown specification](https://github.github.com/gfm/). /// /// See also: /// /// * [Markdown], which is a scrolling container of Markdown. /// * [MarkdownBody], which is a non-scrolling container of Markdown. /// * <https://github.github.com/gfm/> abstract class MarkdownWidget extends StatefulWidget { /// Creates a widget that parses and displays Markdown. /// /// The [data] argument must not be null. const MarkdownWidget({ super.key, required this.data, this.selectable = false, this.styleSheet, this.styleSheetTheme = MarkdownStyleSheetBaseTheme.material, this.syntaxHighlighter, this.onSelectionChanged, this.onTapLink, this.onTapText, this.imageDirectory, this.blockSyntaxes, this.inlineSyntaxes, this.extensionSet, this.imageBuilder, this.checkboxBuilder, this.bulletBuilder, this.builders = const <String, MarkdownElementBuilder>{}, this.paddingBuilders = const <String, MarkdownPaddingBuilder>{}, this.fitContent = false, this.listItemCrossAxisAlignment = MarkdownListItemCrossAxisAlignment.baseline, this.softLineBreak = false, }); /// The Markdown to display. final String data; /// If true, the text is selectable. /// /// Defaults to false. final bool selectable; /// The styles to use when displaying the Markdown. /// /// If null, the styles are inferred from the current [Theme]. final MarkdownStyleSheet? styleSheet; /// Setting to specify base theme for MarkdownStyleSheet /// /// Default to [MarkdownStyleSheetBaseTheme.material] final MarkdownStyleSheetBaseTheme? styleSheetTheme; /// The syntax highlighter used to color text in `pre` elements. /// /// If null, the [MarkdownStyleSheet.code] style is used for `pre` elements. final SyntaxHighlighter? syntaxHighlighter; /// Called when the user taps a link. final MarkdownTapLinkCallback? onTapLink; /// Called when the user changes selection when [selectable] is set to true. final MarkdownOnSelectionChangedCallback? onSelectionChanged; /// Default tap handler used when [selectable] is set to true final VoidCallback? onTapText; /// The base directory holding images referenced by Img tags with local or network file paths. final String? imageDirectory; /// Collection of custom block syntax types to be used parsing the Markdown data. final List<md.BlockSyntax>? blockSyntaxes; /// Collection of custom inline syntax types to be used parsing the Markdown data. final List<md.InlineSyntax>? inlineSyntaxes; /// Markdown syntax extension set /// /// Defaults to [md.ExtensionSet.gitHubFlavored] final md.ExtensionSet? extensionSet; /// Call when build an image widget. final MarkdownImageBuilder? imageBuilder; /// Call when build a checkbox widget. final MarkdownCheckboxBuilder? checkboxBuilder; /// Called when building a bullet final MarkdownBulletBuilder? bulletBuilder; /// Render certain tags, usually used with [extensionSet] /// /// For example, we will add support for `sub` tag: /// /// ```dart /// builders: { /// 'sub': SubscriptBuilder(), /// } /// ``` /// /// The `SubscriptBuilder` is a subclass of [MarkdownElementBuilder]. final Map<String, MarkdownElementBuilder> builders; /// Add padding for different tags (use only for block elements and img) /// /// For example, we will add padding for `img` tag: /// /// ```dart /// paddingBuilders: { /// 'img': ImgPaddingBuilder(), /// } /// ``` /// /// The `ImgPaddingBuilder` is a subclass of [MarkdownPaddingBuilder]. final Map<String, MarkdownPaddingBuilder> paddingBuilders; /// Whether to allow the widget to fit the child content. final bool fitContent; /// Controls the cross axis alignment for the bullet and list item content /// in lists. /// /// Defaults to [MarkdownListItemCrossAxisAlignment.baseline], which /// does not allow for intrinsic height measurements. final MarkdownListItemCrossAxisAlignment listItemCrossAxisAlignment; /// The soft line break is used to identify the spaces at the end of aline of /// text and the leading spaces in the immediately following the line of text. /// /// Default these spaces are removed in accordance with the Markdown /// specification on soft line breaks when lines of text are joined. final bool softLineBreak; /// Subclasses should override this function to display the given children, /// which are the parsed representation of [data]. @protected Widget build(BuildContext context, List<Widget>? children); @override State<MarkdownWidget> createState() => _MarkdownWidgetState(); } class _MarkdownWidgetState extends State<MarkdownWidget> implements MarkdownBuilderDelegate { List<Widget>? _children; final List<GestureRecognizer> _recognizers = <GestureRecognizer>[]; @override void didChangeDependencies() { _parseMarkdown(); super.didChangeDependencies(); } @override void didUpdateWidget(MarkdownWidget oldWidget) { super.didUpdateWidget(oldWidget); if (widget.data != oldWidget.data || widget.styleSheet != oldWidget.styleSheet) { _parseMarkdown(); } } @override void dispose() { _disposeRecognizers(); super.dispose(); } void _parseMarkdown() { final MarkdownStyleSheet fallbackStyleSheet = kFallbackStyle(context, widget.styleSheetTheme); final MarkdownStyleSheet styleSheet = fallbackStyleSheet.merge(widget.styleSheet); _disposeRecognizers(); final md.Document document = md.Document( blockSyntaxes: widget.blockSyntaxes, inlineSyntaxes: widget.inlineSyntaxes, extensionSet: widget.extensionSet ?? md.ExtensionSet.gitHubFlavored, encodeHtml: false, ); // Parse the source Markdown data into nodes of an Abstract Syntax Tree. final List<String> lines = const LineSplitter().convert(widget.data); final List<md.Node> astNodes = document.parseLines(lines); // Configure a Markdown widget builder to traverse the AST nodes and // create a widget tree based on the elements. final MarkdownBuilder builder = MarkdownBuilder( delegate: this, selectable: widget.selectable, styleSheet: styleSheet, imageDirectory: widget.imageDirectory, imageBuilder: widget.imageBuilder, checkboxBuilder: widget.checkboxBuilder, bulletBuilder: widget.bulletBuilder, builders: widget.builders, paddingBuilders: widget.paddingBuilders, fitContent: widget.fitContent, listItemCrossAxisAlignment: widget.listItemCrossAxisAlignment, onSelectionChanged: widget.onSelectionChanged, onTapText: widget.onTapText, softLineBreak: widget.softLineBreak, ); _children = builder.build(astNodes); } void _disposeRecognizers() { if (_recognizers.isEmpty) { return; } final List<GestureRecognizer> localRecognizers = List<GestureRecognizer>.from(_recognizers); _recognizers.clear(); for (final GestureRecognizer recognizer in localRecognizers) { recognizer.dispose(); } } @override GestureRecognizer createLink(String text, String? href, String title) { final TapGestureRecognizer recognizer = TapGestureRecognizer() ..onTap = () { if (widget.onTapLink != null) { widget.onTapLink!(text, href, title); } }; _recognizers.add(recognizer); return recognizer; } @override TextSpan formatText(MarkdownStyleSheet styleSheet, String code) { code = code.replaceAll(RegExp(r'\n$'), ''); if (widget.syntaxHighlighter != null) { return widget.syntaxHighlighter!.format(code); } return TextSpan(style: styleSheet.code, text: code); } @override Widget build(BuildContext context) => widget.build(context, _children); } /// A non-scrolling widget that parses and displays Markdown. /// /// Supports all GitHub Flavored Markdown from the /// [specification](https://github.github.com/gfm/). /// /// See also: /// /// * [Markdown], which is a scrolling container of Markdown. /// * <https://github.github.com/gfm/> class MarkdownBody extends MarkdownWidget { /// Creates a non-scrolling widget that parses and displays Markdown. const MarkdownBody({ super.key, required super.data, super.selectable, super.styleSheet, super.styleSheetTheme = null, super.syntaxHighlighter, super.onSelectionChanged, super.onTapLink, super.onTapText, super.imageDirectory, super.blockSyntaxes, super.inlineSyntaxes, super.extensionSet, super.imageBuilder, super.checkboxBuilder, super.bulletBuilder, super.builders, super.paddingBuilders, super.listItemCrossAxisAlignment, this.shrinkWrap = true, super.fitContent = true, super.softLineBreak, }); /// If [shrinkWrap] is `true`, [MarkdownBody] will take the minimum height /// that wraps its content. Otherwise, [MarkdownBody] will expand to the /// maximum allowed height. final bool shrinkWrap; @override Widget build(BuildContext context, List<Widget>? children) { if (children!.length == 1 && shrinkWrap) { return children.single; } return Column( mainAxisSize: shrinkWrap ? MainAxisSize.min : MainAxisSize.max, crossAxisAlignment: fitContent ? CrossAxisAlignment.start : CrossAxisAlignment.stretch, children: children, ); } } /// A scrolling widget that parses and displays Markdown. /// /// Supports all GitHub Flavored Markdown from the /// [specification](https://github.github.com/gfm/). /// /// See also: /// /// * [MarkdownBody], which is a non-scrolling container of Markdown. /// * <https://github.github.com/gfm/> class Markdown extends MarkdownWidget { /// Creates a scrolling widget that parses and displays Markdown. const Markdown({ super.key, required super.data, super.selectable, super.styleSheet, super.styleSheetTheme = null, super.syntaxHighlighter, super.onSelectionChanged, super.onTapLink, super.onTapText, super.imageDirectory, super.blockSyntaxes, super.inlineSyntaxes, super.extensionSet, super.imageBuilder, super.checkboxBuilder, super.bulletBuilder, super.builders, super.paddingBuilders, super.listItemCrossAxisAlignment, this.padding = const EdgeInsets.all(16.0), this.controller, this.physics, this.shrinkWrap = false, super.softLineBreak, }); /// The amount of space by which to inset the children. final EdgeInsets padding; /// An object that can be used to control the position to which this scroll view is scrolled. /// /// See also: [ScrollView.controller] final ScrollController? controller; /// How the scroll view should respond to user input. /// /// See also: [ScrollView.physics] final ScrollPhysics? physics; /// Whether the extent of the scroll view in the scroll direction should be /// determined by the contents being viewed. /// /// See also: [ScrollView.shrinkWrap] final bool shrinkWrap; @override Widget build(BuildContext context, List<Widget>? children) { return ListView( padding: padding, controller: controller, physics: physics, shrinkWrap: shrinkWrap, children: children!, ); } } /// Parse [task list items](https://github.github.com/gfm/#task-list-items-extension-). /// /// This class is no longer used as Markdown now supports checkbox syntax natively. @Deprecated( 'Use [OrderedListWithCheckBoxSyntax] or [UnorderedListWithCheckBoxSyntax]') class TaskListSyntax extends md.InlineSyntax { /// Creates a new instance. @Deprecated( 'Use [OrderedListWithCheckBoxSyntax] or [UnorderedListWithCheckBoxSyntax]') TaskListSyntax() : super(_pattern); static const String _pattern = r'^ *\[([ xX])\] +'; @override bool onMatch(md.InlineParser parser, Match match) { final md.Element el = md.Element.withTag('input'); el.attributes['type'] = 'checkbox'; el.attributes['disabled'] = 'true'; el.attributes['checked'] = '${match[1]!.trim().isNotEmpty}'; parser.addNode(el); return true; } } /// An interface for an padding builder for element. abstract class MarkdownPaddingBuilder { /// Called when an Element has been reached, before its children have been /// visited. void visitElementBefore(md.Element element) {} /// Called when a widget node has been rendering and need tag padding. EdgeInsets getPadding() => EdgeInsets.zero; }
packages/packages/flutter_markdown/lib/src/widget.dart/0
{ "file_path": "packages/packages/flutter_markdown/lib/src/widget.dart", "repo_id": "packages", "token_count": 5825 }
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. import 'package:flutter/widgets.dart'; import 'package:flutter_markdown/flutter_markdown.dart'; import 'package:flutter_test/flutter_test.dart'; import 'utils.dart'; void main() => defineTests(); void defineTests() { group('Hard Line Breaks', () { testWidgets( // Example 654 from GFM. 'two spaces at end of line', (WidgetTester tester) async { const String data = 'foo \nbar'; await tester.pumpWidget( boilerplate( const MarkdownBody(data: data), ), ); final Finder richTextFinder = find.byType(RichText); expect(richTextFinder, findsOneWidget); final RichText richText = richTextFinder.evaluate().first.widget as RichText; final String text = richText.text.toPlainText(); expect(text, 'foo\nbar'); }, ); testWidgets( // Example 655 from GFM. 'backslash at end of line', (WidgetTester tester) async { const String data = 'foo\\\nbar'; await tester.pumpWidget( boilerplate( const MarkdownBody(data: data), ), ); final Finder richTextFinder = find.byType(RichText); expect(richTextFinder, findsOneWidget); final RichText richText = richTextFinder.evaluate().first.widget as RichText; final String text = richText.text.toPlainText(); expect(text, 'foo\nbar'); }, ); testWidgets( // Example 656 from GFM. 'more than two spaces at end of line', (WidgetTester tester) async { const String data = 'foo \nbar'; await tester.pumpWidget( boilerplate( const MarkdownBody(data: data), ), ); final Finder richTextFinder = find.byType(RichText); expect(richTextFinder, findsOneWidget); final RichText richText = richTextFinder.evaluate().first.widget as RichText; final String text = richText.text.toPlainText(); expect(text, 'foo\nbar'); }, ); testWidgets( // Example 657 from GFM. 'leading spaces at beginning of next line are ignored', (WidgetTester tester) async { const String data = 'foo \n bar'; await tester.pumpWidget( boilerplate( const MarkdownBody(data: data), ), ); final Finder richTextFinder = find.byType(RichText); expect(richTextFinder, findsOneWidget); final RichText richText = richTextFinder.evaluate().first.widget as RichText; final String text = richText.text.toPlainText(); expect(text, 'foo\nbar'); }, ); testWidgets( // Example 658 from GFM. 'leading spaces at beginning of next line are ignored', (WidgetTester tester) async { const String data = 'foo\\\n bar'; await tester.pumpWidget( boilerplate( const MarkdownBody(data: data), ), ); final Finder richTextFinder = find.byType(RichText); expect(richTextFinder, findsOneWidget); final RichText richText = richTextFinder.evaluate().first.widget as RichText; final String text = richText.text.toPlainText(); expect(text, 'foo\nbar'); }, ); testWidgets( // Example 659 from GFM. 'two spaces line break inside emphasis', (WidgetTester tester) async { const String data = '*foo \nbar*'; await tester.pumpWidget( boilerplate( const MarkdownBody(data: data), ), ); final Finder textFinder = find.byType(Text); expect(textFinder, findsOneWidget); final Text textWidget = textFinder.evaluate().first.widget as Text; final String text = textWidget.textSpan!.toPlainText(); expect(text, 'foo\nbar'); // There should be three spans of text. final TextSpan textSpan = textWidget.textSpan! as TextSpan; expect(textSpan, isNotNull); expect(textSpan.children!.length == 3, isTrue); // First text span has italic style with normal weight. final InlineSpan firstSpan = textSpan.children![0]; expectTextSpanStyle( firstSpan as TextSpan, FontStyle.italic, FontWeight.normal); // Second span is just the newline character with no font style or weight. // Third text span has italic style with normal weight. final InlineSpan thirdSpan = textSpan.children![2]; expectTextSpanStyle( thirdSpan as TextSpan, FontStyle.italic, FontWeight.normal); }, ); testWidgets( // Example 660 from GFM. 'backslash line break inside emphasis', (WidgetTester tester) async { const String data = '*foo\\\nbar*'; await tester.pumpWidget( boilerplate( const MarkdownBody(data: data), ), ); final Finder textFinder = find.byType(Text); expect(textFinder, findsOneWidget); final Text textWidget = textFinder.evaluate().first.widget as Text; final String text = textWidget.textSpan!.toPlainText(); expect(text, 'foo\nbar'); // There should be three spans of text. final TextSpan textSpan = textWidget.textSpan! as TextSpan; expect(textSpan, isNotNull); expect(textSpan.children!.length == 3, isTrue); // First text span has italic style with normal weight. final InlineSpan firstSpan = textSpan.children![0]; expectTextSpanStyle( firstSpan as TextSpan, FontStyle.italic, FontWeight.normal); // Second span is just the newline character with no font style or weight. // Third text span has italic style with normal weight. final InlineSpan thirdSpan = textSpan.children![2]; expectTextSpanStyle( thirdSpan as TextSpan, FontStyle.italic, FontWeight.normal); }, ); testWidgets( // Example 661 from GFM. 'two space line break does not occur in code span', (WidgetTester tester) async { const String data = '`code \nspan`'; await tester.pumpWidget( boilerplate( const MarkdownBody(data: data), ), ); final Finder textFinder = find.byType(Text); expect(textFinder, findsOneWidget); final Text textWidget = textFinder.evaluate().first.widget as Text; final String text = textWidget.textSpan!.toPlainText(); expect(text, 'code span'); final TextSpan textSpan = textWidget.textSpan! as TextSpan; expect(textSpan, isNotNull); expect(textSpan.style, isNotNull); expect(textSpan.style!.fontFamily == 'monospace', isTrue); }, ); testWidgets( // Example 662 from GFM. 'backslash line break does not occur in code span', (WidgetTester tester) async { const String data = '`code\\\nspan`'; await tester.pumpWidget( boilerplate( const MarkdownBody(data: data), ), ); final Finder textFinder = find.byType(Text); expect(textFinder, findsOneWidget); final Text textWidget = textFinder.evaluate().first.widget as Text; final String text = textWidget.textSpan!.toPlainText(); expect(text, r'code\ span'); final TextSpan textSpan = textWidget.textSpan! as TextSpan; expect(textSpan, isNotNull); expect(textSpan.style, isNotNull); expect(textSpan.style!.fontFamily == 'monospace', isTrue); }, ); testWidgets( // Example 665 from GFM. 'backslash at end of paragraph is ignored', (WidgetTester tester) async { const String data = r'foo\'; await tester.pumpWidget( boilerplate( const MarkdownBody(data: data), ), ); final Finder richTextFinder = find.byType(RichText); expect(richTextFinder, findsOneWidget); final RichText richText = richTextFinder.evaluate().first.widget as RichText; final String text = richText.text.toPlainText(); expect(text, r'foo\'); }, ); testWidgets( // Example 666 from GFM. 'two spaces at end of paragraph is ignored', (WidgetTester tester) async { const String data = 'foo '; await tester.pumpWidget( boilerplate( const MarkdownBody(data: data), ), ); final Finder richTextFinder = find.byType(RichText); expect(richTextFinder, findsOneWidget); final RichText richText = richTextFinder.evaluate().first.widget as RichText; final String text = richText.text.toPlainText(); expect(text, 'foo'); }, ); testWidgets( // Example 667 from GFM. 'backslash at end of header is ignored', (WidgetTester tester) async { const String data = r'### foo\'; await tester.pumpWidget( boilerplate( const MarkdownBody(data: data), ), ); final Finder richTextFinder = find.byType(RichText); expect(richTextFinder, findsOneWidget); final RichText richText = richTextFinder.evaluate().first.widget as RichText; final String text = richText.text.toPlainText(); expect(text, r'foo\'); }, ); testWidgets( // Example 668 from GFM. 'two spaces at end of header is ignored', (WidgetTester tester) async { const String data = '### foo '; await tester.pumpWidget( boilerplate( const MarkdownBody(data: data), ), ); final Finder richTextFinder = find.byType(RichText); expect(richTextFinder, findsOneWidget); final RichText richText = richTextFinder.evaluate().first.widget as RichText; final String text = richText.text.toPlainText(); expect(text, 'foo'); }, ); }); group('Soft Line Breaks', () { testWidgets( // Example 669 from GFM. 'lines of text in paragraph', (WidgetTester tester) async { const String data = 'foo\nbaz'; await tester.pumpWidget( boilerplate( const MarkdownBody(data: data), ), ); final Finder richTextFinder = find.byType(RichText); expect(richTextFinder, findsOneWidget); final RichText richText = richTextFinder.evaluate().first.widget as RichText; final String text = richText.text.toPlainText(); expect(text, 'foo baz'); }, ); testWidgets( // Example 670 from GFM. 'spaces at beginning and end of lines of text in paragraph are removed', (WidgetTester tester) async { const String data = 'foo \n baz'; await tester.pumpWidget( boilerplate( const MarkdownBody(data: data), ), ); final Finder richTextFinder = find.byType(RichText); expect(richTextFinder, findsOneWidget); final RichText richText = richTextFinder.evaluate().first.widget as RichText; final String text = richText.text.toPlainText(); expect(text, 'foo baz'); }, ); }); }
packages/packages/flutter_markdown/test/line_break_test.dart/0
{ "file_path": "packages/packages/flutter_markdown/test/line_break_test.dart", "repo_id": "packages", "token_count": 5016 }
953
## NEXT * Updates minimum supported SDK version to Flutter 3.13/Dart 3.1. ## 0.0.1+3 * Removes obsolete null checks on non-nullable values. ## 0.0.1+2 * Removes use of `runtimeType.toString()`. ## 0.0.1+1 * Updates code to fix strict-cast violations. ## 0.0.1 * Initial version.
packages/packages/flutter_migrate/CHANGELOG.md/0
{ "file_path": "packages/packages/flutter_migrate/CHANGELOG.md", "repo_id": "packages", "token_count": 110 }
954
// 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'; import 'package:process/process.dart'; import 'base/common.dart'; import 'base/file_system.dart'; import 'base/io.dart'; import 'base/logger.dart'; import 'base/signals.dart'; import 'base/terminal.dart'; /// Initializes the boilerplate dependencies needed by the migrate tool. class MigrateBaseDependencies { MigrateBaseDependencies() { processManager = const LocalProcessManager(); fileSystem = LocalFileSystem( LocalSignals.instance, Signals.defaultExitSignals, ShutdownHooks()); stdio = Stdio(); terminal = AnsiTerminal(stdio: stdio); final LoggerFactory loggerFactory = LoggerFactory( outputPreferences: OutputPreferences( wrapText: stdio.hasTerminal, showColor: stdout.supportsAnsiEscapes, stdio: stdio, ), terminal: terminal, stdio: stdio, ); logger = loggerFactory.createLogger( windows: isWindows, ); } late final ProcessManager processManager; late final LocalFileSystem fileSystem; late final Stdio stdio; late final Terminal terminal; late final Logger logger; } /// An abstraction for instantiation of the correct logger type. /// /// Our logger class hierarchy and runtime requirements are overly complicated. class LoggerFactory { LoggerFactory({ required Terminal terminal, required Stdio stdio, required OutputPreferences outputPreferences, StopwatchFactory stopwatchFactory = const StopwatchFactory(), }) : _terminal = terminal, _stdio = stdio, _stopwatchFactory = stopwatchFactory, _outputPreferences = outputPreferences; final Terminal _terminal; final Stdio _stdio; final StopwatchFactory _stopwatchFactory; final OutputPreferences _outputPreferences; /// Create the appropriate logger for the current platform and configuration. Logger createLogger({ required bool windows, }) { Logger logger; if (windows) { logger = WindowsStdoutLogger( terminal: _terminal, stdio: _stdio, outputPreferences: _outputPreferences, stopwatchFactory: _stopwatchFactory, ); } else { logger = StdoutLogger( terminal: _terminal, stdio: _stdio, outputPreferences: _outputPreferences, stopwatchFactory: _stopwatchFactory); } return logger; } }
packages/packages/flutter_migrate/lib/src/base_dependencies.dart/0
{ "file_path": "packages/packages/flutter_migrate/lib/src/base_dependencies.dart", "repo_id": "packages", "token_count": 867 }
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. import 'package:flutter_migrate/src/base/context.dart'; import 'package:flutter_migrate/src/base/file_system.dart'; import 'package:flutter_migrate/src/base/io.dart'; import 'package:flutter_migrate/src/base/logger.dart'; import 'package:flutter_migrate/src/base/signals.dart'; import 'package:flutter_migrate/src/base/terminal.dart'; import 'package:flutter_migrate/src/commands/apply.dart'; import 'package:flutter_migrate/src/utils.dart'; import 'package:process/process.dart'; import 'src/common.dart'; import 'src/context.dart'; import 'src/test_flutter_command_runner.dart'; void main() { late FileSystem fileSystem; late BufferLogger logger; late Terminal terminal; late ProcessManager processManager; late Directory appDir; setUp(() { fileSystem = LocalFileSystem.test(signals: LocalSignals.instance); appDir = fileSystem.systemTempDirectory.createTempSync('apptestdir'); logger = BufferLogger.test(); terminal = Terminal.test(); processManager = const LocalProcessManager(); }); tearDown(() async { tryToDelete(appDir); }); testUsingContext('Apply produces all outputs', () async { final ProcessResult result = await processManager .run(<String>['flutter', '--version'], workingDirectory: appDir.path); final String versionOutput = result.stdout as String; final List<String> versionSplit = versionOutput.substring(8, 14).split('.'); expect(versionSplit.length >= 2, true); if (!(int.parse(versionSplit[0]) > 3 || int.parse(versionSplit[0]) == 3 && int.parse(versionSplit[1]) > 3)) { // Apply not supported on stable version 3.3 and below return; } final MigrateApplyCommand command = MigrateApplyCommand( verbose: true, logger: logger, fileSystem: fileSystem, terminal: terminal, processManager: processManager, ); final Directory workingDir = appDir.childDirectory(kDefaultMigrateStagingDirectoryName); appDir.childFile('lib/main.dart').createSync(recursive: true); final File pubspecOriginal = appDir.childFile('pubspec.yaml'); pubspecOriginal.createSync(); pubspecOriginal.writeAsStringSync(''' name: originalname description: A new Flutter project. version: 1.0.0+1 environment: sdk: '>=2.18.0-58.0.dev <3.0.0' dependencies: flutter: sdk: flutter dev_dependencies: flutter_test: sdk: flutter flutter: uses-material-design: true''', flush: true); final File gitignore = appDir.childFile('.gitignore'); gitignore.createSync(); gitignore.writeAsStringSync(kDefaultMigrateStagingDirectoryName, flush: true); logger.clear(); await createTestCommandRunner(command).run(<String>[ 'apply', '--staging-directory=${workingDir.path}', '--project-directory=${appDir.path}', '--flutter-subcommand', ]); expect( logger.statusText, contains( 'Project is not a git repo. Please initialize a git repo and try again.')); await processManager .run(<String>['git', 'init'], workingDirectory: appDir.path); logger.clear(); await createTestCommandRunner(command).run(<String>[ 'apply', '--staging-directory=${workingDir.path}', '--project-directory=${appDir.path}', '--flutter-subcommand', ]); expect(logger.statusText, contains('No migration in progress')); final File pubspecModified = workingDir.childFile('pubspec.yaml'); pubspecModified.createSync(recursive: true); pubspecModified.writeAsStringSync(''' name: newname description: new description of the test project version: 1.0.0+1 environment: sdk: '>=2.18.0-58.0.dev <3.0.0' dependencies: flutter: sdk: flutter dev_dependencies: flutter_test: sdk: flutter flutter: uses-material-design: false # EXTRALINE:''', flush: true); final File addedFile = workingDir.childFile('added.file'); addedFile.createSync(recursive: true); addedFile.writeAsStringSync('new file contents'); final File manifestFile = workingDir.childFile('.migrate_manifest'); manifestFile.createSync(recursive: true); manifestFile.writeAsStringSync(''' merged_files: - pubspec.yaml conflict_files: - conflict/conflict.file added_files: - added.file deleted_files: '''); // Add conflict file final File conflictFile = workingDir.childDirectory('conflict').childFile('conflict.file'); conflictFile.createSync(recursive: true); conflictFile.writeAsStringSync(''' line1 <<<<<<< /conflcit/conflict.file line2 ======= linetwo >>>>>>> /var/folders/md/gm0zgfcj07vcsj6jkh_mp_wh00ff02/T/flutter_tools.4Xdep8/generatedTargetTemplatetlN44S/conflict/conflict.file line3 ''', flush: true); final File conflictFileOriginal = appDir.childDirectory('conflict').childFile('conflict.file'); conflictFileOriginal.createSync(recursive: true); conflictFileOriginal.writeAsStringSync(''' line1 line2 line3 ''', flush: true); logger.clear(); await createTestCommandRunner(command).run(<String>[ 'apply', '--staging-directory=${workingDir.path}', '--project-directory=${appDir.path}', '--flutter-subcommand', ]); expect(logger.statusText, contains(r''' Added files: - added.file Modified files: - pubspec.yaml Unable to apply migration. The following files in the migration working directory still have unresolved conflicts: - conflict/conflict.file Conflicting files found. Resolve these conflicts and try again. Guided conflict resolution wizard: $ flutter migrate resolve-conflicts''')); conflictFile.writeAsStringSync(''' line1 linetwo line3 ''', flush: true); logger.clear(); await createTestCommandRunner(command).run(<String>[ 'apply', '--staging-directory=${workingDir.path}', '--project-directory=${appDir.path}', '--flutter-subcommand', ]); expect( logger.statusText, contains( 'There are uncommitted changes in your project. Please git commit, abandon, or stash your changes before trying again.')); await processManager .run(<String>['git', 'add', '.'], workingDirectory: appDir.path); await processManager.run(<String>['git', 'commit', '-m', 'Initial commit'], workingDirectory: appDir.path); logger.clear(); await createTestCommandRunner(command).run(<String>[ 'apply', '--staging-directory=${workingDir.path}', '--project-directory=${appDir.path}', '--flutter-subcommand', ]); expect(logger.statusText, contains(r''' Added files: - added.file Modified files: - conflict/conflict.file - pubspec.yaml Applying migration. Modifying 3 files. Writing pubspec.yaml Writing conflict/conflict.file Writing added.file Updating .migrate_configs Migration complete. You may use commands like `git status`, `git diff` and `git restore <file>` to continue working with the migrated files.''')); expect(pubspecOriginal.readAsStringSync(), contains('# EXTRALINE')); expect(conflictFileOriginal.readAsStringSync(), contains('linetwo')); expect(appDir.childFile('added.file').existsSync(), true); expect(appDir.childFile('added.file').readAsStringSync(), contains('new file contents')); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => processManager, }); }
packages/packages/flutter_migrate/test/apply_test.dart/0
{ "file_path": "packages/packages/flutter_migrate/test/apply_test.dart", "repo_id": "packages", "token_count": 2677 }
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 'dart:io' as io show Directory, File, IOOverrides, Link; import 'package:flutter_migrate/src/base/file_system.dart'; /// An [IOOverrides] that can delegate to [FileSystem] implementation if provided. /// /// Does not override any of the socket facilities. /// /// Do not provide a [LocalFileSystem] as a delegate. Since internally this calls /// out to `dart:io` classes, it will result in a stack overflow error as the /// IOOverrides and LocalFileSystem call each other endlessly. /// /// The only safe delegate types are those that do not call out to `dart:io`, /// like the [MemoryFileSystem]. class FlutterIOOverrides extends io.IOOverrides { FlutterIOOverrides({FileSystem? fileSystem}) : _fileSystemDelegate = fileSystem; final FileSystem? _fileSystemDelegate; @override io.Directory createDirectory(String path) { if (_fileSystemDelegate == null) { return super.createDirectory(path); } return _fileSystemDelegate!.directory(path); } @override io.File createFile(String path) { if (_fileSystemDelegate == null) { return super.createFile(path); } return _fileSystemDelegate!.file(path); } @override io.Link createLink(String path) { if (_fileSystemDelegate == null) { return super.createLink(path); } return _fileSystemDelegate!.link(path); } @override Stream<FileSystemEvent> fsWatch(String path, int events, bool recursive) { if (_fileSystemDelegate == null) { return super.fsWatch(path, events, recursive); } return _fileSystemDelegate! .file(path) .watch(events: events, recursive: recursive); } @override bool fsWatchIsSupported() { if (_fileSystemDelegate == null) { return super.fsWatchIsSupported(); } return _fileSystemDelegate!.isWatchSupported; } @override Future<FileSystemEntityType> fseGetType(String path, bool followLinks) { if (_fileSystemDelegate == null) { return super.fseGetType(path, followLinks); } return _fileSystemDelegate!.type(path, followLinks: followLinks); } @override FileSystemEntityType fseGetTypeSync(String path, bool followLinks) { if (_fileSystemDelegate == null) { return super.fseGetTypeSync(path, followLinks); } return _fileSystemDelegate!.typeSync(path, followLinks: followLinks); } @override Future<bool> fseIdentical(String path1, String path2) { if (_fileSystemDelegate == null) { return super.fseIdentical(path1, path2); } return _fileSystemDelegate!.identical(path1, path2); } @override bool fseIdenticalSync(String path1, String path2) { if (_fileSystemDelegate == null) { return super.fseIdenticalSync(path1, path2); } return _fileSystemDelegate!.identicalSync(path1, path2); } @override io.Directory getCurrentDirectory() { if (_fileSystemDelegate == null) { return super.getCurrentDirectory(); } return _fileSystemDelegate!.currentDirectory; } @override io.Directory getSystemTempDirectory() { if (_fileSystemDelegate == null) { return super.getSystemTempDirectory(); } return _fileSystemDelegate!.systemTempDirectory; } @override void setCurrentDirectory(String path) { if (_fileSystemDelegate == null) { return super.setCurrentDirectory(path); } _fileSystemDelegate!.currentDirectory = path; } @override Future<FileStat> stat(String path) { if (_fileSystemDelegate == null) { return super.stat(path); } return _fileSystemDelegate!.stat(path); } @override FileStat statSync(String path) { if (_fileSystemDelegate == null) { return super.statSync(path); } return _fileSystemDelegate!.statSync(path); } }
packages/packages/flutter_migrate/test/src/io.dart/0
{ "file_path": "packages/packages/flutter_migrate/test/src/io.dart", "repo_id": "packages", "token_count": 1338 }
957
group 'io.flutter.plugins.flutter_plugin_android_lifecycle' version '1.0' buildscript { repositories { google() mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:7.2.1' } } rootProject.allprojects { repositories { google() mavenCentral() } } apply plugin: 'com.android.library' android { // Conditional for compatibility with AGP <4.2. if (project.android.hasProperty("namespace")) { namespace 'io.flutter.plugins.flutter_plugin_android_lifecycle' } compileSdk 34 defaultConfig { minSdkVersion 16 testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" consumerProguardFiles 'proguard.txt' } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } lintOptions { checkAllWarnings true warningsAsErrors true disable 'AndroidGradlePluginVersion', 'InvalidPackage', 'GradleDependency' } dependencies { implementation "androidx.annotation:annotation:1.7.0" } testOptions { unitTests.includeAndroidResources = true unitTests.returnDefaultValues = true unitTests.all { testLogging { events "passed", "skipped", "failed", "standardOut", "standardError" outputs.upToDateWhen {false} showStandardStreams = true } } } } dependencies { testImplementation 'junit:junit:4.13.2' testImplementation 'org.mockito:mockito-core:5.1.1' }
packages/packages/flutter_plugin_android_lifecycle/android/build.gradle/0
{ "file_path": "packages/packages/flutter_plugin_android_lifecycle/android/build.gradle", "repo_id": "packages", "token_count": 695 }
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. package io.flutter.plugins.flutter_plugin_android_lifecycle_example; import android.util.Log; import androidx.lifecycle.Lifecycle; import dev.flutter.plugins.integration_test.IntegrationTestPlugin; import io.flutter.embedding.android.FlutterActivity; import io.flutter.embedding.engine.FlutterEngine; import io.flutter.embedding.engine.plugins.FlutterPlugin; import io.flutter.embedding.engine.plugins.activity.ActivityAware; import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding; import io.flutter.embedding.engine.plugins.lifecycle.FlutterLifecycleAdapter; public class MainActivity extends FlutterActivity { private static final String TAG = "MainActivity"; @Override public void configureFlutterEngine(FlutterEngine flutterEngine) { flutterEngine.getPlugins().add(new TestPlugin()); flutterEngine.getPlugins().add(new IntegrationTestPlugin()); } private static class TestPlugin implements FlutterPlugin, ActivityAware { @Override public void onAttachedToEngine(FlutterPluginBinding flutterPluginBinding) {} @Override public void onDetachedFromEngine(FlutterPluginBinding binding) {} @Override public void onAttachedToActivity(ActivityPluginBinding binding) { Lifecycle lifecycle = FlutterLifecycleAdapter.getActivityLifecycle(binding); if (lifecycle == null) { Log.d(TAG, "Couldn't obtained Lifecycle!"); return; // TODO(amirh): make this throw once the lifecycle API is available on stable. // https://github.com/flutter/flutter/issues/42875 // throw new RuntimeException( // "The FlutterLifecycleAdapter did not correctly provide a Lifecycle instance. Source reference: " // + flutterPluginBinding.getLifecycle()); } Log.d(TAG, "Successfully obtained Lifecycle: " + lifecycle); } @Override public void onDetachedFromActivity() {} @Override public void onDetachedFromActivityForConfigChanges() {} @Override public void onReattachedToActivityForConfigChanges(ActivityPluginBinding binding) {} } }
packages/packages/flutter_plugin_android_lifecycle/example/android/app/src/main/java/io/flutter/plugins/flutter_plugin_android_lifecycle_example/MainActivity.java/0
{ "file_path": "packages/packages/flutter_plugin_android_lifecycle/example/android/app/src/main/java/io/flutter/plugins/flutter_plugin_android_lifecycle_example/MainActivity.java", "repo_id": "packages", "token_count": 714 }
959
name: flutter_plugin_android_lifecycle description: Flutter plugin for accessing an Android Lifecycle within other plugins. repository: https://github.com/flutter/packages/tree/main/packages/flutter_plugin_android_lifecycle issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+flutter_plugin_android_lifecycle%22 version: 2.0.17 environment: sdk: ^3.1.0 flutter: ">=3.13.0" flutter: plugin: platforms: android: package: io.flutter.plugins.flutter_plugin_android_lifecycle pluginClass: FlutterAndroidLifecyclePlugin dependencies: flutter: sdk: flutter dev_dependencies: flutter_test: sdk: flutter topics: - android - plugin-development
packages/packages/flutter_plugin_android_lifecycle/pubspec.yaml/0
{ "file_path": "packages/packages/flutter_plugin_android_lifecycle/pubspec.yaml", "repo_id": "packages", "token_count": 276 }
960
Create a GoRouter configuration by calling the [GoRouter][] constructor and providing list of [GoRoute][] objects: ```dart GoRouter( routes: [ GoRoute( path: '/', builder: (context, state) => const Page1Screen(), ), GoRoute( path: '/page2', builder: (context, state) => const Page2Screen(), ), ], ); ``` # GoRoute To configure a GoRoute, a path template and builder must be provided. Specify a path template to handle by providing a `path` parameter, and a builder by providing either the `builder` or `pageBuilder` parameter: ```dart GoRoute( path: '/users/:userId', builder: (context, state) => const UserScreen(), ), ``` To navigate to this route, use [go()](https://pub.dev/documentation/go_router/latest/go_router/GoRouter/go.html). To learn more about how navigation works, visit the [Navigation](https://pub.dev/documentation/go_router/latest/topics/Navigation-topic.html) topic. # Parameters To specify a path parameter, prefix a path segment with a `:` character, followed by a unique name, for example, `:userId`. You can access the value of the parameter by accessing it through the [GoRouterState][] object provided to the builder callback: ```dart GoRoute( path: '/users/:userId', builder: (context, state) => const UserScreen(id: state.pathParameters['userId']), ), ``` Similarly, to access a [query string](https://en.wikipedia.org/wiki/Query_string) parameter (the part of URL after the `?`), use [GoRouterState][]. For example, a URL path such as `/users?filter=admins` can read the `filter` parameter: ```dart GoRoute( path: '/users', builder: (context, state) => const UsersScreen(filter: state.uri.queryParameters['filter']), ), ``` # Child routes A matched route can result in more than one screen being displayed on a Navigator. This is equivalent to calling `push()`, where a new screen is displayed above the previous screen with a transition animation, and with an in-app back button in the `AppBar` widget, if it is used. To display a screen on top of another, add a child route by adding it to the parent route's `routes` list: ```dart GoRoute( path: '/', builder: (context, state) { return HomeScreen(); }, routes: [ GoRoute( path: 'details', builder: (context, state) { return DetailsScreen(); }, ), ], ) ``` # Dynamic RoutingConfig The [RoutingConfig][] provides a way to update the GoRoute\[s\] after the [GoRouter][] has already created. This can be done by creating a GoRouter with special constructor [GoRouter.routingConfig][] ```dart final ValueNotifier<RoutingConfig> myRoutingConfig = ValueNotifier<RoutingConfig>( RoutingConfig( routes: <RouteBase>[GoRoute(path: '/', builder: (_, __) => HomeScreen())], ), ); final GoRouter router = GoRouter.routingConfig(routingConfig: myRoutingConfig); ``` To change the GoRoute later, modify the value of the [ValueNotifier][] directly. ```dart myRoutingConfig.value = RoutingConfig( routes: <RouteBase>[ GoRoute(path: '/', builder: (_, __) => AlternativeHomeScreen()), GoRoute(path: '/a-new-route', builder: (_, __) => SomeScreen()), ], ); ``` The value change is automatically picked up by GoRouter and causes it to reparse the current routes, i.e. RouteMatchList, stored in GoRouter. The RouteMatchList will reflect the latest change of the `RoutingConfig`. # Nested navigation Some apps display destinations in a subsection of the screen, for example, an app using a BottomNavigationBar that stays on-screen when navigating between destinations. To add an additional Navigator, use [ShellRoute][] and provide a builder that returns a widget: ```dart ShellRoute( builder: (BuildContext context, GoRouterState state, Widget child) { return Scaffold( body: child, /* ... */ bottomNavigationBar: BottomNavigationBar( /* ... */ ), ); }, routes: <RouteBase>[ GoRoute( path: 'details', builder: (BuildContext context, GoRouterState state) { return const DetailsScreen(); }, ), ], ), ``` The `child` widget is a Navigator configured to display the matching sub-routes. For more details, see the [ShellRoute API documentation](https://pub.dev/documentation/go_router/latest/go_router/ShellRoute-class.html). For a complete example, see the [ShellRoute sample](https://github.com/flutter/packages/tree/main/packages/go_router/example/lib/shell_route.dart) in the example/ directory. # Initial location The initial location is shown when the app first opens and there is no deep link provided by the platform. To specify the initial location, provide the `initialLocation` parameter to the GoRouter constructor: ```dart GoRouter( initialLocation: '/details', /* ... */ ); ``` # Logging To enable log output, enable the `debugLogDiagnostics` parameter: ```dart final _router = GoRouter( routes: [/* ... */], debugLogDiagnostics: true, ); ``` [GoRouter]: https://pub.dev/documentation/go_router/latest/go_router/GoRouter-class.html [GoRoute]: https://pub.dev/documentation/go_router/latest/go_router/GoRoute-class.html [GoRouterState]: https://pub.dev/documentation/go_router/latest/go_router/GoRouterState-class.html [ShellRoute]: https://pub.dev/documentation/go_router/latest/go_router/ShellRoute-class.html
packages/packages/go_router/doc/configuration.md/0
{ "file_path": "packages/packages/go_router/doc/configuration.md", "repo_id": "packages", "token_count": 1739 }
961
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import '../data.dart'; import '../widgets/book_list.dart'; /// The author detail screen. class AuthorDetailsScreen extends StatelessWidget { /// Creates an author detail screen. const AuthorDetailsScreen({ required this.author, super.key, }); /// The author to be displayed. final Author? author; @override Widget build(BuildContext context) { if (author == null) { return const Scaffold( body: Center( child: Text('No author found.'), ), ); } return Scaffold( appBar: AppBar( title: Text(author!.name), ), body: Center( child: Column( children: <Widget>[ Expanded( child: BookList( books: author!.books, onTap: (Book book) => context.go('/book/${book.id}'), ), ), ], ), ), ); } }
packages/packages/go_router/example/lib/books/src/screens/author_details.dart/0
{ "file_path": "packages/packages/go_router/example/lib/books/src/screens/author_details.dart", "repo_id": "packages", "token_count": 498 }
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 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; /// Family data class. class Family { /// Create a family. const Family({required this.name, required this.people}); /// The last name of the family. final String name; /// The people in the family. final Map<String, Person> people; } /// Person data class. class Person { /// Creates a person. const Person({required this.name}); /// The first name of the person. final String name; } const Map<String, Family> _families = <String, Family>{ 'f1': Family( name: 'Doe', people: <String, Person>{ 'p1': Person(name: 'Jane'), 'p2': Person(name: 'John'), }, ), 'f2': Family( name: 'Wong', people: <String, Person>{ 'p1': Person(name: 'June'), 'p2': Person(name: 'Xin'), }, ), }; void main() => runApp(App()); /// The main app. class App extends StatelessWidget { /// Creates an [App]. App({super.key}); /// The title of the app. static const String title = 'GoRouter Example: Extra Parameter'; @override Widget build(BuildContext context) => MaterialApp.router( routerConfig: _router, title: title, ); late final GoRouter _router = GoRouter( routes: <GoRoute>[ GoRoute( name: 'home', path: '/', builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: <GoRoute>[ GoRoute( name: 'family', path: 'family', builder: (BuildContext context, GoRouterState state) { final Map<String, Object> params = state.extra! as Map<String, String>; final String fid = params['fid']! as String; return FamilyScreen(fid: fid); }, ), ], ), ], ); } /// The home screen that shows a list of families. class HomeScreen extends StatelessWidget { /// Creates a [HomeScreen]. const HomeScreen({super.key}); @override Widget build(BuildContext context) => Scaffold( appBar: AppBar(title: const Text(App.title)), body: ListView( children: <Widget>[ for (final MapEntry<String, Family> entry in _families.entries) ListTile( title: Text(entry.value.name), onTap: () => context.goNamed('family', extra: <String, String>{'fid': entry.key}), ) ], ), ); } /// The screen that shows a list of persons in a family. class FamilyScreen extends StatelessWidget { /// Creates a [FamilyScreen]. const FamilyScreen({required this.fid, super.key}); /// The family to display. final String fid; @override Widget build(BuildContext context) { final Map<String, Person> people = _families[fid]!.people; return Scaffold( appBar: AppBar(title: Text(_families[fid]!.name)), body: ListView( children: <Widget>[ for (final Person p in people.values) ListTile( title: Text(p.name), ), ], ), ); } }
packages/packages/go_router/example/lib/others/extra_param.dart/0
{ "file_path": "packages/packages/go_router/example/lib/others/extra_param.dart", "repo_id": "packages", "token_count": 1373 }
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 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router_examples/path_and_query_parameters.dart' as example; void main() { testWidgets('example works', (WidgetTester tester) async { await tester.pumpWidget(example.App()); expect(find.text(example.App.title), findsOneWidget); // Directly set the url through platform message. Map<String, dynamic> testRouteInformation = <String, dynamic>{ 'location': '/family/f1?sort=asc', }; ByteData message = const JSONMethodCodec().encodeMethodCall( MethodCall('pushRouteInformation', testRouteInformation), ); await tester.binding.defaultBinaryMessenger .handlePlatformMessage('flutter/navigation', message, (_) {}); await tester.pumpAndSettle(); // 'Chris' should be higher than 'Tom'. expect( tester.getCenter(find.text('Jane')).dy < tester.getCenter(find.text('John')).dy, isTrue); testRouteInformation = <String, dynamic>{ 'location': '/family/f1?privacy=false', }; message = const JSONMethodCodec().encodeMethodCall( MethodCall('pushRouteInformation', testRouteInformation), ); await tester.binding.defaultBinaryMessenger .handlePlatformMessage('flutter/navigation', message, (_) {}); await tester.pumpAndSettle(); // 'Chris' should be lower than 'Tom'. expect( tester.getCenter(find.text('Jane')).dy > tester.getCenter(find.text('John')).dy, isTrue); }); }
packages/packages/go_router/example/test/path_and_query_params_test.dart/0
{ "file_path": "packages/packages/go_router/example/test/path_and_query_params_test.dart", "repo_id": "packages", "token_count": 616 }
964
// 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:collection/collection.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'match.dart'; /// The type of the navigation. /// /// This enum is used by [RouteInformationState] to denote the navigation /// operations. enum NavigatingType { /// Push new location on top of the [RouteInformationState.baseRouteMatchList]. push, /// Push new location and remove top-most [RouteMatch] of the /// [RouteInformationState.baseRouteMatchList]. pushReplacement, /// Push new location and replace top-most [RouteMatch] of the /// [RouteInformationState.baseRouteMatchList]. replace, /// Replace the entire [RouteMatchList] with the new location. go, /// Restore the current match list with /// [RouteInformationState.baseRouteMatchList]. restore, } /// The data class to be stored in [RouteInformation.state] to be used by /// [GoRouteInformationParser]. /// /// This state class is used internally in go_router and will not be sent to /// the engine. class RouteInformationState<T> { /// Creates an InternalRouteInformationState. @visibleForTesting RouteInformationState({ this.extra, this.completer, this.baseRouteMatchList, required this.type, }) : assert((type == NavigatingType.go || type == NavigatingType.restore) == (completer == null)), assert((type != NavigatingType.go) == (baseRouteMatchList != null)); /// The extra object used when navigating with [GoRouter]. final Object? extra; /// The completer that needs to be completed when the newly added route is /// popped off the screen. /// /// This is only null if [type] is [NavigatingType.go] or /// [NavigatingType.restore]. final Completer<T?>? completer; /// The base route match list to push on top to. /// /// This is only null if [type] is [NavigatingType.go]. final RouteMatchList? baseRouteMatchList; /// The type of navigation. final NavigatingType type; } /// The [RouteInformationProvider] created by go_router. class GoRouteInformationProvider extends RouteInformationProvider with WidgetsBindingObserver, ChangeNotifier { /// Creates a [GoRouteInformationProvider]. GoRouteInformationProvider({ required String initialLocation, required Object? initialExtra, Listenable? refreshListenable, }) : _refreshListenable = refreshListenable, _value = RouteInformation( uri: Uri.parse(initialLocation), state: RouteInformationState<void>( extra: initialExtra, type: NavigatingType.go), ), _valueInEngine = _kEmptyRouteInformation { _refreshListenable?.addListener(notifyListeners); } final Listenable? _refreshListenable; static WidgetsBinding get _binding => WidgetsBinding.instance; static final RouteInformation _kEmptyRouteInformation = RouteInformation(uri: Uri.parse('')); @override void routerReportsNewRouteInformation(RouteInformation routeInformation, {RouteInformationReportingType type = RouteInformationReportingType.none}) { // GoRouteInformationParser should always report encoded route match list // in the state. assert(routeInformation.state != null); final bool replace; switch (type) { case RouteInformationReportingType.none: if (!_valueHasChanged( newLocationUri: routeInformation.uri, newState: routeInformation.state)) { return; } replace = _valueInEngine == _kEmptyRouteInformation; case RouteInformationReportingType.neglect: replace = true; case RouteInformationReportingType.navigate: replace = false; } SystemNavigator.selectMultiEntryHistory(); SystemNavigator.routeInformationUpdated( uri: routeInformation.uri, state: routeInformation.state, replace: replace, ); _value = _valueInEngine = routeInformation; } @override RouteInformation get value => _value; RouteInformation _value; @override void notifyListeners() { super.notifyListeners(); } void _setValue(String location, Object state) { final Uri uri = Uri.parse(location); final bool shouldNotify = _valueHasChanged(newLocationUri: uri, newState: state); _value = RouteInformation(uri: Uri.parse(location), state: state); if (shouldNotify) { notifyListeners(); } } /// Pushes the `location` as a new route on top of `base`. Future<T?> push<T>(String location, {required RouteMatchList base, Object? extra}) { final Completer<T?> completer = Completer<T?>(); _setValue( location, RouteInformationState<T>( extra: extra, baseRouteMatchList: base, completer: completer, type: NavigatingType.push, ), ); return completer.future; } /// Replace the current route matches with the `location`. void go(String location, {Object? extra}) { _setValue( location, RouteInformationState<void>( extra: extra, type: NavigatingType.go, ), ); } /// Restores the current route matches with the `matchList`. void restore(String location, {required RouteMatchList matchList}) { _setValue( matchList.uri.toString(), RouteInformationState<void>( extra: matchList.extra, baseRouteMatchList: matchList, type: NavigatingType.restore, ), ); } /// Removes the top-most route match from `base` and pushes the `location` as a /// new route on top. Future<T?> pushReplacement<T>(String location, {required RouteMatchList base, Object? extra}) { final Completer<T?> completer = Completer<T?>(); _setValue( location, RouteInformationState<T>( extra: extra, baseRouteMatchList: base, completer: completer, type: NavigatingType.pushReplacement, ), ); return completer.future; } /// Replaces the top-most route match from `base` with the `location`. Future<T?> replace<T>(String location, {required RouteMatchList base, Object? extra}) { final Completer<T?> completer = Completer<T?>(); _setValue( location, RouteInformationState<T>( extra: extra, baseRouteMatchList: base, completer: completer, type: NavigatingType.replace, ), ); return completer.future; } RouteInformation _valueInEngine; void _platformReportsNewRouteInformation(RouteInformation routeInformation) { if (_value == routeInformation) { return; } if (routeInformation.state != null) { _value = _valueInEngine = routeInformation; } else { _value = RouteInformation( uri: routeInformation.uri, state: RouteInformationState<void>(type: NavigatingType.go), ); _valueInEngine = _kEmptyRouteInformation; } notifyListeners(); } bool _valueHasChanged( {required Uri newLocationUri, required Object? newState}) { const DeepCollectionEquality deepCollectionEquality = DeepCollectionEquality(); return !deepCollectionEquality.equals( _value.uri.path, newLocationUri.path) || !deepCollectionEquality.equals( _value.uri.queryParameters, newLocationUri.queryParameters) || !deepCollectionEquality.equals( _value.uri.fragment, newLocationUri.fragment) || !deepCollectionEquality.equals(_value.state, newState); } @override void addListener(VoidCallback listener) { if (!hasListeners) { _binding.addObserver(this); } super.addListener(listener); } @override void removeListener(VoidCallback listener) { super.removeListener(listener); if (!hasListeners) { _binding.removeObserver(this); } } @override void dispose() { if (hasListeners) { _binding.removeObserver(this); } _refreshListenable?.removeListener(notifyListeners); super.dispose(); } @override Future<bool> didPushRouteInformation(RouteInformation routeInformation) { assert(hasListeners); _platformReportsNewRouteInformation(routeInformation); return SynchronousFuture<bool>(true); } }
packages/packages/go_router/lib/src/information_provider.dart/0
{ "file_path": "packages/packages/go_router/lib/src/information_provider.dart", "repo_id": "packages", "token_count": 2928 }
965
name: go_router description: A declarative router for Flutter based on Navigation 2 supporting deep linking, data-driven routes and more version: 13.2.1 repository: https://github.com/flutter/packages/tree/main/packages/go_router issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+go_router%22 environment: sdk: ">=3.2.0 <4.0.0" flutter: ">=3.16.0" dependencies: collection: ^1.15.0 flutter: sdk: flutter flutter_web_plugins: sdk: flutter logging: ^1.0.0 meta: ^1.7.0 dev_dependencies: flutter_test: sdk: flutter io: ^1.0.4 path: ^1.8.2 topics: - deep-linking - go-router - navigation
packages/packages/go_router/pubspec.yaml/0
{ "file_path": "packages/packages/go_router/pubspec.yaml", "repo_id": "packages", "token_count": 290 }
966
// 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_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; const String initialRoute = '/'; const String newRoute = '/new'; void main() { group('GoRouteInformationProvider', () { testWidgets('notifies its listeners when set by the app', (WidgetTester tester) async { late final GoRouteInformationProvider provider = GoRouteInformationProvider( initialLocation: initialRoute, initialExtra: null); provider.addListener(expectAsync0(() {})); provider.go(newRoute); }); testWidgets('notifies its listeners when set by the platform', (WidgetTester tester) async { late final GoRouteInformationProvider provider = GoRouteInformationProvider( initialLocation: initialRoute, initialExtra: null); provider.addListener(expectAsync0(() {})); provider .didPushRouteInformation(RouteInformation(uri: Uri.parse(newRoute))); }); testWidgets('didPushRouteInformation maintains uri scheme and host', (WidgetTester tester) async { const String expectedScheme = 'https'; const String expectedHost = 'www.example.com'; const String expectedPath = '/some/path'; const String expectedUriString = '$expectedScheme://$expectedHost$expectedPath'; late final GoRouteInformationProvider provider = GoRouteInformationProvider( initialLocation: initialRoute, initialExtra: null); provider.addListener(expectAsync0(() {})); provider.didPushRouteInformation( RouteInformation(uri: Uri.parse(expectedUriString))); expect(provider.value.uri.scheme, 'https'); expect(provider.value.uri.host, 'www.example.com'); expect(provider.value.uri.path, '/some/path'); expect(provider.value.uri.toString(), expectedUriString); }); testWidgets('didPushRoute maintains uri scheme and host', (WidgetTester tester) async { const String expectedScheme = 'https'; const String expectedHost = 'www.example.com'; const String expectedPath = '/some/path'; const String expectedUriString = '$expectedScheme://$expectedHost$expectedPath'; late final GoRouteInformationProvider provider = GoRouteInformationProvider( initialLocation: initialRoute, initialExtra: null); provider.addListener(expectAsync0(() {})); provider.didPushRouteInformation( RouteInformation(uri: Uri.parse(expectedUriString))); expect(provider.value.uri.scheme, 'https'); expect(provider.value.uri.host, 'www.example.com'); expect(provider.value.uri.path, '/some/path'); expect(provider.value.uri.toString(), expectedUriString); }); }); }
packages/packages/go_router/test/information_provider_test.dart/0
{ "file_path": "packages/packages/go_router/test/information_provider_test.dart", "repo_id": "packages", "token_count": 1064 }
967
## Directory contents The Dart files and golden master `.expect` files in this directory are used to test the [`dart fix` framework](https://dart.dev/tools/dart-fix) refactorings used by the go_router package See the packages/packages/go_router/lib/fix_data.yaml directory for the current package:go_router data-driven fixes. To run these tests locally, execute this command in the packages/packages/go_router/test_fixes directory. ```sh dart fix --compare-to-golden ``` For more documentation about Data Driven Fixes, see https://dart.dev/go/data-driven-fixes#test-folder.
packages/packages/go_router/test_fixes/README.md/0
{ "file_path": "packages/packages/go_router/test_fixes/README.md", "repo_id": "packages", "token_count": 177 }
968
// GENERATED CODE - DO NOT MODIFY BY HAND // ignore_for_file: always_specify_types, public_member_api_docs part of 'all_types.dart'; // ************************************************************************** // GoRouterGenerator // ************************************************************************** List<RouteBase> get $appRoutes => [ $allTypesBaseRoute, ]; RouteBase get $allTypesBaseRoute => GoRouteData.$route( path: '/', factory: $AllTypesBaseRouteExtension._fromState, routes: [ GoRouteData.$route( path: 'big-int-route/:requiredBigIntField', factory: $BigIntRouteExtension._fromState, ), GoRouteData.$route( path: 'bool-route/:requiredBoolField', factory: $BoolRouteExtension._fromState, ), GoRouteData.$route( path: 'date-time-route/:requiredDateTimeField', factory: $DateTimeRouteExtension._fromState, ), GoRouteData.$route( path: 'double-route/:requiredDoubleField', factory: $DoubleRouteExtension._fromState, ), GoRouteData.$route( path: 'int-route/:requiredIntField', factory: $IntRouteExtension._fromState, ), GoRouteData.$route( path: 'num-route/:requiredNumField', factory: $NumRouteExtension._fromState, ), GoRouteData.$route( path: 'double-route/:requiredDoubleField', factory: $DoubleRouteExtension._fromState, ), GoRouteData.$route( path: 'enum-route/:requiredEnumField', factory: $EnumRouteExtension._fromState, ), GoRouteData.$route( path: 'enhanced-enum-route/:requiredEnumField', factory: $EnhancedEnumRouteExtension._fromState, ), GoRouteData.$route( path: 'string-route/:requiredStringField', factory: $StringRouteExtension._fromState, ), GoRouteData.$route( path: 'uri-route/:requiredUriField', factory: $UriRouteExtension._fromState, ), GoRouteData.$route( path: 'iterable-route', factory: $IterableRouteExtension._fromState, ), GoRouteData.$route( path: 'iterable-route-with-default-values', factory: $IterableRouteWithDefaultValuesExtension._fromState, ), ], ); extension $AllTypesBaseRouteExtension on AllTypesBaseRoute { static AllTypesBaseRoute _fromState(GoRouterState state) => const AllTypesBaseRoute(); String get location => GoRouteData.$location( '/', ); void go(BuildContext context) => context.go(location); Future<T?> push<T>(BuildContext context) => context.push<T>(location); void pushReplacement(BuildContext context) => context.pushReplacement(location); void replace(BuildContext context) => context.replace(location); } extension $BigIntRouteExtension on BigIntRoute { static BigIntRoute _fromState(GoRouterState state) => BigIntRoute( requiredBigIntField: BigInt.parse(state.pathParameters['requiredBigIntField']!), bigIntField: _$convertMapValue( 'big-int-field', state.uri.queryParameters, BigInt.parse), ); String get location => GoRouteData.$location( '/big-int-route/${Uri.encodeComponent(requiredBigIntField.toString())}', queryParams: { if (bigIntField != null) 'big-int-field': bigIntField!.toString(), }, ); void go(BuildContext context) => context.go(location); Future<T?> push<T>(BuildContext context) => context.push<T>(location); void pushReplacement(BuildContext context) => context.pushReplacement(location); void replace(BuildContext context) => context.replace(location); } extension $BoolRouteExtension on BoolRoute { static BoolRoute _fromState(GoRouterState state) => BoolRoute( requiredBoolField: _$boolConverter(state.pathParameters['requiredBoolField']!), boolField: _$convertMapValue( 'bool-field', state.uri.queryParameters, _$boolConverter), boolFieldWithDefaultValue: _$convertMapValue( 'bool-field-with-default-value', state.uri.queryParameters, _$boolConverter) ?? true, ); String get location => GoRouteData.$location( '/bool-route/${Uri.encodeComponent(requiredBoolField.toString())}', queryParams: { if (boolField != null) 'bool-field': boolField!.toString(), if (boolFieldWithDefaultValue != true) 'bool-field-with-default-value': boolFieldWithDefaultValue.toString(), }, ); void go(BuildContext context) => context.go(location); Future<T?> push<T>(BuildContext context) => context.push<T>(location); void pushReplacement(BuildContext context) => context.pushReplacement(location); void replace(BuildContext context) => context.replace(location); } extension $DateTimeRouteExtension on DateTimeRoute { static DateTimeRoute _fromState(GoRouterState state) => DateTimeRoute( requiredDateTimeField: DateTime.parse(state.pathParameters['requiredDateTimeField']!), dateTimeField: _$convertMapValue( 'date-time-field', state.uri.queryParameters, DateTime.parse), ); String get location => GoRouteData.$location( '/date-time-route/${Uri.encodeComponent(requiredDateTimeField.toString())}', queryParams: { if (dateTimeField != null) 'date-time-field': dateTimeField!.toString(), }, ); void go(BuildContext context) => context.go(location); Future<T?> push<T>(BuildContext context) => context.push<T>(location); void pushReplacement(BuildContext context) => context.pushReplacement(location); void replace(BuildContext context) => context.replace(location); } extension $DoubleRouteExtension on DoubleRoute { static DoubleRoute _fromState(GoRouterState state) => DoubleRoute( requiredDoubleField: double.parse(state.pathParameters['requiredDoubleField']!), doubleField: _$convertMapValue( 'double-field', state.uri.queryParameters, double.parse), doubleFieldWithDefaultValue: _$convertMapValue( 'double-field-with-default-value', state.uri.queryParameters, double.parse) ?? 1.0, ); String get location => GoRouteData.$location( '/double-route/${Uri.encodeComponent(requiredDoubleField.toString())}', queryParams: { if (doubleField != null) 'double-field': doubleField!.toString(), if (doubleFieldWithDefaultValue != 1.0) 'double-field-with-default-value': doubleFieldWithDefaultValue.toString(), }, ); void go(BuildContext context) => context.go(location); Future<T?> push<T>(BuildContext context) => context.push<T>(location); void pushReplacement(BuildContext context) => context.pushReplacement(location); void replace(BuildContext context) => context.replace(location); } extension $IntRouteExtension on IntRoute { static IntRoute _fromState(GoRouterState state) => IntRoute( requiredIntField: int.parse(state.pathParameters['requiredIntField']!), intField: _$convertMapValue( 'int-field', state.uri.queryParameters, int.parse), intFieldWithDefaultValue: _$convertMapValue( 'int-field-with-default-value', state.uri.queryParameters, int.parse) ?? 1, ); String get location => GoRouteData.$location( '/int-route/${Uri.encodeComponent(requiredIntField.toString())}', queryParams: { if (intField != null) 'int-field': intField!.toString(), if (intFieldWithDefaultValue != 1) 'int-field-with-default-value': intFieldWithDefaultValue.toString(), }, ); void go(BuildContext context) => context.go(location); Future<T?> push<T>(BuildContext context) => context.push<T>(location); void pushReplacement(BuildContext context) => context.pushReplacement(location); void replace(BuildContext context) => context.replace(location); } extension $NumRouteExtension on NumRoute { static NumRoute _fromState(GoRouterState state) => NumRoute( requiredNumField: num.parse(state.pathParameters['requiredNumField']!), numField: _$convertMapValue( 'num-field', state.uri.queryParameters, num.parse), numFieldWithDefaultValue: _$convertMapValue( 'num-field-with-default-value', state.uri.queryParameters, num.parse) ?? 1, ); String get location => GoRouteData.$location( '/num-route/${Uri.encodeComponent(requiredNumField.toString())}', queryParams: { if (numField != null) 'num-field': numField!.toString(), if (numFieldWithDefaultValue != 1) 'num-field-with-default-value': numFieldWithDefaultValue.toString(), }, ); void go(BuildContext context) => context.go(location); Future<T?> push<T>(BuildContext context) => context.push<T>(location); void pushReplacement(BuildContext context) => context.pushReplacement(location); void replace(BuildContext context) => context.replace(location); } extension $EnumRouteExtension on EnumRoute { static EnumRoute _fromState(GoRouterState state) => EnumRoute( requiredEnumField: _$PersonDetailsEnumMap ._$fromName(state.pathParameters['requiredEnumField']!), enumField: _$convertMapValue('enum-field', state.uri.queryParameters, _$PersonDetailsEnumMap._$fromName), enumFieldWithDefaultValue: _$convertMapValue( 'enum-field-with-default-value', state.uri.queryParameters, _$PersonDetailsEnumMap._$fromName) ?? PersonDetails.favoriteFood, ); String get location => GoRouteData.$location( '/enum-route/${Uri.encodeComponent(_$PersonDetailsEnumMap[requiredEnumField]!)}', queryParams: { if (enumField != null) 'enum-field': _$PersonDetailsEnumMap[enumField!], if (enumFieldWithDefaultValue != PersonDetails.favoriteFood) 'enum-field-with-default-value': _$PersonDetailsEnumMap[enumFieldWithDefaultValue], }, ); void go(BuildContext context) => context.go(location); Future<T?> push<T>(BuildContext context) => context.push<T>(location); void pushReplacement(BuildContext context) => context.pushReplacement(location); void replace(BuildContext context) => context.replace(location); } const _$PersonDetailsEnumMap = { PersonDetails.hobbies: 'hobbies', PersonDetails.favoriteFood: 'favorite-food', PersonDetails.favoriteSport: 'favorite-sport', }; extension $EnhancedEnumRouteExtension on EnhancedEnumRoute { static EnhancedEnumRoute _fromState(GoRouterState state) => EnhancedEnumRoute( requiredEnumField: _$SportDetailsEnumMap ._$fromName(state.pathParameters['requiredEnumField']!), enumField: _$convertMapValue('enum-field', state.uri.queryParameters, _$SportDetailsEnumMap._$fromName), enumFieldWithDefaultValue: _$convertMapValue( 'enum-field-with-default-value', state.uri.queryParameters, _$SportDetailsEnumMap._$fromName) ?? SportDetails.football, ); String get location => GoRouteData.$location( '/enhanced-enum-route/${Uri.encodeComponent(_$SportDetailsEnumMap[requiredEnumField]!)}', queryParams: { if (enumField != null) 'enum-field': _$SportDetailsEnumMap[enumField!], if (enumFieldWithDefaultValue != SportDetails.football) 'enum-field-with-default-value': _$SportDetailsEnumMap[enumFieldWithDefaultValue], }, ); void go(BuildContext context) => context.go(location); Future<T?> push<T>(BuildContext context) => context.push<T>(location); void pushReplacement(BuildContext context) => context.pushReplacement(location); void replace(BuildContext context) => context.replace(location); } const _$SportDetailsEnumMap = { SportDetails.volleyball: 'volleyball', SportDetails.football: 'football', SportDetails.tennis: 'tennis', SportDetails.hockey: 'hockey', }; extension $StringRouteExtension on StringRoute { static StringRoute _fromState(GoRouterState state) => StringRoute( requiredStringField: state.pathParameters['requiredStringField']!, stringField: state.uri.queryParameters['string-field'], stringFieldWithDefaultValue: state.uri.queryParameters['string-field-with-default-value'] ?? 'defaultValue', ); String get location => GoRouteData.$location( '/string-route/${Uri.encodeComponent(requiredStringField)}', queryParams: { if (stringField != null) 'string-field': stringField, if (stringFieldWithDefaultValue != 'defaultValue') 'string-field-with-default-value': stringFieldWithDefaultValue, }, ); void go(BuildContext context) => context.go(location); Future<T?> push<T>(BuildContext context) => context.push<T>(location); void pushReplacement(BuildContext context) => context.pushReplacement(location); void replace(BuildContext context) => context.replace(location); } extension $UriRouteExtension on UriRoute { static UriRoute _fromState(GoRouterState state) => UriRoute( requiredUriField: Uri.parse(state.pathParameters['requiredUriField']!), uriField: _$convertMapValue( 'uri-field', state.uri.queryParameters, Uri.parse), ); String get location => GoRouteData.$location( '/uri-route/${Uri.encodeComponent(requiredUriField.toString())}', queryParams: { if (uriField != null) 'uri-field': uriField!.toString(), }, ); void go(BuildContext context) => context.go(location); Future<T?> push<T>(BuildContext context) => context.push<T>(location); void pushReplacement(BuildContext context) => context.pushReplacement(location); void replace(BuildContext context) => context.replace(location); } extension $IterableRouteExtension on IterableRoute { static IterableRoute _fromState(GoRouterState state) => IterableRoute( intIterableField: state.uri.queryParametersAll['int-iterable-field']?.map(int.parse), doubleIterableField: state .uri.queryParametersAll['double-iterable-field'] ?.map(double.parse), stringIterableField: state .uri.queryParametersAll['string-iterable-field'] ?.map((e) => e), boolIterableField: state.uri.queryParametersAll['bool-iterable-field'] ?.map(_$boolConverter), enumIterableField: state.uri.queryParametersAll['enum-iterable-field'] ?.map(_$SportDetailsEnumMap._$fromName), enumOnlyInIterableField: state .uri.queryParametersAll['enum-only-in-iterable-field'] ?.map(_$CookingRecipeEnumMap._$fromName), intListField: state.uri.queryParametersAll['int-list-field'] ?.map(int.parse) .toList(), doubleListField: state.uri.queryParametersAll['double-list-field'] ?.map(double.parse) .toList(), stringListField: state.uri.queryParametersAll['string-list-field'] ?.map((e) => e) .toList(), boolListField: state.uri.queryParametersAll['bool-list-field'] ?.map(_$boolConverter) .toList(), enumListField: state.uri.queryParametersAll['enum-list-field'] ?.map(_$SportDetailsEnumMap._$fromName) .toList(), enumOnlyInListField: state .uri.queryParametersAll['enum-only-in-list-field'] ?.map(_$CookingRecipeEnumMap._$fromName) .toList(), intSetField: state.uri.queryParametersAll['int-set-field'] ?.map(int.parse) .toSet(), doubleSetField: state.uri.queryParametersAll['double-set-field'] ?.map(double.parse) .toSet(), stringSetField: state.uri.queryParametersAll['string-set-field'] ?.map((e) => e) .toSet(), boolSetField: state.uri.queryParametersAll['bool-set-field'] ?.map(_$boolConverter) .toSet(), enumSetField: state.uri.queryParametersAll['enum-set-field'] ?.map(_$SportDetailsEnumMap._$fromName) .toSet(), enumOnlyInSetField: state .uri.queryParametersAll['enum-only-in-set-field'] ?.map(_$CookingRecipeEnumMap._$fromName) .toSet(), ); String get location => GoRouteData.$location( '/iterable-route', queryParams: { if (intIterableField != null) 'int-iterable-field': intIterableField?.map((e) => e.toString()).toList(), if (doubleIterableField != null) 'double-iterable-field': doubleIterableField?.map((e) => e.toString()).toList(), if (stringIterableField != null) 'string-iterable-field': stringIterableField?.map((e) => e).toList(), if (boolIterableField != null) 'bool-iterable-field': boolIterableField?.map((e) => e.toString()).toList(), if (enumIterableField != null) 'enum-iterable-field': enumIterableField ?.map((e) => _$SportDetailsEnumMap[e]) .toList(), if (enumOnlyInIterableField != null) 'enum-only-in-iterable-field': enumOnlyInIterableField ?.map((e) => _$CookingRecipeEnumMap[e]) .toList(), if (intListField != null) 'int-list-field': intListField?.map((e) => e.toString()).toList(), if (doubleListField != null) 'double-list-field': doubleListField?.map((e) => e.toString()).toList(), if (stringListField != null) 'string-list-field': stringListField?.map((e) => e).toList(), if (boolListField != null) 'bool-list-field': boolListField?.map((e) => e.toString()).toList(), if (enumListField != null) 'enum-list-field': enumListField?.map((e) => _$SportDetailsEnumMap[e]).toList(), if (enumOnlyInListField != null) 'enum-only-in-list-field': enumOnlyInListField ?.map((e) => _$CookingRecipeEnumMap[e]) .toList(), if (intSetField != null) 'int-set-field': intSetField?.map((e) => e.toString()).toList(), if (doubleSetField != null) 'double-set-field': doubleSetField?.map((e) => e.toString()).toList(), if (stringSetField != null) 'string-set-field': stringSetField?.map((e) => e).toList(), if (boolSetField != null) 'bool-set-field': boolSetField?.map((e) => e.toString()).toList(), if (enumSetField != null) 'enum-set-field': enumSetField?.map((e) => _$SportDetailsEnumMap[e]).toList(), if (enumOnlyInSetField != null) 'enum-only-in-set-field': enumOnlyInSetField ?.map((e) => _$CookingRecipeEnumMap[e]) .toList(), }, ); void go(BuildContext context) => context.go(location); Future<T?> push<T>(BuildContext context) => context.push<T>(location); void pushReplacement(BuildContext context) => context.pushReplacement(location); void replace(BuildContext context) => context.replace(location); } const _$CookingRecipeEnumMap = { CookingRecipe.burger: 'burger', CookingRecipe.pizza: 'pizza', CookingRecipe.tacos: 'tacos', }; extension $IterableRouteWithDefaultValuesExtension on IterableRouteWithDefaultValues { static IterableRouteWithDefaultValues _fromState(GoRouterState state) => IterableRouteWithDefaultValues( intIterableField: state.uri.queryParametersAll['int-iterable-field'] ?.map(int.parse) ?? const <int>[0], doubleIterableField: state .uri.queryParametersAll['double-iterable-field'] ?.map(double.parse) ?? const <double>[0, 1, 2], stringIterableField: state .uri.queryParametersAll['string-iterable-field'] ?.map((e) => e) ?? const <String>['defaultValue'], boolIterableField: state.uri.queryParametersAll['bool-iterable-field'] ?.map(_$boolConverter) ?? const <bool>[false], enumIterableField: state.uri.queryParametersAll['enum-iterable-field'] ?.map(_$SportDetailsEnumMap._$fromName) ?? const <SportDetails>[SportDetails.tennis, SportDetails.hockey], intListField: state.uri.queryParametersAll['int-list-field'] ?.map(int.parse) .toList() ?? const <int>[0], doubleListField: state.uri.queryParametersAll['double-list-field'] ?.map(double.parse) .toList() ?? const <double>[1, 2, 3], stringListField: state.uri.queryParametersAll['string-list-field'] ?.map((e) => e) .toList() ?? const <String>['defaultValue0', 'defaultValue1'], boolListField: state.uri.queryParametersAll['bool-list-field'] ?.map(_$boolConverter) .toList() ?? const <bool>[true], enumListField: state.uri.queryParametersAll['enum-list-field'] ?.map(_$SportDetailsEnumMap._$fromName) .toList() ?? const <SportDetails>[SportDetails.football], intSetField: state.uri.queryParametersAll['int-set-field'] ?.map(int.parse) .toSet() ?? const <int>{0, 1}, doubleSetField: state.uri.queryParametersAll['double-set-field'] ?.map(double.parse) .toSet() ?? const <double>{}, stringSetField: state.uri.queryParametersAll['string-set-field'] ?.map((e) => e) .toSet() ?? const <String>{'defaultValue'}, boolSetField: state.uri.queryParametersAll['bool-set-field'] ?.map(_$boolConverter) .toSet() ?? const <bool>{true, false}, enumSetField: state.uri.queryParametersAll['enum-set-field'] ?.map(_$SportDetailsEnumMap._$fromName) .toSet() ?? const <SportDetails>{SportDetails.hockey}, ); String get location => GoRouteData.$location( '/iterable-route-with-default-values', queryParams: { if (intIterableField != const <int>[0]) 'int-iterable-field': intIterableField.map((e) => e.toString()).toList(), if (doubleIterableField != const <double>[0, 1, 2]) 'double-iterable-field': doubleIterableField.map((e) => e.toString()).toList(), if (stringIterableField != const <String>['defaultValue']) 'string-iterable-field': stringIterableField.map((e) => e).toList(), if (boolIterableField != const <bool>[false]) 'bool-iterable-field': boolIterableField.map((e) => e.toString()).toList(), if (enumIterableField != const <SportDetails>[SportDetails.tennis, SportDetails.hockey]) 'enum-iterable-field': enumIterableField.map((e) => _$SportDetailsEnumMap[e]).toList(), if (intListField != const <int>[0]) 'int-list-field': intListField.map((e) => e.toString()).toList(), if (doubleListField != const <double>[1, 2, 3]) 'double-list-field': doubleListField.map((e) => e.toString()).toList(), if (stringListField != const <String>['defaultValue0', 'defaultValue1']) 'string-list-field': stringListField.map((e) => e).toList(), if (boolListField != const <bool>[true]) 'bool-list-field': boolListField.map((e) => e.toString()).toList(), if (enumListField != const <SportDetails>[SportDetails.football]) 'enum-list-field': enumListField.map((e) => _$SportDetailsEnumMap[e]).toList(), if (intSetField != const <int>{0, 1}) 'int-set-field': intSetField.map((e) => e.toString()).toList(), if (doubleSetField != const <double>{}) 'double-set-field': doubleSetField.map((e) => e.toString()).toList(), if (stringSetField != const <String>{'defaultValue'}) 'string-set-field': stringSetField.map((e) => e).toList(), if (boolSetField != const <bool>{true, false}) 'bool-set-field': boolSetField.map((e) => e.toString()).toList(), if (enumSetField != const <SportDetails>{SportDetails.hockey}) 'enum-set-field': enumSetField.map((e) => _$SportDetailsEnumMap[e]).toList(), }, ); void go(BuildContext context) => context.go(location); Future<T?> push<T>(BuildContext context) => context.push<T>(location); void pushReplacement(BuildContext context) => context.pushReplacement(location); void replace(BuildContext context) => context.replace(location); } T? _$convertMapValue<T>( String key, Map<String, String> map, T Function(String) converter, ) { final value = map[key]; return value == null ? null : converter(value); } bool _$boolConverter(String value) { switch (value) { case 'true': return true; case 'false': return false; default: throw UnsupportedError('Cannot convert "$value" into a bool.'); } } extension<T extends Enum> on Map<T, String> { T _$fromName(String value) => entries.singleWhere((element) => element.value == value).key; }
packages/packages/go_router_builder/example/lib/all_types.g.dart/0
{ "file_path": "packages/packages/go_router_builder/example/lib/all_types.g.dart", "repo_id": "packages", "token_count": 11246 }
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. // ignore_for_file: public_member_api_docs, unreachable_from_main import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; part 'stateful_shell_route_initial_location_example.g.dart'; void main() => runApp(App()); class App extends StatelessWidget { App({super.key}); @override Widget build(BuildContext context) => MaterialApp.router( routerConfig: _router, ); final GoRouter _router = GoRouter( routes: $appRoutes, initialLocation: '/home', ); } class HomeScreen extends StatelessWidget { const HomeScreen({super.key}); @override Widget build(BuildContext context) => Scaffold( appBar: AppBar(title: const Text('foo')), ); } @TypedStatefulShellRoute<MainShellRouteData>( branches: <TypedStatefulShellBranch<StatefulShellBranchData>>[ TypedStatefulShellBranch<HomeShellBranchData>( routes: <TypedRoute<RouteData>>[ TypedGoRoute<HomeRouteData>( path: '/home', ), ], ), TypedStatefulShellBranch<NotificationsShellBranchData>( routes: <TypedRoute<RouteData>>[ TypedGoRoute<NotificationsRouteData>( path: '/notifications/:section', ), ], ), TypedStatefulShellBranch<OrdersShellBranchData>( routes: <TypedRoute<RouteData>>[ TypedGoRoute<OrdersRouteData>( path: '/orders', ), ], ), ], ) class MainShellRouteData extends StatefulShellRouteData { const MainShellRouteData(); @override Widget builder( BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell, ) { return MainPageView( navigationShell: navigationShell, ); } } class HomeShellBranchData extends StatefulShellBranchData { const HomeShellBranchData(); } class NotificationsShellBranchData extends StatefulShellBranchData { const NotificationsShellBranchData(); static String $initialLocation = '/notifications/old'; } class OrdersShellBranchData extends StatefulShellBranchData { const OrdersShellBranchData(); } class HomeRouteData extends GoRouteData { const HomeRouteData(); @override Widget build(BuildContext context, GoRouterState state) { return const HomePageView(label: 'Home page'); } } enum NotificationsPageSection { latest, old, archive, } class NotificationsRouteData extends GoRouteData { const NotificationsRouteData({ required this.section, }); final NotificationsPageSection section; @override Widget build(BuildContext context, GoRouterState state) { return NotificationsPageView( section: section, ); } } class OrdersRouteData extends GoRouteData { const OrdersRouteData(); @override Widget build(BuildContext context, GoRouterState state) { return const OrdersPageView(label: 'Orders page'); } } class MainPageView extends StatelessWidget { const MainPageView({ required this.navigationShell, super.key, }); final StatefulNavigationShell navigationShell; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), body: navigationShell, bottomNavigationBar: BottomNavigationBar( items: const <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: Icon(Icons.home), label: 'Home', ), BottomNavigationBarItem( icon: Icon(Icons.favorite), label: 'Notifications', ), BottomNavigationBarItem( icon: Icon(Icons.list), label: 'Orders', ), ], currentIndex: navigationShell.currentIndex, onTap: (int index) => _onTap(context, index), ), ); } void _onTap(BuildContext context, int index) { navigationShell.goBranch( index, initialLocation: index == navigationShell.currentIndex, ); } } class HomePageView extends StatelessWidget { const HomePageView({ required this.label, super.key, }); final String label; @override Widget build(BuildContext context) { return Center( child: Text(label), ); } } class NotificationsPageView extends StatelessWidget { const NotificationsPageView({ super.key, required this.section, }); final NotificationsPageSection section; @override Widget build(BuildContext context) { return DefaultTabController( length: 3, initialIndex: NotificationsPageSection.values.indexOf(section), child: const Column( children: <Widget>[ TabBar( tabs: <Tab>[ Tab( child: Text( 'Latest', style: TextStyle(color: Colors.black87), ), ), Tab( child: Text( 'Old', style: TextStyle(color: Colors.black87), ), ), Tab( child: Text( 'Archive', style: TextStyle(color: Colors.black87), ), ), ], ), Expanded( child: TabBarView( children: <Widget>[ NotificationsSubPageView( label: 'Latest notifications', ), NotificationsSubPageView( label: 'Old notifications', ), NotificationsSubPageView( label: 'Archived notifications', ), ], ), ), ], ), ); } } class NotificationsSubPageView extends StatelessWidget { const NotificationsSubPageView({ required this.label, super.key, }); final String label; @override Widget build(BuildContext context) { return Center( child: Text(label), ); } } class OrdersPageView extends StatelessWidget { const OrdersPageView({ required this.label, super.key, }); final String label; @override Widget build(BuildContext context) { return Center( child: Text(label), ); } }
packages/packages/go_router_builder/example/lib/stateful_shell_route_initial_location_example.dart/0
{ "file_path": "packages/packages/go_router_builder/example/lib/stateful_shell_route_initial_location_example.dart", "repo_id": "packages", "token_count": 2620 }
970
name: go_router_builder description: >- A builder that supports generated strongly-typed route helpers for package:go_router version: 2.4.1 repository: https://github.com/flutter/packages/tree/main/packages/go_router_builder issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+go_router_builder%22 environment: sdk: ^3.1.0 dependencies: analyzer: ">=5.2.0 <7.0.0" async: ^2.8.0 build: ^2.0.0 build_config: ^1.0.0 collection: ^1.14.0 meta: ^1.7.0 path: ^1.8.0 source_gen: ^1.0.0 source_helper: ^1.3.0 dev_dependencies: build_test: ^2.1.7 dart_style: 2.3.2 go_router: ^10.0.0 test: ^1.20.0 topics: - codegen - deep-linking - go-router - navigation
packages/packages/go_router_builder/pubspec.yaml/0
{ "file_path": "packages/packages/go_router_builder/pubspec.yaml", "repo_id": "packages", "token_count": 333 }
971
// 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:go_router/go_router.dart'; @TypedShellRoute<ShellRouteNoConstConstructor>( routes: <TypedRoute<RouteData>>[], ) class ShellRouteNoConstConstructor extends ShellRouteData {} @TypedShellRoute<ShellRouteWithConstConstructor>( routes: <TypedRoute<RouteData>>[], ) class ShellRouteWithConstConstructor extends ShellRouteData { const ShellRouteWithConstConstructor(); }
packages/packages/go_router_builder/test_inputs/shell_route_data.dart/0
{ "file_path": "packages/packages/go_router_builder/test_inputs/shell_route_data.dart", "repo_id": "packages", "token_count": 160 }
972
<!DOCTYPE html> <!-- Copyright 2013 The Flutter Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. --> <html> <!--#docregion script-tag--> <head> <!--#enddocregion script-tag--> <base href="$FLUTTER_BASE_HREF"> <meta charset="UTF-8"> <meta content="IE=Edge" http-equiv="X-UA-Compatible"> <meta name="description" content="A new Flutter project."> <!-- iOS meta tags & icons --> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="black"> <meta name="apple-mobile-web-app-title" content="example"> <link rel="apple-touch-icon" href="icons/Icon-192.png"> <!-- Favicon --> <link rel="icon" type="image/png" href="favicon.png"/> <title>Authentication Example</title> <link rel="manifest" href="manifest.json"> <script> // The value below is injected by flutter build, do not touch. var serviceWorkerVersion = null; </script> <!--#docregion script-tag--> <!-- Include the GSI SDK below --> <script src="https://accounts.google.com/gsi/client" async defer></script> <!-- This script adds the flutter initialization JS code --> <script src="flutter.js" defer></script> </head> <!--#enddocregion script-tag--> <body> <script> window.addEventListener('load', function(ev) { // Download main.dart.js _flutter.loader.loadEntrypoint({ serviceWorker: { serviceWorkerVersion: serviceWorkerVersion, }, onEntrypointLoaded: function(engineInitializer) { engineInitializer.autoStart(); } }); }); </script> </body> </html>
packages/packages/google_identity_services_web/example/web/index-with-script-tag.html/0
{ "file_path": "packages/packages/google_identity_services_web/example/web/index-with-script-tag.html", "repo_id": "packages", "token_count": 595 }
973
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @TestOn('browser') // Uses package:web library; import 'dart:async'; import 'dart:js_interop'; import 'package:google_identity_services_web/loader.dart'; import 'package:google_identity_services_web/src/js_loader.dart'; import 'package:test/test.dart'; import 'package:web/web.dart' as web; // NOTE: This file needs to be separated from the others because Content // Security Policies can never be *relaxed* once set. // // In order to not introduce a dependency in the order of the tests, we split // them in different files, depending on the strictness of their CSP: // // * js_loader_test.dart : default TT configuration (not enforced) // * js_loader_tt_custom_test.dart : TT are customized, but allowed // * js_loader_tt_forbidden_test.dart: TT are completely disallowed void main() { group('loadWebSdk (no TrustedTypes)', () { final web.HTMLDivElement target = web.document.createElement('div') as web.HTMLDivElement; test('Injects script into desired target', () async { // This test doesn't simulate the callback that completes the future, and // the code being tested runs synchronously. unawaited(loadWebSdk(target: target)); // Target now should have a child that is a script element final web.Node? injected = target.firstChild; expect(injected, isNotNull); expect(injected, isA<web.HTMLScriptElement>()); final web.HTMLScriptElement script = injected! as web.HTMLScriptElement; expect(script.defer, isTrue); expect(script.async, isTrue); expect(script.src, 'https://accounts.google.com/gsi/client'); }); test('Completes when the script loads', () async { final Future<void> loadFuture = loadWebSdk(target: target); Future<void>.delayed(const Duration(milliseconds: 100), () { // Simulate the library calling `window.onGoogleLibraryLoad`. web.window.onGoogleLibraryLoad(); }); await expectLater(loadFuture, completes); }); }); } extension on web.Window { void onGoogleLibraryLoad() => _onGoogleLibraryLoad(); @JS('onGoogleLibraryLoad') external JSFunction? _onGoogleLibraryLoad(); }
packages/packages/google_identity_services_web/test/js_loader_test.dart/0
{ "file_path": "packages/packages/google_identity_services_web/test/js_loader_test.dart", "repo_id": "packages", "token_count": 753 }
974
// 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/foundation.dart'; import 'package:flutter/material.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'package:google_maps_flutter_android/google_maps_flutter_android.dart'; import 'main.dart'; import 'page.dart'; class MapIdPage extends GoogleMapExampleAppPage { const MapIdPage({Key? key}) : super(const Icon(Icons.map), 'Cloud-based maps styling', key: key); @override Widget build(BuildContext context) { return const MapIdBody(); } } class MapIdBody extends StatefulWidget { const MapIdBody({super.key}); @override State<StatefulWidget> createState() => MapIdBodyState(); } const LatLng _kMapCenter = LatLng(52.4478, -3.5402); class MapIdBodyState extends State<MapIdBody> { GoogleMapController? controller; Key _key = const Key('mapId#'); String? _mapId; final TextEditingController _mapIdController = TextEditingController(); AndroidMapRenderer? _initializedRenderer; @override void initState() { initializeMapRenderer() .then<void>((AndroidMapRenderer? initializedRenderer) => setState(() { _initializedRenderer = initializedRenderer; })); super.initState(); } String _getInitializedsRendererType() { switch (_initializedRenderer) { case AndroidMapRenderer.latest: return 'latest'; case AndroidMapRenderer.legacy: return 'legacy'; case AndroidMapRenderer.platformDefault: case null: break; } return 'unknown'; } void _setMapId() { setState(() { _mapId = _mapIdController.text; // Change key to initialize new map instance for new mapId. _key = Key(_mapId ?? 'mapId#'); }); } @override Widget build(BuildContext context) { final GoogleMap googleMap = GoogleMap( onMapCreated: _onMapCreated, initialCameraPosition: const CameraPosition( target: _kMapCenter, zoom: 7.0, ), key: _key, cloudMapId: _mapId); final List<Widget> columnChildren = <Widget>[ Padding( padding: const EdgeInsets.all(10.0), child: Center( child: SizedBox( width: 300.0, height: 200.0, child: googleMap, ), ), ), Padding( padding: const EdgeInsets.all(10.0), child: TextField( controller: _mapIdController, decoration: const InputDecoration( hintText: 'Map Id', ), )), Padding( padding: const EdgeInsets.all(10.0), child: ElevatedButton( onPressed: () => _setMapId(), child: const Text( 'Press to use specified map Id', ), )), if (!kIsWeb && Platform.isAndroid && _initializedRenderer != AndroidMapRenderer.latest) Padding( padding: const EdgeInsets.all(10.0), child: Text( 'On Android, Cloud-based maps styling only works with "latest" renderer.\n\n' 'Current initialized renderer is "${_getInitializedsRendererType()}".'), ), ]; return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: columnChildren, ); } @override void dispose() { _mapIdController.dispose(); super.dispose(); } void _onMapCreated(GoogleMapController controllerParam) { setState(() { controller = controllerParam; }); } }
packages/packages/google_maps_flutter/google_maps_flutter/example/lib/map_map_id.dart/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter/example/lib/map_map_id.dart", "repo_id": "packages", "token_count": 1567 }
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. import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart'; import 'fake_google_maps_flutter_platform.dart'; Widget _mapWithPolygons(Set<Polygon> polygons) { return Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), polygons: polygons, ), ); } List<LatLng> _rectPoints({ required double size, LatLng center = const LatLng(0, 0), }) { final double halfSize = size / 2; return <LatLng>[ LatLng(center.latitude + halfSize, center.longitude + halfSize), LatLng(center.latitude - halfSize, center.longitude + halfSize), LatLng(center.latitude - halfSize, center.longitude - halfSize), LatLng(center.latitude + halfSize, center.longitude - halfSize), ]; } Polygon _polygonWithPointsAndHole(PolygonId polygonId) { _rectPoints(size: 1); return Polygon( polygonId: polygonId, points: _rectPoints(size: 1), holes: <List<LatLng>>[_rectPoints(size: 0.5)], ); } void main() { late FakeGoogleMapsFlutterPlatform platform; setUp(() { platform = FakeGoogleMapsFlutterPlatform(); GoogleMapsFlutterPlatform.instance = platform; }); testWidgets('Initializing a polygon', (WidgetTester tester) async { const Polygon p1 = Polygon(polygonId: PolygonId('polygon_1')); await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1})); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.polygonUpdates.last.polygonsToAdd.length, 1); final Polygon initializedPolygon = map.polygonUpdates.last.polygonsToAdd.first; expect(initializedPolygon, equals(p1)); expect(map.polygonUpdates.last.polygonIdsToRemove.isEmpty, true); expect(map.polygonUpdates.last.polygonsToChange.isEmpty, true); }); testWidgets('Adding a polygon', (WidgetTester tester) async { const Polygon p1 = Polygon(polygonId: PolygonId('polygon_1')); const Polygon p2 = Polygon(polygonId: PolygonId('polygon_2')); await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1})); await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1, p2})); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.polygonUpdates.last.polygonsToAdd.length, 1); final Polygon addedPolygon = map.polygonUpdates.last.polygonsToAdd.first; expect(addedPolygon, equals(p2)); expect(map.polygonUpdates.last.polygonIdsToRemove.isEmpty, true); expect(map.polygonUpdates.last.polygonsToChange.isEmpty, true); }); testWidgets('Removing a polygon', (WidgetTester tester) async { const Polygon p1 = Polygon(polygonId: PolygonId('polygon_1')); await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1})); await tester.pumpWidget(_mapWithPolygons(<Polygon>{})); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.polygonUpdates.last.polygonIdsToRemove.length, 1); expect( map.polygonUpdates.last.polygonIdsToRemove.first, equals(p1.polygonId)); expect(map.polygonUpdates.last.polygonsToChange.isEmpty, true); expect(map.polygonUpdates.last.polygonsToAdd.isEmpty, true); }); testWidgets('Updating a polygon', (WidgetTester tester) async { const Polygon p1 = Polygon(polygonId: PolygonId('polygon_1')); const Polygon p2 = Polygon(polygonId: PolygonId('polygon_1'), geodesic: true); await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1})); await tester.pumpWidget(_mapWithPolygons(<Polygon>{p2})); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.polygonUpdates.last.polygonsToChange.length, 1); expect(map.polygonUpdates.last.polygonsToChange.first, equals(p2)); expect(map.polygonUpdates.last.polygonIdsToRemove.isEmpty, true); expect(map.polygonUpdates.last.polygonsToAdd.isEmpty, true); }); testWidgets('Mutate a polygon', (WidgetTester tester) async { final List<LatLng> points = <LatLng>[const LatLng(0.0, 0.0)]; final Polygon p1 = Polygon( polygonId: const PolygonId('polygon_1'), points: points, ); await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1})); p1.points.add(const LatLng(1.0, 1.0)); await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1})); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.polygonUpdates.last.polygonsToChange.length, 1); expect(map.polygonUpdates.last.polygonsToChange.first, equals(p1)); expect(map.polygonUpdates.last.polygonIdsToRemove.isEmpty, true); expect(map.polygonUpdates.last.polygonsToAdd.isEmpty, true); }); testWidgets('Multi Update', (WidgetTester tester) async { Polygon p1 = const Polygon(polygonId: PolygonId('polygon_1')); Polygon p2 = const Polygon(polygonId: PolygonId('polygon_2')); final Set<Polygon> prev = <Polygon>{p1, p2}; p1 = const Polygon(polygonId: PolygonId('polygon_1'), visible: false); p2 = const Polygon(polygonId: PolygonId('polygon_2'), geodesic: true); final Set<Polygon> cur = <Polygon>{p1, p2}; await tester.pumpWidget(_mapWithPolygons(prev)); await tester.pumpWidget(_mapWithPolygons(cur)); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.polygonUpdates.last.polygonsToChange, cur); expect(map.polygonUpdates.last.polygonIdsToRemove.isEmpty, true); expect(map.polygonUpdates.last.polygonsToAdd.isEmpty, true); }); testWidgets('Multi Update', (WidgetTester tester) async { Polygon p2 = const Polygon(polygonId: PolygonId('polygon_2')); const Polygon p3 = Polygon(polygonId: PolygonId('polygon_3')); final Set<Polygon> prev = <Polygon>{p2, p3}; // p1 is added, p2 is updated, p3 is removed. const Polygon p1 = Polygon(polygonId: PolygonId('polygon_1')); p2 = const Polygon(polygonId: PolygonId('polygon_2'), geodesic: true); final Set<Polygon> cur = <Polygon>{p1, p2}; await tester.pumpWidget(_mapWithPolygons(prev)); await tester.pumpWidget(_mapWithPolygons(cur)); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.polygonUpdates.last.polygonsToChange.length, 1); expect(map.polygonUpdates.last.polygonsToAdd.length, 1); expect(map.polygonUpdates.last.polygonIdsToRemove.length, 1); expect(map.polygonUpdates.last.polygonsToChange.first, equals(p2)); expect(map.polygonUpdates.last.polygonsToAdd.first, equals(p1)); expect( map.polygonUpdates.last.polygonIdsToRemove.first, equals(p3.polygonId)); }); testWidgets('Partial Update', (WidgetTester tester) async { const Polygon p1 = Polygon(polygonId: PolygonId('polygon_1')); const Polygon p2 = Polygon(polygonId: PolygonId('polygon_2')); Polygon p3 = const Polygon(polygonId: PolygonId('polygon_3')); final Set<Polygon> prev = <Polygon>{p1, p2, p3}; p3 = const Polygon(polygonId: PolygonId('polygon_3'), geodesic: true); final Set<Polygon> cur = <Polygon>{p1, p2, p3}; await tester.pumpWidget(_mapWithPolygons(prev)); await tester.pumpWidget(_mapWithPolygons(cur)); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.polygonUpdates.last.polygonsToChange, <Polygon>{p3}); expect(map.polygonUpdates.last.polygonIdsToRemove.isEmpty, true); expect(map.polygonUpdates.last.polygonsToAdd.isEmpty, true); }); testWidgets('Update non platform related attr', (WidgetTester tester) async { Polygon p1 = const Polygon(polygonId: PolygonId('polygon_1')); final Set<Polygon> prev = <Polygon>{p1}; p1 = Polygon(polygonId: const PolygonId('polygon_1'), onTap: () {}); final Set<Polygon> cur = <Polygon>{p1}; await tester.pumpWidget(_mapWithPolygons(prev)); await tester.pumpWidget(_mapWithPolygons(cur)); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.polygonUpdates.last.polygonsToChange.isEmpty, true); expect(map.polygonUpdates.last.polygonIdsToRemove.isEmpty, true); expect(map.polygonUpdates.last.polygonsToAdd.isEmpty, true); }); testWidgets('Initializing a polygon with points and hole', (WidgetTester tester) async { final Polygon p1 = _polygonWithPointsAndHole(const PolygonId('polygon_1')); await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1})); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.polygonUpdates.last.polygonsToAdd.length, 1); final Polygon initializedPolygon = map.polygonUpdates.last.polygonsToAdd.first; expect(initializedPolygon, equals(p1)); expect(map.polygonUpdates.last.polygonIdsToRemove.isEmpty, true); expect(map.polygonUpdates.last.polygonsToChange.isEmpty, true); }); testWidgets('Adding a polygon with points and hole', (WidgetTester tester) async { const Polygon p1 = Polygon(polygonId: PolygonId('polygon_1')); final Polygon p2 = _polygonWithPointsAndHole(const PolygonId('polygon_2')); await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1})); await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1, p2})); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.polygonUpdates.last.polygonsToAdd.length, 1); final Polygon addedPolygon = map.polygonUpdates.last.polygonsToAdd.first; expect(addedPolygon, equals(p2)); expect(map.polygonUpdates.last.polygonIdsToRemove.isEmpty, true); expect(map.polygonUpdates.last.polygonsToChange.isEmpty, true); }); testWidgets('Removing a polygon with points and hole', (WidgetTester tester) async { final Polygon p1 = _polygonWithPointsAndHole(const PolygonId('polygon_1')); await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1})); await tester.pumpWidget(_mapWithPolygons(<Polygon>{})); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.polygonUpdates.last.polygonIdsToRemove.length, 1); expect( map.polygonUpdates.last.polygonIdsToRemove.first, equals(p1.polygonId)); expect(map.polygonUpdates.last.polygonsToChange.isEmpty, true); expect(map.polygonUpdates.last.polygonsToAdd.isEmpty, true); }); testWidgets('Updating a polygon by adding points and hole', (WidgetTester tester) async { const Polygon p1 = Polygon(polygonId: PolygonId('polygon_1')); final Polygon p2 = _polygonWithPointsAndHole(const PolygonId('polygon_1')); await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1})); await tester.pumpWidget(_mapWithPolygons(<Polygon>{p2})); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.polygonUpdates.last.polygonsToChange.length, 1); expect(map.polygonUpdates.last.polygonsToChange.first, equals(p2)); expect(map.polygonUpdates.last.polygonIdsToRemove.isEmpty, true); expect(map.polygonUpdates.last.polygonsToAdd.isEmpty, true); }); testWidgets('Mutate a polygon with points and holes', (WidgetTester tester) async { final Polygon p1 = Polygon( polygonId: const PolygonId('polygon_1'), points: _rectPoints(size: 1), holes: <List<LatLng>>[_rectPoints(size: 0.5)], ); await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1})); p1.points ..clear() ..addAll(_rectPoints(size: 2)); p1.holes ..clear() ..addAll(<List<LatLng>>[_rectPoints(size: 1)]); await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1})); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.polygonUpdates.last.polygonsToChange.length, 1); expect(map.polygonUpdates.last.polygonsToChange.first, equals(p1)); expect(map.polygonUpdates.last.polygonIdsToRemove.isEmpty, true); expect(map.polygonUpdates.last.polygonsToAdd.isEmpty, true); }); testWidgets('Multi Update polygons with points and hole', (WidgetTester tester) async { Polygon p1 = const Polygon(polygonId: PolygonId('polygon_1')); Polygon p2 = Polygon( polygonId: const PolygonId('polygon_2'), points: _rectPoints(size: 2), holes: <List<LatLng>>[_rectPoints(size: 1)], ); final Set<Polygon> prev = <Polygon>{p1, p2}; p1 = const Polygon(polygonId: PolygonId('polygon_1'), visible: false); p2 = p2.copyWith( pointsParam: _rectPoints(size: 5), holesParam: <List<LatLng>>[_rectPoints(size: 2)], ); final Set<Polygon> cur = <Polygon>{p1, p2}; await tester.pumpWidget(_mapWithPolygons(prev)); await tester.pumpWidget(_mapWithPolygons(cur)); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.polygonUpdates.last.polygonsToChange, cur); expect(map.polygonUpdates.last.polygonIdsToRemove.isEmpty, true); expect(map.polygonUpdates.last.polygonsToAdd.isEmpty, true); }); testWidgets('Multi Update polygons with points and hole', (WidgetTester tester) async { Polygon p2 = Polygon( polygonId: const PolygonId('polygon_2'), points: _rectPoints(size: 2), holes: <List<LatLng>>[_rectPoints(size: 1)], ); const Polygon p3 = Polygon(polygonId: PolygonId('polygon_3')); final Set<Polygon> prev = <Polygon>{p2, p3}; // p1 is added, p2 is updated, p3 is removed. final Polygon p1 = _polygonWithPointsAndHole(const PolygonId('polygon_1')); p2 = p2.copyWith( pointsParam: _rectPoints(size: 5), holesParam: <List<LatLng>>[_rectPoints(size: 3)], ); final Set<Polygon> cur = <Polygon>{p1, p2}; await tester.pumpWidget(_mapWithPolygons(prev)); await tester.pumpWidget(_mapWithPolygons(cur)); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.polygonUpdates.last.polygonsToChange.length, 1); expect(map.polygonUpdates.last.polygonsToAdd.length, 1); expect(map.polygonUpdates.last.polygonIdsToRemove.length, 1); expect(map.polygonUpdates.last.polygonsToChange.first, equals(p2)); expect(map.polygonUpdates.last.polygonsToAdd.first, equals(p1)); expect( map.polygonUpdates.last.polygonIdsToRemove.first, equals(p3.polygonId)); }); testWidgets('Partial Update polygons with points and hole', (WidgetTester tester) async { final Polygon p1 = _polygonWithPointsAndHole(const PolygonId('polygon_1')); const Polygon p2 = Polygon(polygonId: PolygonId('polygon_2')); Polygon p3 = Polygon( polygonId: const PolygonId('polygon_3'), points: _rectPoints(size: 2), holes: <List<LatLng>>[_rectPoints(size: 1)], ); final Set<Polygon> prev = <Polygon>{p1, p2, p3}; p3 = p3.copyWith( pointsParam: _rectPoints(size: 5), holesParam: <List<LatLng>>[_rectPoints(size: 3)], ); final Set<Polygon> cur = <Polygon>{p1, p2, p3}; await tester.pumpWidget(_mapWithPolygons(prev)); await tester.pumpWidget(_mapWithPolygons(cur)); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.polygonUpdates.last.polygonsToChange, <Polygon>{p3}); expect(map.polygonUpdates.last.polygonIdsToRemove.isEmpty, true); expect(map.polygonUpdates.last.polygonsToAdd.isEmpty, true); }); testWidgets('multi-update with delays', (WidgetTester tester) async { platform.simulatePlatformDelay = true; const Polygon p1 = Polygon(polygonId: PolygonId('polygon_1')); const Polygon p2 = Polygon(polygonId: PolygonId('polygon_2')); const Polygon p3 = Polygon(polygonId: PolygonId('polygon_3'), strokeWidth: 1); const Polygon p3updated = Polygon(polygonId: PolygonId('polygon_3'), strokeWidth: 2); // First remove one and add another, then update the new one. await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1, p2})); await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1, p3})); await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1, p3updated})); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.polygonUpdates.length, 3); expect(map.polygonUpdates[0].polygonsToChange.isEmpty, true); expect(map.polygonUpdates[0].polygonsToAdd, <Polygon>{p1, p2}); expect(map.polygonUpdates[0].polygonIdsToRemove.isEmpty, true); expect(map.polygonUpdates[1].polygonsToChange.isEmpty, true); expect(map.polygonUpdates[1].polygonsToAdd, <Polygon>{p3}); expect(map.polygonUpdates[1].polygonIdsToRemove, <PolygonId>{p2.polygonId}); expect(map.polygonUpdates[2].polygonsToChange, <Polygon>{p3updated}); expect(map.polygonUpdates[2].polygonsToAdd.isEmpty, true); expect(map.polygonUpdates[2].polygonIdsToRemove.isEmpty, true); await tester.pumpAndSettle(); }); }
packages/packages/google_maps_flutter/google_maps_flutter/test/polygon_updates_test.dart/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter/test/polygon_updates_test.dart", "repo_id": "packages", "token_count": 6557 }
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. package io.flutter.plugins.googlemaps; import android.Manifest; import android.annotation.SuppressLint; import android.content.Context; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.Point; import android.graphics.SurfaceTexture; import android.os.Bundle; import android.util.Log; import android.view.TextureView; import android.view.TextureView.SurfaceTextureListener; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import androidx.lifecycle.DefaultLifecycleObserver; import androidx.lifecycle.Lifecycle; import androidx.lifecycle.LifecycleOwner; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.GoogleMap.SnapshotReadyCallback; import com.google.android.gms.maps.GoogleMapOptions; import com.google.android.gms.maps.MapView; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.Circle; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import com.google.android.gms.maps.model.MapStyleOptions; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.Polygon; import com.google.android.gms.maps.model.Polyline; import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodChannel; import io.flutter.plugin.platform.PlatformView; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; /** Controller of a single GoogleMaps MapView instance. */ final class GoogleMapController implements DefaultLifecycleObserver, ActivityPluginBinding.OnSaveInstanceStateListener, GoogleMapOptionsSink, MethodChannel.MethodCallHandler, OnMapReadyCallback, GoogleMapListener, PlatformView { private static final String TAG = "GoogleMapController"; private final int id; private final MethodChannel methodChannel; private final GoogleMapOptions options; @Nullable private MapView mapView; @Nullable private GoogleMap googleMap; private boolean trackCameraPosition = false; private boolean myLocationEnabled = false; private boolean myLocationButtonEnabled = false; private boolean zoomControlsEnabled = true; private boolean indoorEnabled = true; private boolean trafficEnabled = false; private boolean buildingsEnabled = true; private boolean disposed = false; @VisibleForTesting final float density; private MethodChannel.Result mapReadyResult; private final Context context; private final LifecycleProvider lifecycleProvider; private final MarkersController markersController; private final PolygonsController polygonsController; private final PolylinesController polylinesController; private final CirclesController circlesController; private final TileOverlaysController tileOverlaysController; private List<Object> initialMarkers; private List<Object> initialPolygons; private List<Object> initialPolylines; private List<Object> initialCircles; private List<Map<String, ?>> initialTileOverlays; // Null except between initialization and onMapReady. private @Nullable String initialMapStyle; private @Nullable String lastStyleError; @VisibleForTesting List<Float> initialPadding; GoogleMapController( int id, Context context, BinaryMessenger binaryMessenger, LifecycleProvider lifecycleProvider, GoogleMapOptions options) { this.id = id; this.context = context; this.options = options; this.mapView = new MapView(context, options); this.density = context.getResources().getDisplayMetrics().density; methodChannel = new MethodChannel(binaryMessenger, "plugins.flutter.dev/google_maps_android_" + id); methodChannel.setMethodCallHandler(this); this.lifecycleProvider = lifecycleProvider; this.markersController = new MarkersController(methodChannel); this.polygonsController = new PolygonsController(methodChannel, density); this.polylinesController = new PolylinesController(methodChannel, density); this.circlesController = new CirclesController(methodChannel, density); this.tileOverlaysController = new TileOverlaysController(methodChannel); } @Override public View getView() { return mapView; } @VisibleForTesting /*package*/ void setView(MapView view) { mapView = view; } void init() { lifecycleProvider.getLifecycle().addObserver(this); mapView.getMapAsync(this); } private void moveCamera(CameraUpdate cameraUpdate) { googleMap.moveCamera(cameraUpdate); } private void animateCamera(CameraUpdate cameraUpdate) { googleMap.animateCamera(cameraUpdate); } private CameraPosition getCameraPosition() { return trackCameraPosition ? googleMap.getCameraPosition() : null; } @Override public void onMapReady(GoogleMap googleMap) { this.googleMap = googleMap; this.googleMap.setIndoorEnabled(this.indoorEnabled); this.googleMap.setTrafficEnabled(this.trafficEnabled); this.googleMap.setBuildingsEnabled(this.buildingsEnabled); installInvalidator(); googleMap.setOnInfoWindowClickListener(this); if (mapReadyResult != null) { mapReadyResult.success(null); mapReadyResult = null; } setGoogleMapListener(this); updateMyLocationSettings(); markersController.setGoogleMap(googleMap); polygonsController.setGoogleMap(googleMap); polylinesController.setGoogleMap(googleMap); circlesController.setGoogleMap(googleMap); tileOverlaysController.setGoogleMap(googleMap); updateInitialMarkers(); updateInitialPolygons(); updateInitialPolylines(); updateInitialCircles(); updateInitialTileOverlays(); if (initialPadding != null && initialPadding.size() == 4) { setPadding( initialPadding.get(0), initialPadding.get(1), initialPadding.get(2), initialPadding.get(3)); } if (initialMapStyle != null) { updateMapStyle(initialMapStyle); initialMapStyle = null; } } // Returns the first TextureView found in the view hierarchy. private static TextureView findTextureView(ViewGroup group) { final int n = group.getChildCount(); for (int i = 0; i < n; i++) { View view = group.getChildAt(i); if (view instanceof TextureView) { return (TextureView) view; } if (view instanceof ViewGroup) { TextureView r = findTextureView((ViewGroup) view); if (r != null) { return r; } } } return null; } private void installInvalidator() { if (mapView == null) { // This should only happen in tests. return; } TextureView textureView = findTextureView(mapView); if (textureView == null) { Log.i(TAG, "No TextureView found. Likely using the LEGACY renderer."); return; } Log.i(TAG, "Installing custom TextureView driven invalidator."); SurfaceTextureListener internalListener = textureView.getSurfaceTextureListener(); // Override the Maps internal SurfaceTextureListener with our own. Our listener // mostly just invokes the internal listener callbacks but in onSurfaceTextureUpdated // the mapView is invalidated which ensures that all map updates are presented to the // screen. final MapView mapView = this.mapView; textureView.setSurfaceTextureListener( new TextureView.SurfaceTextureListener() { public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) { if (internalListener != null) { internalListener.onSurfaceTextureAvailable(surface, width, height); } } public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) { if (internalListener != null) { return internalListener.onSurfaceTextureDestroyed(surface); } return true; } public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) { if (internalListener != null) { internalListener.onSurfaceTextureSizeChanged(surface, width, height); } } public void onSurfaceTextureUpdated(SurfaceTexture surface) { if (internalListener != null) { internalListener.onSurfaceTextureUpdated(surface); } mapView.invalidate(); } }); } @Override public void onMethodCall(MethodCall call, MethodChannel.Result result) { switch (call.method) { case "map#waitForMap": if (googleMap != null) { result.success(null); return; } mapReadyResult = result; break; case "map#update": { Convert.interpretGoogleMapOptions(call.argument("options"), this); result.success(Convert.cameraPositionToJson(getCameraPosition())); break; } case "map#getVisibleRegion": { if (googleMap != null) { LatLngBounds latLngBounds = googleMap.getProjection().getVisibleRegion().latLngBounds; result.success(Convert.latlngBoundsToJson(latLngBounds)); } else { result.error( "GoogleMap uninitialized", "getVisibleRegion called prior to map initialization", null); } break; } case "map#getScreenCoordinate": { if (googleMap != null) { LatLng latLng = Convert.toLatLng(call.arguments); Point screenLocation = googleMap.getProjection().toScreenLocation(latLng); result.success(Convert.pointToJson(screenLocation)); } else { result.error( "GoogleMap uninitialized", "getScreenCoordinate called prior to map initialization", null); } break; } case "map#getLatLng": { if (googleMap != null) { Point point = Convert.toPoint(call.arguments); LatLng latLng = googleMap.getProjection().fromScreenLocation(point); result.success(Convert.latLngToJson(latLng)); } else { result.error( "GoogleMap uninitialized", "getLatLng called prior to map initialization", null); } break; } case "map#takeSnapshot": { if (googleMap != null) { final MethodChannel.Result _result = result; googleMap.snapshot( new SnapshotReadyCallback() { @Override public void onSnapshotReady(Bitmap bitmap) { ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); byte[] byteArray = stream.toByteArray(); bitmap.recycle(); _result.success(byteArray); } }); } else { result.error("GoogleMap uninitialized", "takeSnapshot", null); } break; } case "camera#move": { final CameraUpdate cameraUpdate = Convert.toCameraUpdate(call.argument("cameraUpdate"), density); moveCamera(cameraUpdate); result.success(null); break; } case "camera#animate": { final CameraUpdate cameraUpdate = Convert.toCameraUpdate(call.argument("cameraUpdate"), density); animateCamera(cameraUpdate); result.success(null); break; } case "markers#update": { List<Object> markersToAdd = call.argument("markersToAdd"); markersController.addMarkers(markersToAdd); List<Object> markersToChange = call.argument("markersToChange"); markersController.changeMarkers(markersToChange); List<Object> markerIdsToRemove = call.argument("markerIdsToRemove"); markersController.removeMarkers(markerIdsToRemove); result.success(null); break; } case "markers#showInfoWindow": { Object markerId = call.argument("markerId"); markersController.showMarkerInfoWindow((String) markerId, result); break; } case "markers#hideInfoWindow": { Object markerId = call.argument("markerId"); markersController.hideMarkerInfoWindow((String) markerId, result); break; } case "markers#isInfoWindowShown": { Object markerId = call.argument("markerId"); markersController.isInfoWindowShown((String) markerId, result); break; } case "polygons#update": { List<Object> polygonsToAdd = call.argument("polygonsToAdd"); polygonsController.addPolygons(polygonsToAdd); List<Object> polygonsToChange = call.argument("polygonsToChange"); polygonsController.changePolygons(polygonsToChange); List<Object> polygonIdsToRemove = call.argument("polygonIdsToRemove"); polygonsController.removePolygons(polygonIdsToRemove); result.success(null); break; } case "polylines#update": { List<Object> polylinesToAdd = call.argument("polylinesToAdd"); polylinesController.addPolylines(polylinesToAdd); List<Object> polylinesToChange = call.argument("polylinesToChange"); polylinesController.changePolylines(polylinesToChange); List<Object> polylineIdsToRemove = call.argument("polylineIdsToRemove"); polylinesController.removePolylines(polylineIdsToRemove); result.success(null); break; } case "circles#update": { List<Object> circlesToAdd = call.argument("circlesToAdd"); circlesController.addCircles(circlesToAdd); List<Object> circlesToChange = call.argument("circlesToChange"); circlesController.changeCircles(circlesToChange); List<Object> circleIdsToRemove = call.argument("circleIdsToRemove"); circlesController.removeCircles(circleIdsToRemove); result.success(null); break; } case "map#isCompassEnabled": { result.success(googleMap.getUiSettings().isCompassEnabled()); break; } case "map#isMapToolbarEnabled": { result.success(googleMap.getUiSettings().isMapToolbarEnabled()); break; } case "map#getMinMaxZoomLevels": { List<Float> zoomLevels = new ArrayList<>(2); zoomLevels.add(googleMap.getMinZoomLevel()); zoomLevels.add(googleMap.getMaxZoomLevel()); result.success(zoomLevels); break; } case "map#isZoomGesturesEnabled": { result.success(googleMap.getUiSettings().isZoomGesturesEnabled()); break; } case "map#isLiteModeEnabled": { result.success(options.getLiteMode()); break; } case "map#isZoomControlsEnabled": { result.success(googleMap.getUiSettings().isZoomControlsEnabled()); break; } case "map#isScrollGesturesEnabled": { result.success(googleMap.getUiSettings().isScrollGesturesEnabled()); break; } case "map#isTiltGesturesEnabled": { result.success(googleMap.getUiSettings().isTiltGesturesEnabled()); break; } case "map#isRotateGesturesEnabled": { result.success(googleMap.getUiSettings().isRotateGesturesEnabled()); break; } case "map#isMyLocationButtonEnabled": { result.success(googleMap.getUiSettings().isMyLocationButtonEnabled()); break; } case "map#isTrafficEnabled": { result.success(googleMap.isTrafficEnabled()); break; } case "map#isBuildingsEnabled": { result.success(googleMap.isBuildingsEnabled()); break; } case "map#getZoomLevel": { result.success(googleMap.getCameraPosition().zoom); break; } case "map#setStyle": { Object arg = call.arguments; final String style = arg instanceof String ? (String) arg : null; final boolean mapStyleSet = updateMapStyle(style); ArrayList<Object> mapStyleResult = new ArrayList<>(2); mapStyleResult.add(mapStyleSet); if (!mapStyleSet) { mapStyleResult.add(lastStyleError); } result.success(mapStyleResult); break; } case "map#getStyleError": { result.success(lastStyleError); break; } case "tileOverlays#update": { List<Map<String, ?>> tileOverlaysToAdd = call.argument("tileOverlaysToAdd"); tileOverlaysController.addTileOverlays(tileOverlaysToAdd); List<Map<String, ?>> tileOverlaysToChange = call.argument("tileOverlaysToChange"); tileOverlaysController.changeTileOverlays(tileOverlaysToChange); List<String> tileOverlaysToRemove = call.argument("tileOverlayIdsToRemove"); tileOverlaysController.removeTileOverlays(tileOverlaysToRemove); result.success(null); break; } case "tileOverlays#clearTileCache": { String tileOverlayId = call.argument("tileOverlayId"); tileOverlaysController.clearTileCache(tileOverlayId); result.success(null); break; } case "map#getTileOverlayInfo": { String tileOverlayId = call.argument("tileOverlayId"); result.success(tileOverlaysController.getTileOverlayInfo(tileOverlayId)); break; } default: result.notImplemented(); } } @Override public void onMapClick(LatLng latLng) { final Map<String, Object> arguments = new HashMap<>(2); arguments.put("position", Convert.latLngToJson(latLng)); methodChannel.invokeMethod("map#onTap", arguments); } @Override public void onMapLongClick(LatLng latLng) { final Map<String, Object> arguments = new HashMap<>(2); arguments.put("position", Convert.latLngToJson(latLng)); methodChannel.invokeMethod("map#onLongPress", arguments); } @Override public void onCameraMoveStarted(int reason) { final Map<String, Object> arguments = new HashMap<>(2); boolean isGesture = reason == GoogleMap.OnCameraMoveStartedListener.REASON_GESTURE; arguments.put("isGesture", isGesture); methodChannel.invokeMethod("camera#onMoveStarted", arguments); } @Override public void onInfoWindowClick(Marker marker) { markersController.onInfoWindowTap(marker.getId()); } @Override public void onCameraMove() { if (!trackCameraPosition) { return; } final Map<String, Object> arguments = new HashMap<>(2); arguments.put("position", Convert.cameraPositionToJson(googleMap.getCameraPosition())); methodChannel.invokeMethod("camera#onMove", arguments); } @Override public void onCameraIdle() { methodChannel.invokeMethod("camera#onIdle", Collections.singletonMap("map", id)); } @Override public boolean onMarkerClick(Marker marker) { return markersController.onMarkerTap(marker.getId()); } @Override public void onMarkerDragStart(Marker marker) { markersController.onMarkerDragStart(marker.getId(), marker.getPosition()); } @Override public void onMarkerDrag(Marker marker) { markersController.onMarkerDrag(marker.getId(), marker.getPosition()); } @Override public void onMarkerDragEnd(Marker marker) { markersController.onMarkerDragEnd(marker.getId(), marker.getPosition()); } @Override public void onPolygonClick(Polygon polygon) { polygonsController.onPolygonTap(polygon.getId()); } @Override public void onPolylineClick(Polyline polyline) { polylinesController.onPolylineTap(polyline.getId()); } @Override public void onCircleClick(Circle circle) { circlesController.onCircleTap(circle.getId()); } @Override public void dispose() { if (disposed) { return; } disposed = true; methodChannel.setMethodCallHandler(null); setGoogleMapListener(null); destroyMapViewIfNecessary(); Lifecycle lifecycle = lifecycleProvider.getLifecycle(); if (lifecycle != null) { lifecycle.removeObserver(this); } } private void setGoogleMapListener(@Nullable GoogleMapListener listener) { if (googleMap == null) { Log.v(TAG, "Controller was disposed before GoogleMap was ready."); return; } googleMap.setOnCameraMoveStartedListener(listener); googleMap.setOnCameraMoveListener(listener); googleMap.setOnCameraIdleListener(listener); googleMap.setOnMarkerClickListener(listener); googleMap.setOnMarkerDragListener(listener); googleMap.setOnPolygonClickListener(listener); googleMap.setOnPolylineClickListener(listener); googleMap.setOnCircleClickListener(listener); googleMap.setOnMapClickListener(listener); googleMap.setOnMapLongClickListener(listener); } // DefaultLifecycleObserver @Override public void onCreate(@NonNull LifecycleOwner owner) { if (disposed) { return; } mapView.onCreate(null); } @Override public void onStart(@NonNull LifecycleOwner owner) { if (disposed) { return; } mapView.onStart(); } @Override public void onResume(@NonNull LifecycleOwner owner) { if (disposed) { return; } mapView.onResume(); } @Override public void onPause(@NonNull LifecycleOwner owner) { if (disposed) { return; } mapView.onResume(); } @Override public void onStop(@NonNull LifecycleOwner owner) { if (disposed) { return; } mapView.onStop(); } @Override public void onDestroy(@NonNull LifecycleOwner owner) { owner.getLifecycle().removeObserver(this); if (disposed) { return; } destroyMapViewIfNecessary(); } @Override public void onRestoreInstanceState(Bundle bundle) { if (disposed) { return; } mapView.onCreate(bundle); } @Override public void onSaveInstanceState(Bundle bundle) { if (disposed) { return; } mapView.onSaveInstanceState(bundle); } // GoogleMapOptionsSink methods @Override public void setCameraTargetBounds(LatLngBounds bounds) { googleMap.setLatLngBoundsForCameraTarget(bounds); } @Override public void setCompassEnabled(boolean compassEnabled) { googleMap.getUiSettings().setCompassEnabled(compassEnabled); } @Override public void setMapToolbarEnabled(boolean mapToolbarEnabled) { googleMap.getUiSettings().setMapToolbarEnabled(mapToolbarEnabled); } @Override public void setMapType(int mapType) { googleMap.setMapType(mapType); } @Override public void setTrackCameraPosition(boolean trackCameraPosition) { this.trackCameraPosition = trackCameraPosition; } @Override public void setRotateGesturesEnabled(boolean rotateGesturesEnabled) { googleMap.getUiSettings().setRotateGesturesEnabled(rotateGesturesEnabled); } @Override public void setScrollGesturesEnabled(boolean scrollGesturesEnabled) { googleMap.getUiSettings().setScrollGesturesEnabled(scrollGesturesEnabled); } @Override public void setTiltGesturesEnabled(boolean tiltGesturesEnabled) { googleMap.getUiSettings().setTiltGesturesEnabled(tiltGesturesEnabled); } @Override public void setMinMaxZoomPreference(Float min, Float max) { googleMap.resetMinMaxZoomPreference(); if (min != null) { googleMap.setMinZoomPreference(min); } if (max != null) { googleMap.setMaxZoomPreference(max); } } @Override public void setPadding(float top, float left, float bottom, float right) { if (googleMap != null) { googleMap.setPadding( (int) (left * density), (int) (top * density), (int) (right * density), (int) (bottom * density)); } else { setInitialPadding(top, left, bottom, right); } } @VisibleForTesting void setInitialPadding(float top, float left, float bottom, float right) { if (initialPadding == null) { initialPadding = new ArrayList<>(); } else { initialPadding.clear(); } initialPadding.add(top); initialPadding.add(left); initialPadding.add(bottom); initialPadding.add(right); } @Override public void setZoomGesturesEnabled(boolean zoomGesturesEnabled) { googleMap.getUiSettings().setZoomGesturesEnabled(zoomGesturesEnabled); } /** This call will have no effect on already created map */ @Override public void setLiteModeEnabled(boolean liteModeEnabled) { options.liteMode(liteModeEnabled); } @Override public void setMyLocationEnabled(boolean myLocationEnabled) { if (this.myLocationEnabled == myLocationEnabled) { return; } this.myLocationEnabled = myLocationEnabled; if (googleMap != null) { updateMyLocationSettings(); } } @Override public void setMyLocationButtonEnabled(boolean myLocationButtonEnabled) { if (this.myLocationButtonEnabled == myLocationButtonEnabled) { return; } this.myLocationButtonEnabled = myLocationButtonEnabled; if (googleMap != null) { updateMyLocationSettings(); } } @Override public void setZoomControlsEnabled(boolean zoomControlsEnabled) { if (this.zoomControlsEnabled == zoomControlsEnabled) { return; } this.zoomControlsEnabled = zoomControlsEnabled; if (googleMap != null) { googleMap.getUiSettings().setZoomControlsEnabled(zoomControlsEnabled); } } @Override public void setInitialMarkers(Object initialMarkers) { ArrayList<?> markers = (ArrayList<?>) initialMarkers; this.initialMarkers = markers != null ? new ArrayList<>(markers) : null; if (googleMap != null) { updateInitialMarkers(); } } private void updateInitialMarkers() { markersController.addMarkers(initialMarkers); } @Override public void setInitialPolygons(Object initialPolygons) { ArrayList<?> polygons = (ArrayList<?>) initialPolygons; this.initialPolygons = polygons != null ? new ArrayList<>(polygons) : null; if (googleMap != null) { updateInitialPolygons(); } } private void updateInitialPolygons() { polygonsController.addPolygons(initialPolygons); } @Override public void setInitialPolylines(Object initialPolylines) { ArrayList<?> polylines = (ArrayList<?>) initialPolylines; this.initialPolylines = polylines != null ? new ArrayList<>(polylines) : null; if (googleMap != null) { updateInitialPolylines(); } } private void updateInitialPolylines() { polylinesController.addPolylines(initialPolylines); } @Override public void setInitialCircles(Object initialCircles) { ArrayList<?> circles = (ArrayList<?>) initialCircles; this.initialCircles = circles != null ? new ArrayList<>(circles) : null; if (googleMap != null) { updateInitialCircles(); } } private void updateInitialCircles() { circlesController.addCircles(initialCircles); } @Override public void setInitialTileOverlays(List<Map<String, ?>> initialTileOverlays) { this.initialTileOverlays = initialTileOverlays; if (googleMap != null) { updateInitialTileOverlays(); } } private void updateInitialTileOverlays() { tileOverlaysController.addTileOverlays(initialTileOverlays); } @SuppressLint("MissingPermission") private void updateMyLocationSettings() { if (hasLocationPermission()) { // The plugin doesn't add the location permission by default so that apps that don't need // the feature won't require the permission. // Gradle is doing a static check for missing permission and in some configurations will // fail the build if the permission is missing. The following disables the Gradle lint. //noinspection ResourceType googleMap.setMyLocationEnabled(myLocationEnabled); googleMap.getUiSettings().setMyLocationButtonEnabled(myLocationButtonEnabled); } else { // TODO(amirh): Make the options update fail. // https://github.com/flutter/flutter/issues/24327 Log.e(TAG, "Cannot enable MyLocation layer as location permissions are not granted"); } } private boolean hasLocationPermission() { return checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED; } private int checkSelfPermission(String permission) { if (permission == null) { throw new IllegalArgumentException("permission is null"); } return context.checkPermission( permission, android.os.Process.myPid(), android.os.Process.myUid()); } private void destroyMapViewIfNecessary() { if (mapView == null) { return; } mapView.onDestroy(); mapView = null; } public void setIndoorEnabled(boolean indoorEnabled) { this.indoorEnabled = indoorEnabled; } public void setTrafficEnabled(boolean trafficEnabled) { this.trafficEnabled = trafficEnabled; if (googleMap == null) { return; } googleMap.setTrafficEnabled(trafficEnabled); } public void setBuildingsEnabled(boolean buildingsEnabled) { this.buildingsEnabled = buildingsEnabled; } public void setMapStyle(@Nullable String style) { if (googleMap == null) { initialMapStyle = style; } else { updateMapStyle(style); } } private boolean updateMapStyle(String style) { // Dart passes an empty string to indicate that the style should be cleared. final MapStyleOptions mapStyleOptions = style == null || style.isEmpty() ? null : new MapStyleOptions(style); final boolean set = Objects.requireNonNull(googleMap).setMapStyle(mapStyleOptions); lastStyleError = set ? null : "Unable to set the map style. Please check console logs for errors."; return set; } }
packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/GoogleMapController.java/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/GoogleMapController.java", "repo_id": "packages", "token_count": 11863 }
977
// 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.googlemaps; import com.google.android.gms.maps.model.Cap; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.PatternItem; import com.google.android.gms.maps.model.Polyline; import java.util.List; /** Controller of a single Polyline on the map. */ class PolylineController implements PolylineOptionsSink { private final Polyline polyline; private final String googleMapsPolylineId; private boolean consumeTapEvents; private final float density; PolylineController(Polyline polyline, boolean consumeTapEvents, float density) { this.polyline = polyline; this.consumeTapEvents = consumeTapEvents; this.density = density; this.googleMapsPolylineId = polyline.getId(); } void remove() { polyline.remove(); } @Override public void setConsumeTapEvents(boolean consumeTapEvents) { this.consumeTapEvents = consumeTapEvents; polyline.setClickable(consumeTapEvents); } @Override public void setColor(int color) { polyline.setColor(color); } @Override public void setEndCap(Cap endCap) { polyline.setEndCap(endCap); } @Override public void setGeodesic(boolean geodesic) { polyline.setGeodesic(geodesic); } @Override public void setJointType(int jointType) { polyline.setJointType(jointType); } @Override public void setPattern(List<PatternItem> pattern) { polyline.setPattern(pattern); } @Override public void setPoints(List<LatLng> points) { polyline.setPoints(points); } @Override public void setStartCap(Cap startCap) { polyline.setStartCap(startCap); } @Override public void setVisible(boolean visible) { polyline.setVisible(visible); } @Override public void setWidth(float width) { polyline.setWidth(width * density); } @Override public void setZIndex(float zIndex) { polyline.setZIndex(zIndex); } String getGoogleMapsPolylineId() { return googleMapsPolylineId; } boolean consumeTapEvents() { return consumeTapEvents; } }
packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/PolylineController.java/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/PolylineController.java", "repo_id": "packages", "token_count": 736 }
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. package io.flutter.plugins.googlemaps; import static junit.framework.TestCase.assertEquals; import com.google.android.gms.maps.model.PolylineOptions; import org.junit.Test; public class PolylineBuilderTest { @Test public void density_AppliesToStrokeWidth() { final float density = 5; final float strokeWidth = 3; final PolylineBuilder builder = new PolylineBuilder(density); builder.setWidth(strokeWidth); final PolylineOptions options = builder.build(); final float width = options.getWidth(); assertEquals(density * strokeWidth, width); } }
packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/test/java/io/flutter/plugins/googlemaps/PolylineBuilderTest.java/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/test/java/io/flutter/plugins/googlemaps/PolylineBuilderTest.java", "repo_id": "packages", "token_count": 224 }
979
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:google_maps_flutter_android/google_maps_flutter_android.dart'; import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart'; import 'package:integration_test/integration_test.dart'; import 'google_maps_tests.dart' show googleMapsTests; void main() { late AndroidMapRenderer initializedRenderer; IntegrationTestWidgetsFlutterBinding.ensureInitialized(); setUpAll(() async { final GoogleMapsFlutterAndroid instance = GoogleMapsFlutterPlatform.instance as GoogleMapsFlutterAndroid; initializedRenderer = await instance.initializeWithRenderer(AndroidMapRenderer.legacy); }); testWidgets('initialized with legacy renderer', (WidgetTester _) async { expect(initializedRenderer, AndroidMapRenderer.legacy); }); testWidgets('throws PlatformException on multiple renderer initializations', (WidgetTester _) async { final GoogleMapsFlutterAndroid instance = GoogleMapsFlutterPlatform.instance as GoogleMapsFlutterAndroid; expect( () async => instance.initializeWithRenderer(AndroidMapRenderer.legacy), throwsA(isA<PlatformException>().having((PlatformException e) => e.code, 'code', 'Renderer already initialized'))); }); // Run tests. googleMapsTests(); }
packages/packages/google_maps_flutter/google_maps_flutter_android/example/integration_test/legacy_renderer_test.dart/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/example/integration_test/legacy_renderer_test.dart", "repo_id": "packages", "token_count": 499 }
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. import 'package:flutter/foundation.dart' show immutable, objectRuntimeType; /// Uniquely identifies object an among [GoogleMap] collections of a specific /// type. /// /// This does not have to be globally unique, only unique among the collection. @immutable class MapsObjectId<T> { /// Creates an immutable object representing a [T] among [GoogleMap] Ts. /// /// An [AssertionError] will be thrown if [value] is null. const MapsObjectId(this.value); /// The value of the id. final String value; @override bool operator ==(Object other) { if (identical(this, other)) { return true; } if (other.runtimeType != runtimeType) { return false; } return other is MapsObjectId<T> && value == other.value; } @override int get hashCode => value.hashCode; @override String toString() { return '${objectRuntimeType(this, 'MapsObjectId')}($value)'; } } /// A common interface for maps types. abstract class MapsObject<T> { /// A identifier for this object. MapsObjectId<T> get mapsId; /// Returns a duplicate of this object. T clone(); /// Converts this object to something serializable in JSON. Object toJson(); }
packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/maps_object.dart/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/maps_object.dart", "repo_id": "packages", "token_count": 415 }
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 '../types.dart'; import 'maps_object.dart'; /// Converts an [Iterable] of Circles in a Map of CircleId -> Circle. Map<CircleId, Circle> keyByCircleId(Iterable<Circle> circles) { return keyByMapsObjectId<Circle>(circles).cast<CircleId, Circle>(); } /// Converts a Set of Circles into something serializable in JSON. Object serializeCircleSet(Set<Circle> circles) { return serializeMapsObjectSet(circles); }
packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/utils/circle.dart/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/utils/circle.dart", "repo_id": "packages", "token_count": 182 }
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_test/flutter_test.dart'; import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('$Cluster', () { test('constructor', () { final Cluster cluster = Cluster( const ClusterManagerId('3456787654'), const <MarkerId>[MarkerId('23456')], position: const LatLng(55.0, 66.0), bounds: LatLngBounds( northeast: const LatLng(88.0, 22.0), southwest: const LatLng(11.0, 99.0), ), ); expect(cluster.clusterManagerId.value, equals('3456787654')); expect(cluster.markerIds[0].value, equals('23456')); expect(cluster.position, equals(const LatLng(55.0, 66.0))); expect( cluster.bounds, LatLngBounds( northeast: const LatLng(88.0, 22.0), southwest: const LatLng(11.0, 99.0), )); }); test('constructor markerIds length is > 0', () { void initWithMarkerIds(List<MarkerId> markerIds) { Cluster( const ClusterManagerId('3456787654'), markerIds, position: const LatLng(55.0, 66.0), bounds: LatLngBounds( northeast: const LatLng(88.0, 22.0), southwest: const LatLng(11.0, 99.0), ), ); } expect(() => initWithMarkerIds(<MarkerId>[const MarkerId('12342323')]), isNot(throwsAssertionError)); expect(() => initWithMarkerIds(<MarkerId>[]), throwsAssertionError); }); }); }
packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/cluster_test.dart/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/cluster_test.dart", "repo_id": "packages", "token_count": 784 }
983
// 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. part of '../google_maps_flutter_web.dart'; /// This class manages all the [TileOverlayController]s associated to a [GoogleMapController]. class TileOverlaysController extends GeometryController { final Map<TileOverlayId, TileOverlayController> _tileOverlays = <TileOverlayId, TileOverlayController>{}; final List<TileOverlayController> _visibleTileOverlays = <TileOverlayController>[]; // Inserts `tileOverlayController` into the list of visible overlays, and the current [googleMap]. // // After insertion, the arrays stay sorted by ascending z-index. void _insertZSorted(TileOverlayController tileOverlayController) { final int index = _visibleTileOverlays.lowerBoundBy<num>( tileOverlayController, (TileOverlayController c) => c.tileOverlay.zIndex); googleMap.overlayMapTypes!.insertAt(index, tileOverlayController.gmMapType); _visibleTileOverlays.insert(index, tileOverlayController); } // Removes `tileOverlayController` from the list of visible overlays. void _remove(TileOverlayController tileOverlayController) { final int index = _visibleTileOverlays.indexOf(tileOverlayController); if (index < 0) { return; } googleMap.overlayMapTypes!.removeAt(index); _visibleTileOverlays.removeAt(index); } /// Adds new [TileOverlay]s to this controller. /// /// Wraps the [TileOverlay]s in corresponding [TileOverlayController]s. void addTileOverlays(Set<TileOverlay> tileOverlaysToAdd) { tileOverlaysToAdd.forEach(_addTileOverlay); } void _addTileOverlay(TileOverlay tileOverlay) { final TileOverlayController controller = TileOverlayController( tileOverlay: tileOverlay, ); _tileOverlays[tileOverlay.tileOverlayId] = controller; if (tileOverlay.visible) { _insertZSorted(controller); } } /// Updates [TileOverlay]s with new options. void changeTileOverlays(Set<TileOverlay> tileOverlays) { tileOverlays.forEach(_changeTileOverlay); } void _changeTileOverlay(TileOverlay tileOverlay) { final TileOverlayController controller = _tileOverlays[tileOverlay.tileOverlayId]!; final bool wasVisible = controller.tileOverlay.visible; final bool isVisible = tileOverlay.visible; controller.update(tileOverlay); if (wasVisible) { _remove(controller); } if (isVisible) { _insertZSorted(controller); } } /// Removes the tile overlays associated with the given [TileOverlayId]s. void removeTileOverlays(Set<TileOverlayId> tileOverlayIds) { tileOverlayIds.forEach(_removeTileOverlay); } void _removeTileOverlay(TileOverlayId tileOverlayId) { final TileOverlayController? controller = _tileOverlays.remove(tileOverlayId); if (controller != null) { _remove(controller); } } /// Invalidates the tile overlay associated with the given [TileOverlayId]. void clearTileCache(TileOverlayId tileOverlayId) { final TileOverlayController? controller = _tileOverlays[tileOverlayId]; if (controller != null && controller.tileOverlay.visible) { final int i = _visibleTileOverlays.indexOf(controller); // This causes the map to reload the overlay. googleMap.overlayMapTypes!.setAt(i, controller.gmMapType); } } }
packages/packages/google_maps_flutter/google_maps_flutter_web/lib/src/overlays.dart/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_web/lib/src/overlays.dart", "repo_id": "packages", "token_count": 1159 }
984
[![pub package](https://img.shields.io/pub/v/google_sign_in.svg)](https://pub.dev/packages/google_sign_in) A Flutter plugin for [Google Sign In](https://developers.google.com/identity/). | | Android | iOS | macOS | Web | |-------------|---------|-------|--------|-----| | **Support** | SDK 16+ | 12.0+ | 10.15+ | Any | ## Platform integration ### Android integration To access Google Sign-In, you'll need to make sure to [register your application](https://firebase.google.com/docs/android/setup). You don't need to include the google-services.json file in your app unless you are using Google services that require it. You do need to enable the OAuth APIs that you want, using the [Google Cloud Platform API manager](https://console.developers.google.com/). For example, if you want to mimic the behavior of the Google Sign-In sample app, you'll need to enable the [Google People API](https://developers.google.com/people/). Make sure you've filled out all required fields in the console for [OAuth consent screen](https://console.developers.google.com/apis/credentials/consent). Otherwise, you may encounter `APIException` errors. ### iOS integration Please see [instructions on integrating Google Sign-In for iOS](https://pub.dev/packages/google_sign_in_ios#ios-integration). #### iOS additional requirement Note that according to https://developer.apple.com/sign-in-with-apple/get-started, starting June 30, 2020, apps that use login services must also offer a "Sign in with Apple" option when submitting to the Apple App Store. Consider also using an Apple sign in plugin from pub.dev. The Flutter Favorite [sign_in_with_apple](https://pub.dev/packages/sign_in_with_apple) plugin could be an option. ### macOS integration Please see [instructions on integrating Google Sign-In for macOS](https://pub.dev/packages/google_sign_in_ios#macos-setup). ### Web integration The new SDK used by the web has fully separated Authentication from Authorization, so `signIn` and `signInSilently` no longer authorize OAuth `scopes`. Flutter apps must be able to detect what scopes have been granted by their users, and if the grants are still valid. Read below about **Working with scopes, and incremental authorization** for general information about changes that may be needed on an app, and for more specific web integration details, see the [`google_sign_in_web` package](https://pub.dev/packages/google_sign_in_web). ## Usage ### Import the package To use this plugin, follow the [plugin installation instructions](https://pub.dev/packages/google_sign_in/install). ### Use the plugin Initialize `GoogleSignIn` with the scopes you want: <?code-excerpt "example/lib/main.dart (Initialize)"?> ```dart const List<String> scopes = <String>[ 'email', 'https://www.googleapis.com/auth/contacts.readonly', ]; GoogleSignIn _googleSignIn = GoogleSignIn( // Optional clientId // clientId: 'your-client_id.apps.googleusercontent.com', scopes: scopes, ); ``` [Full list of available scopes](https://developers.google.com/identity/protocols/googlescopes). You can now use the `GoogleSignIn` class to authenticate in your Dart code, e.g. <?code-excerpt "example/lib/main.dart (SignIn)"?> ```dart Future<void> _handleSignIn() async { try { await _googleSignIn.signIn(); } catch (error) { print(error); } } ``` In the web, you should use the **Google Sign In button** (and not the `signIn` method) to guarantee that your user authentication contains a valid `idToken`. For more details, take a look at the [`google_sign_in_web` package](https://pub.dev/packages/google_sign_in_web). ## Working with scopes, and incremental authorization. If your app supports both mobile and web, read this section! ### Checking if scopes have been granted Users may (or may *not*) grant all the scopes that an application requests at Sign In. In fact, in the web, no scopes are granted by `signIn`, `silentSignIn` or the `renderButton` widget anymore. Applications must be able to: * Detect if the authenticated user has authorized the scopes they need. * Determine if the scopes that were granted a few minutes ago are still valid. There's a new method that enables the checks above, `canAccessScopes`: <?code-excerpt "example/lib/main.dart (CanAccessScopes)"?> ```dart // In mobile, being authenticated means being authorized... bool isAuthorized = account != null; // However, on web... if (kIsWeb && account != null) { isAuthorized = await _googleSignIn.canAccessScopes(scopes); } ``` _(Only implemented in the web platform, from version 6.1.0 of this package)_ ### Requesting more scopes when needed If an app determines that the user hasn't granted the scopes it requires, it should initiate an Authorization request. (Remember that in the web platform, this request **must be initiated from an user interaction**, like a button press). <?code-excerpt "example/lib/main.dart (RequestScopes)" plaster="none"?> ```dart Future<void> _handleAuthorizeScopes() async { final bool isAuthorized = await _googleSignIn.requestScopes(scopes); if (isAuthorized) { unawaited(_handleGetContact(_currentUser!)); } ``` The `requestScopes` returns a `boolean` value that is `true` if the user has granted all the requested scopes or `false` otherwise. Once your app determines that the current user `isAuthorized` to access the services for which you need `scopes`, it can proceed normally. ### Authorization expiration In the web, **the `accessToken` is no longer refreshed**. It expires after 3600 seconds (one hour), so your app needs to be able to handle failed REST requests, and update its UI to prompt the user for a new Authorization round. This can be done by combining the error responses from your REST requests with the `canAccessScopes` and `requestScopes` methods described above. For more details, take a look at the [`google_sign_in_web` package](https://pub.dev/packages/google_sign_in_web). ### Does an app always need to check `canAccessScopes`? The new web SDK implicitly grant access to the `email`, `profile` and `openid` scopes when users complete the sign-in process (either via the One Tap UX or the Google Sign In button). If an app only needs an `idToken`, or only requests permissions to any/all of the three scopes mentioned above ([OpenID Connect scopes](https://developers.google.com/identity/protocols/oauth2/scopes#openid-connect)), it won't need to implement any additional scope handling. If an app needs any scope other than `email`, `profile` and `openid`, it **must** implement a more complete scope handling, as described above. ## Example Find the example wiring in the [Google sign-in example application](https://github.com/flutter/packages/blob/main/packages/google_sign_in/google_sign_in/example/lib/main.dart).
packages/packages/google_sign_in/google_sign_in/README.md/0
{ "file_path": "packages/packages/google_sign_in/google_sign_in/README.md", "repo_id": "packages", "token_count": 1966 }
985
#include "../../Flutter/Flutter-Release.xcconfig" #include "Warnings.xcconfig"
packages/packages/google_sign_in/google_sign_in/example/macos/Runner/Configs/Release.xcconfig/0
{ "file_path": "packages/packages/google_sign_in/google_sign_in/example/macos/Runner/Configs/Release.xcconfig", "repo_id": "packages", "token_count": 32 }
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. // Autogenerated from Pigeon (v10.1.0), do not edit directly. // See also: https://pub.dev/packages/pigeon package io.flutter.plugins.googlesignin; 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.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; /** 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; } /** Pigeon version of SignInOption. */ public enum SignInType { /** Default configuration. */ STANDARD(0), /** Recommended configuration for game sign in. */ GAMES(1); final int index; private SignInType(final int index) { this.index = index; } } /** * Pigeon version of SignInInitParams. * * <p>See SignInInitParams for details. * * <p>Generated class from Pigeon that represents data sent in messages. */ public static final class InitParams { private @NonNull List<String> scopes; public @NonNull List<String> getScopes() { return scopes; } public void setScopes(@NonNull List<String> setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"scopes\" is null."); } this.scopes = setterArg; } private @NonNull SignInType signInType; public @NonNull SignInType getSignInType() { return signInType; } public void setSignInType(@NonNull SignInType setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"signInType\" is null."); } this.signInType = setterArg; } private @Nullable String hostedDomain; public @Nullable String getHostedDomain() { return hostedDomain; } public void setHostedDomain(@Nullable String setterArg) { this.hostedDomain = setterArg; } private @Nullable String clientId; public @Nullable String getClientId() { return clientId; } public void setClientId(@Nullable String setterArg) { this.clientId = setterArg; } private @Nullable String serverClientId; public @Nullable String getServerClientId() { return serverClientId; } public void setServerClientId(@Nullable String setterArg) { this.serverClientId = setterArg; } private @NonNull Boolean forceCodeForRefreshToken; public @NonNull Boolean getForceCodeForRefreshToken() { return forceCodeForRefreshToken; } public void setForceCodeForRefreshToken(@NonNull Boolean setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"forceCodeForRefreshToken\" is null."); } this.forceCodeForRefreshToken = setterArg; } /** Constructor is non-public to enforce null safety; use Builder. */ InitParams() {} public static final class Builder { private @Nullable List<String> scopes; public @NonNull Builder setScopes(@NonNull List<String> setterArg) { this.scopes = setterArg; return this; } private @Nullable SignInType signInType; public @NonNull Builder setSignInType(@NonNull SignInType setterArg) { this.signInType = setterArg; return this; } private @Nullable String hostedDomain; public @NonNull Builder setHostedDomain(@Nullable String setterArg) { this.hostedDomain = setterArg; return this; } private @Nullable String clientId; public @NonNull Builder setClientId(@Nullable String setterArg) { this.clientId = setterArg; return this; } private @Nullable String serverClientId; public @NonNull Builder setServerClientId(@Nullable String setterArg) { this.serverClientId = setterArg; return this; } private @Nullable Boolean forceCodeForRefreshToken; public @NonNull Builder setForceCodeForRefreshToken(@NonNull Boolean setterArg) { this.forceCodeForRefreshToken = setterArg; return this; } public @NonNull InitParams build() { InitParams pigeonReturn = new InitParams(); pigeonReturn.setScopes(scopes); pigeonReturn.setSignInType(signInType); pigeonReturn.setHostedDomain(hostedDomain); pigeonReturn.setClientId(clientId); pigeonReturn.setServerClientId(serverClientId); pigeonReturn.setForceCodeForRefreshToken(forceCodeForRefreshToken); return pigeonReturn; } } @NonNull ArrayList<Object> toList() { ArrayList<Object> toListResult = new ArrayList<Object>(6); toListResult.add(scopes); toListResult.add(signInType == null ? null : signInType.index); toListResult.add(hostedDomain); toListResult.add(clientId); toListResult.add(serverClientId); toListResult.add(forceCodeForRefreshToken); return toListResult; } static @NonNull InitParams fromList(@NonNull ArrayList<Object> list) { InitParams pigeonResult = new InitParams(); Object scopes = list.get(0); pigeonResult.setScopes((List<String>) scopes); Object signInType = list.get(1); pigeonResult.setSignInType(signInType == null ? null : SignInType.values()[(int) signInType]); Object hostedDomain = list.get(2); pigeonResult.setHostedDomain((String) hostedDomain); Object clientId = list.get(3); pigeonResult.setClientId((String) clientId); Object serverClientId = list.get(4); pigeonResult.setServerClientId((String) serverClientId); Object forceCodeForRefreshToken = list.get(5); pigeonResult.setForceCodeForRefreshToken((Boolean) forceCodeForRefreshToken); return pigeonResult; } } /** * Pigeon version of GoogleSignInUserData. * * <p>See GoogleSignInUserData for details. * * <p>Generated class from Pigeon that represents data sent in messages. */ public static final class UserData { private @Nullable String displayName; public @Nullable String getDisplayName() { return displayName; } public void setDisplayName(@Nullable String setterArg) { this.displayName = setterArg; } private @NonNull String email; public @NonNull String getEmail() { return email; } public void setEmail(@NonNull String setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"email\" is null."); } this.email = setterArg; } private @NonNull String id; public @NonNull String getId() { return id; } public void setId(@NonNull String setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"id\" is null."); } this.id = setterArg; } private @Nullable String photoUrl; public @Nullable String getPhotoUrl() { return photoUrl; } public void setPhotoUrl(@Nullable String setterArg) { this.photoUrl = setterArg; } private @Nullable String idToken; public @Nullable String getIdToken() { return idToken; } public void setIdToken(@Nullable String setterArg) { this.idToken = setterArg; } private @Nullable String serverAuthCode; public @Nullable String getServerAuthCode() { return serverAuthCode; } public void setServerAuthCode(@Nullable String setterArg) { this.serverAuthCode = setterArg; } /** Constructor is non-public to enforce null safety; use Builder. */ UserData() {} public static final class Builder { private @Nullable String displayName; public @NonNull Builder setDisplayName(@Nullable String setterArg) { this.displayName = setterArg; return this; } private @Nullable String email; public @NonNull Builder setEmail(@NonNull String setterArg) { this.email = setterArg; return this; } private @Nullable String id; public @NonNull Builder setId(@NonNull String setterArg) { this.id = setterArg; return this; } private @Nullable String photoUrl; public @NonNull Builder setPhotoUrl(@Nullable String setterArg) { this.photoUrl = setterArg; return this; } private @Nullable String idToken; public @NonNull Builder setIdToken(@Nullable String setterArg) { this.idToken = setterArg; return this; } private @Nullable String serverAuthCode; public @NonNull Builder setServerAuthCode(@Nullable String setterArg) { this.serverAuthCode = setterArg; return this; } public @NonNull UserData build() { UserData pigeonReturn = new UserData(); pigeonReturn.setDisplayName(displayName); pigeonReturn.setEmail(email); pigeonReturn.setId(id); pigeonReturn.setPhotoUrl(photoUrl); pigeonReturn.setIdToken(idToken); pigeonReturn.setServerAuthCode(serverAuthCode); return pigeonReturn; } } @NonNull ArrayList<Object> toList() { ArrayList<Object> toListResult = new ArrayList<Object>(6); toListResult.add(displayName); toListResult.add(email); toListResult.add(id); toListResult.add(photoUrl); toListResult.add(idToken); toListResult.add(serverAuthCode); return toListResult; } static @NonNull UserData fromList(@NonNull ArrayList<Object> list) { UserData pigeonResult = new UserData(); Object displayName = list.get(0); pigeonResult.setDisplayName((String) displayName); Object email = list.get(1); pigeonResult.setEmail((String) email); Object id = list.get(2); pigeonResult.setId((String) id); Object photoUrl = list.get(3); pigeonResult.setPhotoUrl((String) photoUrl); Object idToken = list.get(4); pigeonResult.setIdToken((String) idToken); Object serverAuthCode = list.get(5); pigeonResult.setServerAuthCode((String) serverAuthCode); return pigeonResult; } } public interface Result<T> { @SuppressWarnings("UnknownNullness") void success(T result); void error(@NonNull Throwable error); } private static class GoogleSignInApiCodec extends StandardMessageCodec { public static final GoogleSignInApiCodec INSTANCE = new GoogleSignInApiCodec(); private GoogleSignInApiCodec() {} @Override protected Object readValueOfType(byte type, @NonNull ByteBuffer buffer) { switch (type) { case (byte) 128: return InitParams.fromList((ArrayList<Object>) readValue(buffer)); case (byte) 129: return UserData.fromList((ArrayList<Object>) readValue(buffer)); default: return super.readValueOfType(type, buffer); } } @Override protected void writeValue(@NonNull ByteArrayOutputStream stream, Object value) { if (value instanceof InitParams) { stream.write(128); writeValue(stream, ((InitParams) value).toList()); } else if (value instanceof UserData) { stream.write(129); writeValue(stream, ((UserData) value).toList()); } else { super.writeValue(stream, value); } } } /** Generated interface from Pigeon that represents a handler of messages from Flutter. */ public interface GoogleSignInApi { /** Initializes a sign in request with the given parameters. */ void init(@NonNull InitParams params); /** Starts a silent sign in. */ void signInSilently(@NonNull Result<UserData> result); /** Starts a sign in with user interaction. */ void signIn(@NonNull Result<UserData> result); /** Requests the access token for the current sign in. */ void getAccessToken( @NonNull String email, @NonNull Boolean shouldRecoverAuth, @NonNull Result<String> result); /** Signs out the current user. */ void signOut(@NonNull Result<Void> result); /** Revokes scope grants to the application. */ void disconnect(@NonNull Result<Void> result); /** Returns whether the user is currently signed in. */ @NonNull Boolean isSignedIn(); /** Clears the authentication caching for the given token, requiring a new sign in. */ void clearAuthCache(@NonNull String token, @NonNull Result<Void> result); /** Requests access to the given scopes. */ void requestScopes(@NonNull List<String> scopes, @NonNull Result<Boolean> result); /** The codec used by GoogleSignInApi. */ static @NonNull MessageCodec<Object> getCodec() { return GoogleSignInApiCodec.INSTANCE; } /** * Sets up an instance of `GoogleSignInApi` to handle messages through the `binaryMessenger`. */ static void setup(@NonNull BinaryMessenger binaryMessenger, @Nullable GoogleSignInApi api) { { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.GoogleSignInApi.init", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; InitParams paramsArg = (InitParams) args.get(0); try { api.init(paramsArg); wrapped.add(0, null); } 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.GoogleSignInApi.signInSilently", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); Result<UserData> resultCallback = new Result<UserData>() { public void success(UserData result) { wrapped.add(0, result); reply.reply(wrapped); } public void error(Throwable error) { ArrayList<Object> wrappedError = wrapError(error); reply.reply(wrappedError); } }; api.signInSilently(resultCallback); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.GoogleSignInApi.signIn", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); Result<UserData> resultCallback = new Result<UserData>() { public void success(UserData result) { wrapped.add(0, result); reply.reply(wrapped); } public void error(Throwable error) { ArrayList<Object> wrappedError = wrapError(error); reply.reply(wrappedError); } }; api.signIn(resultCallback); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.GoogleSignInApi.getAccessToken", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; String emailArg = (String) args.get(0); Boolean shouldRecoverAuthArg = (Boolean) args.get(1); Result<String> resultCallback = new Result<String>() { public void success(String result) { wrapped.add(0, result); reply.reply(wrapped); } public void error(Throwable error) { ArrayList<Object> wrappedError = wrapError(error); reply.reply(wrappedError); } }; api.getAccessToken(emailArg, shouldRecoverAuthArg, resultCallback); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.GoogleSignInApi.signOut", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); Result<Void> resultCallback = new Result<Void>() { public void success(Void result) { wrapped.add(0, null); reply.reply(wrapped); } public void error(Throwable error) { ArrayList<Object> wrappedError = wrapError(error); reply.reply(wrappedError); } }; api.signOut(resultCallback); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.GoogleSignInApi.disconnect", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); Result<Void> resultCallback = new Result<Void>() { public void success(Void result) { wrapped.add(0, null); reply.reply(wrapped); } public void error(Throwable error) { ArrayList<Object> wrappedError = wrapError(error); reply.reply(wrappedError); } }; api.disconnect(resultCallback); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.GoogleSignInApi.isSignedIn", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); try { Boolean output = api.isSignedIn(); 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.GoogleSignInApi.clearAuthCache", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; String tokenArg = (String) args.get(0); Result<Void> resultCallback = new Result<Void>() { public void success(Void result) { wrapped.add(0, null); reply.reply(wrapped); } public void error(Throwable error) { ArrayList<Object> wrappedError = wrapError(error); reply.reply(wrappedError); } }; api.clearAuthCache(tokenArg, resultCallback); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.GoogleSignInApi.requestScopes", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; List<String> scopesArg = (List<String>) 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.requestScopes(scopesArg, resultCallback); }); } else { channel.setMessageHandler(null); } } } } }
packages/packages/google_sign_in/google_sign_in_android/android/src/main/java/io/flutter/plugins/googlesignin/Messages.java/0
{ "file_path": "packages/packages/google_sign_in/google_sign_in_android/android/src/main/java/io/flutter/plugins/googlesignin/Messages.java", "repo_id": "packages", "token_count": 10392 }
987
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:pigeon/pigeon.dart'; @ConfigurePigeon(PigeonOptions( dartOut: 'lib/src/messages.g.dart', javaOut: 'android/src/main/java/io/flutter/plugins/googlesignin/Messages.java', javaOptions: JavaOptions(package: 'io.flutter.plugins.googlesignin'), copyrightHeader: 'pigeons/copyright.txt', )) /// Pigeon version of SignInOption. enum SignInType { /// Default configuration. standard, /// Recommended configuration for game sign in. games, } /// Pigeon version of SignInInitParams. /// /// See SignInInitParams for details. class InitParams { /// The parameters to use when initializing the sign in process. const InitParams({ this.scopes = const <String>[], this.signInType = SignInType.standard, this.hostedDomain, this.clientId, this.serverClientId, this.forceCodeForRefreshToken = false, }); // TODO(stuartmorgan): Make the generic type non-nullable once supported. // https://github.com/flutter/flutter/issues/97848 // The Java code treats the values as non-nullable. final List<String?> scopes; final SignInType signInType; final String? hostedDomain; final String? clientId; final String? serverClientId; final bool forceCodeForRefreshToken; } /// Pigeon version of GoogleSignInUserData. /// /// See GoogleSignInUserData for details. class UserData { UserData({ required this.email, required this.id, this.displayName, this.photoUrl, this.idToken, this.serverAuthCode, }); final String? displayName; final String email; final String id; final String? photoUrl; final String? idToken; final String? serverAuthCode; } @HostApi() abstract class GoogleSignInApi { /// Initializes a sign in request with the given parameters. void init(InitParams params); /// Starts a silent sign in. @async UserData signInSilently(); /// Starts a sign in with user interaction. @async UserData signIn(); /// Requests the access token for the current sign in. @async String getAccessToken(String email, bool shouldRecoverAuth); /// Signs out the current user. @async void signOut(); /// Revokes scope grants to the application. @async void disconnect(); /// Returns whether the user is currently signed in. bool isSignedIn(); /// Clears the authentication caching for the given token, requiring a /// new sign in. @async void clearAuthCache(String token); /// Requests access to the given scopes. @async bool requestScopes(List<String> scopes); }
packages/packages/google_sign_in/google_sign_in_android/pigeons/messages.dart/0
{ "file_path": "packages/packages/google_sign_in/google_sign_in_android/pigeons/messages.dart", "repo_id": "packages", "token_count": 855 }
988
# google_sign_in_platform_interface A common platform interface for the [`google_sign_in`][1] plugin. This interface allows platform-specific implementations of the `google_sign_in` plugin, as well as the plugin itself, to ensure they are supporting the same interface. # Usage To implement a new platform-specific implementation of `google_sign_in`, extend [`GoogleSignInPlatform`][2] with an implementation that performs the platform-specific behavior, and when you register your plugin, set the default `GoogleSignInPlatform` by calling `GoogleSignInPlatform.instance = MyPlatformGoogleSignIn()`. # Note on breaking changes Strongly prefer non-breaking changes (such as adding a method to the interface) over breaking changes for this package. See https://flutter.dev/go/platform-interface-breaking-changes for a discussion on why a less-clean interface is preferable to a breaking change. [1]: ../google_sign_in [2]: lib/google_sign_in_platform_interface.dart
packages/packages/google_sign_in/google_sign_in_platform_interface/README.md/0
{ "file_path": "packages/packages/google_sign_in/google_sign_in_platform_interface/README.md", "repo_id": "packages", "token_count": 252 }
989
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:js_interop'; import 'dart:ui_web' as ui_web; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:web/web.dart' as web; /// An HTMLElementView widget that resizes with its contents. class FlexHtmlElementView extends StatefulWidget { /// Constructor const FlexHtmlElementView({ super.key, required this.viewType, this.onElementCreated, this.initialSize, }); /// See [HtmlElementView.viewType]. final String viewType; /// See [HtmlElementView.fromTagName] `onElementCreated`. final ElementCreatedCallback? onElementCreated; /// The initial Size for the widget, before it starts tracking its contents. final Size? initialSize; @override State<StatefulWidget> createState() => _FlexHtmlElementView(); } class _FlexHtmlElementView extends State<FlexHtmlElementView> { /// The last measured size of the watched element. Size? _lastReportedSize; /// Watches for changes being made to the DOM tree. /// /// See: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver web.MutationObserver? _mutationObserver; /// Reports changes to the dimensions of an Element's content box. /// /// See: https://developer.mozilla.org/en-US/docs/Web/API/Resize_Observer_API web.ResizeObserver? _resizeObserver; @override void dispose() { // Disconnect the observers _mutationObserver?.disconnect(); _resizeObserver?.disconnect(); super.dispose(); } /// Update the state with the new `size`, if needed. void _doResize(Size size) { if (size != _lastReportedSize) { if (kDebugMode) { final String log = <Object?>[ 'Resizing: ', widget.viewType, size.width, size.height ].join(' '); web.console.debug(log.toJS); } setState(() { _lastReportedSize = size; }); } } /// The function called whenever an observed resize occurs. void _onResizeEntries( JSArray<web.ResizeObserverEntry> resizes, web.ResizeObserver observer, ) { final web.DOMRectReadOnly rect = resizes.toDart.last.contentRect; if (rect.width > 0 && rect.height > 0) { _doResize(Size(rect.width.toDouble(), rect.height.toDouble())); } } /// A function which will be called on each DOM change that qualifies given the observed node and options. /// /// When mutations are received, this function attaches a Resize Observer to /// the first child of the mutation, which will drive void _onMutationRecords( JSArray<web.MutationRecord> mutations, web.MutationObserver observer, ) { for (final web.MutationRecord mutation in mutations.toDart) { if (mutation.addedNodes.length > 0) { final web.Element? element = _locateSizeProvider(mutation.addedNodes); if (element != null) { _resizeObserver = web.ResizeObserver(_onResizeEntries.toJS); _resizeObserver?.observe(element); // Stop looking at other mutations observer.disconnect(); return; } } } } /// Registers a MutationObserver on the root element of the HtmlElementView. void _registerListeners(web.Element root) { _mutationObserver = web.MutationObserver(_onMutationRecords.toJS); // Monitor the size of the child element, whenever it's created... _mutationObserver!.observe( root, web.MutationObserverInit( childList: true, ), ); } @override Widget build(BuildContext context) { return SizedBox.fromSize( size: _lastReportedSize ?? widget.initialSize ?? const Size(1, 1), child: HtmlElementView( viewType: widget.viewType, onPlatformViewCreated: (int viewId) { final ElementCreatedCallback? callback = widget.onElementCreated; final web.Element root = ui_web.platformViewRegistry.getViewById(viewId) as web.Element; _registerListeners(root); if (callback != null) { callback(root); } }), ); } } /// Locates which of the elements will act as the size provider. /// /// The `elements` list should contain a single element: the only child of the /// element returned by `_locatePlatformViewRoot`. web.Element? _locateSizeProvider(web.NodeList elements) { return elements.item(0) as web.Element?; }
packages/packages/google_sign_in/google_sign_in_web/lib/src/flexible_size_html_element_view.dart/0
{ "file_path": "packages/packages/google_sign_in/google_sign_in_web/lib/src/flexible_size_html_element_view.dart", "repo_id": "packages", "token_count": 1676 }
990
// 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.content.Context; import android.content.SharedPreferences; import android.net.Uri; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; class ImagePickerCache { public enum CacheType { IMAGE, VIDEO } static final String MAP_KEY_PATH_LIST = "pathList"; static final String MAP_KEY_MAX_WIDTH = "maxWidth"; static final String MAP_KEY_MAX_HEIGHT = "maxHeight"; static final String MAP_KEY_IMAGE_QUALITY = "imageQuality"; static final String MAP_KEY_TYPE = "type"; static final String MAP_KEY_ERROR = "error"; private static final String MAP_TYPE_VALUE_IMAGE = "image"; private static final String MAP_TYPE_VALUE_VIDEO = "video"; private static final String FLUTTER_IMAGE_PICKER_IMAGE_PATH_KEY = "flutter_image_picker_image_path"; private static final String SHARED_PREFERENCE_ERROR_CODE_KEY = "flutter_image_picker_error_code"; private static final String SHARED_PREFERENCE_ERROR_MESSAGE_KEY = "flutter_image_picker_error_message"; private static final String SHARED_PREFERENCE_MAX_WIDTH_KEY = "flutter_image_picker_max_width"; private static final String SHARED_PREFERENCE_MAX_HEIGHT_KEY = "flutter_image_picker_max_height"; private static final String SHARED_PREFERENCE_IMAGE_QUALITY_KEY = "flutter_image_picker_image_quality"; private static final String SHARED_PREFERENCE_TYPE_KEY = "flutter_image_picker_type"; private static final String SHARED_PREFERENCE_PENDING_IMAGE_URI_PATH_KEY = "flutter_image_picker_pending_image_uri"; @VisibleForTesting static final String SHARED_PREFERENCES_NAME = "flutter_image_picker_shared_preference"; private final @NonNull Context context; ImagePickerCache(final @NonNull Context context) { this.context = context; } void saveType(CacheType type) { switch (type) { case IMAGE: setType(MAP_TYPE_VALUE_IMAGE); break; case VIDEO: setType(MAP_TYPE_VALUE_VIDEO); break; } } private void setType(String type) { final SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE); prefs.edit().putString(SHARED_PREFERENCE_TYPE_KEY, type).apply(); } void saveDimensionWithOutputOptions(Messages.ImageSelectionOptions options) { final SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); if (options.getMaxWidth() != null) { editor.putLong( SHARED_PREFERENCE_MAX_WIDTH_KEY, Double.doubleToRawLongBits(options.getMaxWidth())); } if (options.getMaxHeight() != null) { editor.putLong( SHARED_PREFERENCE_MAX_HEIGHT_KEY, Double.doubleToRawLongBits(options.getMaxHeight())); } editor.putInt(SHARED_PREFERENCE_IMAGE_QUALITY_KEY, options.getQuality().intValue()); editor.apply(); } void savePendingCameraMediaUriPath(Uri uri) { final SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE); prefs.edit().putString(SHARED_PREFERENCE_PENDING_IMAGE_URI_PATH_KEY, uri.getPath()).apply(); } String retrievePendingCameraMediaUriPath() { final SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE); return prefs.getString(SHARED_PREFERENCE_PENDING_IMAGE_URI_PATH_KEY, ""); } void saveResult( @Nullable ArrayList<String> path, @Nullable String errorCode, @Nullable String errorMessage) { final SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); if (path != null) { Set<String> imageSet = new HashSet<>(path); editor.putStringSet(FLUTTER_IMAGE_PICKER_IMAGE_PATH_KEY, imageSet); } if (errorCode != null) { editor.putString(SHARED_PREFERENCE_ERROR_CODE_KEY, errorCode); } if (errorMessage != null) { editor.putString(SHARED_PREFERENCE_ERROR_MESSAGE_KEY, errorMessage); } editor.apply(); } void clear() { final SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE); prefs.edit().clear().apply(); } Map<String, Object> getCacheMap() { Map<String, Object> resultMap = new HashMap<>(); boolean hasData = false; final SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE); if (prefs.contains(FLUTTER_IMAGE_PICKER_IMAGE_PATH_KEY)) { final Set<String> imagePathList = prefs.getStringSet(FLUTTER_IMAGE_PICKER_IMAGE_PATH_KEY, null); if (imagePathList != null) { ArrayList<String> pathList = new ArrayList<>(imagePathList); resultMap.put(MAP_KEY_PATH_LIST, pathList); hasData = true; } } if (prefs.contains(SHARED_PREFERENCE_ERROR_CODE_KEY)) { final Messages.CacheRetrievalError.Builder error = new Messages.CacheRetrievalError.Builder(); error.setCode(prefs.getString(SHARED_PREFERENCE_ERROR_CODE_KEY, "")); hasData = true; if (prefs.contains(SHARED_PREFERENCE_ERROR_MESSAGE_KEY)) { error.setMessage(prefs.getString(SHARED_PREFERENCE_ERROR_MESSAGE_KEY, "")); } resultMap.put(MAP_KEY_ERROR, error.build()); } if (hasData) { if (prefs.contains(SHARED_PREFERENCE_TYPE_KEY)) { final String typeValue = prefs.getString(SHARED_PREFERENCE_TYPE_KEY, ""); resultMap.put( MAP_KEY_TYPE, typeValue.equals(MAP_TYPE_VALUE_VIDEO) ? Messages.CacheRetrievalType.VIDEO : Messages.CacheRetrievalType.IMAGE); } if (prefs.contains(SHARED_PREFERENCE_MAX_WIDTH_KEY)) { final long maxWidthValue = prefs.getLong(SHARED_PREFERENCE_MAX_WIDTH_KEY, 0); resultMap.put(MAP_KEY_MAX_WIDTH, Double.longBitsToDouble(maxWidthValue)); } if (prefs.contains(SHARED_PREFERENCE_MAX_HEIGHT_KEY)) { final long maxHeightValue = prefs.getLong(SHARED_PREFERENCE_MAX_HEIGHT_KEY, 0); resultMap.put(MAP_KEY_MAX_HEIGHT, Double.longBitsToDouble(maxHeightValue)); } final int imageQuality = prefs.getInt(SHARED_PREFERENCE_IMAGE_QUALITY_KEY, 100); resultMap.put(MAP_KEY_IMAGE_QUALITY, imageQuality); } return resultMap; } }
packages/packages/image_picker/image_picker_android/android/src/main/java/io/flutter/plugins/imagepicker/ImagePickerCache.java/0
{ "file_path": "packages/packages/image_picker/image_picker_android/android/src/main/java/io/flutter/plugins/imagepicker/ImagePickerCache.java", "repo_id": "packages", "token_count": 2669 }
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. // Autogenerated from Pigeon (v9.2.5), do not edit directly. // See also: https://pub.dev/packages/pigeon // ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import import 'dart:async'; import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; import 'package:flutter/services.dart'; enum SourceCamera { rear, front, } enum SourceType { camera, gallery, } enum CacheRetrievalType { image, video, } class GeneralOptions { GeneralOptions({ required this.allowMultiple, required this.usePhotoPicker, }); bool allowMultiple; bool usePhotoPicker; Object encode() { return <Object?>[ allowMultiple, usePhotoPicker, ]; } static GeneralOptions decode(Object result) { result as List<Object?>; return GeneralOptions( allowMultiple: result[0]! as bool, usePhotoPicker: result[1]! as bool, ); } } /// Options for image selection and output. class ImageSelectionOptions { ImageSelectionOptions({ this.maxWidth, this.maxHeight, required this.quality, }); /// If set, the max width that the image should be resized to fit in. double? maxWidth; /// If set, the max height that the image should be resized to fit in. double? maxHeight; /// The quality of the output image, from 0-100. /// /// 100 indicates original quality. int quality; Object encode() { return <Object?>[ maxWidth, maxHeight, quality, ]; } static ImageSelectionOptions decode(Object result) { result as List<Object?>; return ImageSelectionOptions( maxWidth: result[0] as double?, maxHeight: result[1] as double?, quality: result[2]! as int, ); } } class MediaSelectionOptions { MediaSelectionOptions({ required this.imageSelectionOptions, }); ImageSelectionOptions imageSelectionOptions; Object encode() { return <Object?>[ imageSelectionOptions.encode(), ]; } static MediaSelectionOptions decode(Object result) { result as List<Object?>; return MediaSelectionOptions( imageSelectionOptions: ImageSelectionOptions.decode(result[0]! as List<Object?>), ); } } /// Options for image selection and output. class VideoSelectionOptions { VideoSelectionOptions({ this.maxDurationSeconds, }); /// The maximum desired length for the video, in seconds. int? maxDurationSeconds; Object encode() { return <Object?>[ maxDurationSeconds, ]; } static VideoSelectionOptions decode(Object result) { result as List<Object?>; return VideoSelectionOptions( maxDurationSeconds: result[0] as int?, ); } } /// Specification for the source of an image or video selection. class SourceSpecification { SourceSpecification({ required this.type, this.camera, }); SourceType type; SourceCamera? camera; Object encode() { return <Object?>[ type.index, camera?.index, ]; } static SourceSpecification decode(Object result) { result as List<Object?>; return SourceSpecification( type: SourceType.values[result[0]! as int], camera: result[1] != null ? SourceCamera.values[result[1]! as int] : null, ); } } /// An error that occurred during lost result retrieval. /// /// The data here maps to the `PlatformException` that will be created from it. class CacheRetrievalError { CacheRetrievalError({ required this.code, this.message, }); String code; String? message; Object encode() { return <Object?>[ code, message, ]; } static CacheRetrievalError decode(Object result) { result as List<Object?>; return CacheRetrievalError( code: result[0]! as String, message: result[1] as String?, ); } } /// The result of retrieving cached results from a previous run. class CacheRetrievalResult { CacheRetrievalResult({ required this.type, this.error, required this.paths, }); /// The type of the retrieved data. CacheRetrievalType type; /// The error from the last selection, if any. CacheRetrievalError? error; /// The results from the last selection, if any. /// /// Elements must not be null, by convention. See /// https://github.com/flutter/flutter/issues/97848 List<String?> paths; Object encode() { return <Object?>[ type.index, error?.encode(), paths, ]; } static CacheRetrievalResult decode(Object result) { result as List<Object?>; return CacheRetrievalResult( type: CacheRetrievalType.values[result[0]! as int], error: result[1] != null ? CacheRetrievalError.decode(result[1]! as List<Object?>) : null, paths: (result[2] as List<Object?>?)!.cast<String?>(), ); } } class _ImagePickerApiCodec extends StandardMessageCodec { const _ImagePickerApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { if (value is CacheRetrievalError) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else if (value is CacheRetrievalResult) { buffer.putUint8(129); writeValue(buffer, value.encode()); } else if (value is GeneralOptions) { buffer.putUint8(130); writeValue(buffer, value.encode()); } else if (value is ImageSelectionOptions) { buffer.putUint8(131); writeValue(buffer, value.encode()); } else if (value is MediaSelectionOptions) { buffer.putUint8(132); writeValue(buffer, value.encode()); } else if (value is SourceSpecification) { buffer.putUint8(133); writeValue(buffer, value.encode()); } else if (value is VideoSelectionOptions) { buffer.putUint8(134); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } } @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: return CacheRetrievalError.decode(readValue(buffer)!); case 129: return CacheRetrievalResult.decode(readValue(buffer)!); case 130: return GeneralOptions.decode(readValue(buffer)!); case 131: return ImageSelectionOptions.decode(readValue(buffer)!); case 132: return MediaSelectionOptions.decode(readValue(buffer)!); case 133: return SourceSpecification.decode(readValue(buffer)!); case 134: return VideoSelectionOptions.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } } } class ImagePickerApi { /// Constructor for [ImagePickerApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. ImagePickerApi({BinaryMessenger? binaryMessenger}) : _binaryMessenger = binaryMessenger; final BinaryMessenger? _binaryMessenger; static const MessageCodec<Object?> codec = _ImagePickerApiCodec(); /// Selects images and returns their paths. /// /// Elements must not be null, by convention. See /// https://github.com/flutter/flutter/issues/97848 Future<List<String?>> pickImages( SourceSpecification arg_source, ImageSelectionOptions arg_options, GeneralOptions arg_generalOptions) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.ImagePickerApi.pickImages', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel .send(<Object?>[arg_source, arg_options, arg_generalOptions]) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (replyList[0] as List<Object?>?)!.cast<String?>(); } } /// Selects video and returns their paths. /// /// Elements must not be null, by convention. See /// https://github.com/flutter/flutter/issues/97848 Future<List<String?>> pickVideos( SourceSpecification arg_source, VideoSelectionOptions arg_options, GeneralOptions arg_generalOptions) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.ImagePickerApi.pickVideos', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel .send(<Object?>[arg_source, arg_options, arg_generalOptions]) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (replyList[0] as List<Object?>?)!.cast<String?>(); } } /// Selects images and videos and returns their paths. /// /// Elements must not be null, by convention. See /// https://github.com/flutter/flutter/issues/97848 Future<List<String?>> pickMedia( MediaSelectionOptions arg_mediaSelectionOptions, GeneralOptions arg_generalOptions) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.ImagePickerApi.pickMedia', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel .send(<Object?>[arg_mediaSelectionOptions, arg_generalOptions]) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (replyList[0] as List<Object?>?)!.cast<String?>(); } } /// Returns results from a previous app session, if any. Future<CacheRetrievalResult?> retrieveLostResults() async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.ImagePickerApi.retrieveLostResults', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(null) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else { return (replyList[0] as CacheRetrievalResult?); } } }
packages/packages/image_picker/image_picker_android/lib/src/messages.g.dart/0
{ "file_path": "packages/packages/image_picker/image_picker_android/lib/src/messages.g.dart", "repo_id": "packages", "token_count": 4429 }
992
// 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 "ImagePickerTestImages.h" @import image_picker_ios; @import image_picker_ios.Test; @import UniformTypeIdentifiers; @import XCTest; #import <OCMock/OCMock.h> @interface MockViewController : UIViewController @property(nonatomic, retain) UIViewController *mockPresented; @end @implementation MockViewController @synthesize mockPresented; - (UIViewController *)presentedViewController { return mockPresented; } @end @interface ImagePickerPluginTests : XCTestCase @end @implementation ImagePickerPluginTests - (void)testPluginPickImageDeviceBack { id mockUIImagePicker = OCMClassMock([UIImagePickerController class]); id mockAVCaptureDevice = OCMClassMock([AVCaptureDevice class]); // UIImagePickerControllerSourceTypeCamera is supported OCMStub(ClassMethod( [mockUIImagePicker isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])) .andReturn(YES); // UIImagePickerControllerCameraDeviceRear is supported OCMStub(ClassMethod( [mockUIImagePicker isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear])) .andReturn(YES); // AVAuthorizationStatusAuthorized is supported OCMStub([mockAVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo]) .andReturn(AVAuthorizationStatusAuthorized); // Run test FLTImagePickerPlugin *plugin = [[FLTImagePickerPlugin alloc] init]; UIImagePickerController *controller = [[UIImagePickerController alloc] init]; [plugin setImagePickerControllerOverrides:@[ controller ]]; [plugin pickImageWithSource:[FLTSourceSpecification makeWithType:FLTSourceTypeCamera camera:FLTSourceCameraRear] maxSize:[[FLTMaxSize alloc] init] quality:nil fullMetadata:YES completion:^(NSString *_Nullable result, FlutterError *_Nullable error){ }]; XCTAssertEqual(controller.cameraDevice, UIImagePickerControllerCameraDeviceRear); } - (void)testPluginPickImageDeviceFront { id mockUIImagePicker = OCMClassMock([UIImagePickerController class]); id mockAVCaptureDevice = OCMClassMock([AVCaptureDevice class]); // UIImagePickerControllerSourceTypeCamera is supported OCMStub(ClassMethod( [mockUIImagePicker isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])) .andReturn(YES); // UIImagePickerControllerCameraDeviceFront is supported OCMStub(ClassMethod( [mockUIImagePicker isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront])) .andReturn(YES); // AVAuthorizationStatusAuthorized is supported OCMStub([mockAVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo]) .andReturn(AVAuthorizationStatusAuthorized); // Run test FLTImagePickerPlugin *plugin = [[FLTImagePickerPlugin alloc] init]; UIImagePickerController *controller = [[UIImagePickerController alloc] init]; [plugin setImagePickerControllerOverrides:@[ controller ]]; [plugin pickImageWithSource:[FLTSourceSpecification makeWithType:FLTSourceTypeCamera camera:FLTSourceCameraFront] maxSize:[[FLTMaxSize alloc] init] quality:nil fullMetadata:YES completion:^(NSString *_Nullable result, FlutterError *_Nullable error){ }]; XCTAssertEqual(controller.cameraDevice, UIImagePickerControllerCameraDeviceFront); } - (void)testPluginPickVideoDeviceBack { id mockUIImagePicker = OCMClassMock([UIImagePickerController class]); id mockAVCaptureDevice = OCMClassMock([AVCaptureDevice class]); // UIImagePickerControllerSourceTypeCamera is supported OCMStub(ClassMethod( [mockUIImagePicker isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])) .andReturn(YES); // UIImagePickerControllerCameraDeviceRear is supported OCMStub(ClassMethod( [mockUIImagePicker isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear])) .andReturn(YES); // AVAuthorizationStatusAuthorized is supported OCMStub([mockAVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo]) .andReturn(AVAuthorizationStatusAuthorized); // Run test FLTImagePickerPlugin *plugin = [[FLTImagePickerPlugin alloc] init]; UIImagePickerController *controller = [[UIImagePickerController alloc] init]; [plugin setImagePickerControllerOverrides:@[ controller ]]; [plugin pickVideoWithSource:[FLTSourceSpecification makeWithType:FLTSourceTypeCamera camera:FLTSourceCameraRear] maxDuration:nil completion:^(NSString *_Nullable result, FlutterError *_Nullable error){ }]; XCTAssertEqual(controller.cameraDevice, UIImagePickerControllerCameraDeviceRear); } - (void)testPluginPickVideoDeviceFront { id mockUIImagePicker = OCMClassMock([UIImagePickerController class]); id mockAVCaptureDevice = OCMClassMock([AVCaptureDevice class]); // UIImagePickerControllerSourceTypeCamera is supported OCMStub(ClassMethod( [mockUIImagePicker isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])) .andReturn(YES); // UIImagePickerControllerCameraDeviceFront is supported OCMStub(ClassMethod( [mockUIImagePicker isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront])) .andReturn(YES); // AVAuthorizationStatusAuthorized is supported OCMStub([mockAVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo]) .andReturn(AVAuthorizationStatusAuthorized); // Run test FLTImagePickerPlugin *plugin = [[FLTImagePickerPlugin alloc] init]; UIImagePickerController *controller = [[UIImagePickerController alloc] init]; [plugin setImagePickerControllerOverrides:@[ controller ]]; [plugin pickVideoWithSource:[FLTSourceSpecification makeWithType:FLTSourceTypeCamera camera:FLTSourceCameraFront] maxDuration:nil completion:^(NSString *_Nullable result, FlutterError *_Nullable error){ }]; XCTAssertEqual(controller.cameraDevice, UIImagePickerControllerCameraDeviceFront); } - (void)testPickMultiImageShouldUseUIImagePickerControllerOnPreiOS14 { if (@available(iOS 14, *)) { return; } id mockUIImagePicker = OCMClassMock([UIImagePickerController class]); id photoLibrary = OCMClassMock([PHPhotoLibrary class]); OCMStub(ClassMethod([photoLibrary authorizationStatus])) .andReturn(PHAuthorizationStatusAuthorized); FLTImagePickerPlugin *plugin = [[FLTImagePickerPlugin alloc] init]; [plugin setImagePickerControllerOverrides:@[ mockUIImagePicker ]]; [plugin pickMultiImageWithMaxSize:[FLTMaxSize makeWithWidth:@(100) height:@(200)] quality:@(50) fullMetadata:YES completion:^(NSArray<NSString *> *_Nullable result, FlutterError *_Nullable error){ }]; OCMVerify(times(1), [mockUIImagePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary]); } - (void)testPickMediaShouldUseUIImagePickerControllerOnPreiOS14 { if (@available(iOS 14, *)) { return; } id mockUIImagePicker = OCMClassMock([UIImagePickerController class]); id photoLibrary = OCMClassMock([PHPhotoLibrary class]); OCMStub(ClassMethod([photoLibrary authorizationStatus])) .andReturn(PHAuthorizationStatusAuthorized); FLTImagePickerPlugin *plugin = [[FLTImagePickerPlugin alloc] init]; [plugin setImagePickerControllerOverrides:@[ mockUIImagePicker ]]; FLTMediaSelectionOptions *mediaSelectionOptions = [FLTMediaSelectionOptions makeWithMaxSize:[FLTMaxSize makeWithWidth:@(100) height:@(200)] imageQuality:@(50) requestFullMetadata:YES allowMultiple:YES]; [plugin pickMediaWithMediaSelectionOptions:mediaSelectionOptions completion:^(NSArray<NSString *> *_Nullable result, FlutterError *_Nullable error){ }]; OCMVerify(times(1), [mockUIImagePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary]); } - (void)testPickImageWithoutFullMetadata { id mockUIImagePicker = OCMClassMock([UIImagePickerController class]); id photoLibrary = OCMClassMock([PHPhotoLibrary class]); FLTImagePickerPlugin *plugin = [[FLTImagePickerPlugin alloc] init]; [plugin setImagePickerControllerOverrides:@[ mockUIImagePicker ]]; [plugin pickImageWithSource:[FLTSourceSpecification makeWithType:FLTSourceTypeGallery camera:FLTSourceCameraFront] maxSize:[[FLTMaxSize alloc] init] quality:nil fullMetadata:NO completion:^(NSString *_Nullable result, FlutterError *_Nullable error){ }]; OCMVerify(times(0), [photoLibrary authorizationStatus]); } - (void)testPickMultiImageWithoutFullMetadata { id mockUIImagePicker = OCMClassMock([UIImagePickerController class]); id photoLibrary = OCMClassMock([PHPhotoLibrary class]); FLTImagePickerPlugin *plugin = [[FLTImagePickerPlugin alloc] init]; [plugin setImagePickerControllerOverrides:@[ mockUIImagePicker ]]; [plugin pickMultiImageWithMaxSize:[[FLTMaxSize alloc] init] quality:nil fullMetadata:NO completion:^(NSArray<NSString *> *_Nullable result, FlutterError *_Nullable error){ }]; OCMVerify(times(0), [photoLibrary authorizationStatus]); } - (void)testPickMediaWithoutFullMetadata { id mockUIImagePicker = OCMClassMock([UIImagePickerController class]); id photoLibrary = OCMClassMock([PHPhotoLibrary class]); FLTImagePickerPlugin *plugin = [[FLTImagePickerPlugin alloc] init]; [plugin setImagePickerControllerOverrides:@[ mockUIImagePicker ]]; FLTMediaSelectionOptions *mediaSelectionOptions = [FLTMediaSelectionOptions makeWithMaxSize:[FLTMaxSize makeWithWidth:@(100) height:@(200)] imageQuality:@(50) requestFullMetadata:YES allowMultiple:YES]; [plugin pickMediaWithMediaSelectionOptions:mediaSelectionOptions completion:^(NSArray<NSString *> *_Nullable result, FlutterError *_Nullable error){ }]; OCMVerify(times(0), [photoLibrary authorizationStatus]); } #pragma mark - Test camera devices, no op on simulators - (void)testPluginPickImageDeviceCancelClickMultipleTimes { if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) { return; } FLTImagePickerPlugin *plugin = [[FLTImagePickerPlugin alloc] init]; UIImagePickerController *controller = [[UIImagePickerController alloc] init]; plugin.imagePickerControllerOverrides = @[ controller ]; [plugin pickImageWithSource:[FLTSourceSpecification makeWithType:FLTSourceTypeCamera camera:FLTSourceCameraRear] maxSize:[[FLTMaxSize alloc] init] quality:nil fullMetadata:YES completion:^(NSString *_Nullable result, FlutterError *_Nullable error){ }]; // To ensure the flow does not crash by multiple cancel call [plugin imagePickerControllerDidCancel:controller]; [plugin imagePickerControllerDidCancel:controller]; } #pragma mark - Test video duration - (void)testPickingVideoWithDuration { FLTImagePickerPlugin *plugin = [[FLTImagePickerPlugin alloc] init]; UIImagePickerController *controller = [[UIImagePickerController alloc] init]; [plugin setImagePickerControllerOverrides:@[ controller ]]; [plugin pickVideoWithSource:[FLTSourceSpecification makeWithType:FLTSourceTypeCamera camera:FLTSourceCameraRear] maxDuration:@(95) completion:^(NSString *_Nullable result, FlutterError *_Nullable error){ }]; XCTAssertEqual(controller.videoMaximumDuration, 95); } - (void)testViewController { UIWindow *window = [UIWindow new]; MockViewController *vc1 = [MockViewController new]; window.rootViewController = vc1; UIViewController *vc2 = [UIViewController new]; vc1.mockPresented = vc2; FLTImagePickerPlugin *plugin = [[FLTImagePickerPlugin alloc] init]; XCTAssertEqual([plugin viewControllerWithWindow:window], vc2); } - (void)testPluginMultiImagePathHasNullItem { FLTImagePickerPlugin *plugin = [[FLTImagePickerPlugin alloc] init]; XCTestExpectation *resultExpectation = [self expectationWithDescription:@"result"]; plugin.callContext = [[FLTImagePickerMethodCallContext alloc] initWithResult:^(NSArray<NSString *> *_Nullable result, FlutterError *_Nullable error) { XCTAssertEqualObjects(error.code, @"create_error"); [resultExpectation fulfill]; }]; [plugin sendCallResultWithSavedPathList:@[ [NSNull null] ]]; [self waitForExpectationsWithTimeout:30 handler:nil]; } - (void)testPluginMultiImagePathHasItem { FLTImagePickerPlugin *plugin = [[FLTImagePickerPlugin alloc] init]; NSArray *pathList = @[ @"test" ]; XCTestExpectation *resultExpectation = [self expectationWithDescription:@"result"]; plugin.callContext = [[FLTImagePickerMethodCallContext alloc] initWithResult:^(NSArray<NSString *> *_Nullable result, FlutterError *_Nullable error) { XCTAssertEqualObjects(result, pathList); [resultExpectation fulfill]; }]; [plugin sendCallResultWithSavedPathList:pathList]; [self waitForExpectationsWithTimeout:30 handler:nil]; } - (void)testPluginMediaPathHasNoItem { FLTImagePickerPlugin *plugin = [[FLTImagePickerPlugin alloc] init]; XCTestExpectation *resultExpectation = [self expectationWithDescription:@"result"]; plugin.callContext = [[FLTImagePickerMethodCallContext alloc] initWithResult:^(NSArray<NSString *> *_Nullable result, FlutterError *_Nullable error) { XCTAssertEqualObjects(result, @[]); [resultExpectation fulfill]; }]; [plugin sendCallResultWithSavedPathList:@[]]; [self waitForExpectationsWithTimeout:30 handler:nil]; } - (void)testPluginMediaPathConvertsNilToEmptyList { FLTImagePickerPlugin *plugin = [[FLTImagePickerPlugin alloc] init]; XCTestExpectation *resultExpectation = [self expectationWithDescription:@"result"]; plugin.callContext = [[FLTImagePickerMethodCallContext alloc] initWithResult:^(NSArray<NSString *> *_Nullable result, FlutterError *_Nullable error) { XCTAssertEqualObjects(result, @[]); [resultExpectation fulfill]; }]; [plugin sendCallResultWithSavedPathList:nil]; [self waitForExpectationsWithTimeout:30 handler:nil]; } - (void)testPluginMediaPathHasItem { FLTImagePickerPlugin *plugin = [[FLTImagePickerPlugin alloc] init]; NSArray *pathList = @[ @"test" ]; XCTestExpectation *resultExpectation = [self expectationWithDescription:@"result"]; plugin.callContext = [[FLTImagePickerMethodCallContext alloc] initWithResult:^(NSArray<NSString *> *_Nullable result, FlutterError *_Nullable error) { XCTAssertEqualObjects(result, pathList); [resultExpectation fulfill]; }]; [plugin sendCallResultWithSavedPathList:pathList]; [self waitForExpectationsWithTimeout:30 handler:nil]; } - (void)testSendsImageInvalidSourceError API_AVAILABLE(ios(14)) { id mockPickerViewController = OCMClassMock([PHPickerViewController class]); id mockItemProvider = OCMClassMock([NSItemProvider class]); // Does not conform to image, invalid source. OCMStub([mockItemProvider hasItemConformingToTypeIdentifier:OCMOCK_ANY]).andReturn(NO); PHPickerResult *failResult1 = OCMClassMock([PHPickerResult class]); OCMStub([failResult1 itemProvider]).andReturn(mockItemProvider); PHPickerResult *failResult2 = OCMClassMock([PHPickerResult class]); OCMStub([failResult2 itemProvider]).andReturn(mockItemProvider); FLTImagePickerPlugin *plugin = [[FLTImagePickerPlugin alloc] init]; XCTestExpectation *resultExpectation = [self expectationWithDescription:@"result"]; plugin.callContext = [[FLTImagePickerMethodCallContext alloc] initWithResult:^(NSArray<NSString *> *result, FlutterError *error) { XCTAssertTrue(NSThread.isMainThread); XCTAssertNil(result); XCTAssertEqualObjects(error.code, @"invalid_source"); [resultExpectation fulfill]; }]; [plugin picker:mockPickerViewController didFinishPicking:@[ failResult1, failResult2 ]]; [self waitForExpectationsWithTimeout:30 handler:nil]; } - (void)testSendsImageInvalidErrorWhenOneFails API_AVAILABLE(ios(14)) { id mockPickerViewController = OCMClassMock([PHPickerViewController class]); NSError *loadDataError = [NSError errorWithDomain:@"PHPickerDomain" code:1234 userInfo:nil]; id mockFailItemProvider = OCMClassMock([NSItemProvider class]); OCMStub([mockFailItemProvider hasItemConformingToTypeIdentifier:OCMOCK_ANY]).andReturn(YES); [[mockFailItemProvider stub] loadDataRepresentationForTypeIdentifier:OCMOCK_ANY completionHandler:[OCMArg invokeBlockWithArgs:[NSNull null], loadDataError, nil]]; PHPickerResult *failResult = OCMClassMock([PHPickerResult class]); OCMStub([failResult itemProvider]).andReturn(mockFailItemProvider); NSURL *tiffURL = [[NSBundle bundleForClass:[self class]] URLForResource:@"tiffImage" withExtension:@"tiff"]; NSItemProvider *tiffItemProvider = [[NSItemProvider alloc] initWithContentsOfURL:tiffURL]; PHPickerResult *tiffResult = OCMClassMock([PHPickerResult class]); OCMStub([tiffResult itemProvider]).andReturn(tiffItemProvider); FLTImagePickerPlugin *plugin = [[FLTImagePickerPlugin alloc] init]; XCTestExpectation *resultExpectation = [self expectationWithDescription:@"result"]; plugin.callContext = [[FLTImagePickerMethodCallContext alloc] initWithResult:^(NSArray<NSString *> *result, FlutterError *error) { XCTAssertTrue(NSThread.isMainThread); XCTAssertNil(result); XCTAssertEqualObjects(error.code, @"invalid_image"); [resultExpectation fulfill]; }]; [plugin picker:mockPickerViewController didFinishPicking:@[ failResult, tiffResult ]]; [self waitForExpectationsWithTimeout:30 handler:nil]; } - (void)testSavesImages API_AVAILABLE(ios(14)) { id mockPickerViewController = OCMClassMock([PHPickerViewController class]); NSURL *tiffURL = [[NSBundle bundleForClass:[self class]] URLForResource:@"tiffImage" withExtension:@"tiff"]; NSItemProvider *tiffItemProvider = [[NSItemProvider alloc] initWithContentsOfURL:tiffURL]; PHPickerResult *tiffResult = OCMClassMock([PHPickerResult class]); OCMStub([tiffResult itemProvider]).andReturn(tiffItemProvider); NSURL *pngURL = [[NSBundle bundleForClass:[self class]] URLForResource:@"pngImage" withExtension:@"png"]; NSItemProvider *pngItemProvider = [[NSItemProvider alloc] initWithContentsOfURL:pngURL]; PHPickerResult *pngResult = OCMClassMock([PHPickerResult class]); OCMStub([pngResult itemProvider]).andReturn(pngItemProvider); FLTImagePickerPlugin *plugin = [[FLTImagePickerPlugin alloc] init]; XCTestExpectation *resultExpectation = [self expectationWithDescription:@"result"]; plugin.callContext = [[FLTImagePickerMethodCallContext alloc] initWithResult:^(NSArray<NSString *> *result, FlutterError *error) { XCTAssertTrue(NSThread.isMainThread); XCTAssertEqual(result.count, 2); XCTAssertNil(error); [resultExpectation fulfill]; }]; [plugin picker:mockPickerViewController didFinishPicking:@[ tiffResult, pngResult ]]; [self waitForExpectationsWithTimeout:30 handler:nil]; } - (void)testPickImageRequestAuthorization API_AVAILABLE(ios(14)) { id mockPhotoLibrary = OCMClassMock([PHPhotoLibrary class]); OCMStub([mockPhotoLibrary authorizationStatusForAccessLevel:PHAccessLevelReadWrite]) .andReturn(PHAuthorizationStatusNotDetermined); OCMExpect([mockPhotoLibrary requestAuthorizationForAccessLevel:PHAccessLevelReadWrite handler:OCMOCK_ANY]); FLTImagePickerPlugin *plugin = [[FLTImagePickerPlugin alloc] init]; [plugin pickImageWithSource:[FLTSourceSpecification makeWithType:FLTSourceTypeGallery camera:FLTSourceCameraFront] maxSize:[[FLTMaxSize alloc] init] quality:nil fullMetadata:YES completion:^(NSString *result, FlutterError *error){ }]; OCMVerifyAll(mockPhotoLibrary); } - (void)testPickImageAuthorizationDenied API_AVAILABLE(ios(14)) { id mockPhotoLibrary = OCMClassMock([PHPhotoLibrary class]); OCMStub([mockPhotoLibrary authorizationStatusForAccessLevel:PHAccessLevelReadWrite]) .andReturn(PHAuthorizationStatusDenied); FLTImagePickerPlugin *plugin = [[FLTImagePickerPlugin alloc] init]; XCTestExpectation *resultExpectation = [self expectationWithDescription:@"result"]; [plugin pickImageWithSource:[FLTSourceSpecification makeWithType:FLTSourceTypeGallery camera:FLTSourceCameraFront] maxSize:[[FLTMaxSize alloc] init] quality:nil fullMetadata:YES completion:^(NSString *result, FlutterError *error) { XCTAssertNil(result); XCTAssertEqualObjects(error.code, @"photo_access_denied"); XCTAssertEqualObjects(error.message, @"The user did not allow photo access."); [resultExpectation fulfill]; }]; [self waitForExpectationsWithTimeout:30 handler:nil]; } - (void)testPickMultiImageDuplicateCallCancels API_AVAILABLE(ios(14)) { id mockPhotoLibrary = OCMClassMock([PHPhotoLibrary class]); OCMStub([mockPhotoLibrary authorizationStatusForAccessLevel:PHAccessLevelReadWrite]) .andReturn(PHAuthorizationStatusNotDetermined); OCMExpect([mockPhotoLibrary requestAuthorizationForAccessLevel:PHAccessLevelReadWrite handler:OCMOCK_ANY]); FLTImagePickerPlugin *plugin = [[FLTImagePickerPlugin alloc] init]; XCTestExpectation *firstCallExpectation = [self expectationWithDescription:@"first call"]; [plugin pickMultiImageWithMaxSize:[FLTMaxSize makeWithWidth:@100 height:@100] quality:nil fullMetadata:YES completion:^(NSArray<NSString *> *result, FlutterError *error) { XCTAssertNotNil(error); XCTAssertEqualObjects(error.code, @"multiple_request"); [firstCallExpectation fulfill]; }]; [plugin pickMultiImageWithMaxSize:[FLTMaxSize makeWithWidth:@100 height:@100] quality:nil fullMetadata:YES completion:^(NSArray<NSString *> *result, FlutterError *error){ }]; [self waitForExpectationsWithTimeout:30 handler:nil]; } - (void)testPickMediaDuplicateCallCancels API_AVAILABLE(ios(14)) { id mockPhotoLibrary = OCMClassMock([PHPhotoLibrary class]); OCMStub([mockPhotoLibrary authorizationStatusForAccessLevel:PHAccessLevelReadWrite]) .andReturn(PHAuthorizationStatusNotDetermined); OCMExpect([mockPhotoLibrary requestAuthorizationForAccessLevel:PHAccessLevelReadWrite handler:OCMOCK_ANY]); FLTImagePickerPlugin *plugin = [[FLTImagePickerPlugin alloc] init]; FLTMediaSelectionOptions *options = [FLTMediaSelectionOptions makeWithMaxSize:[FLTMaxSize makeWithWidth:@(100) height:@(200)] imageQuality:@(50) requestFullMetadata:YES allowMultiple:YES]; XCTestExpectation *firstCallExpectation = [self expectationWithDescription:@"first call"]; [plugin pickMediaWithMediaSelectionOptions:options completion:^(NSArray<NSString *> *result, FlutterError *error) { XCTAssertNotNil(error); XCTAssertEqualObjects(error.code, @"multiple_request"); [firstCallExpectation fulfill]; }]; [plugin pickMediaWithMediaSelectionOptions:options completion:^(NSArray<NSString *> *result, FlutterError *error){ }]; [self waitForExpectationsWithTimeout:30 handler:nil]; } - (void)testPickVideoDuplicateCallCancels API_AVAILABLE(ios(14)) { id mockPhotoLibrary = OCMClassMock([AVCaptureDevice class]); OCMStub([mockPhotoLibrary authorizationStatusForMediaType:AVMediaTypeVideo]) .andReturn(AVAuthorizationStatusNotDetermined); FLTImagePickerPlugin *plugin = [[FLTImagePickerPlugin alloc] init]; FLTSourceSpecification *source = [FLTSourceSpecification makeWithType:FLTSourceTypeCamera camera:FLTSourceCameraRear]; XCTestExpectation *firstCallExpectation = [self expectationWithDescription:@"first call"]; [plugin pickVideoWithSource:source maxDuration:nil completion:^(NSString *result, FlutterError *error) { XCTAssertNotNil(error); XCTAssertEqualObjects(error.code, @"multiple_request"); [firstCallExpectation fulfill]; }]; [plugin pickVideoWithSource:source maxDuration:nil completion:^(NSString *result, FlutterError *error){ }]; [self waitForExpectationsWithTimeout:30 handler:nil]; } @end
packages/packages/image_picker/image_picker_ios/example/ios/RunnerTests/ImagePickerPluginTests.m/0
{ "file_path": "packages/packages/image_picker/image_picker_ios/example/ios/RunnerTests/ImagePickerPluginTests.m", "repo_id": "packages", "token_count": 10950 }
993
// 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 <Foundation/Foundation.h> #import <Photos/Photos.h> #import <PhotosUI/PhotosUI.h> #import "FLTImagePickerImageUtil.h" NS_ASSUME_NONNULL_BEGIN @interface FLTImagePickerPhotoAssetUtil : NSObject + (nullable PHAsset *)getAssetFromImagePickerInfo:(NSDictionary *)info; + (nullable PHAsset *)getAssetFromPHPickerResult:(PHPickerResult *)result API_AVAILABLE(ios(14)); // Saves video to temporary URL. Returns nil on failure; + (NSURL *)saveVideoFromURL:(NSURL *)videoURL; // Saves image with correct meta data and extention copied from the original asset. // maxWidth and maxHeight are used only for GIF images. + (NSString *)saveImageWithOriginalImageData:(NSData *)originalImageData image:(UIImage *)image maxWidth:(nullable NSNumber *)maxWidth maxHeight:(nullable NSNumber *)maxHeight imageQuality:(nullable NSNumber *)imageQuality; // Save image with correct meta data and extention copied from image picker result info. + (NSString *)saveImageWithPickerInfo:(nullable NSDictionary *)info image:(UIImage *)image imageQuality:(nullable NSNumber *)imageQuality; @end NS_ASSUME_NONNULL_END
packages/packages/image_picker/image_picker_ios/ios/Classes/FLTImagePickerPhotoAssetUtil.h/0
{ "file_path": "packages/packages/image_picker/image_picker_ios/ios/Classes/FLTImagePickerPhotoAssetUtil.h", "repo_id": "packages", "token_count": 575 }
994
#include "../../Flutter/Flutter-Debug.xcconfig" #include "Warnings.xcconfig"
packages/packages/image_picker/image_picker_macos/example/macos/Runner/Configs/Debug.xcconfig/0
{ "file_path": "packages/packages/image_picker/image_picker_macos/example/macos/Runner/Configs/Debug.xcconfig", "repo_id": "packages", "token_count": 32 }
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 './base.dart'; /// A PickedFile is a cross-platform, simplified File abstraction. /// /// It wraps the bytes of a selected file, and its (platform-dependant) path. class PickedFile extends PickedFileBase { /// Construct a PickedFile object, from its `bytes`. /// /// Optionally, you may pass a `path`. See caveats in [PickedFileBase.path]. PickedFile(super.path) { throw UnimplementedError( 'PickedFile is not available in your current platform.'); } }
packages/packages/image_picker/image_picker_platform_interface/lib/src/types/picked_file/unsupported.dart/0
{ "file_path": "packages/packages/image_picker/image_picker_platform_interface/lib/src/types/picked_file/unsupported.dart", "repo_id": "packages", "token_count": 192 }
996
// 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:file_selector_platform_interface/file_selector_platform_interface.dart'; import 'package:file_selector_windows/file_selector_windows.dart'; import 'package:flutter/foundation.dart'; import 'package:image_picker_platform_interface/image_picker_platform_interface.dart'; /// The Windows implementation of [ImagePickerPlatform]. /// /// This class implements the `package:image_picker` functionality for /// Windows. class ImagePickerWindows extends CameraDelegatingImagePickerPlatform { /// Constructs a ImagePickerWindows. ImagePickerWindows(); /// List of image extensions used when picking images @visibleForTesting static const List<String> imageFormats = <String>[ 'jpg', 'jpeg', 'png', 'bmp', 'webp', 'gif', 'tif', 'tiff', 'apng' ]; /// List of video extensions used when picking videos @visibleForTesting static const List<String> videoFormats = <String>[ 'mov', 'wmv', 'mkv', 'mp4', 'webm', 'avi', 'mpeg', 'mpg' ]; /// The file selector used to prompt the user to select images or videos. @visibleForTesting static FileSelectorPlatform fileSelector = FileSelectorWindows(); /// Registers this class as the default instance of [ImagePickerPlatform]. static void registerWith() { ImagePickerPlatform.instance = ImagePickerWindows(); } // This is soft-deprecated in the platform interface, and is only implemented // for compatibility. Callers should be using getImageFromSource. @override Future<PickedFile?> pickImage({ required ImageSource source, double? maxWidth, double? maxHeight, int? imageQuality, CameraDevice preferredCameraDevice = CameraDevice.rear, }) async { final XFile? file = await getImageFromSource( source: source, options: ImagePickerOptions( maxWidth: maxWidth, maxHeight: maxHeight, imageQuality: imageQuality, preferredCameraDevice: preferredCameraDevice)); if (file != null) { return PickedFile(file.path); } return null; } // This is soft-deprecated in the platform interface, and is only implemented // for compatibility. Callers should be using getVideo. @override Future<PickedFile?> pickVideo({ required ImageSource source, CameraDevice preferredCameraDevice = CameraDevice.rear, Duration? maxDuration, }) async { final XFile? file = await getVideo( source: source, preferredCameraDevice: preferredCameraDevice, maxDuration: maxDuration); if (file != null) { return PickedFile(file.path); } return null; } // This is soft-deprecated in the platform interface, and is only implemented // for compatibility. Callers should be using getImageFromSource. @override Future<XFile?> getImage({ required ImageSource source, double? maxWidth, double? maxHeight, int? imageQuality, CameraDevice preferredCameraDevice = CameraDevice.rear, }) async { return getImageFromSource( source: source, options: ImagePickerOptions( maxWidth: maxWidth, maxHeight: maxHeight, imageQuality: imageQuality, preferredCameraDevice: preferredCameraDevice)); } // [ImagePickerOptions] options are not currently supported. If any // of its fields are set, they will be silently ignored. // // If source is `ImageSource.camera`, a `StateError` will be thrown // unless a [cameraDelegate] is set. @override Future<XFile?> getImageFromSource({ required ImageSource source, ImagePickerOptions options = const ImagePickerOptions(), }) async { switch (source) { case ImageSource.camera: return super.getImageFromSource(source: source); case ImageSource.gallery: const XTypeGroup typeGroup = XTypeGroup(label: 'Images', extensions: imageFormats); final XFile? file = await fileSelector .openFile(acceptedTypeGroups: <XTypeGroup>[typeGroup]); return file; } // Ensure that there's a fallback in case a new source is added. // ignore: dead_code throw UnimplementedError('Unknown ImageSource: $source'); } // `preferredCameraDevice` and `maxDuration` arguments are not currently // supported. If either of these arguments are supplied, they will be silently // ignored. // // If source is `ImageSource.camera`, a `StateError` will be thrown // unless a [cameraDelegate] is set. @override Future<XFile?> getVideo({ required ImageSource source, CameraDevice preferredCameraDevice = CameraDevice.rear, Duration? maxDuration, }) async { switch (source) { case ImageSource.camera: return super.getVideo( source: source, preferredCameraDevice: preferredCameraDevice, maxDuration: maxDuration); case ImageSource.gallery: const XTypeGroup typeGroup = XTypeGroup(label: 'Videos', extensions: videoFormats); final XFile? file = await fileSelector .openFile(acceptedTypeGroups: <XTypeGroup>[typeGroup]); return file; } // Ensure that there's a fallback in case a new source is added. // ignore: dead_code throw UnimplementedError('Unknown ImageSource: $source'); } // `maxWidth`, `maxHeight`, and `imageQuality` arguments are not currently // supported. If any of these arguments are supplied, they will be silently // ignored. @override Future<List<XFile>> getMultiImage({ double? maxWidth, double? maxHeight, int? imageQuality, }) async { const XTypeGroup typeGroup = XTypeGroup(label: 'Images', extensions: imageFormats); final List<XFile> files = await fileSelector .openFiles(acceptedTypeGroups: <XTypeGroup>[typeGroup]); return files; } // `maxWidth`, `maxHeight`, and `imageQuality` arguments are not // supported on Windows. If any of these arguments is supplied, // they will be silently ignored by the Windows version of the plugin. @override Future<List<XFile>> getMedia({required MediaOptions options}) async { const XTypeGroup typeGroup = XTypeGroup( label: 'images and videos', extensions: <String>[...imageFormats, ...videoFormats]); List<XFile> files; if (options.allowMultiple) { files = await fileSelector .openFiles(acceptedTypeGroups: <XTypeGroup>[typeGroup]); } else { final XFile? file = await fileSelector .openFile(acceptedTypeGroups: <XTypeGroup>[typeGroup]); files = <XFile>[ if (file != null) file, ]; } return files; } }
packages/packages/image_picker/image_picker_windows/lib/image_picker_windows.dart/0
{ "file_path": "packages/packages/image_picker/image_picker_windows/lib/image_picker_windows.dart", "repo_id": "packages", "token_count": 2351 }
997
{ "products" : [ { "displayPrice" : "0.99", "familyShareable" : false, "internalID" : "AE10D05D", "localizations" : [ { "description" : "A consumable product.", "displayName" : "Consumable", "locale" : "en_US" } ], "productID" : "consumable", "referenceName" : "consumable", "type" : "Consumable" }, { "displayPrice" : "10.99", "familyShareable" : false, "internalID" : "FABCF067", "localizations" : [ { "description" : "An non-consumable product.", "displayName" : "Upgrade", "locale" : "en_US" } ], "productID" : "upgrade", "referenceName" : "upgrade", "type" : "NonConsumable" } ], "settings" : { }, "subscriptionGroups" : [ { "id" : "D0FEE8D8", "localizations" : [ ], "name" : "Example Subscriptions", "subscriptions" : [ { "adHocOffers" : [ ], "displayPrice" : "3.99", "familyShareable" : false, "groupNumber" : 1, "internalID" : "922EB597", "introductoryOffer" : null, "localizations" : [ { "description" : "A lower level subscription.", "displayName" : "Subscription Silver", "locale" : "en_US" } ], "productID" : "subscription_silver", "recurringSubscriptionPeriod" : "P1M", "referenceName" : "subscription_silver", "subscriptionGroupID" : "D0FEE8D8", "type" : "RecurringSubscription" }, { "adHocOffers" : [ ], "displayPrice" : "5.99", "familyShareable" : false, "groupNumber" : 2, "internalID" : "0BC7FF5E", "introductoryOffer" : null, "localizations" : [ { "description" : "A higher level subscription.", "displayName" : "Subscription Gold", "locale" : "en_US" } ], "productID" : "subscription_gold", "recurringSubscriptionPeriod" : "P1M", "referenceName" : "subscription_gold", "subscriptionGroupID" : "D0FEE8D8", "type" : "RecurringSubscription" } ] } ], "version" : { "major" : 1, "minor" : 0 } }
packages/packages/in_app_purchase/in_app_purchase/example/ios/Runner/Configuration.storekit/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase/example/ios/Runner/Configuration.storekit", "repo_id": "packages", "token_count": 1317 }
998
#include "../../Flutter/Flutter-Debug.xcconfig" #include "Warnings.xcconfig"
packages/packages/in_app_purchase/in_app_purchase/example/macos/Runner/Configs/Debug.xcconfig/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase/example/macos/Runner/Configs/Debug.xcconfig", "repo_id": "packages", "token_count": 32 }
999
group 'io.flutter.plugins.inapppurchase' version '1.0-SNAPSHOT' buildscript { repositories { google() mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:7.3.1' } } rootProject.allprojects { repositories { google() mavenCentral() } } apply plugin: 'com.android.library' android { // Conditional for compatibility with AGP <4.2. if (project.android.hasProperty("namespace")) { namespace 'io.flutter.plugins.inapppurchase' } compileSdk 34 defaultConfig { minSdk 19 testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } lintOptions { checkAllWarnings true warningsAsErrors true disable 'AndroidGradlePluginVersion', 'InvalidPackage', 'GradleDependency' } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } testOptions { unitTests.includeAndroidResources = true unitTests.returnDefaultValues = true unitTests.all { testLogging { events "passed", "skipped", "failed", "standardOut", "standardError" outputs.upToDateWhen {false} showStandardStreams = true } } } } dependencies { implementation 'androidx.annotation:annotation:1.7.1' // org.jetbrains.kotlin:kotlin-bom artifact purpose is to align kotlin stdlib and related code versions. // See: https://youtrack.jetbrains.com/issue/KT-55297/kotlin-stdlib-should-declare-constraints-on-kotlin-stdlib-jdk8-and-kotlin-stdlib-jdk7 implementation(platform("org.jetbrains.kotlin:kotlin-bom:1.8.22")) implementation 'com.android.billingclient:billing:6.1.0' testImplementation 'junit:junit:4.13.2' testImplementation 'org.json:json:20231013' testImplementation 'org.mockito:mockito-core:5.4.0' androidTestImplementation 'androidx.test:runner:1.5.2' androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1' }
packages/packages/in_app_purchase/in_app_purchase_android/android/build.gradle/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_android/android/build.gradle", "repo_id": "packages", "token_count": 886 }
1,000
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'user_choice_details_wrapper.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** UserChoiceDetailsWrapper _$UserChoiceDetailsWrapperFromJson(Map json) => UserChoiceDetailsWrapper( originalExternalTransactionId: json['originalExternalTransactionId'] as String? ?? '', externalTransactionToken: json['externalTransactionToken'] as String? ?? '', products: (json['products'] as List<dynamic>?) ?.map((e) => UserChoiceDetailsProductWrapper.fromJson( Map<String, dynamic>.from(e as Map))) .toList() ?? [], ); Map<String, dynamic> _$UserChoiceDetailsWrapperToJson( UserChoiceDetailsWrapper instance) => <String, dynamic>{ 'originalExternalTransactionId': instance.originalExternalTransactionId, 'externalTransactionToken': instance.externalTransactionToken, 'products': instance.products.map((e) => e.toJson()).toList(), }; UserChoiceDetailsProductWrapper _$UserChoiceDetailsProductWrapperFromJson( Map json) => UserChoiceDetailsProductWrapper( id: json['id'] as String? ?? '', offerToken: json['offerToken'] as String? ?? '', productType: const ProductTypeConverter().fromJson(json['productType'] as String?), ); Map<String, dynamic> _$UserChoiceDetailsProductWrapperToJson( UserChoiceDetailsProductWrapper instance) => <String, dynamic>{ 'id': instance.id, 'offerToken': instance.offerToken, 'productType': const ProductTypeConverter().toJson(instance.productType), };
packages/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/user_choice_details_wrapper.g.dart/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/user_choice_details_wrapper.g.dart", "repo_id": "packages", "token_count": 612 }
1,001
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:in_app_purchase_android/billing_client_wrappers.dart'; import 'package:in_app_purchase_android/src/types/google_play_product_details.dart'; import 'package:test/test.dart'; const ProductDetailsWrapper dummyOneTimeProductDetails = ProductDetailsWrapper( description: 'description', name: 'name', productId: 'productId', productType: ProductType.inapp, title: 'title', oneTimePurchaseOfferDetails: OneTimePurchaseOfferDetailsWrapper( formattedPrice: r'$100', priceAmountMicros: 100000000, priceCurrencyCode: 'USD', ), ); const ProductDetailsWrapper dummySubscriptionProductDetails = ProductDetailsWrapper( description: 'description', name: 'name', productId: 'productId', productType: ProductType.subs, title: 'title', subscriptionOfferDetails: <SubscriptionOfferDetailsWrapper>[ SubscriptionOfferDetailsWrapper( basePlanId: 'basePlanId', offerTags: <String>['offerTags'], offerId: 'offerId', offerIdToken: 'offerToken', pricingPhases: <PricingPhaseWrapper>[ PricingPhaseWrapper( billingCycleCount: 4, billingPeriod: 'billingPeriod', formattedPrice: r'$100', priceAmountMicros: 100000000, priceCurrencyCode: 'USD', recurrenceMode: RecurrenceMode.finiteRecurring, ), ], ), ], ); void main() { group('ProductDetailsWrapper', () { test('converts one-time purchase from map', () { const ProductDetailsWrapper expected = dummyOneTimeProductDetails; final ProductDetailsWrapper parsed = ProductDetailsWrapper.fromJson(buildProductMap(expected)); expect(parsed, equals(expected)); }); test('converts subscription from map', () { const ProductDetailsWrapper expected = dummySubscriptionProductDetails; final ProductDetailsWrapper parsed = ProductDetailsWrapper.fromJson(buildProductMap(expected)); expect(parsed, equals(expected)); }); }); group('ProductDetailsResponseWrapper', () { test('parsed from map', () { const BillingResponse responseCode = BillingResponse.ok; const String debugMessage = 'dummy message'; final List<ProductDetailsWrapper> productsDetails = <ProductDetailsWrapper>[ dummyOneTimeProductDetails, dummyOneTimeProductDetails, ]; const BillingResultWrapper result = BillingResultWrapper( responseCode: responseCode, debugMessage: debugMessage); final ProductDetailsResponseWrapper expected = ProductDetailsResponseWrapper( billingResult: result, productDetailsList: productsDetails); final ProductDetailsResponseWrapper parsed = ProductDetailsResponseWrapper.fromJson(<String, dynamic>{ 'billingResult': <String, dynamic>{ 'responseCode': const BillingResponseConverter().toJson(responseCode), 'debugMessage': debugMessage, }, 'productDetailsList': <Map<String, dynamic>>[ buildProductMap(dummyOneTimeProductDetails), buildProductMap(dummyOneTimeProductDetails), ], }); expect(parsed.billingResult, equals(expected.billingResult)); expect( parsed.productDetailsList, containsAll(expected.productDetailsList)); }); test('toProductDetails() should return correct Product object', () { final ProductDetailsWrapper wrapper = ProductDetailsWrapper.fromJson( buildProductMap(dummyOneTimeProductDetails)); final GooglePlayProductDetails product = GooglePlayProductDetails.fromProductDetails(wrapper).first; expect(product.title, wrapper.title); expect(product.description, wrapper.description); expect(product.id, wrapper.productId); expect( product.price, wrapper.oneTimePurchaseOfferDetails?.formattedPrice); expect(product.productDetails, wrapper); }); test('handles empty list of productDetails', () { const BillingResponse responseCode = BillingResponse.error; const String debugMessage = 'dummy message'; final List<ProductDetailsWrapper> productsDetails = <ProductDetailsWrapper>[]; const BillingResultWrapper billingResult = BillingResultWrapper( responseCode: responseCode, debugMessage: debugMessage); final ProductDetailsResponseWrapper expected = ProductDetailsResponseWrapper( billingResult: billingResult, productDetailsList: productsDetails); final ProductDetailsResponseWrapper parsed = ProductDetailsResponseWrapper.fromJson(<String, dynamic>{ 'billingResult': <String, dynamic>{ 'responseCode': const BillingResponseConverter().toJson(responseCode), 'debugMessage': debugMessage, }, 'productDetailsList': const <Map<String, dynamic>>[] }); expect(parsed.billingResult, equals(expected.billingResult)); expect( parsed.productDetailsList, containsAll(expected.productDetailsList)); }); test('fromJson creates an object with default values', () { final ProductDetailsResponseWrapper productDetails = ProductDetailsResponseWrapper.fromJson(const <String, dynamic>{}); expect( productDetails.billingResult, equals(const BillingResultWrapper( responseCode: BillingResponse.error, debugMessage: kInvalidBillingResultErrorMessage))); expect(productDetails.productDetailsList, isEmpty); }); }); group('BillingResultWrapper', () { test('fromJson on empty map creates an object with default values', () { final BillingResultWrapper billingResult = BillingResultWrapper.fromJson(const <String, dynamic>{}); expect(billingResult.debugMessage, kInvalidBillingResultErrorMessage); expect(billingResult.responseCode, BillingResponse.error); }); test('fromJson on null creates an object with default values', () { final BillingResultWrapper billingResult = BillingResultWrapper.fromJson(null); expect(billingResult.debugMessage, kInvalidBillingResultErrorMessage); expect(billingResult.responseCode, BillingResponse.error); }); test('operator == of ProductDetailsWrapper works fine', () { const ProductDetailsWrapper firstProductDetailsInstance = ProductDetailsWrapper( description: 'description', title: 'title', productType: ProductType.inapp, name: 'name', productId: 'productId', oneTimePurchaseOfferDetails: OneTimePurchaseOfferDetailsWrapper( formattedPrice: 'formattedPrice', priceAmountMicros: 10, priceCurrencyCode: 'priceCurrencyCode', ), subscriptionOfferDetails: <SubscriptionOfferDetailsWrapper>[ SubscriptionOfferDetailsWrapper( basePlanId: 'basePlanId', offerTags: <String>['offerTags'], offerIdToken: 'offerToken', pricingPhases: <PricingPhaseWrapper>[ PricingPhaseWrapper( billingCycleCount: 4, billingPeriod: 'billingPeriod', formattedPrice: 'formattedPrice', priceAmountMicros: 10, priceCurrencyCode: 'priceCurrencyCode', recurrenceMode: RecurrenceMode.finiteRecurring, ), ], ), ], ); const ProductDetailsWrapper secondProductDetailsInstance = ProductDetailsWrapper( description: 'description', title: 'title', productType: ProductType.inapp, name: 'name', productId: 'productId', oneTimePurchaseOfferDetails: OneTimePurchaseOfferDetailsWrapper( formattedPrice: 'formattedPrice', priceAmountMicros: 10, priceCurrencyCode: 'priceCurrencyCode', ), subscriptionOfferDetails: <SubscriptionOfferDetailsWrapper>[ SubscriptionOfferDetailsWrapper( basePlanId: 'basePlanId', offerTags: <String>['offerTags'], offerIdToken: 'offerToken', pricingPhases: <PricingPhaseWrapper>[ PricingPhaseWrapper( billingCycleCount: 4, billingPeriod: 'billingPeriod', formattedPrice: 'formattedPrice', priceAmountMicros: 10, priceCurrencyCode: 'priceCurrencyCode', recurrenceMode: RecurrenceMode.finiteRecurring, ), ], ), ], ); expect( firstProductDetailsInstance == secondProductDetailsInstance, isTrue); }); test('operator == of BillingResultWrapper works fine', () { const BillingResultWrapper firstBillingResultInstance = BillingResultWrapper( responseCode: BillingResponse.ok, debugMessage: 'debugMessage', ); const BillingResultWrapper secondBillingResultInstance = BillingResultWrapper( responseCode: BillingResponse.ok, debugMessage: 'debugMessage', ); expect(firstBillingResultInstance == secondBillingResultInstance, isTrue); }); }); } Map<String, dynamic> buildProductMap(ProductDetailsWrapper original) { final Map<String, dynamic> map = <String, dynamic>{ 'title': original.title, 'description': original.description, 'productId': original.productId, 'productType': const ProductTypeConverter().toJson(original.productType), 'name': original.name, }; if (original.oneTimePurchaseOfferDetails != null) { map.putIfAbsent('oneTimePurchaseOfferDetails', () => buildOneTimePurchaseMap(original.oneTimePurchaseOfferDetails!)); } if (original.subscriptionOfferDetails != null) { map.putIfAbsent('subscriptionOfferDetails', () => buildSubscriptionMapList(original.subscriptionOfferDetails!)); } return map; } Map<String, dynamic> buildOneTimePurchaseMap( OneTimePurchaseOfferDetailsWrapper original) { return <String, dynamic>{ 'priceAmountMicros': original.priceAmountMicros, 'priceCurrencyCode': original.priceCurrencyCode, 'formattedPrice': original.formattedPrice, }; } List<Map<String, dynamic>> buildSubscriptionMapList( List<SubscriptionOfferDetailsWrapper> original) { return original .map((SubscriptionOfferDetailsWrapper subscriptionOfferDetails) => buildSubscriptionMap(subscriptionOfferDetails)) .toList(); } Map<String, dynamic> buildSubscriptionMap( SubscriptionOfferDetailsWrapper original) { return <String, dynamic>{ 'offerId': original.offerId, 'basePlanId': original.basePlanId, 'offerTags': original.offerTags, 'offerIdToken': original.offerIdToken, 'pricingPhases': buildPricingPhaseMapList(original.pricingPhases), }; } List<Map<String, dynamic>> buildPricingPhaseMapList( List<PricingPhaseWrapper> original) { return original .map((PricingPhaseWrapper pricingPhase) => buildPricingPhaseMap(pricingPhase)) .toList(); } Map<String, dynamic> buildPricingPhaseMap(PricingPhaseWrapper original) { return <String, dynamic>{ 'formattedPrice': original.formattedPrice, 'priceCurrencyCode': original.priceCurrencyCode, 'priceAmountMicros': original.priceAmountMicros, 'billingCycleCount': original.billingCycleCount, 'billingPeriod': original.billingPeriod, 'recurrenceMode': const RecurrenceModeConverter().toJson(original.recurrenceMode), }; }
packages/packages/in_app_purchase/in_app_purchase_android/test/billing_client_wrappers/product_details_wrapper_test.dart/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_android/test/billing_client_wrappers/product_details_wrapper_test.dart", "repo_id": "packages", "token_count": 4388 }
1,002
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:in_app_purchase_storekit/src/messages.g.dart'; import 'package:in_app_purchase_storekit/store_kit_wrappers.dart'; const SKPaymentWrapper dummyPayment = SKPaymentWrapper( productIdentifier: 'prod-id', applicationUsername: 'app-user-name', requestData: 'fake-data-utf8', quantity: 2, simulatesAskToBuyInSandbox: true); SKPaymentMessage dummyPaymentMessage = SKPaymentMessage( productIdentifier: 'prod-id', applicationUsername: 'app-user-name', requestData: 'fake-data-utf8', quantity: 2, simulatesAskToBuyInSandbox: true); final SKPaymentWrapper dummyPaymentWithDiscount = SKPaymentWrapper( productIdentifier: 'prod-id', applicationUsername: 'app-user-name', requestData: 'fake-data-utf8', quantity: 2, simulatesAskToBuyInSandbox: true, paymentDiscount: dummyPaymentDiscountWrapper); const SKError dummyError = SKError( code: 111, domain: 'dummy-domain', userInfo: <String, dynamic>{'key': 'value'}); final SKPaymentTransactionWrapper dummyOriginalTransaction = SKPaymentTransactionWrapper( transactionState: SKPaymentTransactionStateWrapper.purchased, payment: dummyPayment, transactionTimeStamp: 1231231231.00, transactionIdentifier: '123123', error: dummyError, ); final SKPaymentTransactionWrapper dummyTransaction = SKPaymentTransactionWrapper( transactionState: SKPaymentTransactionStateWrapper.purchased, payment: dummyPayment, originalTransaction: dummyOriginalTransaction, transactionTimeStamp: 1231231231.00, transactionIdentifier: '123123', error: dummyError, ); final SKPaymentTransactionMessage dummyTransactionMessage = SKPaymentTransactionMessage( payment: dummyPaymentMessage, transactionState: SKPaymentTransactionStateMessage.purchased); final SKPriceLocaleWrapper dollarLocale = SKPriceLocaleWrapper( currencySymbol: r'$', currencyCode: 'USD', countryCode: 'US', ); final SKPriceLocaleMessage dollarLocaleMessage = SKPriceLocaleMessage( currencySymbol: r'$', currencyCode: 'USD', countryCode: 'US', ); final SKPriceLocaleWrapper noSymbolLocale = SKPriceLocaleWrapper( currencySymbol: '', currencyCode: 'EUR', countryCode: 'UK', ); final SKProductSubscriptionPeriodWrapper dummySubscription = SKProductSubscriptionPeriodWrapper( numberOfUnits: 1, unit: SKSubscriptionPeriodUnit.month, ); final SKProductSubscriptionPeriodMessage dummySubscriptionMessage = SKProductSubscriptionPeriodMessage( numberOfUnits: 1, unit: SKSubscriptionPeriodUnitMessage.month, ); final SKProductDiscountWrapper dummyDiscount = SKProductDiscountWrapper( price: '1.0', priceLocale: dollarLocale, numberOfPeriods: 1, paymentMode: SKProductDiscountPaymentMode.payUpFront, subscriptionPeriod: dummySubscription, identifier: 'id', type: SKProductDiscountType.subscription, ); final SKProductDiscountMessage dummyDiscountMessage = SKProductDiscountMessage( price: '1.0', priceLocale: dollarLocaleMessage, numberOfPeriods: 1, paymentMode: SKProductDiscountPaymentModeMessage.payUpFront, subscriptionPeriod: dummySubscriptionMessage, identifier: 'id', type: SKProductDiscountTypeMessage.subscription, ); final SKProductDiscountWrapper dummyDiscountMissingIdentifierAndType = SKProductDiscountWrapper( price: '1.0', priceLocale: dollarLocale, numberOfPeriods: 1, paymentMode: SKProductDiscountPaymentMode.payUpFront, subscriptionPeriod: dummySubscription, identifier: null, type: SKProductDiscountType.introductory, ); final SKProductWrapper dummyProductWrapper = SKProductWrapper( productIdentifier: 'id', localizedTitle: 'title', localizedDescription: 'description', priceLocale: dollarLocale, subscriptionGroupIdentifier: 'com.group', price: '1.0', subscriptionPeriod: dummySubscription, introductoryPrice: dummyDiscount, discounts: <SKProductDiscountWrapper>[dummyDiscount], ); final SKProductMessage dummyProductMessage = SKProductMessage( productIdentifier: 'id', localizedTitle: 'title', localizedDescription: 'description', priceLocale: dollarLocaleMessage, subscriptionGroupIdentifier: 'com.group', price: '1.0', subscriptionPeriod: dummySubscriptionMessage, introductoryPrice: dummyDiscountMessage, discounts: <SKProductDiscountMessage>[dummyDiscountMessage], ); final SkProductResponseWrapper dummyProductResponseWrapper = SkProductResponseWrapper( products: <SKProductWrapper>[dummyProductWrapper], invalidProductIdentifiers: const <String>['123'], ); final SKProductsResponseMessage dummyProductResponseMessage = SKProductsResponseMessage( products: <SKProductMessage>[dummyProductMessage], invalidProductIdentifiers: const <String>['123'], ); Map<String, dynamic> buildLocaleMap(SKPriceLocaleWrapper local) { return <String, dynamic>{ 'currencySymbol': local.currencySymbol, 'currencyCode': local.currencyCode, 'countryCode': local.countryCode, }; } Map<String, dynamic>? buildSubscriptionPeriodMap( SKProductSubscriptionPeriodWrapper? sub) { if (sub == null) { return null; } return <String, dynamic>{ 'numberOfUnits': sub.numberOfUnits, 'unit': SKSubscriptionPeriodUnit.values.indexOf(sub.unit), }; } Map<String, dynamic> buildDiscountMap(SKProductDiscountWrapper discount) { return <String, dynamic>{ 'price': discount.price, 'priceLocale': buildLocaleMap(discount.priceLocale), 'numberOfPeriods': discount.numberOfPeriods, 'paymentMode': SKProductDiscountPaymentMode.values.indexOf(discount.paymentMode), 'subscriptionPeriod': buildSubscriptionPeriodMap(discount.subscriptionPeriod), 'identifier': discount.identifier, 'type': SKProductDiscountType.values.indexOf(discount.type) }; } Map<String, dynamic> buildDiscountMapMissingIdentifierAndType( SKProductDiscountWrapper discount) { return <String, dynamic>{ 'price': discount.price, 'priceLocale': buildLocaleMap(discount.priceLocale), 'numberOfPeriods': discount.numberOfPeriods, 'paymentMode': SKProductDiscountPaymentMode.values.indexOf(discount.paymentMode), 'subscriptionPeriod': buildSubscriptionPeriodMap(discount.subscriptionPeriod) }; } Map<String, dynamic> buildProductMap(SKProductWrapper product) { return <String, dynamic>{ 'productIdentifier': product.productIdentifier, 'localizedTitle': product.localizedTitle, 'localizedDescription': product.localizedDescription, 'priceLocale': buildLocaleMap(product.priceLocale), 'subscriptionGroupIdentifier': product.subscriptionGroupIdentifier, 'price': product.price, 'subscriptionPeriod': buildSubscriptionPeriodMap(product.subscriptionPeriod), 'introductoryPrice': buildDiscountMap(product.introductoryPrice!), 'discounts': <dynamic>[buildDiscountMap(product.introductoryPrice!)], }; } Map<String, dynamic> buildProductResponseMap( SkProductResponseWrapper response) { final List<dynamic> productsMap = response.products .map((SKProductWrapper product) => buildProductMap(product)) .toList(); return <String, dynamic>{ 'products': productsMap, 'invalidProductIdentifiers': response.invalidProductIdentifiers }; } Map<String, dynamic> buildErrorMap(SKError error) { return <String, dynamic>{ 'code': error.code, 'domain': error.domain, 'userInfo': error.userInfo, }; } Map<String, dynamic> buildTransactionMap( SKPaymentTransactionWrapper transaction) { final Map<String, dynamic> map = <String, dynamic>{ 'transactionState': SKPaymentTransactionStateWrapper.values .indexOf(SKPaymentTransactionStateWrapper.purchased), 'payment': transaction.payment.toMap(), 'originalTransaction': transaction.originalTransaction == null ? null : buildTransactionMap(transaction.originalTransaction!), 'transactionTimeStamp': transaction.transactionTimeStamp, 'transactionIdentifier': transaction.transactionIdentifier, 'error': buildErrorMap(transaction.error!), }; return map; } Map<String, dynamic> buildTransactionMessage( SKPaymentTransactionWrapper transaction) { final Map<String, dynamic> map = <String, dynamic>{ 'transactionState': SKPaymentTransactionStateWrapper.values .indexOf(SKPaymentTransactionStateWrapper.purchased), 'payment': transaction.payment.toMap(), 'originalTransaction': transaction.originalTransaction == null ? null : buildTransactionMap(transaction.originalTransaction!), 'transactionTimeStamp': transaction.transactionTimeStamp, 'transactionIdentifier': transaction.transactionIdentifier, 'error': buildErrorMap(transaction.error!), }; return map; } final SKPaymentDiscountWrapper dummyPaymentDiscountWrapper = SKPaymentDiscountWrapper.fromJson(const <String, dynamic>{ 'identifier': 'dummy-discount-identifier', 'keyIdentifier': 'KEYIDTEST1', 'nonce': '00000000-0000-0000-0000-000000000000', 'signature': 'dummy-signature-string', 'timestamp': 1231231231, });
packages/packages/in_app_purchase/in_app_purchase_storekit/test/store_kit_wrappers/sk_test_stub_objects.dart/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_storekit/test/store_kit_wrappers/sk_test_stub_objects.dart", "repo_id": "packages", "token_count": 2980 }
1,003
buildFlags: _pluginToolsConfigGlobalKey: - "--no-tree-shake-icons" - "--dart-define=buildmode=testing"
packages/packages/local_auth/local_auth/example/.pluginToolsConfig.yaml/0
{ "file_path": "packages/packages/local_auth/local_auth/example/.pluginToolsConfig.yaml", "repo_id": "packages", "token_count": 45 }
1,004
include ':app'
packages/packages/local_auth/local_auth/example/android/settings_aar.gradle/0
{ "file_path": "packages/packages/local_auth/local_auth/example/android/settings_aar.gradle", "repo_id": "packages", "token_count": 6 }
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. package io.flutter.plugins.localauth; import static android.app.Activity.RESULT_OK; import static android.content.Context.KEYGUARD_SERVICE; import android.app.Activity; import android.app.KeyguardManager; import android.content.Context; import android.content.Intent; import android.os.Build; import androidx.annotation.NonNull; import androidx.annotation.VisibleForTesting; import androidx.biometric.BiometricManager; import androidx.fragment.app.FragmentActivity; import androidx.lifecycle.Lifecycle; import io.flutter.embedding.engine.plugins.FlutterPlugin; import io.flutter.embedding.engine.plugins.activity.ActivityAware; import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding; import io.flutter.embedding.engine.plugins.lifecycle.FlutterLifecycleAdapter; import io.flutter.plugin.common.PluginRegistry; import io.flutter.plugins.localauth.AuthenticationHelper.AuthCompletionHandler; import io.flutter.plugins.localauth.Messages.AuthClassification; import io.flutter.plugins.localauth.Messages.AuthClassificationWrapper; import io.flutter.plugins.localauth.Messages.AuthOptions; import io.flutter.plugins.localauth.Messages.AuthResult; import io.flutter.plugins.localauth.Messages.AuthStrings; import io.flutter.plugins.localauth.Messages.LocalAuthApi; import io.flutter.plugins.localauth.Messages.Result; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; /** * Flutter plugin providing access to local authentication. * * <p>Instantiate this in an add to app scenario to gracefully handle activity and context changes. */ public class LocalAuthPlugin implements FlutterPlugin, ActivityAware, LocalAuthApi { private static final int LOCK_REQUEST_CODE = 221; private Activity activity; private AuthenticationHelper authHelper; @VisibleForTesting final AtomicBoolean authInProgress = new AtomicBoolean(false); // These are null when not using v2 embedding. private Lifecycle lifecycle; private BiometricManager biometricManager; private KeyguardManager keyguardManager; Result<AuthResult> lockRequestResult; private final PluginRegistry.ActivityResultListener resultListener = new PluginRegistry.ActivityResultListener() { @Override public boolean onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == LOCK_REQUEST_CODE) { if (resultCode == RESULT_OK && lockRequestResult != null) { onAuthenticationCompleted(lockRequestResult, AuthResult.SUCCESS); } else { onAuthenticationCompleted(lockRequestResult, AuthResult.FAILURE); } lockRequestResult = null; } return false; } }; /** * Registers a plugin with the v1 embedding api {@code io.flutter.plugin.common}. * * <p>Calling this will register the plugin with the passed registrar. However, plugins * initialized this way won't react to changes in activity or context. * * @param registrar provides access to necessary plugin context. */ @SuppressWarnings("deprecation") public static void registerWith(@NonNull PluginRegistry.Registrar registrar) { final LocalAuthPlugin plugin = new LocalAuthPlugin(); plugin.activity = registrar.activity(); LocalAuthApi.setup(registrar.messenger(), plugin); registrar.addActivityResultListener(plugin.resultListener); } /** * Default constructor for LocalAuthPlugin. * * <p>Use this constructor when adding this plugin to an app with v2 embedding. */ public LocalAuthPlugin() {} public @NonNull Boolean isDeviceSupported() { return isDeviceSecure() || canAuthenticateWithBiometrics(); } public @NonNull Boolean deviceCanSupportBiometrics() { return hasBiometricHardware(); } public @NonNull List<AuthClassificationWrapper> getEnrolledBiometrics() { ArrayList<AuthClassificationWrapper> biometrics = new ArrayList<>(); if (biometricManager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_WEAK) == BiometricManager.BIOMETRIC_SUCCESS) { biometrics.add(wrappedBiometric(AuthClassification.WEAK)); } if (biometricManager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_STRONG) == BiometricManager.BIOMETRIC_SUCCESS) { biometrics.add(wrappedBiometric(AuthClassification.STRONG)); } return biometrics; } private @NonNull AuthClassificationWrapper wrappedBiometric(AuthClassification value) { return new AuthClassificationWrapper.Builder().setValue(value).build(); } public @NonNull Boolean stopAuthentication() { try { if (authHelper != null && authInProgress.get()) { authHelper.stopAuthentication(); authHelper = null; } authInProgress.set(false); return true; } catch (Exception e) { return false; } } public void authenticate( @NonNull AuthOptions options, @NonNull AuthStrings strings, @NonNull Result<AuthResult> result) { if (authInProgress.get()) { result.success(AuthResult.ERROR_ALREADY_IN_PROGRESS); return; } if (activity == null || activity.isFinishing()) { result.success(AuthResult.ERROR_NO_ACTIVITY); return; } if (!(activity instanceof FragmentActivity)) { result.success(AuthResult.ERROR_NOT_FRAGMENT_ACTIVITY); return; } if (!isDeviceSupported()) { result.success(AuthResult.ERROR_NOT_AVAILABLE); return; } authInProgress.set(true); AuthCompletionHandler completionHandler = createAuthCompletionHandler(result); boolean allowCredentials = !options.getBiometricOnly() && canAuthenticateWithDeviceCredential(); sendAuthenticationRequest(options, strings, allowCredentials, completionHandler); } @VisibleForTesting public @NonNull AuthCompletionHandler createAuthCompletionHandler( @NonNull final Result<AuthResult> result) { return authResult -> onAuthenticationCompleted(result, authResult); } @VisibleForTesting public void sendAuthenticationRequest( @NonNull AuthOptions options, @NonNull AuthStrings strings, boolean allowCredentials, @NonNull AuthCompletionHandler completionHandler) { authHelper = new AuthenticationHelper( lifecycle, (FragmentActivity) activity, options, strings, completionHandler, allowCredentials); authHelper.authenticate(); } void onAuthenticationCompleted(Result<AuthResult> result, AuthResult value) { if (authInProgress.compareAndSet(true, false)) { result.success(value); } } @VisibleForTesting public boolean isDeviceSecure() { if (keyguardManager == null) return false; return (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && keyguardManager.isDeviceSecure()); } private boolean canAuthenticateWithBiometrics() { if (biometricManager == null) return false; return biometricManager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_WEAK) == BiometricManager.BIOMETRIC_SUCCESS; } private boolean hasBiometricHardware() { if (biometricManager == null) return false; return biometricManager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_WEAK) != BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE; } @VisibleForTesting public boolean canAuthenticateWithDeviceCredential() { if (Build.VERSION.SDK_INT < 30) { // Checking for device credential only authentication via the BiometricManager // is not allowed before API level 30, so we check for presence of PIN, pattern, // or password instead. return isDeviceSecure(); } if (biometricManager == null) return false; return biometricManager.canAuthenticate(BiometricManager.Authenticators.DEVICE_CREDENTIAL) == BiometricManager.BIOMETRIC_SUCCESS; } @Override public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) { LocalAuthApi.setup(binding.getBinaryMessenger(), this); } @Override public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) { LocalAuthApi.setup(binding.getBinaryMessenger(), null); } private void setServicesFromActivity(Activity activity) { if (activity == null) return; this.activity = activity; Context context = activity.getBaseContext(); biometricManager = BiometricManager.from(activity); keyguardManager = (KeyguardManager) context.getSystemService(KEYGUARD_SERVICE); } @Override public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) { binding.addActivityResultListener(resultListener); setServicesFromActivity(binding.getActivity()); lifecycle = FlutterLifecycleAdapter.getActivityLifecycle(binding); } @Override public void onDetachedFromActivityForConfigChanges() { lifecycle = null; activity = null; } @Override public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding binding) { binding.addActivityResultListener(resultListener); setServicesFromActivity(binding.getActivity()); lifecycle = FlutterLifecycleAdapter.getActivityLifecycle(binding); } @Override public void onDetachedFromActivity() { lifecycle = null; activity = null; } @VisibleForTesting final Activity getActivity() { return activity; } @VisibleForTesting void setBiometricManager(BiometricManager biometricManager) { this.biometricManager = biometricManager; } @VisibleForTesting void setKeyguardManager(KeyguardManager keyguardManager) { this.keyguardManager = keyguardManager; } }
packages/packages/local_auth/local_auth_android/android/src/main/java/io/flutter/plugins/localauth/LocalAuthPlugin.java/0
{ "file_path": "packages/packages/local_auth/local_auth_android/android/src/main/java/io/flutter/plugins/localauth/LocalAuthPlugin.java", "repo_id": "packages", "token_count": 3201 }
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 LocalAuthentication; @import XCTest; @import local_auth_darwin; #import <OCMock/OCMock.h> // Set a long timeout to avoid flake due to slow CI. static const NSTimeInterval kTimeout = 30.0; /** * A context factory that returns preset contexts. */ @interface StubAuthContextFactory : NSObject <FLADAuthContextFactory> @property(copy, nonatomic) NSMutableArray *contexts; - (instancetype)initWithContexts:(NSArray *)contexts; @end @implementation StubAuthContextFactory - (instancetype)initWithContexts:(NSArray *)contexts { self = [super init]; if (self) { _contexts = [contexts mutableCopy]; } return self; } - (LAContext *)createAuthContext { NSAssert(self.contexts.count > 0, @"Insufficient test contexts provided"); LAContext *context = [self.contexts firstObject]; [self.contexts removeObjectAtIndex:0]; return context; } @end #pragma mark - @interface FLALocalAuthPluginTests : XCTestCase @end @implementation FLALocalAuthPluginTests - (void)setUp { self.continueAfterFailure = NO; } - (void)testSuccessfullAuthWithBiometrics { id mockAuthContext = OCMClassMock([LAContext class]); FLALocalAuthPlugin *plugin = [[FLALocalAuthPlugin alloc] initWithContextFactory:[[StubAuthContextFactory alloc] initWithContexts:@[ mockAuthContext ]]]; const LAPolicy policy = LAPolicyDeviceOwnerAuthenticationWithBiometrics; FLADAuthStrings *strings = [self createAuthStrings]; OCMStub([mockAuthContext canEvaluatePolicy:policy error:[OCMArg setTo:nil]]).andReturn(YES); // evaluatePolicy:localizedReason:reply: calls back on an internal queue, which is not // guaranteed to be on the main thread. Ensure that's handled correctly by calling back on // a background thread. void (^backgroundThreadReplyCaller)(NSInvocation *) = ^(NSInvocation *invocation) { void (^reply)(BOOL, NSError *); [invocation getArgument:&reply atIndex:4]; dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), ^{ reply(YES, nil); }); }; OCMStub([mockAuthContext evaluatePolicy:policy localizedReason:strings.reason reply:[OCMArg any]]) .andDo(backgroundThreadReplyCaller); XCTestExpectation *expectation = [self expectationWithDescription:@"Result is called"]; [plugin authenticateWithOptions:[FLADAuthOptions makeWithBiometricOnly:YES sticky:NO useErrorDialogs:NO] strings:strings completion:^(FLADAuthResultDetails *_Nullable resultDetails, FlutterError *_Nullable error) { XCTAssertTrue([NSThread isMainThread]); XCTAssertEqual(resultDetails.result, FLADAuthResultSuccess); XCTAssertNil(error); [expectation fulfill]; }]; [self waitForExpectationsWithTimeout:kTimeout handler:nil]; } - (void)testSuccessfullAuthWithoutBiometrics { id mockAuthContext = OCMClassMock([LAContext class]); FLALocalAuthPlugin *plugin = [[FLALocalAuthPlugin alloc] initWithContextFactory:[[StubAuthContextFactory alloc] initWithContexts:@[ mockAuthContext ]]]; const LAPolicy policy = LAPolicyDeviceOwnerAuthentication; FLADAuthStrings *strings = [self createAuthStrings]; OCMStub([mockAuthContext canEvaluatePolicy:policy error:[OCMArg setTo:nil]]).andReturn(YES); // evaluatePolicy:localizedReason:reply: calls back on an internal queue, which is not // guaranteed to be on the main thread. Ensure that's handled correctly by calling back on // a background thread. void (^backgroundThreadReplyCaller)(NSInvocation *) = ^(NSInvocation *invocation) { void (^reply)(BOOL, NSError *); [invocation getArgument:&reply atIndex:4]; dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), ^{ reply(YES, nil); }); }; OCMStub([mockAuthContext evaluatePolicy:policy localizedReason:strings.reason reply:[OCMArg any]]) .andDo(backgroundThreadReplyCaller); XCTestExpectation *expectation = [self expectationWithDescription:@"Result is called"]; [plugin authenticateWithOptions:[FLADAuthOptions makeWithBiometricOnly:NO sticky:NO useErrorDialogs:NO] strings:strings completion:^(FLADAuthResultDetails *_Nullable resultDetails, FlutterError *_Nullable error) { XCTAssertTrue([NSThread isMainThread]); XCTAssertEqual(resultDetails.result, FLADAuthResultSuccess); XCTAssertNil(error); [expectation fulfill]; }]; [self waitForExpectationsWithTimeout:kTimeout handler:nil]; } - (void)testFailedAuthWithBiometrics { id mockAuthContext = OCMClassMock([LAContext class]); FLALocalAuthPlugin *plugin = [[FLALocalAuthPlugin alloc] initWithContextFactory:[[StubAuthContextFactory alloc] initWithContexts:@[ mockAuthContext ]]]; const LAPolicy policy = LAPolicyDeviceOwnerAuthenticationWithBiometrics; FLADAuthStrings *strings = [self createAuthStrings]; OCMStub([mockAuthContext canEvaluatePolicy:policy error:[OCMArg setTo:nil]]).andReturn(YES); // evaluatePolicy:localizedReason:reply: calls back on an internal queue, which is not // guaranteed to be on the main thread. Ensure that's handled correctly by calling back on // a background thread. void (^backgroundThreadReplyCaller)(NSInvocation *) = ^(NSInvocation *invocation) { void (^reply)(BOOL, NSError *); [invocation getArgument:&reply atIndex:4]; dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), ^{ reply(NO, [NSError errorWithDomain:@"error" code:LAErrorAuthenticationFailed userInfo:nil]); }); }; OCMStub([mockAuthContext evaluatePolicy:policy localizedReason:strings.reason reply:[OCMArg any]]) .andDo(backgroundThreadReplyCaller); XCTestExpectation *expectation = [self expectationWithDescription:@"Result is called"]; [plugin authenticateWithOptions:[FLADAuthOptions makeWithBiometricOnly:YES sticky:NO useErrorDialogs:NO] strings:strings completion:^(FLADAuthResultDetails *_Nullable resultDetails, FlutterError *_Nullable error) { XCTAssertTrue([NSThread isMainThread]); // TODO(stuartmorgan): Fix this; this was the pre-Pigeon-migration // behavior, so is preserved as part of the migration, but a failed // authentication should return failure, not an error that results in a // PlatformException. XCTAssertEqual(resultDetails.result, FLADAuthResultErrorNotAvailable); XCTAssertNil(error); [expectation fulfill]; }]; [self waitForExpectationsWithTimeout:kTimeout handler:nil]; } - (void)testFailedWithUnknownErrorCode { id mockAuthContext = OCMClassMock([LAContext class]); FLALocalAuthPlugin *plugin = [[FLALocalAuthPlugin alloc] initWithContextFactory:[[StubAuthContextFactory alloc] initWithContexts:@[ mockAuthContext ]]]; const LAPolicy policy = LAPolicyDeviceOwnerAuthentication; FLADAuthStrings *strings = [self createAuthStrings]; OCMStub([mockAuthContext canEvaluatePolicy:policy error:[OCMArg setTo:nil]]).andReturn(YES); // evaluatePolicy:localizedReason:reply: calls back on an internal queue, which is not // guaranteed to be on the main thread. Ensure that's handled correctly by calling back on // a background thread. void (^backgroundThreadReplyCaller)(NSInvocation *) = ^(NSInvocation *invocation) { void (^reply)(BOOL, NSError *); [invocation getArgument:&reply atIndex:4]; dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), ^{ reply(NO, [NSError errorWithDomain:@"error" code:99 userInfo:nil]); }); }; OCMStub([mockAuthContext evaluatePolicy:policy localizedReason:strings.reason reply:[OCMArg any]]) .andDo(backgroundThreadReplyCaller); XCTestExpectation *expectation = [self expectationWithDescription:@"Result is called"]; [plugin authenticateWithOptions:[FLADAuthOptions makeWithBiometricOnly:NO sticky:NO useErrorDialogs:NO] strings:strings completion:^(FLADAuthResultDetails *_Nullable resultDetails, FlutterError *_Nullable error) { XCTAssertTrue([NSThread isMainThread]); XCTAssertEqual(resultDetails.result, FLADAuthResultErrorNotAvailable); XCTAssertNil(error); [expectation fulfill]; }]; [self waitForExpectationsWithTimeout:kTimeout handler:nil]; } - (void)testSystemCancelledWithoutStickyAuth { id mockAuthContext = OCMClassMock([LAContext class]); FLALocalAuthPlugin *plugin = [[FLALocalAuthPlugin alloc] initWithContextFactory:[[StubAuthContextFactory alloc] initWithContexts:@[ mockAuthContext ]]]; const LAPolicy policy = LAPolicyDeviceOwnerAuthentication; FLADAuthStrings *strings = [self createAuthStrings]; OCMStub([mockAuthContext canEvaluatePolicy:policy error:[OCMArg setTo:nil]]).andReturn(YES); // evaluatePolicy:localizedReason:reply: calls back on an internal queue, which is not // guaranteed to be on the main thread. Ensure that's handled correctly by calling back on // a background thread. void (^backgroundThreadReplyCaller)(NSInvocation *) = ^(NSInvocation *invocation) { void (^reply)(BOOL, NSError *); [invocation getArgument:&reply atIndex:4]; dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), ^{ reply(NO, [NSError errorWithDomain:@"error" code:LAErrorSystemCancel userInfo:nil]); }); }; OCMStub([mockAuthContext evaluatePolicy:policy localizedReason:strings.reason reply:[OCMArg any]]) .andDo(backgroundThreadReplyCaller); XCTestExpectation *expectation = [self expectationWithDescription:@"Result is called"]; [plugin authenticateWithOptions:[FLADAuthOptions makeWithBiometricOnly:NO sticky:NO useErrorDialogs:NO] strings:strings completion:^(FLADAuthResultDetails *_Nullable resultDetails, FlutterError *_Nullable error) { XCTAssertTrue([NSThread isMainThread]); XCTAssertEqual(resultDetails.result, FLADAuthResultFailure); XCTAssertNil(error); [expectation fulfill]; }]; [self waitForExpectationsWithTimeout:kTimeout handler:nil]; } - (void)testFailedAuthWithoutBiometrics { id mockAuthContext = OCMClassMock([LAContext class]); FLALocalAuthPlugin *plugin = [[FLALocalAuthPlugin alloc] initWithContextFactory:[[StubAuthContextFactory alloc] initWithContexts:@[ mockAuthContext ]]]; const LAPolicy policy = LAPolicyDeviceOwnerAuthentication; FLADAuthStrings *strings = [self createAuthStrings]; OCMStub([mockAuthContext canEvaluatePolicy:policy error:[OCMArg setTo:nil]]).andReturn(YES); // evaluatePolicy:localizedReason:reply: calls back on an internal queue, which is not // guaranteed to be on the main thread. Ensure that's handled correctly by calling back on // a background thread. void (^backgroundThreadReplyCaller)(NSInvocation *) = ^(NSInvocation *invocation) { void (^reply)(BOOL, NSError *); [invocation getArgument:&reply atIndex:4]; dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), ^{ reply(NO, [NSError errorWithDomain:@"error" code:LAErrorAuthenticationFailed userInfo:nil]); }); }; OCMStub([mockAuthContext evaluatePolicy:policy localizedReason:strings.reason reply:[OCMArg any]]) .andDo(backgroundThreadReplyCaller); XCTestExpectation *expectation = [self expectationWithDescription:@"Result is called"]; [plugin authenticateWithOptions:[FLADAuthOptions makeWithBiometricOnly:NO sticky:NO useErrorDialogs:NO] strings:strings completion:^(FLADAuthResultDetails *_Nullable resultDetails, FlutterError *_Nullable error) { XCTAssertTrue([NSThread isMainThread]); // TODO(stuartmorgan): Fix this; this was the pre-Pigeon-migration // behavior, so is preserved as part of the migration, but a failed // authentication should return failure, not an error that results in a // PlatformException. XCTAssertEqual(resultDetails.result, FLADAuthResultErrorNotAvailable); XCTAssertNil(error); [expectation fulfill]; }]; [self waitForExpectationsWithTimeout:kTimeout handler:nil]; } - (void)testLocalizedFallbackTitle { id mockAuthContext = OCMClassMock([LAContext class]); FLALocalAuthPlugin *plugin = [[FLALocalAuthPlugin alloc] initWithContextFactory:[[StubAuthContextFactory alloc] initWithContexts:@[ mockAuthContext ]]]; const LAPolicy policy = LAPolicyDeviceOwnerAuthentication; FLADAuthStrings *strings = [self createAuthStrings]; strings.localizedFallbackTitle = @"a title"; OCMStub([mockAuthContext canEvaluatePolicy:policy error:[OCMArg setTo:nil]]).andReturn(YES); // evaluatePolicy:localizedReason:reply: calls back on an internal queue, which is not // guaranteed to be on the main thread. Ensure that's handled correctly by calling back on // a background thread. void (^backgroundThreadReplyCaller)(NSInvocation *) = ^(NSInvocation *invocation) { void (^reply)(BOOL, NSError *); [invocation getArgument:&reply atIndex:4]; dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), ^{ reply(YES, nil); }); }; OCMStub([mockAuthContext evaluatePolicy:policy localizedReason:strings.reason reply:[OCMArg any]]) .andDo(backgroundThreadReplyCaller); XCTestExpectation *expectation = [self expectationWithDescription:@"Result is called"]; [plugin authenticateWithOptions:[FLADAuthOptions makeWithBiometricOnly:NO sticky:NO useErrorDialogs:NO] strings:strings completion:^(FLADAuthResultDetails *_Nullable resultDetails, FlutterError *_Nullable error) { OCMVerify([mockAuthContext setLocalizedFallbackTitle:strings.localizedFallbackTitle]); [expectation fulfill]; }]; [self waitForExpectationsWithTimeout:kTimeout handler:nil]; } - (void)testSkippedLocalizedFallbackTitle { id mockAuthContext = OCMClassMock([LAContext class]); FLALocalAuthPlugin *plugin = [[FLALocalAuthPlugin alloc] initWithContextFactory:[[StubAuthContextFactory alloc] initWithContexts:@[ mockAuthContext ]]]; const LAPolicy policy = LAPolicyDeviceOwnerAuthentication; FLADAuthStrings *strings = [self createAuthStrings]; strings.localizedFallbackTitle = nil; OCMStub([mockAuthContext canEvaluatePolicy:policy error:[OCMArg setTo:nil]]).andReturn(YES); // evaluatePolicy:localizedReason:reply: calls back on an internal queue, which is not // guaranteed to be on the main thread. Ensure that's handled correctly by calling back on // a background thread. void (^backgroundThreadReplyCaller)(NSInvocation *) = ^(NSInvocation *invocation) { void (^reply)(BOOL, NSError *); [invocation getArgument:&reply atIndex:4]; dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), ^{ reply(YES, nil); }); }; OCMStub([mockAuthContext evaluatePolicy:policy localizedReason:strings.reason reply:[OCMArg any]]) .andDo(backgroundThreadReplyCaller); XCTestExpectation *expectation = [self expectationWithDescription:@"Result is called"]; [plugin authenticateWithOptions:[FLADAuthOptions makeWithBiometricOnly:NO sticky:NO useErrorDialogs:NO] strings:strings completion:^(FLADAuthResultDetails *_Nullable resultDetails, FlutterError *_Nullable error) { OCMVerify([mockAuthContext setLocalizedFallbackTitle:nil]); [expectation fulfill]; }]; [self waitForExpectationsWithTimeout:kTimeout handler:nil]; } - (void)testDeviceSupportsBiometrics_withEnrolledHardware { id mockAuthContext = OCMClassMock([LAContext class]); FLALocalAuthPlugin *plugin = [[FLALocalAuthPlugin alloc] initWithContextFactory:[[StubAuthContextFactory alloc] initWithContexts:@[ mockAuthContext ]]]; const LAPolicy policy = LAPolicyDeviceOwnerAuthenticationWithBiometrics; OCMStub([mockAuthContext canEvaluatePolicy:policy error:[OCMArg setTo:nil]]).andReturn(YES); FlutterError *error; NSNumber *result = [plugin deviceCanSupportBiometricsWithError:&error]; XCTAssertTrue([result boolValue]); XCTAssertNil(error); } - (void)testDeviceSupportsBiometrics_withNonEnrolledHardware { id mockAuthContext = OCMClassMock([LAContext class]); FLALocalAuthPlugin *plugin = [[FLALocalAuthPlugin alloc] initWithContextFactory:[[StubAuthContextFactory alloc] initWithContexts:@[ mockAuthContext ]]]; const LAPolicy policy = LAPolicyDeviceOwnerAuthenticationWithBiometrics; void (^canEvaluatePolicyHandler)(NSInvocation *) = ^(NSInvocation *invocation) { // Write error NSError *__autoreleasing *authError; [invocation getArgument:&authError atIndex:3]; *authError = [NSError errorWithDomain:@"error" code:LAErrorBiometryNotEnrolled userInfo:nil]; // Write return value BOOL returnValue = NO; NSValue *nsReturnValue = [NSValue valueWithBytes:&returnValue objCType:@encode(BOOL)]; [invocation setReturnValue:&nsReturnValue]; }; OCMStub([mockAuthContext canEvaluatePolicy:policy error:(NSError * __autoreleasing *)[OCMArg anyPointer]]) .andDo(canEvaluatePolicyHandler); FlutterError *error; NSNumber *result = [plugin deviceCanSupportBiometricsWithError:&error]; XCTAssertTrue([result boolValue]); XCTAssertNil(error); } - (void)testDeviceSupportsBiometrics_withNoBiometricHardware { id mockAuthContext = OCMClassMock([LAContext class]); FLALocalAuthPlugin *plugin = [[FLALocalAuthPlugin alloc] initWithContextFactory:[[StubAuthContextFactory alloc] initWithContexts:@[ mockAuthContext ]]]; const LAPolicy policy = LAPolicyDeviceOwnerAuthenticationWithBiometrics; void (^canEvaluatePolicyHandler)(NSInvocation *) = ^(NSInvocation *invocation) { // Write error NSError *__autoreleasing *authError; [invocation getArgument:&authError atIndex:3]; *authError = [NSError errorWithDomain:@"error" code:0 userInfo:nil]; // Write return value BOOL returnValue = NO; NSValue *nsReturnValue = [NSValue valueWithBytes:&returnValue objCType:@encode(BOOL)]; [invocation setReturnValue:&nsReturnValue]; }; OCMStub([mockAuthContext canEvaluatePolicy:policy error:(NSError * __autoreleasing *)[OCMArg anyPointer]]) .andDo(canEvaluatePolicyHandler); FlutterError *error; NSNumber *result = [plugin deviceCanSupportBiometricsWithError:&error]; XCTAssertFalse([result boolValue]); XCTAssertNil(error); } - (void)testGetEnrolledBiometricsWithFaceID { id mockAuthContext = OCMClassMock([LAContext class]); FLALocalAuthPlugin *plugin = [[FLALocalAuthPlugin alloc] initWithContextFactory:[[StubAuthContextFactory alloc] initWithContexts:@[ mockAuthContext ]]]; const LAPolicy policy = LAPolicyDeviceOwnerAuthenticationWithBiometrics; OCMStub([mockAuthContext canEvaluatePolicy:policy error:[OCMArg setTo:nil]]).andReturn(YES); OCMStub([mockAuthContext biometryType]).andReturn(LABiometryTypeFaceID); FlutterError *error; NSArray<FLADAuthBiometricWrapper *> *result = [plugin getEnrolledBiometricsWithError:&error]; XCTAssertEqual([result count], 1); XCTAssertEqual(result[0].value, FLADAuthBiometricFace); XCTAssertNil(error); } - (void)testGetEnrolledBiometricsWithTouchID { id mockAuthContext = OCMClassMock([LAContext class]); FLALocalAuthPlugin *plugin = [[FLALocalAuthPlugin alloc] initWithContextFactory:[[StubAuthContextFactory alloc] initWithContexts:@[ mockAuthContext ]]]; const LAPolicy policy = LAPolicyDeviceOwnerAuthenticationWithBiometrics; OCMStub([mockAuthContext canEvaluatePolicy:policy error:[OCMArg setTo:nil]]).andReturn(YES); OCMStub([mockAuthContext biometryType]).andReturn(LABiometryTypeTouchID); FlutterError *error; NSArray<FLADAuthBiometricWrapper *> *result = [plugin getEnrolledBiometricsWithError:&error]; XCTAssertEqual([result count], 1); XCTAssertEqual(result[0].value, FLADAuthBiometricFingerprint); XCTAssertNil(error); } - (void)testGetEnrolledBiometricsWithoutEnrolledHardware { id mockAuthContext = OCMClassMock([LAContext class]); FLALocalAuthPlugin *plugin = [[FLALocalAuthPlugin alloc] initWithContextFactory:[[StubAuthContextFactory alloc] initWithContexts:@[ mockAuthContext ]]]; const LAPolicy policy = LAPolicyDeviceOwnerAuthenticationWithBiometrics; void (^canEvaluatePolicyHandler)(NSInvocation *) = ^(NSInvocation *invocation) { // Write error NSError *__autoreleasing *authError; [invocation getArgument:&authError atIndex:3]; *authError = [NSError errorWithDomain:@"error" code:LAErrorBiometryNotEnrolled userInfo:nil]; // Write return value BOOL returnValue = NO; NSValue *nsReturnValue = [NSValue valueWithBytes:&returnValue objCType:@encode(BOOL)]; [invocation setReturnValue:&nsReturnValue]; }; OCMStub([mockAuthContext canEvaluatePolicy:policy error:(NSError * __autoreleasing *)[OCMArg anyPointer]]) .andDo(canEvaluatePolicyHandler); FlutterError *error; NSArray<FLADAuthBiometricWrapper *> *result = [plugin getEnrolledBiometricsWithError:&error]; XCTAssertEqual([result count], 0); XCTAssertNil(error); } - (void)testIsDeviceSupportedHandlesSupported { id mockAuthContext = OCMClassMock([LAContext class]); OCMStub([mockAuthContext canEvaluatePolicy:LAPolicyDeviceOwnerAuthentication error:[OCMArg setTo:nil]]) .andReturn(YES); FLALocalAuthPlugin *plugin = [[FLALocalAuthPlugin alloc] initWithContextFactory:[[StubAuthContextFactory alloc] initWithContexts:@[ mockAuthContext ]]]; FlutterError *error; NSNumber *result = [plugin isDeviceSupportedWithError:&error]; XCTAssertTrue([result boolValue]); XCTAssertNil(error); } - (void)testIsDeviceSupportedHandlesUnsupported { id mockAuthContext = OCMClassMock([LAContext class]); OCMStub([mockAuthContext canEvaluatePolicy:LAPolicyDeviceOwnerAuthentication error:[OCMArg setTo:nil]]) .andReturn(NO); FLALocalAuthPlugin *plugin = [[FLALocalAuthPlugin alloc] initWithContextFactory:[[StubAuthContextFactory alloc] initWithContexts:@[ mockAuthContext ]]]; FlutterError *error; NSNumber *result = [plugin isDeviceSupportedWithError:&error]; XCTAssertFalse([result boolValue]); XCTAssertNil(error); } // Creates an FLADAuthStrings with placeholder values. - (FLADAuthStrings *)createAuthStrings { return [FLADAuthStrings makeWithReason:@"a reason" lockOut:@"locked out" goToSettingsButton:@"Go To Settings" goToSettingsDescription:@"Settings" cancelButton:@"Cancel" localizedFallbackTitle:nil]; } @end
packages/packages/local_auth/local_auth_darwin/darwin/Tests/FLALocalAuthPluginTests.m/0
{ "file_path": "packages/packages/local_auth/local_auth_darwin/darwin/Tests/FLALocalAuthPluginTests.m", "repo_id": "packages", "token_count": 10634 }
1,007
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'dart:io'; import 'common.dart'; import 'constants.dart'; const String _kTimeUnitKey = 'time_unit'; const List<String> _kNonNumericalValueSubResults = <String>[ kNameKey, _kTimeUnitKey, 'aggregate_name', 'aggregate_unit', 'error_message', 'family_index', 'per_family_instance_index', 'label', 'run_name', 'run_type', 'repetitions', 'repetition_index', 'threads', 'iterations', 'big_o', ]; // Context has some keys such as 'host_name' which need to be ignored // so that we can group series together const List<String> _kContextIgnoreKeys = <String>[ 'host_name', 'load_avg', 'caches', ]; // ignore: avoid_classes_with_only_static_members /// Parse the json result of https://github.com/google/benchmark. class GoogleBenchmarkParser { /// Given a Google benchmark json output, parse its content into a list of [MetricPoint]. static Future<List<MetricPoint>> parse(String jsonFileName) async { final Map<String, dynamic> jsonResult = jsonDecode(File(jsonFileName).readAsStringSync()) as Map<String, dynamic>; final Map<String, dynamic> rawContext = jsonResult['context'] as Map<String, dynamic>; final Map<String, String> context = rawContext.map<String, String>( (String k, dynamic v) => MapEntry<String, String>(k, v.toString()), )..removeWhere((String k, String v) => _kContextIgnoreKeys.contains(k)); final List<MetricPoint> points = <MetricPoint>[]; for (final dynamic item in jsonResult['benchmarks'] as List<dynamic>) { _parseAnItem(item as Map<String, dynamic>, points, context); } return points; } } void _parseAnItem( Map<String, dynamic> item, List<MetricPoint> points, Map<String, String> context, ) { final String name = item[kNameKey] as String; final Map<String, String> timeUnitMap = <String, String>{ if (item.containsKey(_kTimeUnitKey)) kUnitKey: item[_kTimeUnitKey] as String }; for (final String subResult in item.keys) { if (!_kNonNumericalValueSubResults.contains(subResult)) { num? rawValue; try { rawValue = item[subResult] as num?; } catch (e) { // ignore: avoid_print print( '$subResult: ${item[subResult]} (${(item[subResult] as Object?).runtimeType}) is not a number'); rethrow; } final double? value = rawValue is int ? rawValue.toDouble() : rawValue as double?; points.add( MetricPoint( value, <String, String?>{kNameKey: name, kSubResultKey: subResult} ..addAll(context) ..addAll( subResult.endsWith('time') ? timeUnitMap : <String, String>{}), ), ); } } }
packages/packages/metrics_center/lib/src/google_benchmark.dart/0
{ "file_path": "packages/packages/metrics_center/lib/src/google_benchmark.dart", "repo_id": "packages", "token_count": 1108 }
1,008
test_on: vm
packages/packages/multicast_dns/dart_test.yaml/0
{ "file_path": "packages/packages/multicast_dns/dart_test.yaml", "repo_id": "packages", "token_count": 6 }
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. import 'dart:async'; import 'dart:math' as math; import 'package:flutter/material.dart'; import 'package:palette_generator/palette_generator.dart'; void main() => runApp(const MyApp()); const Color _kBackgroundColor = Color(0xffa0a0a0); const Color _kSelectionRectangleBackground = Color(0x15000000); const Color _kSelectionRectangleBorder = Color(0x80000000); const Color _kPlaceholderColor = Color(0x80404040); /// The main Application class. class MyApp extends StatelessWidget { /// Creates the main Application class. const MyApp({super.key}); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Image Colors', theme: ThemeData( primarySwatch: Colors.green, ), home: const ImageColors( title: 'Image Colors', image: AssetImage('assets/landscape.png'), imageSize: Size(256.0, 170.0), ), ); } } /// The home page for this example app. @immutable class ImageColors extends StatefulWidget { /// Creates the home page. const ImageColors({ super.key, this.title, required this.image, this.imageSize, }); /// The title that is shown at the top of the page. final String? title; /// This is the image provider that is used to load the colors from. final ImageProvider image; /// The dimensions of the image. final Size? imageSize; @override State<ImageColors> createState() { return _ImageColorsState(); } } class _ImageColorsState extends State<ImageColors> { Rect? region; Rect? dragRegion; Offset? startDrag; Offset? currentDrag; PaletteGenerator? paletteGenerator; final GlobalKey imageKey = GlobalKey(); @override void initState() { super.initState(); if (widget.imageSize != null) { region = Offset.zero & widget.imageSize!; } _updatePaletteGenerator(region); } Future<void> _updatePaletteGenerator(Rect? newRegion) async { paletteGenerator = await PaletteGenerator.fromImageProvider( widget.image, size: widget.imageSize, region: newRegion, maximumColorCount: 20, ); setState(() {}); } // Called when the user starts to drag void _onPanDown(DragDownDetails details) { final RenderBox box = imageKey.currentContext!.findRenderObject()! as RenderBox; final Offset localPosition = box.globalToLocal(details.globalPosition); setState(() { startDrag = localPosition; currentDrag = localPosition; dragRegion = Rect.fromPoints(localPosition, localPosition); }); } // Called as the user drags: just updates the region, not the colors. void _onPanUpdate(DragUpdateDetails details) { setState(() { currentDrag = currentDrag! + details.delta; dragRegion = Rect.fromPoints(startDrag!, currentDrag!); }); } // Called if the drag is canceled (e.g. by rotating the device or switching // apps) void _onPanCancel() { setState(() { dragRegion = null; startDrag = null; }); } // Called when the drag ends. Sets the region, and updates the colors. Future<void> _onPanEnd(DragEndDetails details) async { final Size? imageSize = imageKey.currentContext?.size; Rect? newRegion; if (imageSize != null) { newRegion = (Offset.zero & imageSize).intersect(dragRegion!); if (newRegion.size.width < 4 && newRegion.size.width < 4) { newRegion = Offset.zero & imageSize; } } await _updatePaletteGenerator(newRegion); setState(() { region = newRegion; dragRegion = null; startDrag = null; }); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: _kBackgroundColor, appBar: AppBar( title: Text(widget.title ?? ''), ), body: Column( children: <Widget>[ Padding( padding: const EdgeInsets.all(20.0), // GestureDetector is used to handle the selection rectangle. child: GestureDetector( onPanDown: _onPanDown, onPanUpdate: _onPanUpdate, onPanCancel: _onPanCancel, onPanEnd: _onPanEnd, child: Stack(children: <Widget>[ Image( key: imageKey, image: widget.image, width: widget.imageSize?.width, height: widget.imageSize?.height, ), // This is the selection rectangle. Positioned.fromRect( rect: dragRegion ?? region ?? Rect.zero, child: Container( decoration: BoxDecoration( color: _kSelectionRectangleBackground, border: Border.all( color: _kSelectionRectangleBorder, )), )), ]), ), ), // Use a FutureBuilder so that the palettes will be displayed when // the palette generator is done generating its data. PaletteSwatches(generator: paletteGenerator), ], ), ); } } /// A widget that draws the swatches for the [PaletteGenerator] it is given, /// and shows the selected target colors. class PaletteSwatches extends StatelessWidget { /// Create a Palette swatch. /// /// The [generator] is optional. If it is null, then the display will /// just be an empty container. const PaletteSwatches({super.key, this.generator}); /// The [PaletteGenerator] that contains all of the swatches that we're going /// to display. final PaletteGenerator? generator; @override Widget build(BuildContext context) { final List<Widget> swatches = <Widget>[]; final PaletteGenerator? paletteGen = generator; if (paletteGen == null || paletteGen.colors.isEmpty) { return Container(); } for (final Color color in paletteGen.colors) { swatches.add(PaletteSwatch(color: color)); } return Column( mainAxisAlignment: MainAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: <Widget>[ Wrap( children: swatches, ), Container(height: 30.0), PaletteSwatch( label: 'Dominant', color: paletteGen.dominantColor?.color), PaletteSwatch( label: 'Light Vibrant', color: paletteGen.lightVibrantColor?.color), PaletteSwatch(label: 'Vibrant', color: paletteGen.vibrantColor?.color), PaletteSwatch( label: 'Dark Vibrant', color: paletteGen.darkVibrantColor?.color), PaletteSwatch( label: 'Light Muted', color: paletteGen.lightMutedColor?.color), PaletteSwatch(label: 'Muted', color: paletteGen.mutedColor?.color), PaletteSwatch( label: 'Dark Muted', color: paletteGen.darkMutedColor?.color), ], ); } } /// A small square of color with an optional label. @immutable class PaletteSwatch extends StatelessWidget { /// Creates a PaletteSwatch. /// /// If the [paletteColor] has property `isTargetColorFound` as `false`, /// then the swatch will show a placeholder instead, to indicate /// that there is no color. const PaletteSwatch({ super.key, this.color, this.label, }); /// The color of the swatch. final Color? color; /// The optional label to display next to the swatch. final String? label; @override Widget build(BuildContext context) { // Compute the "distance" of the color swatch and the background color // so that we can put a border around those color swatches that are too // close to the background's saturation and lightness. We ignore hue for // the comparison. final HSLColor hslColor = HSLColor.fromColor(color ?? Colors.transparent); final HSLColor backgroundAsHsl = HSLColor.fromColor(_kBackgroundColor); final double colorDistance = math.sqrt( math.pow(hslColor.saturation - backgroundAsHsl.saturation, 2.0) + math.pow(hslColor.lightness - backgroundAsHsl.lightness, 2.0)); Widget swatch = Padding( padding: const EdgeInsets.all(2.0), child: color == null ? const Placeholder( fallbackWidth: 34.0, fallbackHeight: 20.0, color: Color(0xff404040), ) : Container( decoration: BoxDecoration( color: color, border: Border.all( color: _kPlaceholderColor, style: colorDistance < 0.2 ? BorderStyle.solid : BorderStyle.none, )), width: 34.0, height: 20.0, ), ); if (label != null) { swatch = ConstrainedBox( constraints: const BoxConstraints(maxWidth: 130.0, minWidth: 130.0), child: Row( children: <Widget>[ swatch, Container(width: 5.0), Text(label!), ], ), ); } return swatch; } }
packages/packages/palette_generator/example/lib/main.dart/0
{ "file_path": "packages/packages/palette_generator/example/lib/main.dart", "repo_id": "packages", "token_count": 3825 }
1,010
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Autogenerated from Pigeon (v10.1.3), do not edit directly. // See also: https://pub.dev/packages/pigeon import Foundation #if os(iOS) import Flutter #elseif os(macOS) import FlutterMacOS #else #error("Unsupported platform.") #endif private func wrapResult(_ result: Any?) -> [Any?] { return [result] } private func wrapError(_ error: Any) -> [Any?] { if let flutterError = error as? FlutterError { return [ flutterError.code, flutterError.message, flutterError.details, ] } return [ "\(error)", "\(type(of: error))", "Stacktrace: \(Thread.callStackSymbols)", ] } private func nilOrValue<T>(_ value: Any?) -> T? { if value is NSNull { return nil } return value as! T? } enum DirectoryType: Int { case applicationDocuments = 0 case applicationSupport = 1 case downloads = 2 case library = 3 case temp = 4 case applicationCache = 5 } /// Generated protocol from Pigeon that represents a handler of messages from Flutter. protocol PathProviderApi { func getDirectoryPath(type: DirectoryType) throws -> String? func getContainerPath(appGroupIdentifier: String) throws -> String? } /// Generated setup class from Pigeon to handle messages through the `binaryMessenger`. class PathProviderApiSetup { /// The codec used by PathProviderApi. /// Sets up an instance of `PathProviderApi` to handle messages through the `binaryMessenger`. static func setUp(binaryMessenger: FlutterBinaryMessenger, api: PathProviderApi?) { let getDirectoryPathChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.PathProviderApi.getDirectoryPath", binaryMessenger: binaryMessenger) if let api = api { getDirectoryPathChannel.setMessageHandler { message, reply in let args = message as! [Any?] let typeArg = DirectoryType(rawValue: args[0] as! Int)! do { let result = try api.getDirectoryPath(type: typeArg) reply(wrapResult(result)) } catch { reply(wrapError(error)) } } } else { getDirectoryPathChannel.setMessageHandler(nil) } let getContainerPathChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.PathProviderApi.getContainerPath", binaryMessenger: binaryMessenger) if let api = api { getContainerPathChannel.setMessageHandler { message, reply in let args = message as! [Any?] let appGroupIdentifierArg = args[0] as! String do { let result = try api.getContainerPath(appGroupIdentifier: appGroupIdentifierArg) reply(wrapResult(result)) } catch { reply(wrapError(error)) } } } else { getContainerPathChannel.setMessageHandler(nil) } } }
packages/packages/path_provider/path_provider_foundation/darwin/Classes/messages.g.swift/0
{ "file_path": "packages/packages/path_provider/path_provider_foundation/darwin/Classes/messages.g.swift", "repo_id": "packages", "token_count": 1026 }
1,011
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Autogenerated from Pigeon (v10.1.3), do not edit directly. // See also: https://pub.dev/packages/pigeon // ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, unnecessary_import // ignore_for_file: avoid_relative_lib_imports import 'dart:async'; import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:path_provider_foundation/messages.g.dart'; abstract class TestPathProviderApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = StandardMessageCodec(); String? getDirectoryPath(DirectoryType type); String? getContainerPath(String appGroupIdentifier); static void setup(TestPathProviderApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.PathProviderApi.getDirectoryPath', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.PathProviderApi.getDirectoryPath was null.'); final List<Object?> args = (message as List<Object?>?)!; final DirectoryType? arg_type = args[0] == null ? null : DirectoryType.values[args[0] as int]; assert(arg_type != null, 'Argument for dev.flutter.pigeon.PathProviderApi.getDirectoryPath was null, expected non-null DirectoryType.'); final String? output = api.getDirectoryPath(arg_type!); return <Object?>[output]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.PathProviderApi.getContainerPath', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.PathProviderApi.getContainerPath was null.'); final List<Object?> args = (message as List<Object?>?)!; final String? arg_appGroupIdentifier = (args[0] as String?); assert(arg_appGroupIdentifier != null, 'Argument for dev.flutter.pigeon.PathProviderApi.getContainerPath was null, expected non-null String.'); final String? output = api.getContainerPath(arg_appGroupIdentifier!); return <Object?>[output]; }); } } } }
packages/packages/path_provider/path_provider_foundation/test/messages_test.g.dart/0
{ "file_path": "packages/packages/path_provider/path_provider_foundation/test/messages_test.g.dart", "repo_id": "packages", "token_count": 1329 }
1,012
## NEXT * Updates minimum supported SDK version to Flutter 3.13/Dart 3.1. ## 2.1.2 * Updates minimum required plugin_platform_interface version to 2.1.7. * Updates minimum supported SDK version to Flutter 3.10/Dart 3.0. ## 2.1.1 * Adds pub topics to package metadata. * Updates minimum supported SDK version to Flutter 3.7/Dart 2.19. ## 2.1.0 * Adds getApplicationCachePath() for storing app-specific cache files. * Updates minimum supported SDK version to Flutter 3.3/Dart 2.18. * Aligns Dart and Flutter SDK constraints. ## 2.0.6 * Updates links for the merge of flutter/plugins into flutter/packages. * Updates minimum Flutter version to 3.0. ## 2.0.5 * Updates imports for `prefer_relative_imports`. * Updates minimum Flutter version to 2.10. ## 2.0.4 * Minor fixes for new analysis options. * Removes unnecessary imports. ## 2.0.3 * Removes dependency on `meta`. ## 2.0.2 * Update to use the `verify` method introduced in plugin_platform_interface 2.1.0. ## 2.0.1 * Update platform_plugin_interface version requirement. ## 2.0.0 * Migrate to null safety. ## 1.0.5 * Update Flutter SDK constraint. ## 1.0.4 * Remove unused `test` dependency. ## 1.0.3 * Increase upper range of `package:platform` constraint to allow 3.X versions. ## 1.0.2 * Update lower bound of dart dependency to 2.1.0. ## 1.0.1 * Rename enum to StorageDirectory for backwards compatibility. ## 1.0.0 * Initial release.
packages/packages/path_provider/path_provider_platform_interface/CHANGELOG.md/0
{ "file_path": "packages/packages/path_provider/path_provider_platform_interface/CHANGELOG.md", "repo_id": "packages", "token_count": 475 }
1,013
## 17.2.0 * [dart] Adds implementation for `@ProxyApi`. ## 17.1.3 * [objc] Fixes double prefixes added to enum names. ## 17.1.2 * [swift] Separates message call code generation into separate methods. ## 17.1.1 * Removes heap allocation in generated C++ code. ## 17.1.0 * [kotlin] Adds `includeErrorClass` to `KotlinOptions`. * Updates minimum supported SDK version to Flutter 3.13/Dart 3.1. ## 17.0.0 * **Breaking Change** [kotlin] Converts Kotlin enum case generation to SCREAMING_SNAKE_CASE. * Updates `writeEnum` function to adhere to Kotlin naming conventions. * Improves handling of complex names with enhanced regex patterns. * Expands unit tests for comprehensive name conversion validation. * **Migration Note**: This change modifies the naming convention of Kotlin enum cases generated from the Pigeon package. It is recommended to review the impact on your existing codebase and update any dependent code accordingly. ## 16.0.5 * Adds ProxyApi to AST generation. ## 16.0.4 * [swift] Improve style of Swift output. ## 16.0.3 * [kotlin] Separates message call code generation into separate methods. ## 16.0.2 * [dart] Separates message call code generation into separate methods. ## 16.0.1 * [dart] Fixes test generation for missing wrapResponse method if only host Api. ## 16.0.0 * [java] Adds `VoidResult` type for `Void` returns. * **Breaking Change** [java] Updates all `Void` return types to use new `VoidResult`. ## 15.0.3 * Fixes new lint warnings. ## 15.0.2 * Prevents optional and non-positional parameters in Flutter APIs. * [dart] Fixes named parameters in test output of host API methods. ## 15.0.1 * [java] Adds @CanIgnoreReturnValue annotation to class builder. ## 15.0.0 * **Breaking Change** [kotlin] Updates Flutter API to use new errorClassName. ## 14.0.1 * Updates minimum supported SDK version to Flutter 3.10/Dart 3.0. * Updates issue_tracker link. ## 14.0.0 * **Breaking change** [dart] Renames locally defined host API variables. * [dart] Host api static field `codec` changed to `pigeonChannelCodec`. * [dart] Adds named parameters to host API methods. * [dart] Adds optional parameters to host API methods. * [dart] Adds default values for class constructors and host API methods. * Adds `isEnum` and `isClass` to `TypeDeclaration`s. * [cpp] Fixes `FlutterError` generation being tied to ErrorOr. ## 13.1.2 * Adds compatibility with `analyzer` 6.x. ## 13.1.1 * [kotlin] Removes unnecessary `;`s in generated code. ## 13.1.0 * [swift] Fixes Flutter Api void return error handling. * This shouldn't be breaking for anyone, but if you were incorrectly getting success responses, you may now be failing (correctly). * Adds method channel name to error response when channel fails to connect. * Reduces code generation duplication. * Changes some methods to only be generated if needed. ## 13.0.0 * **Breaking Change** [objc] Eliminates boxing of non-nullable primitive types (bool, int, double). Changes required: * Implementations of host API methods that take non-nullable primitives will need to be updated to match the new signatures. * Calls to Flutter API methods that take non-nullable primitives will need to be updated to pass unboxed values. * Calls to non-nullable primitive property methods on generated data classes will need to be updated. * **WARNING**: Current versions of `Xcode` do not appear to warn about implicit `NSNumber *` to `BOOL` conversions, so code that is no longer correct after this breaking change may compile without warning. For example, `myGeneratedClass.aBoolProperty = @NO` can silently set `aBoolProperty` to `YES`. Any data class or Flutter API interactions involving `bool`s should be carefully audited by hand when updating. ## 12.0.1 * [swift] Adds protocol for Flutter APIs. ## 12.0.0 * Adds error handling on Flutter API methods. * **Breaking Change** [kotlin] Flutter API methods now return `Result<return-type>`. * **Breaking Change** [swift] Flutter API methods now return `Result<return-type, FlutterError>`. * **Breaking Change** [java] Removes `Reply` class from all method returns and replaces it with `Result`. * Changes required: Replace all `Reply` callbacks with `Result` classes that contain both `success` and `failure` methods. * **Breaking Change** [java] Adds `NullableResult` class for all nullable method returns. * Changes required: Any method that returns a nullable type will need to be updated to return `NullableResult` rather than `Result`. * **Breaking Change** [java] Renames Host API `setup` method to `setUp`. * **Breaking Change** [objc] Boxes all enum returns to allow for `nil` response on error. * **Breaking Change** [objc] Renames `<api>Setup` to `SetUp<api>`. ## 11.0.1 * Adds pub topics to package metadata. ## 11.0.0 * Adds primitive enum support. * [objc] Fixes nullable enums. * **Breaking Change** [objc] Changes all nullable enums to be boxed in custom classes. * **Breaking Change** [objc] Changes all enums names to have class prefix. * Updates minimum supported SDK version to Flutter 3.7/Dart 2.19. ## 10.1.6 * Fixes generation failures when an output file is in a directory that doesn't already exist. ## 10.1.5 * [dart] Fixes import in generated test output when overriding package name. ## 10.1.4 * Adds package name to method channel strings to avoid potential collisions between plugins. * Adds dartPackageName option to `pigeonOptions`. ## 10.1.3 * Adds generic `Object` field support to data classes. ## 10.1.2 * [swift] Fixes a crash when passing `null` for nested nullable classes. ## 10.1.1 * Updates README to better reflect modern usage. ## 10.1.0 * [objc] Adds macOS support to facilitate code sharing with existing iOS plugins. ## 10.0.1 * Requires `analyzer 5.13.0` and replaces use of deprecated APIs. ## 10.0.0 * [swift] Avoids using `Any` to represent `Optional`. * [swift] **Breaking Change** A raw `List` (without generic type argument) in Dart will be translated into `[Any?]` (rather than `[Any]`). * [swift] **Breaking Change** A raw `Map` (without generic type argument) in Dart will be translated into `[AnyHashable:Any?]` (rather than `[AnyHashable:Any]`). * Adds an example application that uses Pigeon directly, rather than in a plugin. ## 9.2.5 * Reports an error when trying to use an enum directly in a `List` or `Map` argument. ## 9.2.4 * [objc] Fixes a warning due to a C++-style function signature in the codec getter's definition. ## 9.2.3 * [java] Fixes `UnknownNullability` and `SyntheticAccessor` warnings. ## 9.2.2 * [cpp] Minor changes to output style. ## 9.2.1 * [swift] Fixes NSNull casting crash. ## 9.2.0 * [cpp] Removes experimental tags. ## 9.1.4 * Migrates off deprecated `BinaryMessenger` API. ## 9.1.3 * [cpp] Requires passing any non-nullable fields of generated data classes as constructor arguments, similar to what is done in other languages. This may require updates to existing code that creates data class instances on the native side. * [cpp] Adds a convenience constructor to generated data classes to set all fields during construction. ## 9.1.2 * [cpp] Fixes class parameters to Flutter APIs. * Updates minimum Flutter version to 3.3. ## 9.1.1 * [swift] Removes experimental tags. * [kotlin] Removes experimental tags. ## 9.1.0 * [java] Adds a `GeneratedApi.FlutterError` exception for passing custom error details (code, message, details). * [kotlin] Adds a `FlutterError` exception for passing custom error details (code, message, details). * [kotlin] Adds an `errorClassName` option in `KotlinOptions` for custom error class names. * [java] Removes legacy try catch from async APIs. * [java] Removes legacy null check on non-nullable method arguments. * [cpp] Fixes wrong order of items in `FlutterError`. * Adds `FlutterError` handling integration tests for all platforms. ## 9.0.7 * [swift] Changes all ints to int64. May require code updates to existing code. * Adds integration tests for int64. ## 9.0.6 * [kotlin] Removes safe casting from decode process. * [swift] Removes safe casting from decode process. ## 9.0.5 * Removes the unnecessary Flutter constraint. * Removes an unnecessary null check. * Aligns Dart and Flutter SDK constraints. ## 9.0.4 * Adds parameter to generate Kotlin code in example README. ## 9.0.3 * [kotlin] Fixes compiler warnings in generated output. * [swift] Fixes compiler warnings in generated output. ## 9.0.2 * [swift] Removes safe casting from decode process. * [kotlin] Removes safe casting from decode process. ## 9.0.1 * Updates links for the merge of flutter/plugins into flutter/packages. ## 9.0.0 * **Breaking Change** Updates `DartOptions` to be immutable and adds const to the constructor. * [java] Reverts `final` changes to Flutter Api classes. ## 8.0.0 * [objc] **BREAKING CHANGE**: FlutterApi calls now return a `FlutterError`, rather than an `NSError`, on failure. * [objc] Fixes an unused function warning when only generating FlutterApi. ## 7.2.1 * [kotlin] Fixes Flutter API int errors with updated casting. ## 7.2.0 * [swift] Changes async method completion types. May require code updates to existing code. * [swift] Adds error handling to async methods. * [kotlin] Changes async method completion types. May require code updates to existing code. * [kotlin] Adds error handling to async methods. * Adds async error handling integration tests for all platforms. ## 7.1.5 * Updates code to fix strict-cast violations. ## 7.1.4 * [java] Fixes raw types lint issues. ## 7.1.3 * [objc] Removes unused function. ## 7.1.2 * [swift] Adds error handling to sync host API methods. ## 7.1.1 * [c++] Fixes handling of the `cpp*` options in `@ConfigurePigeon` annotations. ## 7.1.0 * Adds `@SwiftFunction` annotation for specifying custom swift function signature. ## 7.0.5 * Requires analyzer 5.0.0 and replaces use of deprecated APIs. ## 7.0.4 * [c++] Fixes minor output formatting issues. ## 7.0.3 * Updates scoped methods to prevent symbol-less use. ## 7.0.2 * [kotlin] Fixes a missed casting of not nullable Dart 'int' to Kotlin 64bit long. ## 7.0.1 * [generator_tools] adds `newln` method for adding empty lines and ending lines. * Updates generators to more closely match Flutter formatter tool output. ## 7.0.0 * [java] **BREAKING CHANGE**: Makes data classes final. Updates generators for 1p linters. ## 6.0.3 * [docs] Updates README.md. ## 6.0.2 * [kotlin] Fixes a bug with a missed line break between generated statements in the `fromList` function of the companion object. ## 6.0.1 * [c++] Fixes most non-class arguments and return values in Flutter APIs. The types of arguments and return values have changed, so this may require updates to existing code. ## 6.0.0 * Creates StructuredGenerator class and implements it on all platforms. ## 5.0.1 * [c++] Fixes undefined behavior in `@async` methods. ## 5.0.0 * Creates new Generator classes for each language. ## 4.2.16 * [swift] Fixes warnings with `Object` parameters. * [dart] Fixes warnings with `Object` return values. * [c++] Generation of APIs that use `Object` no longer fails. ## 4.2.15 * Relocates generator classes. (Reverted) ## 4.2.14 * [c++] Fixes reply sending non EncodableValue wrapped lists. ## 4.2.13 * Add documentation comment support for Enum members. ## 4.2.12 * Updates serialization to use lists instead of maps to improve performance. ## 4.2.11 * [swift] Fixes compressed list data types. ## 4.2.10 * [java] Changes generated enum field to be final. ## 4.2.9 * [kotlin] Fixes a bug with some methods that return `void`. ## 4.2.8 * Adds the ability to use `runWithOptions` entrypoint to allow external libraries to use the pigeon easier. ## 4.2.7 * [swift] Fixes a bug when calling methods that return `void`. ## 4.2.6 * Fixes bug with parsing documentation comments that start with '/'. ## 4.2.5 * [dart] Fixes enum parameter handling in Dart test API class. ## 4.2.4 * [kotlin] Fixes Kotlin generated sync host API error. ## 4.2.3 * [java] Adds assert `args != null`. * [java] Changes the args of a single element to `ArrayList` from `Arrays.asList` to `Collections.singletonList`. * [java] Removes cast for `Object`. ## 4.2.2 * Removes unneeded custom codecs for all languages. ## 4.2.1 * Adds documentation comment support for Kotlin. ## 4.2.0 * Adds experimental support for Kotlin generation. ## 4.1.1 * [java] Adds missing `@NonNull` annotations to some methods. ## 4.1.0 * Adds documentation comment support for all currently supported languages. ## 4.0.3 * [swift] Makes swift output work on macOS. ## 4.0.2 * Fixes lint warnings. ## 4.0.1 * Exposes `SwiftOptions`. ## 4.0.0 * [java] **BREAKING CHANGE**: Changes style for enum values from camelCase to snake_case. Generated java enum values will now always be in upper snake_case. ## 3.2.9 * Updates text theme parameters to avoid deprecation issues. ## 3.2.8 * [dart] Deduces the correct import statement for Dart test files made with `dartHostTestHandler` instead of relying on relative imports. ## 3.2.7 * Requires `analyzer 4.4.0`, and replaces use of deprecated APIs. ## 3.2.6 * [java] Fixes returning int values from FlutterApi methods that fit in 32 bits. ## 3.2.5 * [c++] Fixes style issues in `FlutterError` and `ErrorOr`. The names and visibility of some members have changed, so this may require updates to existing code. ## 3.2.4 * [c++] Fixes most non-class arguments and return values in host APIs. The types of arguments and return values have changed, so this may require updates to existing code. ## 3.2.3 * Adds `unnecessary_import` to linter ignore list in generated dart tests. ## 3.2.2 * Adds `unnecessary_import` to linter ignore list for `package:flutter/foundation.dart`. ## 3.2.1 * Removes `@dart = 2.12` from generated Dart code. ## 3.2.0 * Adds experimental support for Swift generation. ## 3.1.7 * [java] Adds option to add javax.annotation.Generated annotation. ## 3.1.6 * Supports newer versions of `analyzer`. ## 3.1.5 * Fixes potential crash bug when using a nullable nested type that has nonnull fields in ObjC. ## 3.1.4 * [c++] Adds support for non-nullable fields, and fixes some issues with nullable fields. The types of some getters and setter have changed, so this may require updates to existing code. ## 3.1.3 * Adds support for enums in arguments to methods for HostApis. ## 3.1.2 * [c++] Fixes minor style issues in generated code. This includes the naming of generated methods and arguments, so will require updates to existing code. ## 3.1.1 * Updates for non-nullable bindings. ## 3.1.0 * [c++] Adds C++ code generator. ## 3.0.4 * [objc] Simplified some code output, including avoiding Xcode warnings about using `NSNumber*` directly as boolean value. * [tests] Moved test script to enable CI. ## 3.0.3 * Adds ability for generators to do AST validation. This can help generators without complete implementations to report gaps in coverage. ## 3.0.2 * Fixes non-nullable classes and enums as fields. * Fixes nullable collections as return types. ## 3.0.1 * Enables NNBD for the Pigeon tool itself. * [tests] Updates legacy Dart commands. ## 3.0.0 * **BREAKING CHANGE**: Removes the `--dart_null_safety` flag. Generated Dart now always uses nullability annotations, and thus requires Dart 2.12 or later. ## 2.0.4 * Fixes bug where Dart `FlutterApi`s would assert that a nullable argument was nonnull. ## 2.0.3 * [java] Makes the generated Builder class final. ## 2.0.2 * [java] Fixes crash for nullable nested type. ## 2.0.1 * Adds support for TaskQueues for serial background execution. ## 2.0.0 * Implements nullable parameters. * **BREAKING CHANGE** - Nonnull parameters to async methods on HostApis for ObjC now have the proper nullability hints. ## 1.0.19 * Implements nullable return types. ## 1.0.18 * [front-end] Fix error caused by parsing `copyrightHeaders` passed to options in `@ConfigurePigeon`. ## 1.0.17 * [dart_test] Adds missing linter ignores. * [objc] Factors out helper function for reading from NSDictionary's. * [objc] Renames static variables to match Google style. ## 1.0.16 * Updates behavior of run\_tests.dart with no arguments. * [debugging] Adds `ast_out` to help with debugging the compiler front-end. * [front-end, dart] Adds support for non-null fields in data classes in the front-end parser and the Dart generator (unsupported languages ignore the designation currently). * [front-end, dart, objc, java] Adds support for non-null fields in data classes. ## 1.0.15 * [java] Fix too little information when having an exception ## 1.0.14 * [tests] Port several generator tests to run in Dart over bash ## 1.0.13 * [style] Fixes new style rules for Dart analyzer. ## 1.0.12 * [java] Fixes enum support for null values. ## 1.0.11 * [ci] Starts transition to a Dart test runner, adds windows support. * [front-end] Starts issuing an error if enums are used in type arguments. * [front-end] Passes through all enums, referenced or not so they can be used as a work around for direct enum support. ## 1.0.10 * [front-end] Made sure that explicit use of Object actually creates the codec that can represent custom classes. ## 1.0.9 * [dart] Fixed cast exception that can happen with primitive data types with type arguments in FlutterApi's. ## 1.0.8 * [front-end] Started accepting explicit Object references in type arguments. * [codecs] Fixed nuisance where duplicate entries could show up in custom codecs. ## 1.0.7 * [front-end] Fixed bug where nested classes' type arguments aren't included in the output (generated class and codec). ## 1.0.6 * Updated example README for set up steps. ## 1.0.5 * [java] Fixed bug when using Integer arguments to methods declared with 'int' arguments. ## 1.0.4 * [front-end] Fixed bug where codecs weren't generating support for types that only show up in type arguments. ## 1.0.3 * [objc] Updated assert message for incomplete implementations of protocols. ## 1.0.2 * [java] Made it so `@async` handlers in `@HostApi()` can report errors explicitly. ## 1.0.1 * [front-end] Fixed bug where classes only referenced as type arguments for generics weren't being generated. ## 1.0.0 * Started allowing primitive data types as arguments and return types. * Generics support. * Support for functions with more than one argument. * [command-line] Added `one_language` flag for allowing Pigeon to only generate code for one platform. * [command-line] Added the optional sdkPath parameter for specifying Dart SDK path. * [dart] Fixed copyright headers for Dart test output. * [front-end] Added more errors for incorrect usage of Pigeon (previously they were just ignored). * [generators] Moved Pigeon to using a custom codec which allows collection types to contain custom classes. * [java] Fixed NPE in Java generated code for nested types. * [objc] **BREAKING CHANGE:** logic for generating selectors has changed. `void add(Input value)` will now translate to `-(void)addValue:(Input*)value`, methods with no arguments will translate to `...WithError:` or `...WithCompletion:`. * [objc] Added `@ObjCSelector` for specifying custom objc selectors. ## 0.3.0 * Updated the front-end parser to use dart [`analyzer`](https://pub.dev/packages/analyzer) instead of `dart:mirrors`. `dart:mirrors` doesn't support null-safe code so there were a class of features we couldn't implement without this migration. * **BREAKING CHANGE** - the `configurePigeon` function has been migrated to a `@ConfigurePigeon` annotation. See `./pigeons/message.dart` for an example. The annotation can be attached to anything in the file to take effect. * **BREAKING CHANGE** - Now Pigeon files must be in one file per invocation of Pigeon. For example, the classes your APIs use must be in the same file as your APIs. If your Pigeon file imports another source file, it won't actually import it. ## 0.2.4 * bugfix in front-end parser for recursively referenced datatypes. ## 0.2.3 * bugfix in iOS async handlers of functions with no arguments. ## 0.2.2 * Added support for enums. ## 0.2.1 * Java: Fixed issue where multiple async HostApis can generate multiple Result interfaces. * Dart: Made it so you can specify the BinaryMessenger of the generated APIs. ## 0.2.0 * **BREAKING CHANGE** - Pigeon files must be null-safe now. That means the fields inside of the classes must be declared nullable ( [non-null fields](https://github.com/flutter/flutter/issues/59118) aren't yet supported). Migration example: ```dart // Version 0.1.x class Foo { int bar; String baz; } // Version 0.2.x class Foo { int? bar; String? baz; } ``` * **BREAKING CHANGE** - The default output from Pigeon is now null-safe. If you want non-null-safe code you must provide the `--no-dart_null_safety` flag. * The Pigeon source code is now null-safe. * Fixed niladic non-value returning async functions in the Java generator. * Made `runCommandLine` return an the status code. ## 0.1.24 * Moved logic from bin/ to lib/ to help customers wrap up the behavior. * Added some more linter ignores for Dart. ## 0.1.23 * More Java linter and linter fixes. ## 0.1.22 * Java code generator enhancements: * Added linter tests to CI. * Fixed some linter issues in the Java code. ## 0.1.21 * Fixed decode method on generated Flutter classes that use null-safety and have null values. ## 0.1.20 * Implemented `@async` HostApi's for iOS. * Fixed async FlutterApi methods with void return. ## 0.1.19 * Fixed a bug introduced in 0.1.17 where methods without arguments were no longer being called. ## 0.1.18 * Null safe requires Dart 2.12. ## 0.1.17 * Split out test code generation for Dart into a separate file via the --dart_test_out flag. ## 0.1.16 * Fixed running in certain environments where NNBD is enabled by default. ## 0.1.15 * Added support for running in versions of Dart that support NNBD. ## 0.1.14 * [Windows] Fixed executing from drives other than C:. ## 0.1.13 * Fixed execution on Windows with certain setups where Dart didn't allow backslashes in `import` statements. ## 0.1.12 * Fixed assert failure with creating a PlatformException as a result of an exception in Java handlers. ## 0.1.11 * Added flag to generate null safety annotated Dart code `--dart_null_safety`. * Made it so Dart API setup methods can take null. ## 0.1.10+1 * Updated the examples page. ## 0.1.10 * Fixed bug that prevented running `pigeon` on Windows (introduced in `0.1.8`). ## 0.1.9 * Fixed bug where executing pigeon without arguments would crash (introduced in 0.1.8). ## 0.1.8 * Started spawning pigeon_lib in an isolate instead of a subprocess. The subprocess could have lead to errors if the dart version on $PATH didn't match the one that comes with flutter. ## 0.1.7 * Fixed Dart compilation for later versions that support null safety, opting out of it for now. * Fixed nested types in the Java runtime. ## 0.1.6 * Fixed unused variable linter warning in Dart code under certain conditions. ## 0.1.5 * Made array datatypes correctly get imported and exported avoiding the need to add extra imports to generated code. ## 0.1.4 * Fixed nullability for NSError's in generated objc code. * Fixed nullability of nested objects in the Dart generator. * Added test to make sure the pigeon version is correct in generated code headers. ## 0.1.3 * Added error message if supported datatypes are used as arguments or return types directly, without an enclosing class. * Added support for List and Map datatypes in Java and Objective-C targets. ## 0.1.2+1 * Updated the Readme.md. ## 0.1.2 * Removed static analysis warnings from generated Java code. ## 0.1.1 * Fixed issue where nested types didn't work if they weren't present in the Api. ## 0.1.0 * Added pigeon.dart. * Fixed some Obj-C linter problems. * Added the ability to generate a mock handler in Dart. ## 0.1.0-experimental.11 * Fixed setting an API to null in Java. ## 0.1.0-experimental.10 * Added support for void argument functions. * Added nullability annotations to generated objc code. ## 0.1.0-experimental.9 * Added e2e tests for iOS. ## 0.1.0-experimental.8 * Renamed `setupPigeon` to `configurePigeon`. ## 0.1.0-experimental.7 * Suppressed or got rid of warnings in generated Dart code. ## 0.1.0-experimental.6 * Added support for void return types. ## 0.1.0-experimental.5 * Fixed runtime exception in Android with values of ints less than 2^32. * Incremented codegen version warning. ## 0.1.0-experimental.4 * Fixed primitive types for Android Java. ## 0.1.0-experimental.3 * Added support for Android Java. ## 0.1.0-experimental.2 * Added Host->Flutter calls for Objective-C ## 0.1.0-experimental.1 * Fixed warning in the README.md ## 0.1.0-experimental.0 * Initial release.
packages/packages/pigeon/CHANGELOG.md/0
{ "file_path": "packages/packages/pigeon/CHANGELOG.md", "repo_id": "packages", "token_count": 7735 }
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. export 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; export 'cpp_generator.dart' show CppOptions; export 'dart_generator.dart' show DartOptions; export 'java_generator.dart' show JavaOptions; export 'kotlin_generator.dart' show KotlinOptions; export 'objc_generator.dart' show ObjcOptions; export 'pigeon_lib.dart'; export 'swift_generator.dart' show SwiftOptions;
packages/packages/pigeon/lib/pigeon.dart/0
{ "file_path": "packages/packages/pigeon/lib/pigeon.dart", "repo_id": "packages", "token_count": 182 }
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 'package:pigeon/pigeon.dart'; enum ProxyApiTestEnum { one, two, three, } /// The core ProxyApi test class that each supported host language must /// implement in platform_tests integration tests. @ProxyApi() abstract class ProxyApiTestClass extends ProxyApiSuperClass implements ProxyApiInterface { ProxyApiTestClass( // ignore: avoid_unused_constructor_parameters bool boolParam, // ignore: avoid_unused_constructor_parameters int intParam, // ignore: avoid_unused_constructor_parameters double doubleParam, // ignore: avoid_unused_constructor_parameters String stringParam, // ignore: avoid_unused_constructor_parameters Uint8List aUint8ListParam, // ignore: avoid_unused_constructor_parameters List<Object?> listParam, // ignore: avoid_unused_constructor_parameters Map<String?, Object?> mapParam, // ignore: avoid_unused_constructor_parameters ProxyApiTestEnum enumParam, // ignore: avoid_unused_constructor_parameters ProxyApiSuperClass proxyApiParam, // ignore: avoid_unused_constructor_parameters bool? nullableBoolParam, // ignore: avoid_unused_constructor_parameters int? nullableIntParam, // ignore: avoid_unused_constructor_parameters double? nullableDoubleParam, // ignore: avoid_unused_constructor_parameters String? nullableStringParam, // ignore: avoid_unused_constructor_parameters Uint8List? nullableUint8ListParam, // ignore: avoid_unused_constructor_parameters List<Object?>? nullableListParam, // ignore: avoid_unused_constructor_parameters Map<String?, Object?>? nullableMapParam, // ignore: avoid_unused_constructor_parameters ProxyApiTestEnum? nullableEnumParam, // ignore: avoid_unused_constructor_parameters ProxyApiSuperClass? nullableProxyApiParam, ); late bool aBool; late int anInt; late double aDouble; late String aString; late Uint8List aUint8List; late List<Object?> aList; late Map<String?, Object?> aMap; late ProxyApiTestEnum anEnum; late ProxyApiSuperClass aProxyApi; late bool? aNullableBool; late int? aNullableInt; late double? aNullableDouble; late String? aNullableString; late Uint8List? aNullableUint8List; late List<Object?>? aNullableList; late Map<String?, Object?>? aNullableMap; late ProxyApiTestEnum? aNullableEnum; late ProxyApiSuperClass? aNullableProxyApi; @attached late ProxyApiSuperClass attachedField; @static late ProxyApiSuperClass staticAttachedField; /// A no-op function taking no arguments and returning no value, to sanity /// test basic calling. late void Function()? flutterNoop; /// Responds with an error from an async function returning a value. late Object? Function()? flutterThrowError; /// Responds with an error from an async void function. late void Function()? flutterThrowErrorFromVoid; // ========== Non-nullable argument/return type tests ========== /// Returns the passed boolean, to test serialization and deserialization. late bool Function(bool aBool)? flutterEchoBool; /// Returns the passed int, to test serialization and deserialization. late int Function(int anInt)? flutterEchoInt; /// Returns the passed double, to test serialization and deserialization. late double Function(double aDouble)? flutterEchoDouble; /// Returns the passed string, to test serialization and deserialization. late String Function(String aString)? flutterEchoString; /// Returns the passed byte list, to test serialization and deserialization. late Uint8List Function(Uint8List aList)? flutterEchoUint8List; /// Returns the passed list, to test serialization and deserialization. late List<Object?> Function(List<Object?> aList)? flutterEchoList; /// Returns the passed list with ProxyApis, to test serialization and /// deserialization. late List<ProxyApiTestClass?> Function(List<ProxyApiTestClass?> aList)? flutterEchoProxyApiList; /// Returns the passed map, to test serialization and deserialization. late Map<String?, Object?> Function(Map<String?, Object?> aMap)? flutterEchoMap; /// Returns the passed map with ProxyApis, to test serialization and /// deserialization. late Map<String?, ProxyApiTestClass?> Function( Map<String?, ProxyApiTestClass?> aMap)? flutterEchoProxyApiMap; /// Returns the passed enum to test serialization and deserialization. late ProxyApiTestEnum Function(ProxyApiTestEnum anEnum)? flutterEchoEnum; /// Returns the passed ProxyApi to test serialization and deserialization. late ProxyApiSuperClass Function(ProxyApiSuperClass aProxyApi)? flutterEchoProxyApi; // ========== Nullable argument/return type tests ========== /// Returns the passed boolean, to test serialization and deserialization. late bool? Function(bool? aBool)? flutterEchoNullableBool; /// Returns the passed int, to test serialization and deserialization. late int? Function(int? anInt)? flutterEchoNullableInt; /// Returns the passed double, to test serialization and deserialization. late double? Function(double? aDouble)? flutterEchoNullableDouble; /// Returns the passed string, to test serialization and deserialization. late String? Function(String? aString)? flutterEchoNullableString; /// Returns the passed byte list, to test serialization and deserialization. late Uint8List? Function(Uint8List? aList)? flutterEchoNullableUint8List; /// Returns the passed list, to test serialization and deserialization. late List<Object?>? Function(List<Object?>? aList)? flutterEchoNullableList; /// Returns the passed map, to test serialization and deserialization. late Map<String?, Object?>? Function(Map<String?, Object?>? aMap)? flutterEchoNullableMap; /// Returns the passed enum to test serialization and deserialization. late ProxyApiTestEnum? Function(ProxyApiTestEnum? anEnum)? flutterEchoNullableEnum; /// Returns the passed ProxyApi to test serialization and deserialization. late ProxyApiSuperClass? Function(ProxyApiSuperClass? aProxyApi)? flutterEchoNullableProxyApi; // ========== Async tests ========== // These are minimal since async FlutterApi only changes Dart generation. // Currently they aren't integration tested, but having them here ensures // analysis coverage. /// A no-op function taking no arguments and returning no value, to sanity /// test basic asynchronous calling. @async late void Function()? flutterNoopAsync; /// Returns the passed in generic Object asynchronously. @async late String Function(String aString)? flutterEchoAsyncString; // ========== Synchronous host method tests ========== /// A no-op function taking no arguments and returning no value, to sanity /// test basic calling. void noop(); /// Returns an error, to test error handling. Object? throwError(); /// Returns an error from a void function, to test error handling. void throwErrorFromVoid(); /// Returns a Flutter error, to test error handling. Object? throwFlutterError(); /// Returns passed in int. int echoInt(int anInt); /// Returns passed in double. double echoDouble(double aDouble); /// Returns the passed in boolean. bool echoBool(bool aBool); /// Returns the passed in string. String echoString(String aString); /// Returns the passed in Uint8List. Uint8List echoUint8List(Uint8List aUint8List); /// Returns the passed in generic Object. Object echoObject(Object anObject); /// Returns the passed list, to test serialization and deserialization. List<Object?> echoList(List<Object?> aList); /// Returns the passed list with ProxyApis, to test serialization and /// deserialization. List<ProxyApiTestClass> echoProxyApiList( List<ProxyApiTestClass> aList, ); /// Returns the passed map, to test serialization and deserialization. Map<String?, Object?> echoMap(Map<String?, Object?> aMap); /// Returns the passed map with ProxyApis, to test serialization and /// deserialization. Map<String, ProxyApiTestClass> echoProxyApiMap( Map<String, ProxyApiTestClass> aMap, ); /// Returns the passed enum to test serialization and deserialization. ProxyApiTestEnum echoEnum(ProxyApiTestEnum anEnum); /// Returns the passed ProxyApi to test serialization and deserialization. ProxyApiSuperClass echoProxyApi(ProxyApiSuperClass aProxyApi); // ========== Synchronous host nullable method tests ========== /// Returns passed in int. int? echoNullableInt(int? aNullableInt); /// Returns passed in double. double? echoNullableDouble(double? aNullableDouble); /// Returns the passed in boolean. bool? echoNullableBool(bool? aNullableBool); /// Returns the passed in string. String? echoNullableString(String? aNullableString); /// Returns the passed in Uint8List. Uint8List? echoNullableUint8List(Uint8List? aNullableUint8List); /// Returns the passed in generic Object. Object? echoNullableObject(Object? aNullableObject); /// Returns the passed list, to test serialization and deserialization. List<Object?>? echoNullableList(List<Object?>? aNullableList); /// Returns the passed map, to test serialization and deserialization. Map<String?, Object?>? echoNullableMap(Map<String?, Object?>? aNullableMap); ProxyApiTestEnum? echoNullableEnum(ProxyApiTestEnum? aNullableEnum); /// Returns the passed ProxyApi to test serialization and deserialization. ProxyApiSuperClass? echoNullableProxyApi( ProxyApiSuperClass? aNullableProxyApi, ); // ========== Asynchronous method tests ========== /// A no-op function taking no arguments and returning no value, to sanity /// test basic asynchronous calling. @async void noopAsync(); /// Returns passed in int asynchronously. @async int echoAsyncInt(int anInt); /// Returns passed in double asynchronously. @async double echoAsyncDouble(double aDouble); /// Returns the passed in boolean asynchronously. @async bool echoAsyncBool(bool aBool); /// Returns the passed string asynchronously. @async String echoAsyncString(String aString); /// Returns the passed in Uint8List asynchronously. @async Uint8List echoAsyncUint8List(Uint8List aUint8List); /// Returns the passed in generic Object asynchronously. @async Object echoAsyncObject(Object anObject); /// Returns the passed list, to test asynchronous serialization and deserialization. @async List<Object?> echoAsyncList(List<Object?> aList); /// Returns the passed map, to test asynchronous serialization and deserialization. @async Map<String?, Object?> echoAsyncMap(Map<String?, Object?> aMap); /// Returns the passed enum, to test asynchronous serialization and deserialization. @async ProxyApiTestEnum echoAsyncEnum(ProxyApiTestEnum anEnum); /// Responds with an error from an async function returning a value. @async Object? throwAsyncError(); /// Responds with an error from an async void function. @async void throwAsyncErrorFromVoid(); /// Responds with a Flutter error from an async function returning a value. @async Object? throwAsyncFlutterError(); /// Returns passed in int asynchronously. @async int? echoAsyncNullableInt(int? anInt); /// Returns passed in double asynchronously. @async double? echoAsyncNullableDouble(double? aDouble); /// Returns the passed in boolean asynchronously. @async bool? echoAsyncNullableBool(bool? aBool); /// Returns the passed string asynchronously. @async String? echoAsyncNullableString(String? aString); /// Returns the passed in Uint8List asynchronously. @async Uint8List? echoAsyncNullableUint8List(Uint8List? aUint8List); /// Returns the passed in generic Object asynchronously. @async Object? echoAsyncNullableObject(Object? anObject); /// Returns the passed list, to test asynchronous serialization and deserialization. @async List<Object?>? echoAsyncNullableList(List<Object?>? aList); /// Returns the passed map, to test asynchronous serialization and deserialization. @async Map<String?, Object?>? echoAsyncNullableMap(Map<String?, Object?>? aMap); /// Returns the passed enum, to test asynchronous serialization and deserialization. @async ProxyApiTestEnum? echoAsyncNullableEnum(ProxyApiTestEnum? anEnum); // ========== Static method test ========== @static void staticNoop(); @static String echoStaticString(String aString); @static @async void staticAsyncNoop(); // ========== Flutter methods test wrappers ========== @async void callFlutterNoop(); @async Object? callFlutterThrowError(); @async void callFlutterThrowErrorFromVoid(); @async bool callFlutterEchoBool(bool aBool); @async int callFlutterEchoInt(int anInt); @async double callFlutterEchoDouble(double aDouble); @async String callFlutterEchoString(String aString); @async Uint8List callFlutterEchoUint8List(Uint8List aUint8List); @async List<Object?> callFlutterEchoList(List<Object?> aList); @async List<ProxyApiTestClass?> callFlutterEchoProxyApiList( List<ProxyApiTestClass?> aList); @async Map<String?, Object?> callFlutterEchoMap(Map<String?, Object?> aMap); @async Map<String?, ProxyApiTestClass?> callFlutterEchoProxyApiMap( Map<String?, ProxyApiTestClass?> aMap); @async ProxyApiTestEnum callFlutterEchoEnum(ProxyApiTestEnum anEnum); @async ProxyApiSuperClass callFlutterEchoProxyApi(ProxyApiSuperClass aProxyApi); @async bool? callFlutterEchoNullableBool(bool? aBool); @async int? callFlutterEchoNullableInt(int? anInt); @async double? callFlutterEchoNullableDouble(double? aDouble); @async String? callFlutterEchoNullableString(String? aString); @async Uint8List? callFlutterEchoNullableUint8List(Uint8List? aUint8List); @async List<Object?>? callFlutterEchoNullableList(List<Object?>? aList); @async Map<String?, Object?>? callFlutterEchoNullableMap( Map<String?, Object?>? aMap, ); @async ProxyApiTestEnum? callFlutterEchoNullableEnum(ProxyApiTestEnum? anEnum); @async ProxyApiSuperClass? callFlutterEchoNullableProxyApi( ProxyApiSuperClass? aProxyApi, ); @async void callFlutterNoopAsync(); @async String callFlutterEchoAsyncString(String aString); } /// ProxyApi to serve as a super class to the core ProxyApi class. @ProxyApi() abstract class ProxyApiSuperClass { ProxyApiSuperClass(); void aSuperMethod(); } /// ProxyApi to serve as an interface to the core ProxyApi class. @ProxyApi() abstract class ProxyApiInterface { late void Function()? anInterfaceMethod; }
packages/packages/pigeon/pigeons/proxy_api_tests.dart/0
{ "file_path": "packages/packages/pigeon/pigeons/proxy_api_tests.dart", "repo_id": "packages", "token_count": 4622 }
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. package com.example.alternate_language_test_plugin; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import com.example.alternate_language_test_plugin.MultipleArity.MultipleArityFlutterApi; import io.flutter.plugin.common.BinaryMessenger; import java.nio.ByteBuffer; import java.util.ArrayList; import org.junit.Test; public class MultipleArityTest { @Test public void subtract() { BinaryMessenger binaryMessenger = mock(BinaryMessenger.class); doAnswer( invocation -> { ByteBuffer message = invocation.getArgument(1); BinaryMessenger.BinaryReply reply = invocation.getArgument(2); message.position(0); @SuppressWarnings("unchecked") ArrayList<Object> args = (ArrayList<Object>) MultipleArityFlutterApi.getCodec().decodeMessage(message); Long arg0 = (Long) args.get(0); Long arg1 = (Long) args.get(1); Long output = arg0 - arg1; ArrayList<Object> wrapped = new ArrayList<Object>(); wrapped.add(0, output); ByteBuffer replyData = MultipleArityFlutterApi.getCodec().encodeMessage(wrapped); replyData.position(0); reply.reply(replyData); return null; }) .when(binaryMessenger) .send(anyString(), any(), any()); MultipleArityFlutterApi api = new MultipleArityFlutterApi(binaryMessenger); api.subtract( 30L, 20L, new MultipleArity.Result<Long>() { public void success(Long result) { assertEquals(10L, (long) result); } public void error(Throwable error) { assertEquals(error, null); } }); } }
packages/packages/pigeon/platform_tests/alternate_language_test_plugin/android/src/test/java/com/example/alternate_language_test_plugin/MultipleArityTest.java/0
{ "file_path": "packages/packages/pigeon/platform_tests/alternate_language_test_plugin/android/src/test/java/com/example/alternate_language_test_plugin/MultipleArityTest.java", "repo_id": "packages", "token_count": 846 }
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 XCTest; @import alternate_language_test_plugin; #import "EchoMessenger.h" #import "MockBinaryMessenger.h" /////////////////////////////////////////////////////////////////////////////////////////// @interface MockNullableArgHostApi : NSObject <NullableArgHostApi> @property(nonatomic, assign) BOOL didCall; @property(nonatomic, copy) NSNumber *x; @end /////////////////////////////////////////////////////////////////////////////////////////// @implementation MockNullableArgHostApi - (nullable NSNumber *)doitX:(NSNumber *_Nullable)x error:(FlutterError *_Nullable __autoreleasing *_Nonnull)error { _didCall = YES; self.x = x; return x; } @end /////////////////////////////////////////////////////////////////////////////////////////// @interface NullableReturnsTest : XCTestCase @end /////////////////////////////////////////////////////////////////////////////////////////// @implementation NullableReturnsTest - (void)testNullableParameterWithFlutterApi { EchoBinaryMessenger *binaryMessenger = [[EchoBinaryMessenger alloc] initWithCodec:NullableArgHostApiGetCodec()]; NullableArgFlutterApi *api = [[NullableArgFlutterApi alloc] initWithBinaryMessenger:binaryMessenger]; XCTestExpectation *expectation = [self expectationWithDescription:@"callback"]; [api doitX:nil completion:^(NSNumber *_Nonnull result, FlutterError *_Nullable error) { XCTAssertNil(result); [expectation fulfill]; }]; [self waitForExpectations:@[ expectation ] timeout:1.0]; } - (void)testNullableParameterWithHostApi { MockNullableArgHostApi *api = [[MockNullableArgHostApi alloc] init]; MockBinaryMessenger *binaryMessenger = [[MockBinaryMessenger alloc] initWithCodec:NullableArgHostApiGetCodec()]; NSString *channel = @"dev.flutter.pigeon.pigeon_integration_tests.NullableArgHostApi.doit"; SetUpNullableArgHostApi(binaryMessenger, api); XCTAssertNotNil(binaryMessenger.handlers[channel]); XCTestExpectation *expectation = [self expectationWithDescription:@"callback"]; NSData *arguments = [NullableArgHostApiGetCodec() encode:@[ [NSNull null] ]]; binaryMessenger.handlers[channel](arguments, ^(NSData *data) { [expectation fulfill]; }); XCTAssertTrue(api.didCall); XCTAssertNil(api.x); [self waitForExpectations:@[ expectation ] timeout:1.0]; } @end
packages/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/RunnerTests/NullableReturnsTest.m/0
{ "file_path": "packages/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/RunnerTests/NullableReturnsTest.m", "repo_id": "packages", "token_count": 808 }
1,018
name: alternate_language_test_plugin_example description: Pigeon test harness for alternate plugin languages. publish_to: 'none' environment: sdk: ^3.1.0 dependencies: alternate_language_test_plugin: path: ../ flutter: sdk: flutter shared_test_plugin_code: path: ../../shared_test_plugin_code dev_dependencies: flutter_test: sdk: flutter integration_test: sdk: flutter flutter: uses-material-design: true
packages/packages/pigeon/platform_tests/alternate_language_test_plugin/example/pubspec.yaml/0
{ "file_path": "packages/packages/pigeon/platform_tests/alternate_language_test_plugin/example/pubspec.yaml", "repo_id": "packages", "token_count": 164 }
1,019
# # To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html. # Run `pod lib lint alternate_language_test_plugin.podspec` to validate before publishing. # Pod::Spec.new do |s| s.name = 'alternate_language_test_plugin' s.version = '0.0.1' s.summary = 'Alternate-language Pigeon test plugin' s.description = <<-DESC A plugin to test Pigeon generation for secondary languages (e.g., Java, Objective-C). DESC s.homepage = 'http://example.com' s.license = { :type => 'BSD', :file => '../../../LICENSE' } s.author = { 'Your Company' => '[email protected]' } s.source = { :http => 'https://github.com/flutter/packages/tree/main/packages/pigeon' } s.source_files = 'Classes/**/*' s.dependency 'FlutterMacOS' s.platform = :osx, '10.14' s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' } s.swift_version = '5.0' end
packages/packages/pigeon/platform_tests/alternate_language_test_plugin/macos/alternate_language_test_plugin.podspec/0
{ "file_path": "packages/packages/pigeon/platform_tests/alternate_language_test_plugin/macos/alternate_language_test_plugin.podspec", "repo_id": "packages", "token_count": 424 }
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. // // Autogenerated from Pigeon, do not edit directly. // See also: https://pub.dev/packages/pigeon // ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import, no_leading_underscores_for_local_identifiers import 'dart:async'; import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; import 'package:flutter/services.dart'; PlatformException _createConnectionError(String channelName) { return PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel: "$channelName".', ); } List<Object?> wrapResponse( {Object? result, PlatformException? error, bool empty = false}) { if (empty) { return <Object?>[]; } if (error == null) { return <Object?>[result]; } return <Object?>[error.code, error.message, error.details]; } class NullableReturnHostApi { /// Constructor for [NullableReturnHostApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. NullableReturnHostApi({BinaryMessenger? binaryMessenger}) : __pigeon_binaryMessenger = binaryMessenger; final BinaryMessenger? __pigeon_binaryMessenger; static const MessageCodec<Object?> pigeonChannelCodec = StandardMessageCodec(); Future<int?> doit() async { const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.NullableReturnHostApi.doit'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(null) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return (__pigeon_replyList[0] as int?); } } } abstract class NullableReturnFlutterApi { static const MessageCodec<Object?> pigeonChannelCodec = StandardMessageCodec(); int? doit(); static void setup(NullableReturnFlutterApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.NullableReturnFlutterApi.doit', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (api == null) { __pigeon_channel.setMessageHandler(null); } else { __pigeon_channel.setMessageHandler((Object? message) async { try { final int? output = api.doit(); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } } } class NullableArgHostApi { /// Constructor for [NullableArgHostApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. NullableArgHostApi({BinaryMessenger? binaryMessenger}) : __pigeon_binaryMessenger = binaryMessenger; final BinaryMessenger? __pigeon_binaryMessenger; static const MessageCodec<Object?> pigeonChannelCodec = StandardMessageCodec(); Future<int> doit(int? x) async { const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.NullableArgHostApi.doit'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[x]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else if (__pigeon_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (__pigeon_replyList[0] as int?)!; } } } abstract class NullableArgFlutterApi { static const MessageCodec<Object?> pigeonChannelCodec = StandardMessageCodec(); int? doit(int? x); static void setup(NullableArgFlutterApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.NullableArgFlutterApi.doit', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (api == null) { __pigeon_channel.setMessageHandler(null); } else { __pigeon_channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.NullableArgFlutterApi.doit was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_x = (args[0] as int?); try { final int? output = api.doit(arg_x); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } } } class NullableCollectionReturnHostApi { /// Constructor for [NullableCollectionReturnHostApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. NullableCollectionReturnHostApi({BinaryMessenger? binaryMessenger}) : __pigeon_binaryMessenger = binaryMessenger; final BinaryMessenger? __pigeon_binaryMessenger; static const MessageCodec<Object?> pigeonChannelCodec = StandardMessageCodec(); Future<List<String?>?> doit() async { const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.NullableCollectionReturnHostApi.doit'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(null) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return (__pigeon_replyList[0] as List<Object?>?)?.cast<String?>(); } } } abstract class NullableCollectionReturnFlutterApi { static const MessageCodec<Object?> pigeonChannelCodec = StandardMessageCodec(); List<String?>? doit(); static void setup(NullableCollectionReturnFlutterApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.NullableCollectionReturnFlutterApi.doit', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (api == null) { __pigeon_channel.setMessageHandler(null); } else { __pigeon_channel.setMessageHandler((Object? message) async { try { final List<String?>? output = api.doit(); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } } } class NullableCollectionArgHostApi { /// Constructor for [NullableCollectionArgHostApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. NullableCollectionArgHostApi({BinaryMessenger? binaryMessenger}) : __pigeon_binaryMessenger = binaryMessenger; final BinaryMessenger? __pigeon_binaryMessenger; static const MessageCodec<Object?> pigeonChannelCodec = StandardMessageCodec(); Future<List<String?>> doit(List<String?>? x) async { const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.NullableCollectionArgHostApi.doit'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[x]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else if (__pigeon_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (__pigeon_replyList[0] as List<Object?>?)!.cast<String?>(); } } } abstract class NullableCollectionArgFlutterApi { static const MessageCodec<Object?> pigeonChannelCodec = StandardMessageCodec(); List<String?> doit(List<String?>? x); static void setup(NullableCollectionArgFlutterApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.NullableCollectionArgFlutterApi.doit', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (api == null) { __pigeon_channel.setMessageHandler(null); } else { __pigeon_channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.NullableCollectionArgFlutterApi.doit was null.'); final List<Object?> args = (message as List<Object?>?)!; final List<String?>? arg_x = (args[0] as List<Object?>?)?.cast<String?>(); try { final List<String?> output = api.doit(arg_x); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } } }
packages/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/nullable_returns.gen.dart/0
{ "file_path": "packages/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/nullable_returns.gen.dart", "repo_id": "packages", "token_count": 4845 }
1,021
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/services.dart'; import 'package:mockito/mockito.dart'; void echoOneArgument( BinaryMessenger mockMessenger, String channel, MessageCodec<Object?> codec, ) { when(mockMessenger.send(channel, any)) .thenAnswer((Invocation realInvocation) async { final Object input = codec .decodeMessage(realInvocation.positionalArguments[1] as ByteData?)!; final List<Object?> args = input as List<Object?>; return codec.encodeMessage(<Object>[args[0]!]); }); }
packages/packages/pigeon/platform_tests/shared_test_plugin_code/test/test_util.dart/0
{ "file_path": "packages/packages/pigeon/platform_tests/shared_test_plugin_code/test/test_util.dart", "repo_id": "packages", "token_count": 224 }
1,022
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package com.example.test_plugin import io.flutter.plugin.common.BinaryMessenger import io.mockk.every import io.mockk.mockk import io.mockk.slot import java.nio.ByteBuffer import java.util.ArrayList import junit.framework.TestCase import org.junit.Test class MultipleArityTests : TestCase() { @Test fun testSimpleHost() { val binaryMessenger = mockk<BinaryMessenger>() val api = mockk<MultipleArityHostApi>() val inputX = 10L val inputY = 5L val channelName = "dev.flutter.pigeon.pigeon_integration_tests.MultipleArityHostApi.subtract" val handlerSlot = slot<BinaryMessenger.BinaryMessageHandler>() every { binaryMessenger.setMessageHandler(channelName, capture(handlerSlot)) } returns Unit every { api.subtract(any(), any()) } answers { firstArg<Long>() - secondArg<Long>() } MultipleArityHostApi.setUp(binaryMessenger, api) val codec = MultipleArityHostApi.codec val message = codec.encodeMessage(listOf(inputX, inputY)) message?.rewind() handlerSlot.captured.onMessage(message) { it?.rewind() @Suppress("UNCHECKED_CAST") val wrapped = codec.decodeMessage(it) as List<Any>? assertNotNull(wrapped) wrapped?.let { assertEquals(inputX - inputY, wrapped[0]) } } } @Test fun testSimpleFlutter() { val binaryMessenger = mockk<BinaryMessenger>() val api = MultipleArityFlutterApi(binaryMessenger) val inputX = 10L val inputY = 5L every { binaryMessenger.send(any(), any(), any()) } answers { val codec = MultipleArityFlutterApi.codec val message = arg<ByteBuffer>(1) val reply = arg<BinaryMessenger.BinaryReply>(2) message.position(0) val args = codec.decodeMessage(message) as ArrayList<*> val argX = args[0] as Long val argY = args[1] as Long val replyData = codec.encodeMessage(listOf(argX - argY)) replyData?.position(0) reply.reply(replyData) } var didCall = false api.subtract(inputX, inputY) { didCall = true assertEquals(inputX - inputY, it.getOrNull()) } assertTrue(didCall) } }
packages/packages/pigeon/platform_tests/test_plugin/android/src/test/kotlin/com/example/test_plugin/MultipleArityTests.kt/0
{ "file_path": "packages/packages/pigeon/platform_tests/test_plugin/android/src/test/kotlin/com/example/test_plugin/MultipleArityTests.kt", "repo_id": "packages", "token_count": 906 }
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 Flutter import XCTest @testable import test_plugin class AllDatatypesTests: XCTestCase { func testAllNull() throws { let everything = AllNullableTypes() let binaryMessenger = EchoBinaryMessenger(codec: FlutterIntegrationCoreApiCodec.shared) let api = FlutterIntegrationCoreApi(binaryMessenger: binaryMessenger) let expectation = XCTestExpectation(description: "callback") api.echoNullable(everything) { result in switch result { case .success(let res): XCTAssertNotNil(res) XCTAssertNil(res!.aNullableBool) XCTAssertNil(res!.aNullableInt) XCTAssertNil(res!.aNullableDouble) XCTAssertNil(res!.aNullableString) XCTAssertNil(res!.aNullableByteArray) XCTAssertNil(res!.aNullable4ByteArray) XCTAssertNil(res!.aNullable8ByteArray) XCTAssertNil(res!.aNullableFloatArray) XCTAssertNil(res!.aNullableList) XCTAssertNil(res!.aNullableMap) XCTAssertNil(res!.nullableNestedList) XCTAssertNil(res!.nullableMapWithAnnotations) XCTAssertNil(res!.nullableMapWithObject) expectation.fulfill() case .failure(_): return } } wait(for: [expectation], timeout: 1.0) } func testAllEquals() throws { let everything = AllNullableTypes( aNullableBool: true, aNullableInt: 1, aNullableDouble: 2.0, aNullableByteArray: FlutterStandardTypedData(bytes: "1234".data(using: .utf8)!), aNullable4ByteArray: FlutterStandardTypedData(int32: "1234".data(using: .utf8)!), aNullable8ByteArray: FlutterStandardTypedData(int64: "12345678".data(using: .utf8)!), aNullableFloatArray: FlutterStandardTypedData(float64: "12345678".data(using: .utf8)!), aNullableList: [1, 2], aNullableMap: ["hello": 1234], nullableNestedList: [[true, false], [true]], nullableMapWithAnnotations: ["hello": "world"], nullableMapWithObject: ["hello": 1234, "goodbye": "world"], aNullableString: "123" ) let binaryMessenger = EchoBinaryMessenger(codec: FlutterIntegrationCoreApiCodec.shared) let api = FlutterIntegrationCoreApi(binaryMessenger: binaryMessenger) let expectation = XCTestExpectation(description: "callback") api.echoNullable(everything) { result in switch result { case .success(let res): XCTAssertNotNil(res) XCTAssertEqual(res!.aNullableBool, everything.aNullableBool) XCTAssertEqual(res!.aNullableInt, everything.aNullableInt) XCTAssertEqual(res!.aNullableDouble, everything.aNullableDouble) XCTAssertEqual(res!.aNullableString, everything.aNullableString) XCTAssertEqual(res!.aNullableByteArray, everything.aNullableByteArray) XCTAssertEqual(res!.aNullable4ByteArray, everything.aNullable4ByteArray) XCTAssertEqual(res!.aNullable8ByteArray, everything.aNullable8ByteArray) XCTAssertEqual(res!.aNullableFloatArray, everything.aNullableFloatArray) XCTAssert(equalsList(res!.aNullableList, everything.aNullableList)) XCTAssert(equalsDictionary(res!.aNullableMap, everything.aNullableMap)) XCTAssertEqual(res!.nullableNestedList, everything.nullableNestedList) XCTAssertEqual(res!.nullableMapWithAnnotations, everything.nullableMapWithAnnotations) XCTAssert(equalsDictionary(res!.nullableMapWithObject, everything.nullableMapWithObject)) expectation.fulfill() return case .failure(_): return } } wait(for: [expectation], timeout: 1.0) } }
packages/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/AllDatatypesTests.swift/0
{ "file_path": "packages/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/AllDatatypesTests.swift", "repo_id": "packages", "token_count": 1525 }
1,024